drc: some more libnx support
[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 #ifdef HAVE_LIBNX
33 #include <switch.h>
34 static Jit g_jit;
35 #endif
36
37 #include "new_dynarec_config.h"
38 #include "../psxhle.h"
39 #include "../psxinterpreter.h"
40 #include "../gte.h"
41 #include "emu_if.h" // emulator interface
42 #include "arm_features.h"
43
44 #ifdef __clang__
45 #define noinline __attribute__((noinline))
46 #else
47 #define noinline __attribute__((noinline,noclone))
48 #endif
49 #ifndef ARRAY_SIZE
50 #define ARRAY_SIZE(x) (sizeof(x) / sizeof(x[0]))
51 #endif
52 #ifndef min
53 #define min(a, b) ((b) < (a) ? (b) : (a))
54 #endif
55 #ifndef max
56 #define max(a, b) ((b) > (a) ? (b) : (a))
57 #endif
58
59 //#define DISASM
60 //#define ASSEM_PRINT
61 //#define STAT_PRINT
62
63 #ifdef ASSEM_PRINT
64 #define assem_debug printf
65 #else
66 #define assem_debug(...)
67 #endif
68 //#define inv_debug printf
69 #define inv_debug(...)
70
71 #ifdef __i386__
72 #include "assem_x86.h"
73 #endif
74 #ifdef __x86_64__
75 #include "assem_x64.h"
76 #endif
77 #ifdef __arm__
78 #include "assem_arm.h"
79 #endif
80 #ifdef __aarch64__
81 #include "assem_arm64.h"
82 #endif
83
84 #define RAM_SIZE 0x200000
85 #define MAXBLOCK 4096
86 #define MAX_OUTPUT_BLOCK_SIZE 262144
87 #define EXPIRITY_OFFSET (MAX_OUTPUT_BLOCK_SIZE * 2)
88 #define PAGE_COUNT 1024
89
90 #if defined(HAVE_CONDITIONAL_CALL) && !defined(DESTRUCTIVE_SHIFT)
91 #define INVALIDATE_USE_COND_CALL
92 #endif
93
94 #ifdef VITA
95 // apparently Vita has a 16MB limit, so either we cut tc in half,
96 // or use this hack (it's a hack because tc size was designed to be power-of-2)
97 #define TC_REDUCE_BYTES 4096
98 #else
99 #define TC_REDUCE_BYTES 0
100 #endif
101
102 struct ndrc_tramp
103 {
104   struct tramp_insns ops[2048 / sizeof(struct tramp_insns)];
105   const void *f[2048 / sizeof(void *)];
106 };
107
108 struct ndrc_mem
109 {
110   u_char translation_cache[(1 << TARGET_SIZE_2) - TC_REDUCE_BYTES];
111   struct ndrc_tramp tramp;
112 };
113
114 #ifdef BASE_ADDR_DYNAMIC
115 static struct ndrc_mem *ndrc;
116 #else
117 static struct ndrc_mem ndrc_ __attribute__((aligned(4096)));
118 static struct ndrc_mem *ndrc = &ndrc_;
119 #endif
120 #ifdef TC_WRITE_OFFSET
121 # ifdef __GLIBC__
122 # include <sys/types.h>
123 # include <sys/stat.h>
124 # include <fcntl.h>
125 # include <unistd.h>
126 # endif
127 static long ndrc_write_ofs;
128 #define NDRC_WRITE_OFFSET(x) (void *)((char *)(x) + ndrc_write_ofs)
129 #else
130 #define NDRC_WRITE_OFFSET(x) (x)
131 #endif
132
133 // stubs
134 enum stub_type {
135   CC_STUB = 1,
136   FP_STUB = 2,
137   LOADB_STUB = 3,
138   LOADH_STUB = 4,
139   LOADW_STUB = 5,
140   LOADD_STUB = 6,
141   LOADBU_STUB = 7,
142   LOADHU_STUB = 8,
143   STOREB_STUB = 9,
144   STOREH_STUB = 10,
145   STOREW_STUB = 11,
146   STORED_STUB = 12,
147   STORELR_STUB = 13,
148   INVCODE_STUB = 14,
149 };
150
151 // regmap_pre[i]    - regs before [i] insn starts; dirty things here that
152 //                    don't match .regmap will be written back
153 // [i].regmap_entry - regs that must be set up if someone jumps here
154 // [i].regmap       - regs [i] insn will read/(over)write
155 // branch_regs[i].* - same as above but for branches, takes delay slot into account
156 struct regstat
157 {
158   signed char regmap_entry[HOST_REGS];
159   signed char regmap[HOST_REGS];
160   uint64_t wasdirty;
161   uint64_t dirty;
162   uint64_t u;
163   u_int wasconst;                // before; for example 'lw r2, (r2)' wasconst is true
164   u_int isconst;                 //  ... but isconst is false when r2 is known
165   u_int loadedconst;             // host regs that have constants loaded
166   u_int waswritten;              // MIPS regs that were used as store base before
167 };
168
169 struct ht_entry
170 {
171   u_int vaddr[2];
172   void *tcaddr[2];
173 };
174
175 struct code_stub
176 {
177   enum stub_type type;
178   void *addr;
179   void *retaddr;
180   u_int a;
181   uintptr_t b;
182   uintptr_t c;
183   u_int d;
184   u_int e;
185 };
186
187 struct link_entry
188 {
189   void *addr;
190   u_int target;
191   u_int internal;
192 };
193
194 struct block_info
195 {
196   struct block_info *next;
197   const void *source;
198   const void *copy;
199   u_int start; // vaddr of the block start
200   u_int len;   // of the whole block source
201   u_int tc_offs;
202   //u_int tc_len;
203   u_int reg_sv_flags;
204   u_char is_dirty;
205   u_char inv_near_misses;
206   u_short jump_in_cnt;
207   struct {
208     u_int vaddr;
209     void *addr;
210   } jump_in[0];
211 };
212
213 struct jump_info
214 {
215   int alloc;
216   int count;
217   struct {
218     u_int target_vaddr;
219     void *stub;
220   } e[0];
221 };
222
223 static struct decoded_insn
224 {
225   u_char itype;
226   u_char opcode;
227   u_char opcode2;
228   u_char rs1;
229   u_char rs2;
230   u_char rt1;
231   u_char rt2;
232   u_char use_lt1:1;
233   u_char bt:1;
234   u_char ooo:1;
235   u_char is_ds:1;
236   u_char is_jump:1;
237   u_char is_ujump:1;
238   u_char is_load:1;
239   u_char is_store:1;
240 } dops[MAXBLOCK];
241
242   static u_char *out;
243   static struct ht_entry hash_table[65536];
244   static struct block_info *blocks[PAGE_COUNT];
245   static struct jump_info *jumps[PAGE_COUNT];
246   static u_int start;
247   static u_int *source;
248   static uint64_t gte_rs[MAXBLOCK]; // gte: 32 data and 32 ctl regs
249   static uint64_t gte_rt[MAXBLOCK];
250   static uint64_t gte_unneeded[MAXBLOCK];
251   static u_int smrv[32]; // speculated MIPS register values
252   static u_int smrv_strong; // mask or regs that are likely to have correct values
253   static u_int smrv_weak; // same, but somewhat less likely
254   static u_int smrv_strong_next; // same, but after current insn executes
255   static u_int smrv_weak_next;
256   static int imm[MAXBLOCK];
257   static u_int ba[MAXBLOCK];
258   static uint64_t unneeded_reg[MAXBLOCK];
259   static uint64_t branch_unneeded_reg[MAXBLOCK];
260   // see 'struct regstat' for a description
261   static signed char regmap_pre[MAXBLOCK][HOST_REGS];
262   // contains 'real' consts at [i] insn, but may differ from what's actually
263   // loaded in host reg as 'final' value is always loaded, see get_final_value()
264   static uint32_t current_constmap[HOST_REGS];
265   static uint32_t constmap[MAXBLOCK][HOST_REGS];
266   static struct regstat regs[MAXBLOCK];
267   static struct regstat branch_regs[MAXBLOCK];
268   static signed char minimum_free_regs[MAXBLOCK];
269   static int ccadj[MAXBLOCK];
270   static int slen;
271   static void *instr_addr[MAXBLOCK];
272   static struct link_entry link_addr[MAXBLOCK];
273   static int linkcount;
274   static struct code_stub stubs[MAXBLOCK*3];
275   static int stubcount;
276   static u_int literals[1024][2];
277   static int literalcount;
278   static int is_delayslot;
279   static char shadow[1048576]  __attribute__((aligned(16)));
280   static void *copy;
281   static u_int expirep;
282   static u_int stop_after_jal;
283   static u_int f1_hack;
284 #ifdef STAT_PRINT
285   static int stat_bc_direct;
286   static int stat_bc_pre;
287   static int stat_bc_restore;
288   static int stat_ht_lookups;
289   static int stat_jump_in_lookups;
290   static int stat_restore_tries;
291   static int stat_restore_compares;
292   static int stat_inv_addr_calls;
293   static int stat_inv_hits;
294   static int stat_blocks;
295   static int stat_links;
296   #define stat_inc(s) s++
297   #define stat_dec(s) s--
298   #define stat_clear(s) s = 0
299 #else
300   #define stat_inc(s)
301   #define stat_dec(s)
302   #define stat_clear(s)
303 #endif
304
305   int new_dynarec_hacks;
306   int new_dynarec_hacks_pergame;
307   int new_dynarec_hacks_old;
308   int new_dynarec_did_compile;
309
310   #define HACK_ENABLED(x) ((new_dynarec_hacks | new_dynarec_hacks_pergame) & (x))
311
312   extern int cycle_count; // ... until end of the timeslice, counts -N -> 0
313   extern int last_count;  // last absolute target, often = next_interupt
314   extern int pcaddr;
315   extern int pending_exception;
316   extern int branch_target;
317   extern uintptr_t ram_offset;
318   extern uintptr_t mini_ht[32][2];
319
320   /* registers that may be allocated */
321   /* 1-31 gpr */
322 #define LOREG 32 // lo
323 #define HIREG 33 // hi
324 //#define FSREG 34 // FPU status (FCSR)
325 #define CSREG 35 // Coprocessor status
326 #define CCREG 36 // Cycle count
327 #define INVCP 37 // Pointer to invalid_code
328 //#define MMREG 38 // Pointer to memory_map
329 #define ROREG 39 // ram offset (if rdram!=0x80000000)
330 #define TEMPREG 40
331 #define FTEMP 40 // FPU temporary register
332 #define PTEMP 41 // Prefetch temporary register
333 //#define TLREG 42 // TLB mapping offset
334 #define RHASH 43 // Return address hash
335 #define RHTBL 44 // Return address hash table address
336 #define RTEMP 45 // JR/JALR address register
337 #define MAXREG 45
338 #define AGEN1 46 // Address generation temporary register
339 //#define AGEN2 47 // Address generation temporary register
340 //#define MGEN1 48 // Maptable address generation temporary register
341 //#define MGEN2 49 // Maptable address generation temporary register
342 #define BTREG 50 // Branch target temporary register
343
344   /* instruction types */
345 #define NOP 0     // No operation
346 #define LOAD 1    // Load
347 #define STORE 2   // Store
348 #define LOADLR 3  // Unaligned load
349 #define STORELR 4 // Unaligned store
350 #define MOV 5     // Move
351 #define ALU 6     // Arithmetic/logic
352 #define MULTDIV 7 // Multiply/divide
353 #define SHIFT 8   // Shift by register
354 #define SHIFTIMM 9// Shift by immediate
355 #define IMM16 10  // 16-bit immediate
356 #define RJUMP 11  // Unconditional jump to register
357 #define UJUMP 12  // Unconditional jump
358 #define CJUMP 13  // Conditional branch (BEQ/BNE/BGTZ/BLEZ)
359 #define SJUMP 14  // Conditional branch (regimm format)
360 #define COP0 15   // Coprocessor 0
361 #define COP1 16   // Coprocessor 1
362 #define C1LS 17   // Coprocessor 1 load/store
363 //#define FJUMP 18  // Conditional branch (floating point)
364 //#define FLOAT 19  // Floating point unit
365 //#define FCONV 20  // Convert integer to float
366 //#define FCOMP 21  // Floating point compare (sets FSREG)
367 #define SYSCALL 22// SYSCALL,BREAK
368 #define OTHER 23  // Other
369 //#define SPAN 24   // Branch/delay slot spans 2 pages
370 #define NI 25     // Not implemented
371 #define HLECALL 26// PCSX fake opcodes for HLE
372 #define COP2 27   // Coprocessor 2 move
373 #define C2LS 28   // Coprocessor 2 load/store
374 #define C2OP 29   // Coprocessor 2 operation
375 #define INTCALL 30// Call interpreter to handle rare corner cases
376
377   /* branch codes */
378 #define TAKEN 1
379 #define NOTTAKEN 2
380 #define NULLDS 3
381
382 #define DJT_1 (void *)1l // no function, just a label in assem_debug log
383 #define DJT_2 (void *)2l
384
385 // asm linkage
386 void dyna_linker();
387 void cc_interrupt();
388 void fp_exception();
389 void fp_exception_ds();
390 void jump_syscall   (u_int u0, u_int u1, u_int pc);
391 void jump_syscall_ds(u_int u0, u_int u1, u_int pc);
392 void jump_break   (u_int u0, u_int u1, u_int pc);
393 void jump_break_ds(u_int u0, u_int u1, u_int pc);
394 void jump_to_new_pc();
395 void call_gteStall();
396 void new_dyna_leave();
397
398 void *ndrc_get_addr_ht_param(u_int vaddr, int can_compile);
399 void *ndrc_get_addr_ht(u_int vaddr);
400 void ndrc_invalidate_addr(u_int addr);
401 void ndrc_add_jump_out(u_int vaddr, void *src);
402
403 static int new_recompile_block(u_int addr);
404 static void invalidate_block(struct block_info *block);
405
406 // Needed by assembler
407 static void wb_register(signed char r, const signed char regmap[], uint64_t dirty);
408 static void wb_dirtys(const signed char i_regmap[], uint64_t i_dirty);
409 static void wb_needed_dirtys(const signed char i_regmap[], uint64_t i_dirty, int addr);
410 static void load_all_regs(const signed char i_regmap[]);
411 static void load_needed_regs(const signed char i_regmap[], const signed char next_regmap[]);
412 static void load_regs_entry(int t);
413 static void load_all_consts(const signed char regmap[], u_int dirty, int i);
414 static u_int get_host_reglist(const signed char *regmap);
415
416 static int get_final_value(int hr, int i, int *value);
417 static void add_stub(enum stub_type type, void *addr, void *retaddr,
418   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e);
419 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
420   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist);
421 static void add_to_linker(void *addr, u_int target, int ext);
422 static void *emit_fastpath_cmp_jump(int i, const struct regstat *i_regs,
423   int addr, int *offset_reg, int *addr_reg_override);
424 static void *get_direct_memhandler(void *table, u_int addr,
425   enum stub_type type, uintptr_t *addr_host);
426 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist);
427 static void pass_args(int a0, int a1);
428 static void emit_far_jump(const void *f);
429 static void emit_far_call(const void *f);
430
431 #ifdef VITA
432 #include <psp2/kernel/sysmem.h>
433 static int sceBlock;
434 // note: this interacts with RetroArch's Vita bootstrap code: bootstrap/vita/sbrk.c
435 extern int getVMBlock();
436 int _newlib_vm_size_user = sizeof(*ndrc);
437 #endif
438
439 static void mprotect_w_x(void *start, void *end, int is_x)
440 {
441 #ifdef NO_WRITE_EXEC
442   #if defined(VITA)
443   // *Open* enables write on all memory that was
444   // allocated by sceKernelAllocMemBlockForVM()?
445   if (is_x)
446     sceKernelCloseVMDomain();
447   else
448     sceKernelOpenVMDomain();
449   #elif defined(HAVE_LIBNX)
450   Result rc;
451   // check to avoid the full flush in jitTransitionToExecutable()
452   if (g_jit.type != JitType_CodeMemory) {
453     if (is_x)
454       rc = jitTransitionToExecutable(&g_jit);
455     else
456       rc = jitTransitionToWritable(&g_jit);
457     if (R_FAILED(rc))
458       ;//SysPrintf("jitTransition %d %08x\n", is_x, rc);
459   }
460   #elif defined(TC_WRITE_OFFSET)
461   // separated rx and rw areas are always available
462   #else
463   u_long mstart = (u_long)start & ~4095ul;
464   u_long mend = (u_long)end;
465   if (mprotect((void *)mstart, mend - mstart,
466                PROT_READ | (is_x ? PROT_EXEC : PROT_WRITE)) != 0)
467     SysPrintf("mprotect(%c) failed: %s\n", is_x ? 'x' : 'w', strerror(errno));
468   #endif
469 #endif
470 }
471
472 static void start_tcache_write(void *start, void *end)
473 {
474   mprotect_w_x(start, end, 0);
475 }
476
477 static void end_tcache_write(void *start, void *end)
478 {
479 #if defined(__arm__) || defined(__aarch64__)
480   size_t len = (char *)end - (char *)start;
481   #if   defined(__BLACKBERRY_QNX__)
482   msync(start, len, MS_SYNC | MS_CACHE_ONLY | MS_INVALIDATE_ICACHE);
483   #elif defined(__MACH__)
484   sys_cache_control(kCacheFunctionPrepareForExecution, start, len);
485   #elif defined(VITA)
486   sceKernelSyncVMDomain(sceBlock, start, len);
487   #elif defined(_3DS)
488   ctr_flush_invalidate_cache();
489   #elif defined(HAVE_LIBNX)
490   if (g_jit.type == JitType_CodeMemory) {
491     armDCacheClean(start, len);
492     armICacheInvalidate((char *)start - ndrc_write_ofs, len);
493   }
494   #elif defined(__aarch64__)
495   // as of 2021, __clear_cache() is still broken on arm64
496   // so here is a custom one :(
497   clear_cache_arm64(start, end);
498   #else
499   __clear_cache(start, end);
500   #endif
501   (void)len;
502 #endif
503
504   mprotect_w_x(start, end, 1);
505 }
506
507 static void *start_block(void)
508 {
509   u_char *end = out + MAX_OUTPUT_BLOCK_SIZE;
510   if (end > ndrc->translation_cache + sizeof(ndrc->translation_cache))
511     end = ndrc->translation_cache + sizeof(ndrc->translation_cache);
512   start_tcache_write(NDRC_WRITE_OFFSET(out), NDRC_WRITE_OFFSET(end));
513   return out;
514 }
515
516 static void end_block(void *start)
517 {
518   end_tcache_write(NDRC_WRITE_OFFSET(start), NDRC_WRITE_OFFSET(out));
519 }
520
521 #ifdef NDRC_CACHE_FLUSH_ALL
522
523 static int needs_clear_cache;
524
525 static void mark_clear_cache(void *target)
526 {
527   if (!needs_clear_cache) {
528     start_tcache_write(NDRC_WRITE_OFFSET(ndrc), NDRC_WRITE_OFFSET(ndrc + 1));
529     needs_clear_cache = 1;
530   }
531 }
532
533 static void do_clear_cache(void)
534 {
535   if (needs_clear_cache) {
536     end_tcache_write(NDRC_WRITE_OFFSET(ndrc), NDRC_WRITE_OFFSET(ndrc + 1));
537     needs_clear_cache = 0;
538   }
539 }
540
541 #else
542
543 // also takes care of w^x mappings when patching code
544 static u_int needs_clear_cache[1<<(TARGET_SIZE_2-17)];
545
546 static void mark_clear_cache(void *target)
547 {
548   uintptr_t offset = (u_char *)target - ndrc->translation_cache;
549   u_int mask = 1u << ((offset >> 12) & 31);
550   if (!(needs_clear_cache[offset >> 17] & mask)) {
551     char *start = (char *)NDRC_WRITE_OFFSET((uintptr_t)target & ~4095l);
552     start_tcache_write(start, start + 4095);
553     needs_clear_cache[offset >> 17] |= mask;
554   }
555 }
556
557 // Clearing the cache is rather slow on ARM Linux, so mark the areas
558 // that need to be cleared, and then only clear these areas once.
559 static void do_clear_cache(void)
560 {
561   int i, j;
562   for (i = 0; i < (1<<(TARGET_SIZE_2-17)); i++)
563   {
564     u_int bitmap = needs_clear_cache[i];
565     if (!bitmap)
566       continue;
567     for (j = 0; j < 32; j++)
568     {
569       u_char *start, *end;
570       if (!(bitmap & (1u << j)))
571         continue;
572
573       start = ndrc->translation_cache + i*131072 + j*4096;
574       end = start + 4095;
575       for (j++; j < 32; j++) {
576         if (!(bitmap & (1u << j)))
577           break;
578         end += 4096;
579       }
580       end_tcache_write(NDRC_WRITE_OFFSET(start), NDRC_WRITE_OFFSET(end));
581     }
582     needs_clear_cache[i] = 0;
583   }
584 }
585
586 #endif // NDRC_CACHE_FLUSH_ALL
587
588 #define NO_CYCLE_PENALTY_THR 12
589
590 int cycle_multiplier = CYCLE_MULT_DEFAULT; // 100 for 1.0
591 int cycle_multiplier_override;
592 int cycle_multiplier_old;
593 static int cycle_multiplier_active;
594
595 static int CLOCK_ADJUST(int x)
596 {
597   int m = cycle_multiplier_active;
598   int s = (x >> 31) | 1;
599   return (x * m + s * 50) / 100;
600 }
601
602 static int ds_writes_rjump_rs(int i)
603 {
604   return dops[i].rs1 != 0 && (dops[i].rs1 == dops[i+1].rt1 || dops[i].rs1 == dops[i+1].rt2);
605 }
606
607 // psx addr mirror masking (for invalidation)
608 static u_int pmmask(u_int vaddr)
609 {
610   vaddr &= ~0xe0000000;
611   if (vaddr < 0x01000000)
612     vaddr &= ~0x00e00000; // RAM mirrors
613   return vaddr;
614 }
615
616 static u_int get_page(u_int vaddr)
617 {
618   u_int page = pmmask(vaddr) >> 12;
619   if (page >= PAGE_COUNT / 2)
620     page = PAGE_COUNT / 2 + (page & (PAGE_COUNT / 2 - 1));
621   return page;
622 }
623
624 // get a page for looking for a block that has vaddr
625 // (needed because the block may start in previous page)
626 static u_int get_page_prev(u_int vaddr)
627 {
628   assert(MAXBLOCK <= (1 << 12));
629   u_int page = get_page(vaddr);
630   if (page & 511)
631     page--;
632   return page;
633 }
634
635 static struct ht_entry *hash_table_get(u_int vaddr)
636 {
637   return &hash_table[((vaddr>>16)^vaddr)&0xFFFF];
638 }
639
640 static void hash_table_add(u_int vaddr, void *tcaddr)
641 {
642   struct ht_entry *ht_bin = hash_table_get(vaddr);
643   assert(tcaddr);
644   ht_bin->vaddr[1] = ht_bin->vaddr[0];
645   ht_bin->tcaddr[1] = ht_bin->tcaddr[0];
646   ht_bin->vaddr[0] = vaddr;
647   ht_bin->tcaddr[0] = tcaddr;
648 }
649
650 static void hash_table_remove(int vaddr)
651 {
652   //printf("remove hash: %x\n",vaddr);
653   struct ht_entry *ht_bin = hash_table_get(vaddr);
654   if (ht_bin->vaddr[1] == vaddr) {
655     ht_bin->vaddr[1] = -1;
656     ht_bin->tcaddr[1] = NULL;
657   }
658   if (ht_bin->vaddr[0] == vaddr) {
659     ht_bin->vaddr[0] = ht_bin->vaddr[1];
660     ht_bin->tcaddr[0] = ht_bin->tcaddr[1];
661     ht_bin->vaddr[1] = -1;
662     ht_bin->tcaddr[1] = NULL;
663   }
664 }
665
666 static void mark_invalid_code(u_int vaddr, u_int len, char invalid)
667 {
668   u_int vaddr_m = vaddr & 0x1fffffff;
669   u_int i, j;
670   for (i = vaddr_m & ~0xfff; i < vaddr_m + len; i += 0x1000) {
671     // ram mirrors, but should not hurt bios
672     for (j = 0; j < 0x800000; j += 0x200000) {
673       invalid_code[(i|j) >> 12] =
674       invalid_code[(i|j|0x80000000u) >> 12] =
675       invalid_code[(i|j|0xa0000000u) >> 12] = invalid;
676     }
677   }
678   if (!invalid && vaddr + len > inv_code_start && vaddr <= inv_code_end)
679     inv_code_start = inv_code_end = ~0;
680 }
681
682 static int doesnt_expire_soon(u_char *tcaddr)
683 {
684   u_int diff = (u_int)(tcaddr - out) & ((1u << TARGET_SIZE_2) - 1u);
685   return diff > EXPIRITY_OFFSET + MAX_OUTPUT_BLOCK_SIZE;
686 }
687
688 static void *try_restore_block(u_int vaddr, u_int start_page, u_int end_page)
689 {
690   void *found_clean = NULL;
691   u_int i, page;
692
693   stat_inc(stat_restore_tries);
694   for (page = start_page; page <= end_page; page++) {
695     struct block_info *block;
696     for (block = blocks[page]; block != NULL; block = block->next) {
697       if (vaddr < block->start)
698         break;
699       if (!block->is_dirty || vaddr >= block->start + block->len)
700         continue;
701       for (i = 0; i < block->jump_in_cnt; i++)
702         if (block->jump_in[i].vaddr == vaddr)
703           break;
704       if (i == block->jump_in_cnt)
705         continue;
706       assert(block->source && block->copy);
707       stat_inc(stat_restore_compares);
708       if (memcmp(block->source, block->copy, block->len))
709         continue;
710
711       block->is_dirty = block->inv_near_misses = 0;
712       found_clean = block->jump_in[i].addr;
713       hash_table_add(vaddr, found_clean);
714       mark_invalid_code(block->start, block->len, 0);
715       stat_inc(stat_bc_restore);
716       inv_debug("INV: restored %08x %p (%d)\n", vaddr, found_clean, block->jump_in_cnt);
717       return found_clean;
718     }
719   }
720   return NULL;
721 }
722
723 // Get address from virtual address
724 // This is called from the recompiled JR/JALR instructions
725 static void noinline *get_addr(u_int vaddr, int can_compile)
726 {
727   u_int start_page = get_page_prev(vaddr);
728   u_int i, page, end_page = get_page(vaddr);
729   void *found_clean = NULL;
730
731   stat_inc(stat_jump_in_lookups);
732   for (page = start_page; page <= end_page; page++) {
733     const struct block_info *block;
734     for (block = blocks[page]; block != NULL; block = block->next) {
735       if (vaddr < block->start)
736         break;
737       if (block->is_dirty || vaddr >= block->start + block->len)
738         continue;
739       for (i = 0; i < block->jump_in_cnt; i++)
740         if (block->jump_in[i].vaddr == vaddr)
741           break;
742       if (i == block->jump_in_cnt)
743         continue;
744       found_clean = block->jump_in[i].addr;
745       hash_table_add(vaddr, found_clean);
746       return found_clean;
747     }
748   }
749   found_clean = try_restore_block(vaddr, start_page, end_page);
750   if (found_clean)
751     return found_clean;
752
753   if (!can_compile)
754     return NULL;
755
756   int r = new_recompile_block(vaddr);
757   if (r == 0)
758     return ndrc_get_addr_ht(vaddr);
759
760   // generate an address error
761   Status|=2;
762   Cause=(vaddr<<31)|(4<<2);
763   EPC=(vaddr&1)?vaddr-5:vaddr;
764   BadVAddr=(vaddr&~1);
765   return ndrc_get_addr_ht(0x80000080);
766 }
767
768 // Look up address in hash table first
769 void *ndrc_get_addr_ht_param(u_int vaddr, int can_compile)
770 {
771   const struct ht_entry *ht_bin = hash_table_get(vaddr);
772   stat_inc(stat_ht_lookups);
773   if (ht_bin->vaddr[0] == vaddr) return ht_bin->tcaddr[0];
774   if (ht_bin->vaddr[1] == vaddr) return ht_bin->tcaddr[1];
775   return get_addr(vaddr, can_compile);
776 }
777
778 void *ndrc_get_addr_ht(u_int vaddr)
779 {
780   return ndrc_get_addr_ht_param(vaddr, 1);
781 }
782
783 static void clear_all_regs(signed char regmap[])
784 {
785   memset(regmap, -1, sizeof(regmap[0]) * HOST_REGS);
786 }
787
788 // get_reg: get allocated host reg from mips reg
789 // returns -1 if no such mips reg was allocated
790 #if defined(__arm__) && defined(HAVE_ARMV6) && HOST_REGS == 13 && EXCLUDE_REG == 11
791
792 extern signed char get_reg(const signed char regmap[], signed char r);
793
794 #else
795
796 static signed char get_reg(const signed char regmap[], signed char r)
797 {
798   int hr;
799   for (hr = 0; hr < HOST_REGS; hr++) {
800     if (hr == EXCLUDE_REG)
801       continue;
802     if (regmap[hr] == r)
803       return hr;
804   }
805   return -1;
806 }
807
808 #endif
809
810 // get reg as mask bit (1 << hr)
811 static u_int get_regm(const signed char regmap[], signed char r)
812 {
813   return (1u << (get_reg(regmap, r) & 31)) & ~(1u << 31);
814 }
815
816 static signed char get_reg_temp(const signed char regmap[])
817 {
818   int hr;
819   for (hr = 0; hr < HOST_REGS; hr++) {
820     if (hr == EXCLUDE_REG)
821       continue;
822     if (regmap[hr] == (signed char)-1)
823       return hr;
824   }
825   return -1;
826 }
827
828 // Find a register that is available for two consecutive cycles
829 static signed char get_reg2(signed char regmap1[], const signed char regmap2[], int r)
830 {
831   int hr;
832   for (hr=0;hr<HOST_REGS;hr++) if(hr!=EXCLUDE_REG&&regmap1[hr]==r&&regmap2[hr]==r) return hr;
833   return -1;
834 }
835
836 // reverse reg map: mips -> host
837 #define RRMAP_SIZE 64
838 static void make_rregs(const signed char regmap[], signed char rrmap[RRMAP_SIZE],
839   u_int *regs_can_change)
840 {
841   u_int r, hr, hr_can_change = 0;
842   memset(rrmap, -1, RRMAP_SIZE);
843   for (hr = 0; hr < HOST_REGS; )
844   {
845     r = regmap[hr];
846     rrmap[r & (RRMAP_SIZE - 1)] = hr;
847     // only add mips $1-$31+$lo, others shifted out
848     hr_can_change |= (uint64_t)1 << (hr + ((r - 1) & 32));
849     hr++;
850     if (hr == EXCLUDE_REG)
851       hr++;
852   }
853   hr_can_change |= 1u << (rrmap[33] & 31);
854   hr_can_change |= 1u << (rrmap[CCREG] & 31);
855   hr_can_change &= ~(1u << 31);
856   *regs_can_change = hr_can_change;
857 }
858
859 // same as get_reg, but takes rrmap
860 static signed char get_rreg(signed char rrmap[RRMAP_SIZE], signed char r)
861 {
862   assert(0 <= r && r < RRMAP_SIZE);
863   return rrmap[r];
864 }
865
866 static int count_free_regs(const signed char regmap[])
867 {
868   int count=0;
869   int hr;
870   for(hr=0;hr<HOST_REGS;hr++)
871   {
872     if(hr!=EXCLUDE_REG) {
873       if(regmap[hr]<0) count++;
874     }
875   }
876   return count;
877 }
878
879 static void dirty_reg(struct regstat *cur, signed char reg)
880 {
881   int hr;
882   if (!reg) return;
883   hr = get_reg(cur->regmap, reg);
884   if (hr >= 0)
885     cur->dirty |= 1<<hr;
886 }
887
888 static void set_const(struct regstat *cur, signed char reg, uint32_t value)
889 {
890   int hr;
891   if (!reg) return;
892   hr = get_reg(cur->regmap, reg);
893   if (hr >= 0) {
894     cur->isconst |= 1<<hr;
895     current_constmap[hr] = value;
896   }
897 }
898
899 static void clear_const(struct regstat *cur, signed char reg)
900 {
901   int hr;
902   if (!reg) return;
903   hr = get_reg(cur->regmap, reg);
904   if (hr >= 0)
905     cur->isconst &= ~(1<<hr);
906 }
907
908 static int is_const(const struct regstat *cur, signed char reg)
909 {
910   int hr;
911   if (reg < 0) return 0;
912   if (!reg) return 1;
913   hr = get_reg(cur->regmap, reg);
914   if (hr >= 0)
915     return (cur->isconst>>hr)&1;
916   return 0;
917 }
918
919 static uint32_t get_const(const struct regstat *cur, signed char reg)
920 {
921   int hr;
922   if (!reg) return 0;
923   hr = get_reg(cur->regmap, reg);
924   if (hr >= 0)
925     return current_constmap[hr];
926
927   SysPrintf("Unknown constant in r%d\n", reg);
928   abort();
929 }
930
931 // Least soon needed registers
932 // Look at the next ten instructions and see which registers
933 // will be used.  Try not to reallocate these.
934 static void lsn(u_char hsn[], int i, int *preferred_reg)
935 {
936   int j;
937   int b=-1;
938   for(j=0;j<9;j++)
939   {
940     if(i+j>=slen) {
941       j=slen-i-1;
942       break;
943     }
944     if (dops[i+j].is_ujump)
945     {
946       // Don't go past an unconditonal jump
947       j++;
948       break;
949     }
950   }
951   for(;j>=0;j--)
952   {
953     if(dops[i+j].rs1) hsn[dops[i+j].rs1]=j;
954     if(dops[i+j].rs2) hsn[dops[i+j].rs2]=j;
955     if(dops[i+j].rt1) hsn[dops[i+j].rt1]=j;
956     if(dops[i+j].rt2) hsn[dops[i+j].rt2]=j;
957     if(dops[i+j].itype==STORE || dops[i+j].itype==STORELR) {
958       // Stores can allocate zero
959       hsn[dops[i+j].rs1]=j;
960       hsn[dops[i+j].rs2]=j;
961     }
962     if (ram_offset && (dops[i+j].is_load || dops[i+j].is_store))
963       hsn[ROREG] = j;
964     // On some architectures stores need invc_ptr
965     #if defined(HOST_IMM8)
966     if (dops[i+j].is_store)
967       hsn[INVCP] = j;
968     #endif
969     if(i+j>=0&&(dops[i+j].itype==UJUMP||dops[i+j].itype==CJUMP||dops[i+j].itype==SJUMP))
970     {
971       hsn[CCREG]=j;
972       b=j;
973     }
974   }
975   if(b>=0)
976   {
977     if(ba[i+b]>=start && ba[i+b]<(start+slen*4))
978     {
979       // Follow first branch
980       int t=(ba[i+b]-start)>>2;
981       j=7-b;if(t+j>=slen) j=slen-t-1;
982       for(;j>=0;j--)
983       {
984         if(dops[t+j].rs1) if(hsn[dops[t+j].rs1]>j+b+2) hsn[dops[t+j].rs1]=j+b+2;
985         if(dops[t+j].rs2) if(hsn[dops[t+j].rs2]>j+b+2) hsn[dops[t+j].rs2]=j+b+2;
986         //if(dops[t+j].rt1) if(hsn[dops[t+j].rt1]>j+b+2) hsn[dops[t+j].rt1]=j+b+2;
987         //if(dops[t+j].rt2) if(hsn[dops[t+j].rt2]>j+b+2) hsn[dops[t+j].rt2]=j+b+2;
988       }
989     }
990     // TODO: preferred register based on backward branch
991   }
992   // Delay slot should preferably not overwrite branch conditions or cycle count
993   if (i > 0 && dops[i-1].is_jump) {
994     if(dops[i-1].rs1) if(hsn[dops[i-1].rs1]>1) hsn[dops[i-1].rs1]=1;
995     if(dops[i-1].rs2) if(hsn[dops[i-1].rs2]>1) hsn[dops[i-1].rs2]=1;
996     hsn[CCREG]=1;
997     // ...or hash tables
998     hsn[RHASH]=1;
999     hsn[RHTBL]=1;
1000   }
1001   // Coprocessor load/store needs FTEMP, even if not declared
1002   if(dops[i].itype==C2LS) {
1003     hsn[FTEMP]=0;
1004   }
1005   // Load L/R also uses FTEMP as a temporary register
1006   if(dops[i].itype==LOADLR) {
1007     hsn[FTEMP]=0;
1008   }
1009   // Also SWL/SWR/SDL/SDR
1010   if(dops[i].opcode==0x2a||dops[i].opcode==0x2e||dops[i].opcode==0x2c||dops[i].opcode==0x2d) {
1011     hsn[FTEMP]=0;
1012   }
1013   // Don't remove the miniht registers
1014   if(dops[i].itype==UJUMP||dops[i].itype==RJUMP)
1015   {
1016     hsn[RHASH]=0;
1017     hsn[RHTBL]=0;
1018   }
1019 }
1020
1021 // We only want to allocate registers if we're going to use them again soon
1022 static int needed_again(int r, int i)
1023 {
1024   int j;
1025   int b=-1;
1026   int rn=10;
1027
1028   if (i > 0 && dops[i-1].is_ujump)
1029   {
1030     if(ba[i-1]<start || ba[i-1]>start+slen*4-4)
1031       return 0; // Don't need any registers if exiting the block
1032   }
1033   for(j=0;j<9;j++)
1034   {
1035     if(i+j>=slen) {
1036       j=slen-i-1;
1037       break;
1038     }
1039     if (dops[i+j].is_ujump)
1040     {
1041       // Don't go past an unconditonal jump
1042       j++;
1043       break;
1044     }
1045     if(dops[i+j].itype==SYSCALL||dops[i+j].itype==HLECALL||dops[i+j].itype==INTCALL||((source[i+j]&0xfc00003f)==0x0d))
1046     {
1047       break;
1048     }
1049   }
1050   for(;j>=1;j--)
1051   {
1052     if(dops[i+j].rs1==r) rn=j;
1053     if(dops[i+j].rs2==r) rn=j;
1054     if((unneeded_reg[i+j]>>r)&1) rn=10;
1055     if(i+j>=0&&(dops[i+j].itype==UJUMP||dops[i+j].itype==CJUMP||dops[i+j].itype==SJUMP))
1056     {
1057       b=j;
1058     }
1059   }
1060   if(rn<10) return 1;
1061   (void)b;
1062   return 0;
1063 }
1064
1065 // Try to match register allocations at the end of a loop with those
1066 // at the beginning
1067 static int loop_reg(int i, int r, int hr)
1068 {
1069   int j,k;
1070   for(j=0;j<9;j++)
1071   {
1072     if(i+j>=slen) {
1073       j=slen-i-1;
1074       break;
1075     }
1076     if (dops[i+j].is_ujump)
1077     {
1078       // Don't go past an unconditonal jump
1079       j++;
1080       break;
1081     }
1082   }
1083   k=0;
1084   if(i>0){
1085     if(dops[i-1].itype==UJUMP||dops[i-1].itype==CJUMP||dops[i-1].itype==SJUMP)
1086       k--;
1087   }
1088   for(;k<j;k++)
1089   {
1090     assert(r < 64);
1091     if((unneeded_reg[i+k]>>r)&1) return hr;
1092     if(i+k>=0&&(dops[i+k].itype==UJUMP||dops[i+k].itype==CJUMP||dops[i+k].itype==SJUMP))
1093     {
1094       if(ba[i+k]>=start && ba[i+k]<(start+i*4))
1095       {
1096         int t=(ba[i+k]-start)>>2;
1097         int reg=get_reg(regs[t].regmap_entry,r);
1098         if(reg>=0) return reg;
1099         //reg=get_reg(regs[t+1].regmap_entry,r);
1100         //if(reg>=0) return reg;
1101       }
1102     }
1103   }
1104   return hr;
1105 }
1106
1107
1108 // Allocate every register, preserving source/target regs
1109 static void alloc_all(struct regstat *cur,int i)
1110 {
1111   int hr;
1112
1113   for(hr=0;hr<HOST_REGS;hr++) {
1114     if(hr!=EXCLUDE_REG) {
1115       if((cur->regmap[hr]!=dops[i].rs1)&&(cur->regmap[hr]!=dops[i].rs2)&&
1116          (cur->regmap[hr]!=dops[i].rt1)&&(cur->regmap[hr]!=dops[i].rt2))
1117       {
1118         cur->regmap[hr]=-1;
1119         cur->dirty&=~(1<<hr);
1120       }
1121       // Don't need zeros
1122       if(cur->regmap[hr]==0)
1123       {
1124         cur->regmap[hr]=-1;
1125         cur->dirty&=~(1<<hr);
1126       }
1127     }
1128   }
1129 }
1130
1131 #ifndef NDEBUG
1132 static int host_tempreg_in_use;
1133
1134 static void host_tempreg_acquire(void)
1135 {
1136   assert(!host_tempreg_in_use);
1137   host_tempreg_in_use = 1;
1138 }
1139
1140 static void host_tempreg_release(void)
1141 {
1142   host_tempreg_in_use = 0;
1143 }
1144 #else
1145 static void host_tempreg_acquire(void) {}
1146 static void host_tempreg_release(void) {}
1147 #endif
1148
1149 #ifdef ASSEM_PRINT
1150 extern void gen_interupt();
1151 extern void do_insn_cmp();
1152 #define FUNCNAME(f) { f, " " #f }
1153 static const struct {
1154   void *addr;
1155   const char *name;
1156 } function_names[] = {
1157   FUNCNAME(cc_interrupt),
1158   FUNCNAME(gen_interupt),
1159   FUNCNAME(ndrc_get_addr_ht),
1160   FUNCNAME(jump_handler_read8),
1161   FUNCNAME(jump_handler_read16),
1162   FUNCNAME(jump_handler_read32),
1163   FUNCNAME(jump_handler_write8),
1164   FUNCNAME(jump_handler_write16),
1165   FUNCNAME(jump_handler_write32),
1166   FUNCNAME(ndrc_invalidate_addr),
1167   FUNCNAME(jump_to_new_pc),
1168   FUNCNAME(jump_break),
1169   FUNCNAME(jump_break_ds),
1170   FUNCNAME(jump_syscall),
1171   FUNCNAME(jump_syscall_ds),
1172   FUNCNAME(call_gteStall),
1173   FUNCNAME(new_dyna_leave),
1174   FUNCNAME(pcsx_mtc0),
1175   FUNCNAME(pcsx_mtc0_ds),
1176 #ifdef DRC_DBG
1177   FUNCNAME(do_insn_cmp),
1178 #endif
1179 };
1180
1181 static const char *func_name(const void *a)
1182 {
1183   int i;
1184   for (i = 0; i < sizeof(function_names)/sizeof(function_names[0]); i++)
1185     if (function_names[i].addr == a)
1186       return function_names[i].name;
1187   return "";
1188 }
1189 #else
1190 #define func_name(x) ""
1191 #endif
1192
1193 #ifdef __i386__
1194 #include "assem_x86.c"
1195 #endif
1196 #ifdef __x86_64__
1197 #include "assem_x64.c"
1198 #endif
1199 #ifdef __arm__
1200 #include "assem_arm.c"
1201 #endif
1202 #ifdef __aarch64__
1203 #include "assem_arm64.c"
1204 #endif
1205
1206 static void *get_trampoline(const void *f)
1207 {
1208   struct ndrc_tramp *tramp = NDRC_WRITE_OFFSET(&ndrc->tramp);
1209   size_t i;
1210
1211   for (i = 0; i < ARRAY_SIZE(tramp->f); i++) {
1212     if (tramp->f[i] == f || tramp->f[i] == NULL)
1213       break;
1214   }
1215   if (i == ARRAY_SIZE(tramp->f)) {
1216     SysPrintf("trampoline table is full, last func %p\n", f);
1217     abort();
1218   }
1219   if (tramp->f[i] == NULL) {
1220     start_tcache_write(&tramp->f[i], &tramp->f[i + 1]);
1221     tramp->f[i] = f;
1222     end_tcache_write(&tramp->f[i], &tramp->f[i + 1]);
1223 #ifdef HAVE_LIBNX
1224     // invalidate the RX mirror (unsure if necessary, but just in case...)
1225     armDCacheFlush(&ndrc->tramp.f[i], sizeof(ndrc->tramp.f[i]));
1226 #endif
1227   }
1228   return &ndrc->tramp.ops[i];
1229 }
1230
1231 static void emit_far_jump(const void *f)
1232 {
1233   if (can_jump_or_call(f)) {
1234     emit_jmp(f);
1235     return;
1236   }
1237
1238   f = get_trampoline(f);
1239   emit_jmp(f);
1240 }
1241
1242 static void emit_far_call(const void *f)
1243 {
1244   if (can_jump_or_call(f)) {
1245     emit_call(f);
1246     return;
1247   }
1248
1249   f = get_trampoline(f);
1250   emit_call(f);
1251 }
1252
1253 // Check if an address is already compiled
1254 // but don't return addresses which are about to expire from the cache
1255 static void *check_addr(u_int vaddr)
1256 {
1257   struct ht_entry *ht_bin = hash_table_get(vaddr);
1258   size_t i;
1259   for (i = 0; i < ARRAY_SIZE(ht_bin->vaddr); i++) {
1260     if (ht_bin->vaddr[i] == vaddr)
1261       if (doesnt_expire_soon(ht_bin->tcaddr[i]))
1262         return ht_bin->tcaddr[i];
1263   }
1264
1265   // refactor to get_addr_nocompile?
1266   u_int start_page = get_page_prev(vaddr);
1267   u_int page, end_page = get_page(vaddr);
1268
1269   stat_inc(stat_jump_in_lookups);
1270   for (page = start_page; page <= end_page; page++) {
1271     const struct block_info *block;
1272     for (block = blocks[page]; block != NULL; block = block->next) {
1273       if (vaddr < block->start)
1274         break;
1275       if (block->is_dirty || vaddr >= block->start + block->len)
1276         continue;
1277       if (!doesnt_expire_soon(ndrc->translation_cache + block->tc_offs))
1278         continue;
1279       for (i = 0; i < block->jump_in_cnt; i++)
1280         if (block->jump_in[i].vaddr == vaddr)
1281           break;
1282       if (i == block->jump_in_cnt)
1283         continue;
1284
1285       // Update existing entry with current address
1286       void *addr = block->jump_in[i].addr;
1287       if (ht_bin->vaddr[0] == vaddr) {
1288         ht_bin->tcaddr[0] = addr;
1289         return addr;
1290       }
1291       if (ht_bin->vaddr[1] == vaddr) {
1292         ht_bin->tcaddr[1] = addr;
1293         return addr;
1294       }
1295       // Insert into hash table with low priority.
1296       // Don't evict existing entries, as they are probably
1297       // addresses that are being accessed frequently.
1298       if (ht_bin->vaddr[0] == -1) {
1299         ht_bin->vaddr[0] = vaddr;
1300         ht_bin->tcaddr[0] = addr;
1301       }
1302       else if (ht_bin->vaddr[1] == -1) {
1303         ht_bin->vaddr[1] = vaddr;
1304         ht_bin->tcaddr[1] = addr;
1305       }
1306       return addr;
1307     }
1308   }
1309   return NULL;
1310 }
1311
1312 static void blocks_clear(struct block_info **head)
1313 {
1314   struct block_info *cur, *next;
1315
1316   if ((cur = *head)) {
1317     *head = NULL;
1318     while (cur) {
1319       next = cur->next;
1320       free(cur);
1321       cur = next;
1322     }
1323   }
1324 }
1325
1326 static int blocks_remove_matching_addrs(struct block_info **head,
1327   u_int base_offs, int shift)
1328 {
1329   struct block_info *next;
1330   int hit = 0;
1331   while (*head) {
1332     if ((((*head)->tc_offs ^ base_offs) >> shift) == 0) {
1333       inv_debug("EXP: rm block %08x (tc_offs %zx)\n", (*head)->start, (*head)->tc_offs);
1334       invalidate_block(*head);
1335       next = (*head)->next;
1336       free(*head);
1337       *head = next;
1338       stat_dec(stat_blocks);
1339       hit = 1;
1340     }
1341     else
1342     {
1343       head = &((*head)->next);
1344     }
1345   }
1346   return hit;
1347 }
1348
1349 // This is called when we write to a compiled block (see do_invstub)
1350 static void unlink_jumps_vaddr_range(u_int start, u_int end)
1351 {
1352   u_int page, start_page = get_page(start), end_page = get_page(end - 1);
1353   int i;
1354
1355   for (page = start_page; page <= end_page; page++) {
1356     struct jump_info *ji = jumps[page];
1357     if (ji == NULL)
1358       continue;
1359     for (i = 0; i < ji->count; ) {
1360       if (ji->e[i].target_vaddr < start || ji->e[i].target_vaddr >= end) {
1361         i++;
1362         continue;
1363       }
1364
1365       inv_debug("INV: rm link to %08x (tc_offs %zx)\n", ji->e[i].target_vaddr,
1366         (u_char *)ji->e[i].stub - ndrc->translation_cache);
1367       void *host_addr = find_extjump_insn(ji->e[i].stub);
1368       mark_clear_cache(host_addr);
1369       set_jump_target(host_addr, ji->e[i].stub); // point back to dyna_linker stub
1370
1371       stat_dec(stat_links);
1372       ji->count--;
1373       if (i < ji->count) {
1374         ji->e[i] = ji->e[ji->count];
1375         continue;
1376       }
1377       i++;
1378     }
1379   }
1380 }
1381
1382 static void unlink_jumps_tc_range(struct jump_info *ji, u_int base_offs, int shift)
1383 {
1384   int i;
1385   if (ji == NULL)
1386     return;
1387   for (i = 0; i < ji->count; ) {
1388     u_int tc_offs = (u_char *)ji->e[i].stub - ndrc->translation_cache;
1389     if (((tc_offs ^ base_offs) >> shift) != 0) {
1390       i++;
1391       continue;
1392     }
1393
1394     inv_debug("EXP: rm link to %08x (tc_offs %zx)\n", ji->e[i].target_vaddr, tc_offs);
1395     stat_dec(stat_links);
1396     ji->count--;
1397     if (i < ji->count) {
1398       ji->e[i] = ji->e[ji->count];
1399       continue;
1400     }
1401     i++;
1402   }
1403 }
1404
1405 static void invalidate_block(struct block_info *block)
1406 {
1407   u_int i;
1408
1409   block->is_dirty = 1;
1410   unlink_jumps_vaddr_range(block->start, block->start + block->len);
1411   for (i = 0; i < block->jump_in_cnt; i++)
1412     hash_table_remove(block->jump_in[i].vaddr);
1413 }
1414
1415 static int invalidate_range(u_int start, u_int end,
1416   u32 *inv_start_ret, u32 *inv_end_ret)
1417 {
1418   struct block_info *last_block = NULL;
1419   u_int start_page = get_page_prev(start);
1420   u_int end_page = get_page(end - 1);
1421   u_int start_m = pmmask(start);
1422   u_int end_m = pmmask(end - 1);
1423   u_int inv_start, inv_end;
1424   u_int blk_start_m, blk_end_m;
1425   u_int page;
1426   int hit = 0;
1427
1428   // additional area without code (to supplement invalid_code[]), [start, end)
1429   // avoids excessive ndrc_invalidate_addr() calls
1430   inv_start = start_m & ~0xfff;
1431   inv_end = end_m | 0xfff;
1432
1433   for (page = start_page; page <= end_page; page++) {
1434     struct block_info *block;
1435     for (block = blocks[page]; block != NULL; block = block->next) {
1436       if (block->is_dirty)
1437         continue;
1438       last_block = block;
1439       blk_end_m = pmmask(block->start + block->len);
1440       if (blk_end_m <= start_m) {
1441         inv_start = max(inv_start, blk_end_m);
1442         continue;
1443       }
1444       blk_start_m = pmmask(block->start);
1445       if (end_m <= blk_start_m) {
1446         inv_end = min(inv_end, blk_start_m - 1);
1447         continue;
1448       }
1449       if (!block->source) // "hack" block - leave it alone
1450         continue;
1451
1452       hit++;
1453       invalidate_block(block);
1454       stat_inc(stat_inv_hits);
1455     }
1456   }
1457
1458   if (!hit && last_block && last_block->source) {
1459     // could be some leftover unused block, uselessly trapping writes
1460     last_block->inv_near_misses++;
1461     if (last_block->inv_near_misses > 128) {
1462       invalidate_block(last_block);
1463       stat_inc(stat_inv_hits);
1464       hit++;
1465     }
1466   }
1467   if (hit) {
1468     do_clear_cache();
1469 #ifdef USE_MINI_HT
1470     memset(mini_ht, -1, sizeof(mini_ht));
1471 #endif
1472   }
1473
1474   if (inv_start <= (start_m & ~0xfff) && inv_end >= (start_m | 0xfff))
1475     // the whole page is empty now
1476     mark_invalid_code(start, 1, 1);
1477
1478   if (inv_start_ret) *inv_start_ret = inv_start | (start & 0xe0000000);
1479   if (inv_end_ret) *inv_end_ret = inv_end | (end & 0xe0000000);
1480   return hit;
1481 }
1482
1483 void new_dynarec_invalidate_range(unsigned int start, unsigned int end)
1484 {
1485   invalidate_range(start, end, NULL, NULL);
1486 }
1487
1488 void ndrc_invalidate_addr(u_int addr)
1489 {
1490   // this check is done by the caller
1491   //if (inv_code_start<=addr&&addr<=inv_code_end) { rhits++; return; }
1492   int ret = invalidate_range(addr, addr + 4, &inv_code_start, &inv_code_end);
1493   if (ret)
1494     inv_debug("INV ADDR: %08x hit %d blocks\n", addr, ret);
1495   else
1496     inv_debug("INV ADDR: %08x miss, inv %08x-%08x\n", addr, inv_code_start, inv_code_end);
1497   stat_inc(stat_inv_addr_calls);
1498 }
1499
1500 // This is called when loading a save state.
1501 // Anything could have changed, so invalidate everything.
1502 void new_dynarec_invalidate_all_pages(void)
1503 {
1504   struct block_info *block;
1505   u_int page;
1506   for (page = 0; page < ARRAY_SIZE(blocks); page++) {
1507     for (block = blocks[page]; block != NULL; block = block->next) {
1508       if (block->is_dirty)
1509         continue;
1510       if (!block->source) // hack block?
1511         continue;
1512       invalidate_block(block);
1513     }
1514   }
1515
1516   #ifdef USE_MINI_HT
1517   memset(mini_ht, -1, sizeof(mini_ht));
1518   #endif
1519   do_clear_cache();
1520 }
1521
1522 static void do_invstub(int n)
1523 {
1524   literal_pool(20);
1525   u_int reglist = stubs[n].a;
1526   set_jump_target(stubs[n].addr, out);
1527   save_regs(reglist);
1528   if (stubs[n].b != 0)
1529     emit_mov(stubs[n].b, 0);
1530   emit_readword(&inv_code_start, 1);
1531   emit_readword(&inv_code_end, 2);
1532   emit_cmp(0, 1);
1533   emit_cmpcs(2, 0);
1534   void *jaddr = out;
1535   emit_jc(0);
1536   emit_far_call(ndrc_invalidate_addr);
1537   set_jump_target(jaddr, out);
1538   restore_regs(reglist);
1539   emit_jmp(stubs[n].retaddr); // return address
1540 }
1541
1542 // Add an entry to jump_out after making a link
1543 // src should point to code by emit_extjump()
1544 void ndrc_add_jump_out(u_int vaddr, void *src)
1545 {
1546   inv_debug("ndrc_add_jump_out: %p -> %x\n", src, vaddr);
1547   u_int page = get_page(vaddr);
1548   struct jump_info *ji;
1549
1550   stat_inc(stat_links);
1551   check_extjump2(src);
1552   ji = jumps[page];
1553   if (ji == NULL) {
1554     ji = malloc(sizeof(*ji) + sizeof(ji->e[0]) * 16);
1555     ji->alloc = 16;
1556     ji->count = 0;
1557   }
1558   else if (ji->count >= ji->alloc) {
1559     ji->alloc += 16;
1560     ji = realloc(ji, sizeof(*ji) + sizeof(ji->e[0]) * ji->alloc);
1561   }
1562   jumps[page] = ji;
1563   ji->e[ji->count].target_vaddr = vaddr;
1564   ji->e[ji->count].stub = src;
1565   ji->count++;
1566 }
1567
1568 /* Register allocation */
1569
1570 // Note: registers are allocated clean (unmodified state)
1571 // if you intend to modify the register, you must call dirty_reg().
1572 static void alloc_reg(struct regstat *cur,int i,signed char reg)
1573 {
1574   int r,hr;
1575   int preferred_reg = PREFERRED_REG_FIRST
1576     + reg % (PREFERRED_REG_LAST - PREFERRED_REG_FIRST + 1);
1577   if (reg == CCREG) preferred_reg = HOST_CCREG;
1578   if (reg == PTEMP || reg == FTEMP) preferred_reg = 12;
1579   assert(PREFERRED_REG_FIRST != EXCLUDE_REG && EXCLUDE_REG != HOST_REGS);
1580   assert(reg >= 0);
1581
1582   // Don't allocate unused registers
1583   if((cur->u>>reg)&1) return;
1584
1585   // see if it's already allocated
1586   if (get_reg(cur->regmap, reg) >= 0)
1587     return;
1588
1589   // Keep the same mapping if the register was already allocated in a loop
1590   preferred_reg = loop_reg(i,reg,preferred_reg);
1591
1592   // Try to allocate the preferred register
1593   if(cur->regmap[preferred_reg]==-1) {
1594     cur->regmap[preferred_reg]=reg;
1595     cur->dirty&=~(1<<preferred_reg);
1596     cur->isconst&=~(1<<preferred_reg);
1597     return;
1598   }
1599   r=cur->regmap[preferred_reg];
1600   assert(r < 64);
1601   if((cur->u>>r)&1) {
1602     cur->regmap[preferred_reg]=reg;
1603     cur->dirty&=~(1<<preferred_reg);
1604     cur->isconst&=~(1<<preferred_reg);
1605     return;
1606   }
1607
1608   // Clear any unneeded registers
1609   // We try to keep the mapping consistent, if possible, because it
1610   // makes branches easier (especially loops).  So we try to allocate
1611   // first (see above) before removing old mappings.  If this is not
1612   // possible then go ahead and clear out the registers that are no
1613   // longer needed.
1614   for(hr=0;hr<HOST_REGS;hr++)
1615   {
1616     r=cur->regmap[hr];
1617     if(r>=0) {
1618       assert(r < 64);
1619       if((cur->u>>r)&1) {cur->regmap[hr]=-1;break;}
1620     }
1621   }
1622
1623   // Try to allocate any available register, but prefer
1624   // registers that have not been used recently.
1625   if (i > 0) {
1626     for (hr = PREFERRED_REG_FIRST; ; ) {
1627       if (cur->regmap[hr] < 0) {
1628         int oldreg = regs[i-1].regmap[hr];
1629         if (oldreg < 0 || (oldreg != dops[i-1].rs1 && oldreg != dops[i-1].rs2
1630              && oldreg != dops[i-1].rt1 && oldreg != dops[i-1].rt2))
1631         {
1632           cur->regmap[hr]=reg;
1633           cur->dirty&=~(1<<hr);
1634           cur->isconst&=~(1<<hr);
1635           return;
1636         }
1637       }
1638       hr++;
1639       if (hr == EXCLUDE_REG)
1640         hr++;
1641       if (hr == HOST_REGS)
1642         hr = 0;
1643       if (hr == PREFERRED_REG_FIRST)
1644         break;
1645     }
1646   }
1647
1648   // Try to allocate any available register
1649   for (hr = PREFERRED_REG_FIRST; ; ) {
1650     if (cur->regmap[hr] < 0) {
1651       cur->regmap[hr]=reg;
1652       cur->dirty&=~(1<<hr);
1653       cur->isconst&=~(1<<hr);
1654       return;
1655     }
1656     hr++;
1657     if (hr == EXCLUDE_REG)
1658       hr++;
1659     if (hr == HOST_REGS)
1660       hr = 0;
1661     if (hr == PREFERRED_REG_FIRST)
1662       break;
1663   }
1664
1665   // Ok, now we have to evict someone
1666   // Pick a register we hopefully won't need soon
1667   u_char hsn[MAXREG+1];
1668   memset(hsn,10,sizeof(hsn));
1669   int j;
1670   lsn(hsn,i,&preferred_reg);
1671   //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]);
1672   //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]);
1673   if(i>0) {
1674     // Don't evict the cycle count at entry points, otherwise the entry
1675     // stub will have to write it.
1676     if(dops[i].bt&&hsn[CCREG]>2) hsn[CCREG]=2;
1677     if (i>1 && hsn[CCREG] > 2 && dops[i-2].is_jump) hsn[CCREG]=2;
1678     for(j=10;j>=3;j--)
1679     {
1680       // Alloc preferred register if available
1681       if(hsn[r=cur->regmap[preferred_reg]&63]==j) {
1682         for(hr=0;hr<HOST_REGS;hr++) {
1683           // Evict both parts of a 64-bit register
1684           if(cur->regmap[hr]==r) {
1685             cur->regmap[hr]=-1;
1686             cur->dirty&=~(1<<hr);
1687             cur->isconst&=~(1<<hr);
1688           }
1689         }
1690         cur->regmap[preferred_reg]=reg;
1691         return;
1692       }
1693       for(r=1;r<=MAXREG;r++)
1694       {
1695         if(hsn[r]==j&&r!=dops[i-1].rs1&&r!=dops[i-1].rs2&&r!=dops[i-1].rt1&&r!=dops[i-1].rt2) {
1696           for(hr=0;hr<HOST_REGS;hr++) {
1697             if(hr!=HOST_CCREG||j<hsn[CCREG]) {
1698               if(cur->regmap[hr]==r) {
1699                 cur->regmap[hr]=reg;
1700                 cur->dirty&=~(1<<hr);
1701                 cur->isconst&=~(1<<hr);
1702                 return;
1703               }
1704             }
1705           }
1706         }
1707       }
1708     }
1709   }
1710   for(j=10;j>=0;j--)
1711   {
1712     for(r=1;r<=MAXREG;r++)
1713     {
1714       if(hsn[r]==j) {
1715         for(hr=0;hr<HOST_REGS;hr++) {
1716           if(cur->regmap[hr]==r) {
1717             cur->regmap[hr]=reg;
1718             cur->dirty&=~(1<<hr);
1719             cur->isconst&=~(1<<hr);
1720             return;
1721           }
1722         }
1723       }
1724     }
1725   }
1726   SysPrintf("This shouldn't happen (alloc_reg)");abort();
1727 }
1728
1729 // Allocate a temporary register.  This is done without regard to
1730 // dirty status or whether the register we request is on the unneeded list
1731 // Note: This will only allocate one register, even if called multiple times
1732 static void alloc_reg_temp(struct regstat *cur,int i,signed char reg)
1733 {
1734   int r,hr;
1735   int preferred_reg = -1;
1736
1737   // see if it's already allocated
1738   for(hr=0;hr<HOST_REGS;hr++)
1739   {
1740     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==reg) return;
1741   }
1742
1743   // Try to allocate any available register
1744   for(hr=HOST_REGS-1;hr>=0;hr--) {
1745     if(hr!=EXCLUDE_REG&&cur->regmap[hr]==-1) {
1746       cur->regmap[hr]=reg;
1747       cur->dirty&=~(1<<hr);
1748       cur->isconst&=~(1<<hr);
1749       return;
1750     }
1751   }
1752
1753   // Find an unneeded register
1754   for(hr=HOST_REGS-1;hr>=0;hr--)
1755   {
1756     r=cur->regmap[hr];
1757     if(r>=0) {
1758       assert(r < 64);
1759       if((cur->u>>r)&1) {
1760         if(i==0||((unneeded_reg[i-1]>>r)&1)) {
1761           cur->regmap[hr]=reg;
1762           cur->dirty&=~(1<<hr);
1763           cur->isconst&=~(1<<hr);
1764           return;
1765         }
1766       }
1767     }
1768   }
1769
1770   // Ok, now we have to evict someone
1771   // Pick a register we hopefully won't need soon
1772   // TODO: we might want to follow unconditional jumps here
1773   // TODO: get rid of dupe code and make this into a function
1774   u_char hsn[MAXREG+1];
1775   memset(hsn,10,sizeof(hsn));
1776   int j;
1777   lsn(hsn,i,&preferred_reg);
1778   //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]);
1779   if(i>0) {
1780     // Don't evict the cycle count at entry points, otherwise the entry
1781     // stub will have to write it.
1782     if(dops[i].bt&&hsn[CCREG]>2) hsn[CCREG]=2;
1783     if (i>1 && hsn[CCREG] > 2 && dops[i-2].is_jump) hsn[CCREG]=2;
1784     for(j=10;j>=3;j--)
1785     {
1786       for(r=1;r<=MAXREG;r++)
1787       {
1788         if(hsn[r]==j&&r!=dops[i-1].rs1&&r!=dops[i-1].rs2&&r!=dops[i-1].rt1&&r!=dops[i-1].rt2) {
1789           for(hr=0;hr<HOST_REGS;hr++) {
1790             if(hr!=HOST_CCREG||hsn[CCREG]>2) {
1791               if(cur->regmap[hr]==r) {
1792                 cur->regmap[hr]=reg;
1793                 cur->dirty&=~(1<<hr);
1794                 cur->isconst&=~(1<<hr);
1795                 return;
1796               }
1797             }
1798           }
1799         }
1800       }
1801     }
1802   }
1803   for(j=10;j>=0;j--)
1804   {
1805     for(r=1;r<=MAXREG;r++)
1806     {
1807       if(hsn[r]==j) {
1808         for(hr=0;hr<HOST_REGS;hr++) {
1809           if(cur->regmap[hr]==r) {
1810             cur->regmap[hr]=reg;
1811             cur->dirty&=~(1<<hr);
1812             cur->isconst&=~(1<<hr);
1813             return;
1814           }
1815         }
1816       }
1817     }
1818   }
1819   SysPrintf("This shouldn't happen");abort();
1820 }
1821
1822 static void mov_alloc(struct regstat *current,int i)
1823 {
1824   if (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG) {
1825     alloc_cc(current,i); // for stalls
1826     dirty_reg(current,CCREG);
1827   }
1828
1829   // Note: Don't need to actually alloc the source registers
1830   //alloc_reg(current,i,dops[i].rs1);
1831   alloc_reg(current,i,dops[i].rt1);
1832
1833   clear_const(current,dops[i].rs1);
1834   clear_const(current,dops[i].rt1);
1835   dirty_reg(current,dops[i].rt1);
1836 }
1837
1838 static void shiftimm_alloc(struct regstat *current,int i)
1839 {
1840   if(dops[i].opcode2<=0x3) // SLL/SRL/SRA
1841   {
1842     if(dops[i].rt1) {
1843       if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1844       else dops[i].use_lt1=!!dops[i].rs1;
1845       alloc_reg(current,i,dops[i].rt1);
1846       dirty_reg(current,dops[i].rt1);
1847       if(is_const(current,dops[i].rs1)) {
1848         int v=get_const(current,dops[i].rs1);
1849         if(dops[i].opcode2==0x00) set_const(current,dops[i].rt1,v<<imm[i]);
1850         if(dops[i].opcode2==0x02) set_const(current,dops[i].rt1,(u_int)v>>imm[i]);
1851         if(dops[i].opcode2==0x03) set_const(current,dops[i].rt1,v>>imm[i]);
1852       }
1853       else clear_const(current,dops[i].rt1);
1854     }
1855   }
1856   else
1857   {
1858     clear_const(current,dops[i].rs1);
1859     clear_const(current,dops[i].rt1);
1860   }
1861
1862   if(dops[i].opcode2>=0x38&&dops[i].opcode2<=0x3b) // DSLL/DSRL/DSRA
1863   {
1864     assert(0);
1865   }
1866   if(dops[i].opcode2==0x3c) // DSLL32
1867   {
1868     assert(0);
1869   }
1870   if(dops[i].opcode2==0x3e) // DSRL32
1871   {
1872     assert(0);
1873   }
1874   if(dops[i].opcode2==0x3f) // DSRA32
1875   {
1876     assert(0);
1877   }
1878 }
1879
1880 static void shift_alloc(struct regstat *current,int i)
1881 {
1882   if(dops[i].rt1) {
1883     if(dops[i].opcode2<=0x07) // SLLV/SRLV/SRAV
1884     {
1885       if(dops[i].rs1) alloc_reg(current,i,dops[i].rs1);
1886       if(dops[i].rs2) alloc_reg(current,i,dops[i].rs2);
1887       alloc_reg(current,i,dops[i].rt1);
1888       if(dops[i].rt1==dops[i].rs2) {
1889         alloc_reg_temp(current,i,-1);
1890         minimum_free_regs[i]=1;
1891       }
1892     } else { // DSLLV/DSRLV/DSRAV
1893       assert(0);
1894     }
1895     clear_const(current,dops[i].rs1);
1896     clear_const(current,dops[i].rs2);
1897     clear_const(current,dops[i].rt1);
1898     dirty_reg(current,dops[i].rt1);
1899   }
1900 }
1901
1902 static void alu_alloc(struct regstat *current,int i)
1903 {
1904   if(dops[i].opcode2>=0x20&&dops[i].opcode2<=0x23) { // ADD/ADDU/SUB/SUBU
1905     if(dops[i].rt1) {
1906       if(dops[i].rs1&&dops[i].rs2) {
1907         alloc_reg(current,i,dops[i].rs1);
1908         alloc_reg(current,i,dops[i].rs2);
1909       }
1910       else {
1911         if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1912         if(dops[i].rs2&&needed_again(dops[i].rs2,i)) alloc_reg(current,i,dops[i].rs2);
1913       }
1914       alloc_reg(current,i,dops[i].rt1);
1915     }
1916   }
1917   if(dops[i].opcode2==0x2a||dops[i].opcode2==0x2b) { // SLT/SLTU
1918     if(dops[i].rt1) {
1919       alloc_reg(current,i,dops[i].rs1);
1920       alloc_reg(current,i,dops[i].rs2);
1921       alloc_reg(current,i,dops[i].rt1);
1922     }
1923   }
1924   if(dops[i].opcode2>=0x24&&dops[i].opcode2<=0x27) { // AND/OR/XOR/NOR
1925     if(dops[i].rt1) {
1926       if(dops[i].rs1&&dops[i].rs2) {
1927         alloc_reg(current,i,dops[i].rs1);
1928         alloc_reg(current,i,dops[i].rs2);
1929       }
1930       else
1931       {
1932         if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1933         if(dops[i].rs2&&needed_again(dops[i].rs2,i)) alloc_reg(current,i,dops[i].rs2);
1934       }
1935       alloc_reg(current,i,dops[i].rt1);
1936     }
1937   }
1938   if(dops[i].opcode2>=0x2c&&dops[i].opcode2<=0x2f) { // DADD/DADDU/DSUB/DSUBU
1939     assert(0);
1940   }
1941   clear_const(current,dops[i].rs1);
1942   clear_const(current,dops[i].rs2);
1943   clear_const(current,dops[i].rt1);
1944   dirty_reg(current,dops[i].rt1);
1945 }
1946
1947 static void imm16_alloc(struct regstat *current,int i)
1948 {
1949   if(dops[i].rs1&&needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
1950   else dops[i].use_lt1=!!dops[i].rs1;
1951   if(dops[i].rt1) alloc_reg(current,i,dops[i].rt1);
1952   if(dops[i].opcode==0x18||dops[i].opcode==0x19) { // DADDI/DADDIU
1953     assert(0);
1954   }
1955   else if(dops[i].opcode==0x0a||dops[i].opcode==0x0b) { // SLTI/SLTIU
1956     clear_const(current,dops[i].rs1);
1957     clear_const(current,dops[i].rt1);
1958   }
1959   else if(dops[i].opcode>=0x0c&&dops[i].opcode<=0x0e) { // ANDI/ORI/XORI
1960     if(is_const(current,dops[i].rs1)) {
1961       int v=get_const(current,dops[i].rs1);
1962       if(dops[i].opcode==0x0c) set_const(current,dops[i].rt1,v&imm[i]);
1963       if(dops[i].opcode==0x0d) set_const(current,dops[i].rt1,v|imm[i]);
1964       if(dops[i].opcode==0x0e) set_const(current,dops[i].rt1,v^imm[i]);
1965     }
1966     else clear_const(current,dops[i].rt1);
1967   }
1968   else if(dops[i].opcode==0x08||dops[i].opcode==0x09) { // ADDI/ADDIU
1969     if(is_const(current,dops[i].rs1)) {
1970       int v=get_const(current,dops[i].rs1);
1971       set_const(current,dops[i].rt1,v+imm[i]);
1972     }
1973     else clear_const(current,dops[i].rt1);
1974   }
1975   else {
1976     set_const(current,dops[i].rt1,imm[i]<<16); // LUI
1977   }
1978   dirty_reg(current,dops[i].rt1);
1979 }
1980
1981 static void load_alloc(struct regstat *current,int i)
1982 {
1983   clear_const(current,dops[i].rt1);
1984   //if(dops[i].rs1!=dops[i].rt1&&needed_again(dops[i].rs1,i)) clear_const(current,dops[i].rs1); // Does this help or hurt?
1985   if(!dops[i].rs1) current->u&=~1LL; // Allow allocating r0 if it's the source register
1986   if (needed_again(dops[i].rs1, i))
1987     alloc_reg(current, i, dops[i].rs1);
1988   if (ram_offset)
1989     alloc_reg(current, i, ROREG);
1990   if(dops[i].rt1&&!((current->u>>dops[i].rt1)&1)) {
1991     alloc_reg(current,i,dops[i].rt1);
1992     assert(get_reg(current->regmap,dops[i].rt1)>=0);
1993     if(dops[i].opcode==0x27||dops[i].opcode==0x37) // LWU/LD
1994     {
1995       assert(0);
1996     }
1997     else if(dops[i].opcode==0x1A||dops[i].opcode==0x1B) // LDL/LDR
1998     {
1999       assert(0);
2000     }
2001     dirty_reg(current,dops[i].rt1);
2002     // LWL/LWR need a temporary register for the old value
2003     if(dops[i].opcode==0x22||dops[i].opcode==0x26)
2004     {
2005       alloc_reg(current,i,FTEMP);
2006       alloc_reg_temp(current,i,-1);
2007       minimum_free_regs[i]=1;
2008     }
2009   }
2010   else
2011   {
2012     // Load to r0 or unneeded register (dummy load)
2013     // but we still need a register to calculate the address
2014     if(dops[i].opcode==0x22||dops[i].opcode==0x26)
2015     {
2016       alloc_reg(current,i,FTEMP); // LWL/LWR need another temporary
2017     }
2018     alloc_reg_temp(current,i,-1);
2019     minimum_free_regs[i]=1;
2020     if(dops[i].opcode==0x1A||dops[i].opcode==0x1B) // LDL/LDR
2021     {
2022       assert(0);
2023     }
2024   }
2025 }
2026
2027 static void store_alloc(struct regstat *current,int i)
2028 {
2029   clear_const(current,dops[i].rs2);
2030   if(!(dops[i].rs2)) current->u&=~1LL; // Allow allocating r0 if necessary
2031   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
2032   alloc_reg(current,i,dops[i].rs2);
2033   if(dops[i].opcode==0x2c||dops[i].opcode==0x2d||dops[i].opcode==0x3f) { // 64-bit SDL/SDR/SD
2034     assert(0);
2035   }
2036   if (ram_offset)
2037     alloc_reg(current, i, ROREG);
2038   #if defined(HOST_IMM8)
2039   // On CPUs without 32-bit immediates we need a pointer to invalid_code
2040   alloc_reg(current, i, INVCP);
2041   #endif
2042   if(dops[i].opcode==0x2a||dops[i].opcode==0x2e||dops[i].opcode==0x2c||dops[i].opcode==0x2d) { // SWL/SWL/SDL/SDR
2043     alloc_reg(current,i,FTEMP);
2044   }
2045   // We need a temporary register for address generation
2046   alloc_reg_temp(current,i,-1);
2047   minimum_free_regs[i]=1;
2048 }
2049
2050 static void c1ls_alloc(struct regstat *current,int i)
2051 {
2052   clear_const(current,dops[i].rt1);
2053   alloc_reg(current,i,CSREG); // Status
2054 }
2055
2056 static void c2ls_alloc(struct regstat *current,int i)
2057 {
2058   clear_const(current,dops[i].rt1);
2059   if(needed_again(dops[i].rs1,i)) alloc_reg(current,i,dops[i].rs1);
2060   alloc_reg(current,i,FTEMP);
2061   if (ram_offset)
2062     alloc_reg(current, i, ROREG);
2063   #if defined(HOST_IMM8)
2064   // On CPUs without 32-bit immediates we need a pointer to invalid_code
2065   if (dops[i].opcode == 0x3a) // SWC2
2066     alloc_reg(current,i,INVCP);
2067   #endif
2068   // We need a temporary register for address generation
2069   alloc_reg_temp(current,i,-1);
2070   minimum_free_regs[i]=1;
2071 }
2072
2073 #ifndef multdiv_alloc
2074 static void multdiv_alloc(struct regstat *current,int i)
2075 {
2076   //  case 0x18: MULT
2077   //  case 0x19: MULTU
2078   //  case 0x1A: DIV
2079   //  case 0x1B: DIVU
2080   //  case 0x1C: DMULT
2081   //  case 0x1D: DMULTU
2082   //  case 0x1E: DDIV
2083   //  case 0x1F: DDIVU
2084   clear_const(current,dops[i].rs1);
2085   clear_const(current,dops[i].rs2);
2086   alloc_cc(current,i); // for stalls
2087   if(dops[i].rs1&&dops[i].rs2)
2088   {
2089     if((dops[i].opcode2&4)==0) // 32-bit
2090     {
2091       current->u&=~(1LL<<HIREG);
2092       current->u&=~(1LL<<LOREG);
2093       alloc_reg(current,i,HIREG);
2094       alloc_reg(current,i,LOREG);
2095       alloc_reg(current,i,dops[i].rs1);
2096       alloc_reg(current,i,dops[i].rs2);
2097       dirty_reg(current,HIREG);
2098       dirty_reg(current,LOREG);
2099     }
2100     else // 64-bit
2101     {
2102       assert(0);
2103     }
2104   }
2105   else
2106   {
2107     // Multiply by zero is zero.
2108     // MIPS does not have a divide by zero exception.
2109     // The result is undefined, we return zero.
2110     alloc_reg(current,i,HIREG);
2111     alloc_reg(current,i,LOREG);
2112     dirty_reg(current,HIREG);
2113     dirty_reg(current,LOREG);
2114   }
2115 }
2116 #endif
2117
2118 static void cop0_alloc(struct regstat *current,int i)
2119 {
2120   if(dops[i].opcode2==0) // MFC0
2121   {
2122     if(dops[i].rt1) {
2123       clear_const(current,dops[i].rt1);
2124       alloc_all(current,i);
2125       alloc_reg(current,i,dops[i].rt1);
2126       dirty_reg(current,dops[i].rt1);
2127     }
2128   }
2129   else if(dops[i].opcode2==4) // MTC0
2130   {
2131     if(dops[i].rs1){
2132       clear_const(current,dops[i].rs1);
2133       alloc_reg(current,i,dops[i].rs1);
2134       alloc_all(current,i);
2135     }
2136     else {
2137       alloc_all(current,i); // FIXME: Keep r0
2138       current->u&=~1LL;
2139       alloc_reg(current,i,0);
2140     }
2141   }
2142   else
2143   {
2144     // RFE
2145     assert(dops[i].opcode2==0x10);
2146     alloc_all(current,i);
2147   }
2148   minimum_free_regs[i]=HOST_REGS;
2149 }
2150
2151 static void cop2_alloc(struct regstat *current,int i)
2152 {
2153   if (dops[i].opcode2 < 3) // MFC2/CFC2
2154   {
2155     alloc_cc(current,i); // for stalls
2156     dirty_reg(current,CCREG);
2157     if(dops[i].rt1){
2158       clear_const(current,dops[i].rt1);
2159       alloc_reg(current,i,dops[i].rt1);
2160       dirty_reg(current,dops[i].rt1);
2161     }
2162   }
2163   else if (dops[i].opcode2 > 3) // MTC2/CTC2
2164   {
2165     if(dops[i].rs1){
2166       clear_const(current,dops[i].rs1);
2167       alloc_reg(current,i,dops[i].rs1);
2168     }
2169     else {
2170       current->u&=~1LL;
2171       alloc_reg(current,i,0);
2172     }
2173   }
2174   alloc_reg_temp(current,i,-1);
2175   minimum_free_regs[i]=1;
2176 }
2177
2178 static void c2op_alloc(struct regstat *current,int i)
2179 {
2180   alloc_cc(current,i); // for stalls
2181   dirty_reg(current,CCREG);
2182   alloc_reg_temp(current,i,-1);
2183 }
2184
2185 static void syscall_alloc(struct regstat *current,int i)
2186 {
2187   alloc_cc(current,i);
2188   dirty_reg(current,CCREG);
2189   alloc_all(current,i);
2190   minimum_free_regs[i]=HOST_REGS;
2191   current->isconst=0;
2192 }
2193
2194 static void delayslot_alloc(struct regstat *current,int i)
2195 {
2196   switch(dops[i].itype) {
2197     case UJUMP:
2198     case CJUMP:
2199     case SJUMP:
2200     case RJUMP:
2201     case SYSCALL:
2202     case HLECALL:
2203     case IMM16:
2204       imm16_alloc(current,i);
2205       break;
2206     case LOAD:
2207     case LOADLR:
2208       load_alloc(current,i);
2209       break;
2210     case STORE:
2211     case STORELR:
2212       store_alloc(current,i);
2213       break;
2214     case ALU:
2215       alu_alloc(current,i);
2216       break;
2217     case SHIFT:
2218       shift_alloc(current,i);
2219       break;
2220     case MULTDIV:
2221       multdiv_alloc(current,i);
2222       break;
2223     case SHIFTIMM:
2224       shiftimm_alloc(current,i);
2225       break;
2226     case MOV:
2227       mov_alloc(current,i);
2228       break;
2229     case COP0:
2230       cop0_alloc(current,i);
2231       break;
2232     case COP1:
2233       break;
2234     case COP2:
2235       cop2_alloc(current,i);
2236       break;
2237     case C1LS:
2238       c1ls_alloc(current,i);
2239       break;
2240     case C2LS:
2241       c2ls_alloc(current,i);
2242       break;
2243     case C2OP:
2244       c2op_alloc(current,i);
2245       break;
2246   }
2247 }
2248
2249 static void add_stub(enum stub_type type, void *addr, void *retaddr,
2250   u_int a, uintptr_t b, uintptr_t c, u_int d, u_int e)
2251 {
2252   assert(stubcount < ARRAY_SIZE(stubs));
2253   stubs[stubcount].type = type;
2254   stubs[stubcount].addr = addr;
2255   stubs[stubcount].retaddr = retaddr;
2256   stubs[stubcount].a = a;
2257   stubs[stubcount].b = b;
2258   stubs[stubcount].c = c;
2259   stubs[stubcount].d = d;
2260   stubs[stubcount].e = e;
2261   stubcount++;
2262 }
2263
2264 static void add_stub_r(enum stub_type type, void *addr, void *retaddr,
2265   int i, int addr_reg, const struct regstat *i_regs, int ccadj, u_int reglist)
2266 {
2267   add_stub(type, addr, retaddr, i, addr_reg, (uintptr_t)i_regs, ccadj, reglist);
2268 }
2269
2270 // Write out a single register
2271 static void wb_register(signed char r, const signed char regmap[], uint64_t dirty)
2272 {
2273   int hr;
2274   for(hr=0;hr<HOST_REGS;hr++) {
2275     if(hr!=EXCLUDE_REG) {
2276       if(regmap[hr]==r) {
2277         if((dirty>>hr)&1) {
2278           assert(regmap[hr]<64);
2279           emit_storereg(r,hr);
2280         }
2281       }
2282     }
2283   }
2284 }
2285
2286 static void wb_valid(signed char pre[],signed char entry[],u_int dirty_pre,u_int dirty,uint64_t u)
2287 {
2288   //if(dirty_pre==dirty) return;
2289   int hr, r;
2290   for (hr = 0; hr < HOST_REGS; hr++) {
2291     r = pre[hr];
2292     if (r < 1 || r > 33 || ((u >> r) & 1))
2293       continue;
2294     if (((dirty_pre & ~dirty) >> hr) & 1)
2295       emit_storereg(r, hr);
2296   }
2297 }
2298
2299 // trashes r2
2300 static void pass_args(int a0, int a1)
2301 {
2302   if(a0==1&&a1==0) {
2303     // must swap
2304     emit_mov(a0,2); emit_mov(a1,1); emit_mov(2,0);
2305   }
2306   else if(a0!=0&&a1==0) {
2307     emit_mov(a1,1);
2308     if (a0>=0) emit_mov(a0,0);
2309   }
2310   else {
2311     if(a0>=0&&a0!=0) emit_mov(a0,0);
2312     if(a1>=0&&a1!=1) emit_mov(a1,1);
2313   }
2314 }
2315
2316 static void alu_assemble(int i, const struct regstat *i_regs)
2317 {
2318   if(dops[i].opcode2>=0x20&&dops[i].opcode2<=0x23) { // ADD/ADDU/SUB/SUBU
2319     if(dops[i].rt1) {
2320       signed char s1,s2,t;
2321       t=get_reg(i_regs->regmap,dops[i].rt1);
2322       if(t>=0) {
2323         s1=get_reg(i_regs->regmap,dops[i].rs1);
2324         s2=get_reg(i_regs->regmap,dops[i].rs2);
2325         if(dops[i].rs1&&dops[i].rs2) {
2326           assert(s1>=0);
2327           assert(s2>=0);
2328           if(dops[i].opcode2&2) emit_sub(s1,s2,t);
2329           else emit_add(s1,s2,t);
2330         }
2331         else if(dops[i].rs1) {
2332           if(s1>=0) emit_mov(s1,t);
2333           else emit_loadreg(dops[i].rs1,t);
2334         }
2335         else if(dops[i].rs2) {
2336           if(s2>=0) {
2337             if(dops[i].opcode2&2) emit_neg(s2,t);
2338             else emit_mov(s2,t);
2339           }
2340           else {
2341             emit_loadreg(dops[i].rs2,t);
2342             if(dops[i].opcode2&2) emit_neg(t,t);
2343           }
2344         }
2345         else emit_zeroreg(t);
2346       }
2347     }
2348   }
2349   if(dops[i].opcode2>=0x2c&&dops[i].opcode2<=0x2f) { // DADD/DADDU/DSUB/DSUBU
2350     assert(0);
2351   }
2352   if(dops[i].opcode2==0x2a||dops[i].opcode2==0x2b) { // SLT/SLTU
2353     if(dops[i].rt1) {
2354       signed char s1l,s2l,t;
2355       {
2356         t=get_reg(i_regs->regmap,dops[i].rt1);
2357         //assert(t>=0);
2358         if(t>=0) {
2359           s1l=get_reg(i_regs->regmap,dops[i].rs1);
2360           s2l=get_reg(i_regs->regmap,dops[i].rs2);
2361           if(dops[i].rs2==0) // rx<r0
2362           {
2363             if(dops[i].opcode2==0x2a&&dops[i].rs1!=0) { // SLT
2364               assert(s1l>=0);
2365               emit_shrimm(s1l,31,t);
2366             }
2367             else // SLTU (unsigned can not be less than zero, 0<0)
2368               emit_zeroreg(t);
2369           }
2370           else if(dops[i].rs1==0) // r0<rx
2371           {
2372             assert(s2l>=0);
2373             if(dops[i].opcode2==0x2a) // SLT
2374               emit_set_gz32(s2l,t);
2375             else // SLTU (set if not zero)
2376               emit_set_nz32(s2l,t);
2377           }
2378           else{
2379             assert(s1l>=0);assert(s2l>=0);
2380             if(dops[i].opcode2==0x2a) // SLT
2381               emit_set_if_less32(s1l,s2l,t);
2382             else // SLTU
2383               emit_set_if_carry32(s1l,s2l,t);
2384           }
2385         }
2386       }
2387     }
2388   }
2389   if(dops[i].opcode2>=0x24&&dops[i].opcode2<=0x27) { // AND/OR/XOR/NOR
2390     if(dops[i].rt1) {
2391       signed char s1l,s2l,tl;
2392       tl=get_reg(i_regs->regmap,dops[i].rt1);
2393       {
2394         if(tl>=0) {
2395           s1l=get_reg(i_regs->regmap,dops[i].rs1);
2396           s2l=get_reg(i_regs->regmap,dops[i].rs2);
2397           if(dops[i].rs1&&dops[i].rs2) {
2398             assert(s1l>=0);
2399             assert(s2l>=0);
2400             if(dops[i].opcode2==0x24) { // AND
2401               emit_and(s1l,s2l,tl);
2402             } else
2403             if(dops[i].opcode2==0x25) { // OR
2404               emit_or(s1l,s2l,tl);
2405             } else
2406             if(dops[i].opcode2==0x26) { // XOR
2407               emit_xor(s1l,s2l,tl);
2408             } else
2409             if(dops[i].opcode2==0x27) { // NOR
2410               emit_or(s1l,s2l,tl);
2411               emit_not(tl,tl);
2412             }
2413           }
2414           else
2415           {
2416             if(dops[i].opcode2==0x24) { // AND
2417               emit_zeroreg(tl);
2418             } else
2419             if(dops[i].opcode2==0x25||dops[i].opcode2==0x26) { // OR/XOR
2420               if(dops[i].rs1){
2421                 if(s1l>=0) emit_mov(s1l,tl);
2422                 else emit_loadreg(dops[i].rs1,tl); // CHECK: regmap_entry?
2423               }
2424               else
2425               if(dops[i].rs2){
2426                 if(s2l>=0) emit_mov(s2l,tl);
2427                 else emit_loadreg(dops[i].rs2,tl); // CHECK: regmap_entry?
2428               }
2429               else emit_zeroreg(tl);
2430             } else
2431             if(dops[i].opcode2==0x27) { // NOR
2432               if(dops[i].rs1){
2433                 if(s1l>=0) emit_not(s1l,tl);
2434                 else {
2435                   emit_loadreg(dops[i].rs1,tl);
2436                   emit_not(tl,tl);
2437                 }
2438               }
2439               else
2440               if(dops[i].rs2){
2441                 if(s2l>=0) emit_not(s2l,tl);
2442                 else {
2443                   emit_loadreg(dops[i].rs2,tl);
2444                   emit_not(tl,tl);
2445                 }
2446               }
2447               else emit_movimm(-1,tl);
2448             }
2449           }
2450         }
2451       }
2452     }
2453   }
2454 }
2455
2456 static void imm16_assemble(int i, const struct regstat *i_regs)
2457 {
2458   if (dops[i].opcode==0x0f) { // LUI
2459     if(dops[i].rt1) {
2460       signed char t;
2461       t=get_reg(i_regs->regmap,dops[i].rt1);
2462       //assert(t>=0);
2463       if(t>=0) {
2464         if(!((i_regs->isconst>>t)&1))
2465           emit_movimm(imm[i]<<16,t);
2466       }
2467     }
2468   }
2469   if(dops[i].opcode==0x08||dops[i].opcode==0x09) { // ADDI/ADDIU
2470     if(dops[i].rt1) {
2471       signed char s,t;
2472       t=get_reg(i_regs->regmap,dops[i].rt1);
2473       s=get_reg(i_regs->regmap,dops[i].rs1);
2474       if(dops[i].rs1) {
2475         //assert(t>=0);
2476         //assert(s>=0);
2477         if(t>=0) {
2478           if(!((i_regs->isconst>>t)&1)) {
2479             if(s<0) {
2480               if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2481               emit_addimm(t,imm[i],t);
2482             }else{
2483               if(!((i_regs->wasconst>>s)&1))
2484                 emit_addimm(s,imm[i],t);
2485               else
2486                 emit_movimm(constmap[i][s]+imm[i],t);
2487             }
2488           }
2489         }
2490       } else {
2491         if(t>=0) {
2492           if(!((i_regs->isconst>>t)&1))
2493             emit_movimm(imm[i],t);
2494         }
2495       }
2496     }
2497   }
2498   if(dops[i].opcode==0x18||dops[i].opcode==0x19) { // DADDI/DADDIU
2499     if(dops[i].rt1) {
2500       signed char sl,tl;
2501       tl=get_reg(i_regs->regmap,dops[i].rt1);
2502       sl=get_reg(i_regs->regmap,dops[i].rs1);
2503       if(tl>=0) {
2504         if(dops[i].rs1) {
2505           assert(sl>=0);
2506           emit_addimm(sl,imm[i],tl);
2507         } else {
2508           emit_movimm(imm[i],tl);
2509         }
2510       }
2511     }
2512   }
2513   else if(dops[i].opcode==0x0a||dops[i].opcode==0x0b) { // SLTI/SLTIU
2514     if(dops[i].rt1) {
2515       //assert(dops[i].rs1!=0); // r0 might be valid, but it's probably a bug
2516       signed char sl,t;
2517       t=get_reg(i_regs->regmap,dops[i].rt1);
2518       sl=get_reg(i_regs->regmap,dops[i].rs1);
2519       //assert(t>=0);
2520       if(t>=0) {
2521         if(dops[i].rs1>0) {
2522             if(dops[i].opcode==0x0a) { // SLTI
2523               if(sl<0) {
2524                 if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2525                 emit_slti32(t,imm[i],t);
2526               }else{
2527                 emit_slti32(sl,imm[i],t);
2528               }
2529             }
2530             else { // SLTIU
2531               if(sl<0) {
2532                 if(i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2533                 emit_sltiu32(t,imm[i],t);
2534               }else{
2535                 emit_sltiu32(sl,imm[i],t);
2536               }
2537             }
2538         }else{
2539           // SLTI(U) with r0 is just stupid,
2540           // nonetheless examples can be found
2541           if(dops[i].opcode==0x0a) // SLTI
2542             if(0<imm[i]) emit_movimm(1,t);
2543             else emit_zeroreg(t);
2544           else // SLTIU
2545           {
2546             if(imm[i]) emit_movimm(1,t);
2547             else emit_zeroreg(t);
2548           }
2549         }
2550       }
2551     }
2552   }
2553   else if(dops[i].opcode>=0x0c&&dops[i].opcode<=0x0e) { // ANDI/ORI/XORI
2554     if(dops[i].rt1) {
2555       signed char sl,tl;
2556       tl=get_reg(i_regs->regmap,dops[i].rt1);
2557       sl=get_reg(i_regs->regmap,dops[i].rs1);
2558       if(tl>=0 && !((i_regs->isconst>>tl)&1)) {
2559         if(dops[i].opcode==0x0c) //ANDI
2560         {
2561           if(dops[i].rs1) {
2562             if(sl<0) {
2563               if(i_regs->regmap_entry[tl]!=dops[i].rs1) emit_loadreg(dops[i].rs1,tl);
2564               emit_andimm(tl,imm[i],tl);
2565             }else{
2566               if(!((i_regs->wasconst>>sl)&1))
2567                 emit_andimm(sl,imm[i],tl);
2568               else
2569                 emit_movimm(constmap[i][sl]&imm[i],tl);
2570             }
2571           }
2572           else
2573             emit_zeroreg(tl);
2574         }
2575         else
2576         {
2577           if(dops[i].rs1) {
2578             if(sl<0) {
2579               if(i_regs->regmap_entry[tl]!=dops[i].rs1) emit_loadreg(dops[i].rs1,tl);
2580             }
2581             if(dops[i].opcode==0x0d) { // ORI
2582               if(sl<0) {
2583                 emit_orimm(tl,imm[i],tl);
2584               }else{
2585                 if(!((i_regs->wasconst>>sl)&1))
2586                   emit_orimm(sl,imm[i],tl);
2587                 else
2588                   emit_movimm(constmap[i][sl]|imm[i],tl);
2589               }
2590             }
2591             if(dops[i].opcode==0x0e) { // XORI
2592               if(sl<0) {
2593                 emit_xorimm(tl,imm[i],tl);
2594               }else{
2595                 if(!((i_regs->wasconst>>sl)&1))
2596                   emit_xorimm(sl,imm[i],tl);
2597                 else
2598                   emit_movimm(constmap[i][sl]^imm[i],tl);
2599               }
2600             }
2601           }
2602           else {
2603             emit_movimm(imm[i],tl);
2604           }
2605         }
2606       }
2607     }
2608   }
2609 }
2610
2611 static void shiftimm_assemble(int i, const struct regstat *i_regs)
2612 {
2613   if(dops[i].opcode2<=0x3) // SLL/SRL/SRA
2614   {
2615     if(dops[i].rt1) {
2616       signed char s,t;
2617       t=get_reg(i_regs->regmap,dops[i].rt1);
2618       s=get_reg(i_regs->regmap,dops[i].rs1);
2619       //assert(t>=0);
2620       if(t>=0&&!((i_regs->isconst>>t)&1)){
2621         if(dops[i].rs1==0)
2622         {
2623           emit_zeroreg(t);
2624         }
2625         else
2626         {
2627           if(s<0&&i_regs->regmap_entry[t]!=dops[i].rs1) emit_loadreg(dops[i].rs1,t);
2628           if(imm[i]) {
2629             if(dops[i].opcode2==0) // SLL
2630             {
2631               emit_shlimm(s<0?t:s,imm[i],t);
2632             }
2633             if(dops[i].opcode2==2) // SRL
2634             {
2635               emit_shrimm(s<0?t:s,imm[i],t);
2636             }
2637             if(dops[i].opcode2==3) // SRA
2638             {
2639               emit_sarimm(s<0?t:s,imm[i],t);
2640             }
2641           }else{
2642             // Shift by zero
2643             if(s>=0 && s!=t) emit_mov(s,t);
2644           }
2645         }
2646       }
2647       //emit_storereg(dops[i].rt1,t); //DEBUG
2648     }
2649   }
2650   if(dops[i].opcode2>=0x38&&dops[i].opcode2<=0x3b) // DSLL/DSRL/DSRA
2651   {
2652     assert(0);
2653   }
2654   if(dops[i].opcode2==0x3c) // DSLL32
2655   {
2656     assert(0);
2657   }
2658   if(dops[i].opcode2==0x3e) // DSRL32
2659   {
2660     assert(0);
2661   }
2662   if(dops[i].opcode2==0x3f) // DSRA32
2663   {
2664     assert(0);
2665   }
2666 }
2667
2668 #ifndef shift_assemble
2669 static void shift_assemble(int i, const struct regstat *i_regs)
2670 {
2671   signed char s,t,shift;
2672   if (dops[i].rt1 == 0)
2673     return;
2674   assert(dops[i].opcode2<=0x07); // SLLV/SRLV/SRAV
2675   t = get_reg(i_regs->regmap, dops[i].rt1);
2676   s = get_reg(i_regs->regmap, dops[i].rs1);
2677   shift = get_reg(i_regs->regmap, dops[i].rs2);
2678   if (t < 0)
2679     return;
2680
2681   if(dops[i].rs1==0)
2682     emit_zeroreg(t);
2683   else if(dops[i].rs2==0) {
2684     assert(s>=0);
2685     if(s!=t) emit_mov(s,t);
2686   }
2687   else {
2688     host_tempreg_acquire();
2689     emit_andimm(shift,31,HOST_TEMPREG);
2690     switch(dops[i].opcode2) {
2691     case 4: // SLLV
2692       emit_shl(s,HOST_TEMPREG,t);
2693       break;
2694     case 6: // SRLV
2695       emit_shr(s,HOST_TEMPREG,t);
2696       break;
2697     case 7: // SRAV
2698       emit_sar(s,HOST_TEMPREG,t);
2699       break;
2700     default:
2701       assert(0);
2702     }
2703     host_tempreg_release();
2704   }
2705 }
2706
2707 #endif
2708
2709 enum {
2710   MTYPE_8000 = 0,
2711   MTYPE_8020,
2712   MTYPE_0000,
2713   MTYPE_A000,
2714   MTYPE_1F80,
2715 };
2716
2717 static int get_ptr_mem_type(u_int a)
2718 {
2719   if(a < 0x00200000) {
2720     if(a<0x1000&&((start>>20)==0xbfc||(start>>24)==0xa0))
2721       // return wrong, must use memhandler for BIOS self-test to pass
2722       // 007 does similar stuff from a00 mirror, weird stuff
2723       return MTYPE_8000;
2724     return MTYPE_0000;
2725   }
2726   if(0x1f800000 <= a && a < 0x1f801000)
2727     return MTYPE_1F80;
2728   if(0x80200000 <= a && a < 0x80800000)
2729     return MTYPE_8020;
2730   if(0xa0000000 <= a && a < 0xa0200000)
2731     return MTYPE_A000;
2732   return MTYPE_8000;
2733 }
2734
2735 static int get_ro_reg(const struct regstat *i_regs, int host_tempreg_free)
2736 {
2737   int r = get_reg(i_regs->regmap, ROREG);
2738   if (r < 0 && host_tempreg_free) {
2739     host_tempreg_acquire();
2740     emit_loadreg(ROREG, r = HOST_TEMPREG);
2741   }
2742   if (r < 0)
2743     abort();
2744   return r;
2745 }
2746
2747 static void *emit_fastpath_cmp_jump(int i, const struct regstat *i_regs,
2748   int addr, int *offset_reg, int *addr_reg_override)
2749 {
2750   void *jaddr = NULL;
2751   int type = 0;
2752   int mr = dops[i].rs1;
2753   *offset_reg = -1;
2754   if(((smrv_strong|smrv_weak)>>mr)&1) {
2755     type=get_ptr_mem_type(smrv[mr]);
2756     //printf("set %08x @%08x r%d %d\n", smrv[mr], start+i*4, mr, type);
2757   }
2758   else {
2759     // use the mirror we are running on
2760     type=get_ptr_mem_type(start);
2761     //printf("set nospec   @%08x r%d %d\n", start+i*4, mr, type);
2762   }
2763
2764   if(type==MTYPE_8020) { // RAM 80200000+ mirror
2765     host_tempreg_acquire();
2766     emit_andimm(addr,~0x00e00000,HOST_TEMPREG);
2767     addr=*addr_reg_override=HOST_TEMPREG;
2768     type=0;
2769   }
2770   else if(type==MTYPE_0000) { // RAM 0 mirror
2771     host_tempreg_acquire();
2772     emit_orimm(addr,0x80000000,HOST_TEMPREG);
2773     addr=*addr_reg_override=HOST_TEMPREG;
2774     type=0;
2775   }
2776   else if(type==MTYPE_A000) { // RAM A mirror
2777     host_tempreg_acquire();
2778     emit_andimm(addr,~0x20000000,HOST_TEMPREG);
2779     addr=*addr_reg_override=HOST_TEMPREG;
2780     type=0;
2781   }
2782   else if(type==MTYPE_1F80) { // scratchpad
2783     if (psxH == (void *)0x1f800000) {
2784       host_tempreg_acquire();
2785       emit_xorimm(addr,0x1f800000,HOST_TEMPREG);
2786       emit_cmpimm(HOST_TEMPREG,0x1000);
2787       host_tempreg_release();
2788       jaddr=out;
2789       emit_jc(0);
2790     }
2791     else {
2792       // do the usual RAM check, jump will go to the right handler
2793       type=0;
2794     }
2795   }
2796
2797   if (type == 0) // need ram check
2798   {
2799     emit_cmpimm(addr,RAM_SIZE);
2800     jaddr = out;
2801     #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
2802     // Hint to branch predictor that the branch is unlikely to be taken
2803     if (dops[i].rs1 >= 28)
2804       emit_jno_unlikely(0);
2805     else
2806     #endif
2807       emit_jno(0);
2808     if (ram_offset != 0)
2809       *offset_reg = get_ro_reg(i_regs, 0);
2810   }
2811
2812   return jaddr;
2813 }
2814
2815 // return memhandler, or get directly accessable address and return 0
2816 static void *get_direct_memhandler(void *table, u_int addr,
2817   enum stub_type type, uintptr_t *addr_host)
2818 {
2819   uintptr_t msb = 1ull << (sizeof(uintptr_t)*8 - 1);
2820   uintptr_t l1, l2 = 0;
2821   l1 = ((uintptr_t *)table)[addr>>12];
2822   if (!(l1 & msb)) {
2823     uintptr_t v = l1 << 1;
2824     *addr_host = v + addr;
2825     return NULL;
2826   }
2827   else {
2828     l1 <<= 1;
2829     if (type == LOADB_STUB || type == LOADBU_STUB || type == STOREB_STUB)
2830       l2 = ((uintptr_t *)l1)[0x1000/4 + 0x1000/2 + (addr&0xfff)];
2831     else if (type == LOADH_STUB || type == LOADHU_STUB || type == STOREH_STUB)
2832       l2 = ((uintptr_t *)l1)[0x1000/4 + (addr&0xfff)/2];
2833     else
2834       l2 = ((uintptr_t *)l1)[(addr&0xfff)/4];
2835     if (!(l2 & msb)) {
2836       uintptr_t v = l2 << 1;
2837       *addr_host = v + (addr&0xfff);
2838       return NULL;
2839     }
2840     return (void *)(l2 << 1);
2841   }
2842 }
2843
2844 static u_int get_host_reglist(const signed char *regmap)
2845 {
2846   u_int reglist = 0, hr;
2847   for (hr = 0; hr < HOST_REGS; hr++) {
2848     if (hr != EXCLUDE_REG && regmap[hr] >= 0)
2849       reglist |= 1 << hr;
2850   }
2851   return reglist;
2852 }
2853
2854 static u_int reglist_exclude(u_int reglist, int r1, int r2)
2855 {
2856   if (r1 >= 0)
2857     reglist &= ~(1u << r1);
2858   if (r2 >= 0)
2859     reglist &= ~(1u << r2);
2860   return reglist;
2861 }
2862
2863 // find a temp caller-saved register not in reglist (so assumed to be free)
2864 static int reglist_find_free(u_int reglist)
2865 {
2866   u_int free_regs = ~reglist & CALLER_SAVE_REGS;
2867   if (free_regs == 0)
2868     return -1;
2869   return __builtin_ctz(free_regs);
2870 }
2871
2872 static void do_load_word(int a, int rt, int offset_reg)
2873 {
2874   if (offset_reg >= 0)
2875     emit_ldr_dualindexed(offset_reg, a, rt);
2876   else
2877     emit_readword_indexed(0, a, rt);
2878 }
2879
2880 static void do_store_word(int a, int ofs, int rt, int offset_reg, int preseve_a)
2881 {
2882   if (offset_reg < 0) {
2883     emit_writeword_indexed(rt, ofs, a);
2884     return;
2885   }
2886   if (ofs != 0)
2887     emit_addimm(a, ofs, a);
2888   emit_str_dualindexed(offset_reg, a, rt);
2889   if (ofs != 0 && preseve_a)
2890     emit_addimm(a, -ofs, a);
2891 }
2892
2893 static void do_store_hword(int a, int ofs, int rt, int offset_reg, int preseve_a)
2894 {
2895   if (offset_reg < 0) {
2896     emit_writehword_indexed(rt, ofs, a);
2897     return;
2898   }
2899   if (ofs != 0)
2900     emit_addimm(a, ofs, a);
2901   emit_strh_dualindexed(offset_reg, a, rt);
2902   if (ofs != 0 && preseve_a)
2903     emit_addimm(a, -ofs, a);
2904 }
2905
2906 static void do_store_byte(int a, int rt, int offset_reg)
2907 {
2908   if (offset_reg >= 0)
2909     emit_strb_dualindexed(offset_reg, a, rt);
2910   else
2911     emit_writebyte_indexed(rt, 0, a);
2912 }
2913
2914 static void load_assemble(int i, const struct regstat *i_regs, int ccadj_)
2915 {
2916   int s,tl,addr;
2917   int offset;
2918   void *jaddr=0;
2919   int memtarget=0,c=0;
2920   int offset_reg = -1;
2921   int fastio_reg_override = -1;
2922   u_int reglist=get_host_reglist(i_regs->regmap);
2923   tl=get_reg(i_regs->regmap,dops[i].rt1);
2924   s=get_reg(i_regs->regmap,dops[i].rs1);
2925   offset=imm[i];
2926   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
2927   if(s>=0) {
2928     c=(i_regs->wasconst>>s)&1;
2929     if (c) {
2930       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
2931     }
2932   }
2933   //printf("load_assemble: c=%d\n",c);
2934   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2935   // FIXME: Even if the load is a NOP, we should check for pagefaults...
2936   if((tl<0&&(!c||(((u_int)constmap[i][s]+offset)>>16)==0x1f80))
2937     ||dops[i].rt1==0) {
2938       // could be FIFO, must perform the read
2939       // ||dummy read
2940       assem_debug("(forced read)\n");
2941       tl=get_reg_temp(i_regs->regmap);
2942       assert(tl>=0);
2943   }
2944   if(offset||s<0||c) addr=tl;
2945   else addr=s;
2946   //if(tl<0) tl=get_reg_temp(i_regs->regmap);
2947  if(tl>=0) {
2948   //printf("load_assemble: c=%d\n",c);
2949   //if(c) printf("load_assemble: const=%lx\n",(long)constmap[i][s]+offset);
2950   assert(tl>=0); // Even if the load is a NOP, we must check for pagefaults and I/O
2951   reglist&=~(1<<tl);
2952   if(!c) {
2953     #ifdef R29_HACK
2954     // Strmnnrmn's speed hack
2955     if(dops[i].rs1!=29||start<0x80001000||start>=0x80000000+RAM_SIZE)
2956     #endif
2957     {
2958       jaddr = emit_fastpath_cmp_jump(i, i_regs, addr,
2959                 &offset_reg, &fastio_reg_override);
2960     }
2961   }
2962   else if (ram_offset && memtarget) {
2963     offset_reg = get_ro_reg(i_regs, 0);
2964   }
2965   int dummy=(dops[i].rt1==0)||(tl!=get_reg(i_regs->regmap,dops[i].rt1)); // ignore loads to r0 and unneeded reg
2966   switch (dops[i].opcode) {
2967   case 0x20: // LB
2968     if(!c||memtarget) {
2969       if(!dummy) {
2970         int a = tl;
2971         if (!c) a = addr;
2972         if (fastio_reg_override >= 0)
2973           a = fastio_reg_override;
2974
2975         if (offset_reg >= 0)
2976           emit_ldrsb_dualindexed(offset_reg, a, tl);
2977         else
2978           emit_movsbl_indexed(0, a, tl);
2979       }
2980       if(jaddr)
2981         add_stub_r(LOADB_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
2982     }
2983     else
2984       inline_readstub(LOADB_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
2985     break;
2986   case 0x21: // LH
2987     if(!c||memtarget) {
2988       if(!dummy) {
2989         int a = tl;
2990         if (!c) a = addr;
2991         if (fastio_reg_override >= 0)
2992           a = fastio_reg_override;
2993         if (offset_reg >= 0)
2994           emit_ldrsh_dualindexed(offset_reg, a, tl);
2995         else
2996           emit_movswl_indexed(0, a, tl);
2997       }
2998       if(jaddr)
2999         add_stub_r(LOADH_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3000     }
3001     else
3002       inline_readstub(LOADH_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
3003     break;
3004   case 0x23: // LW
3005     if(!c||memtarget) {
3006       if(!dummy) {
3007         int a = addr;
3008         if (fastio_reg_override >= 0)
3009           a = fastio_reg_override;
3010         do_load_word(a, tl, offset_reg);
3011       }
3012       if(jaddr)
3013         add_stub_r(LOADW_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3014     }
3015     else
3016       inline_readstub(LOADW_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
3017     break;
3018   case 0x24: // LBU
3019     if(!c||memtarget) {
3020       if(!dummy) {
3021         int a = tl;
3022         if (!c) a = addr;
3023         if (fastio_reg_override >= 0)
3024           a = fastio_reg_override;
3025
3026         if (offset_reg >= 0)
3027           emit_ldrb_dualindexed(offset_reg, a, tl);
3028         else
3029           emit_movzbl_indexed(0, a, tl);
3030       }
3031       if(jaddr)
3032         add_stub_r(LOADBU_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3033     }
3034     else
3035       inline_readstub(LOADBU_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
3036     break;
3037   case 0x25: // LHU
3038     if(!c||memtarget) {
3039       if(!dummy) {
3040         int a = tl;
3041         if(!c) a = addr;
3042         if (fastio_reg_override >= 0)
3043           a = fastio_reg_override;
3044         if (offset_reg >= 0)
3045           emit_ldrh_dualindexed(offset_reg, a, tl);
3046         else
3047           emit_movzwl_indexed(0, a, tl);
3048       }
3049       if(jaddr)
3050         add_stub_r(LOADHU_STUB,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3051     }
3052     else
3053       inline_readstub(LOADHU_STUB,i,constmap[i][s]+offset,i_regs->regmap,dops[i].rt1,ccadj_,reglist);
3054     break;
3055   case 0x27: // LWU
3056   case 0x37: // LD
3057   default:
3058     assert(0);
3059   }
3060  }
3061  if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3062    host_tempreg_release();
3063 }
3064
3065 #ifndef loadlr_assemble
3066 static void loadlr_assemble(int i, const struct regstat *i_regs, int ccadj_)
3067 {
3068   int s,tl,temp,temp2,addr;
3069   int offset;
3070   void *jaddr=0;
3071   int memtarget=0,c=0;
3072   int offset_reg = -1;
3073   int fastio_reg_override = -1;
3074   u_int reglist=get_host_reglist(i_regs->regmap);
3075   tl=get_reg(i_regs->regmap,dops[i].rt1);
3076   s=get_reg(i_regs->regmap,dops[i].rs1);
3077   temp=get_reg_temp(i_regs->regmap);
3078   temp2=get_reg(i_regs->regmap,FTEMP);
3079   addr=get_reg(i_regs->regmap,AGEN1+(i&1));
3080   assert(addr<0);
3081   offset=imm[i];
3082   reglist|=1<<temp;
3083   if(offset||s<0||c) addr=temp2;
3084   else addr=s;
3085   if(s>=0) {
3086     c=(i_regs->wasconst>>s)&1;
3087     if(c) {
3088       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3089     }
3090   }
3091   if(!c) {
3092     emit_shlimm(addr,3,temp);
3093     if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
3094       emit_andimm(addr,0xFFFFFFFC,temp2); // LWL/LWR
3095     }else{
3096       emit_andimm(addr,0xFFFFFFF8,temp2); // LDL/LDR
3097     }
3098     jaddr = emit_fastpath_cmp_jump(i, i_regs, temp2,
3099               &offset_reg, &fastio_reg_override);
3100   }
3101   else {
3102     if (ram_offset && memtarget) {
3103       offset_reg = get_ro_reg(i_regs, 0);
3104     }
3105     if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
3106       emit_movimm(((constmap[i][s]+offset)<<3)&24,temp); // LWL/LWR
3107     }else{
3108       emit_movimm(((constmap[i][s]+offset)<<3)&56,temp); // LDL/LDR
3109     }
3110   }
3111   if (dops[i].opcode==0x22||dops[i].opcode==0x26) { // LWL/LWR
3112     if(!c||memtarget) {
3113       int a = temp2;
3114       if (fastio_reg_override >= 0)
3115         a = fastio_reg_override;
3116       do_load_word(a, temp2, offset_reg);
3117       if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3118         host_tempreg_release();
3119       if(jaddr) add_stub_r(LOADW_STUB,jaddr,out,i,temp2,i_regs,ccadj_,reglist);
3120     }
3121     else
3122       inline_readstub(LOADW_STUB,i,(constmap[i][s]+offset)&0xFFFFFFFC,i_regs->regmap,FTEMP,ccadj_,reglist);
3123     if(dops[i].rt1) {
3124       assert(tl>=0);
3125       emit_andimm(temp,24,temp);
3126       if (dops[i].opcode==0x22) // LWL
3127         emit_xorimm(temp,24,temp);
3128       host_tempreg_acquire();
3129       emit_movimm(-1,HOST_TEMPREG);
3130       if (dops[i].opcode==0x26) {
3131         emit_shr(temp2,temp,temp2);
3132         emit_bic_lsr(tl,HOST_TEMPREG,temp,tl);
3133       }else{
3134         emit_shl(temp2,temp,temp2);
3135         emit_bic_lsl(tl,HOST_TEMPREG,temp,tl);
3136       }
3137       host_tempreg_release();
3138       emit_or(temp2,tl,tl);
3139     }
3140     //emit_storereg(dops[i].rt1,tl); // DEBUG
3141   }
3142   if (dops[i].opcode==0x1A||dops[i].opcode==0x1B) { // LDL/LDR
3143     assert(0);
3144   }
3145 }
3146 #endif
3147
3148 static void store_assemble(int i, const struct regstat *i_regs, int ccadj_)
3149 {
3150   int s,tl;
3151   int addr,temp;
3152   int offset;
3153   void *jaddr=0;
3154   enum stub_type type=0;
3155   int memtarget=0,c=0;
3156   int agr=AGEN1+(i&1);
3157   int offset_reg = -1;
3158   int fastio_reg_override = -1;
3159   u_int reglist=get_host_reglist(i_regs->regmap);
3160   tl=get_reg(i_regs->regmap,dops[i].rs2);
3161   s=get_reg(i_regs->regmap,dops[i].rs1);
3162   temp=get_reg(i_regs->regmap,agr);
3163   if(temp<0) temp=get_reg_temp(i_regs->regmap);
3164   offset=imm[i];
3165   if(s>=0) {
3166     c=(i_regs->wasconst>>s)&1;
3167     if(c) {
3168       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3169     }
3170   }
3171   assert(tl>=0);
3172   assert(temp>=0);
3173   if(i_regs->regmap[HOST_CCREG]==CCREG) reglist&=~(1<<HOST_CCREG);
3174   if(offset||s<0||c) addr=temp;
3175   else addr=s;
3176   if (!c) {
3177     jaddr = emit_fastpath_cmp_jump(i, i_regs, addr,
3178               &offset_reg, &fastio_reg_override);
3179   }
3180   else if (ram_offset && memtarget) {
3181     offset_reg = get_ro_reg(i_regs, 0);
3182   }
3183
3184   switch (dops[i].opcode) {
3185   case 0x28: // SB
3186     if(!c||memtarget) {
3187       int a = temp;
3188       if (!c) a = addr;
3189       if (fastio_reg_override >= 0)
3190         a = fastio_reg_override;
3191       do_store_byte(a, tl, offset_reg);
3192     }
3193     type = STOREB_STUB;
3194     break;
3195   case 0x29: // SH
3196     if(!c||memtarget) {
3197       int a = temp;
3198       if (!c) a = addr;
3199       if (fastio_reg_override >= 0)
3200         a = fastio_reg_override;
3201       do_store_hword(a, 0, tl, offset_reg, 1);
3202     }
3203     type = STOREH_STUB;
3204     break;
3205   case 0x2B: // SW
3206     if(!c||memtarget) {
3207       int a = addr;
3208       if (fastio_reg_override >= 0)
3209         a = fastio_reg_override;
3210       do_store_word(a, 0, tl, offset_reg, 1);
3211     }
3212     type = STOREW_STUB;
3213     break;
3214   case 0x3F: // SD
3215   default:
3216     assert(0);
3217   }
3218   if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3219     host_tempreg_release();
3220   if(jaddr) {
3221     // PCSX store handlers don't check invcode again
3222     reglist|=1<<addr;
3223     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3224     jaddr=0;
3225   }
3226   if(!(i_regs->waswritten&(1<<dops[i].rs1)) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3227     if(!c||memtarget) {
3228       #ifdef DESTRUCTIVE_SHIFT
3229       // The x86 shift operation is 'destructive'; it overwrites the
3230       // source register, so we need to make a copy first and use that.
3231       addr=temp;
3232       #endif
3233       #if defined(HOST_IMM8)
3234       int ir=get_reg(i_regs->regmap,INVCP);
3235       assert(ir>=0);
3236       emit_cmpmem_indexedsr12_reg(ir,addr,1);
3237       #else
3238       emit_cmpmem_indexedsr12_imm(invalid_code,addr,1);
3239       #endif
3240       #ifdef INVALIDATE_USE_COND_CALL
3241       emit_callne(invalidate_addr_reg[addr]);
3242       #else
3243       void *jaddr2 = out;
3244       emit_jne(0);
3245       add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),addr,0,0,0);
3246       #endif
3247     }
3248   }
3249   u_int addr_val=constmap[i][s]+offset;
3250   if(jaddr) {
3251     add_stub_r(type,jaddr,out,i,addr,i_regs,ccadj_,reglist);
3252   } else if(c&&!memtarget) {
3253     inline_writestub(type,i,addr_val,i_regs->regmap,dops[i].rs2,ccadj_,reglist);
3254   }
3255   // basic current block modification detection..
3256   // not looking back as that should be in mips cache already
3257   // (see Spyro2 title->attract mode)
3258   if(c&&start+i*4<addr_val&&addr_val<start+slen*4) {
3259     SysPrintf("write to %08x hits block %08x, pc=%08x\n",addr_val,start,start+i*4);
3260     assert(i_regs->regmap==regs[i].regmap); // not delay slot
3261     if(i_regs->regmap==regs[i].regmap) {
3262       load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3263       wb_dirtys(regs[i].regmap_entry,regs[i].wasdirty);
3264       emit_movimm(start+i*4+4,0);
3265       emit_writeword(0,&pcaddr);
3266       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3267       emit_far_call(ndrc_get_addr_ht);
3268       emit_jmpreg(0);
3269     }
3270   }
3271 }
3272
3273 static void storelr_assemble(int i, const struct regstat *i_regs, int ccadj_)
3274 {
3275   int s,tl;
3276   int temp;
3277   int offset;
3278   void *jaddr=0;
3279   void *case1, *case23, *case3;
3280   void *done0, *done1, *done2;
3281   int memtarget=0,c=0;
3282   int agr=AGEN1+(i&1);
3283   int offset_reg = -1;
3284   u_int reglist=get_host_reglist(i_regs->regmap);
3285   tl=get_reg(i_regs->regmap,dops[i].rs2);
3286   s=get_reg(i_regs->regmap,dops[i].rs1);
3287   temp=get_reg(i_regs->regmap,agr);
3288   if(temp<0) temp=get_reg_temp(i_regs->regmap);
3289   offset=imm[i];
3290   if(s>=0) {
3291     c=(i_regs->isconst>>s)&1;
3292     if(c) {
3293       memtarget=((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE;
3294     }
3295   }
3296   assert(tl>=0);
3297   assert(temp>=0);
3298   if(!c) {
3299     emit_cmpimm(s<0||offset?temp:s,RAM_SIZE);
3300     if(!offset&&s!=temp) emit_mov(s,temp);
3301     jaddr=out;
3302     emit_jno(0);
3303   }
3304   else
3305   {
3306     if(!memtarget||!dops[i].rs1) {
3307       jaddr=out;
3308       emit_jmp(0);
3309     }
3310   }
3311   if (ram_offset)
3312     offset_reg = get_ro_reg(i_regs, 0);
3313
3314   if (dops[i].opcode==0x2C||dops[i].opcode==0x2D) { // SDL/SDR
3315     assert(0);
3316   }
3317
3318   emit_testimm(temp,2);
3319   case23=out;
3320   emit_jne(0);
3321   emit_testimm(temp,1);
3322   case1=out;
3323   emit_jne(0);
3324   // 0
3325   if (dops[i].opcode == 0x2A) { // SWL
3326     // Write msb into least significant byte
3327     if (dops[i].rs2) emit_rorimm(tl, 24, tl);
3328     do_store_byte(temp, tl, offset_reg);
3329     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3330   }
3331   else if (dops[i].opcode == 0x2E) { // SWR
3332     // Write entire word
3333     do_store_word(temp, 0, tl, offset_reg, 1);
3334   }
3335   done0 = out;
3336   emit_jmp(0);
3337   // 1
3338   set_jump_target(case1, out);
3339   if (dops[i].opcode == 0x2A) { // SWL
3340     // Write two msb into two least significant bytes
3341     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3342     do_store_hword(temp, -1, tl, offset_reg, 0);
3343     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3344   }
3345   else if (dops[i].opcode == 0x2E) { // SWR
3346     // Write 3 lsb into three most significant bytes
3347     do_store_byte(temp, tl, offset_reg);
3348     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3349     do_store_hword(temp, 1, tl, offset_reg, 0);
3350     if (dops[i].rs2) emit_rorimm(tl, 24, tl);
3351   }
3352   done1=out;
3353   emit_jmp(0);
3354   // 2,3
3355   set_jump_target(case23, out);
3356   emit_testimm(temp,1);
3357   case3 = out;
3358   emit_jne(0);
3359   // 2
3360   if (dops[i].opcode==0x2A) { // SWL
3361     // Write 3 msb into three least significant bytes
3362     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3363     do_store_hword(temp, -2, tl, offset_reg, 1);
3364     if (dops[i].rs2) emit_rorimm(tl, 16, tl);
3365     do_store_byte(temp, tl, offset_reg);
3366     if (dops[i].rs2) emit_rorimm(tl, 8, tl);
3367   }
3368   else if (dops[i].opcode == 0x2E) { // SWR
3369     // Write two lsb into two most significant bytes
3370     do_store_hword(temp, 0, tl, offset_reg, 1);
3371   }
3372   done2 = out;
3373   emit_jmp(0);
3374   // 3
3375   set_jump_target(case3, out);
3376   if (dops[i].opcode == 0x2A) { // SWL
3377     do_store_word(temp, -3, tl, offset_reg, 0);
3378   }
3379   else if (dops[i].opcode == 0x2E) { // SWR
3380     do_store_byte(temp, tl, offset_reg);
3381   }
3382   set_jump_target(done0, out);
3383   set_jump_target(done1, out);
3384   set_jump_target(done2, out);
3385   if (offset_reg == HOST_TEMPREG)
3386     host_tempreg_release();
3387   if(!c||!memtarget)
3388     add_stub_r(STORELR_STUB,jaddr,out,i,temp,i_regs,ccadj_,reglist);
3389   if(!(i_regs->waswritten&(1<<dops[i].rs1)) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3390     #if defined(HOST_IMM8)
3391     int ir=get_reg(i_regs->regmap,INVCP);
3392     assert(ir>=0);
3393     emit_cmpmem_indexedsr12_reg(ir,temp,1);
3394     #else
3395     emit_cmpmem_indexedsr12_imm(invalid_code,temp,1);
3396     #endif
3397     #ifdef INVALIDATE_USE_COND_CALL
3398     emit_callne(invalidate_addr_reg[temp]);
3399     #else
3400     void *jaddr2 = out;
3401     emit_jne(0);
3402     add_stub(INVCODE_STUB,jaddr2,out,reglist|(1<<HOST_CCREG),temp,0,0,0);
3403     #endif
3404   }
3405 }
3406
3407 static void cop0_assemble(int i, const struct regstat *i_regs, int ccadj_)
3408 {
3409   if(dops[i].opcode2==0) // MFC0
3410   {
3411     signed char t=get_reg(i_regs->regmap,dops[i].rt1);
3412     u_int copr=(source[i]>>11)&0x1f;
3413     //assert(t>=0); // Why does this happen?  OOT is weird
3414     if(t>=0&&dops[i].rt1!=0) {
3415       emit_readword(&reg_cop0[copr],t);
3416     }
3417   }
3418   else if(dops[i].opcode2==4) // MTC0
3419   {
3420     signed char s=get_reg(i_regs->regmap,dops[i].rs1);
3421     char copr=(source[i]>>11)&0x1f;
3422     assert(s>=0);
3423     wb_register(dops[i].rs1,i_regs->regmap,i_regs->dirty);
3424     if(copr==9||copr==11||copr==12||copr==13) {
3425       emit_readword(&last_count,HOST_TEMPREG);
3426       emit_loadreg(CCREG,HOST_CCREG); // TODO: do proper reg alloc
3427       emit_add(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3428       emit_addimm(HOST_CCREG,ccadj_,HOST_CCREG);
3429       emit_writeword(HOST_CCREG,&Count);
3430     }
3431     // What a mess.  The status register (12) can enable interrupts,
3432     // so needs a special case to handle a pending interrupt.
3433     // The interrupt must be taken immediately, because a subsequent
3434     // instruction might disable interrupts again.
3435     if(copr==12||copr==13) {
3436       if (is_delayslot) {
3437         // burn cycles to cause cc_interrupt, which will
3438         // reschedule next_interupt. Relies on CCREG from above.
3439         assem_debug("MTC0 DS %d\n", copr);
3440         emit_writeword(HOST_CCREG,&last_count);
3441         emit_movimm(0,HOST_CCREG);
3442         emit_storereg(CCREG,HOST_CCREG);
3443         emit_loadreg(dops[i].rs1,1);
3444         emit_movimm(copr,0);
3445         emit_far_call(pcsx_mtc0_ds);
3446         emit_loadreg(dops[i].rs1,s);
3447         return;
3448       }
3449       emit_movimm(start+i*4+4,HOST_TEMPREG);
3450       emit_writeword(HOST_TEMPREG,&pcaddr);
3451       emit_movimm(0,HOST_TEMPREG);
3452       emit_writeword(HOST_TEMPREG,&pending_exception);
3453     }
3454     if(s==HOST_CCREG)
3455       emit_loadreg(dops[i].rs1,1);
3456     else if(s!=1)
3457       emit_mov(s,1);
3458     emit_movimm(copr,0);
3459     emit_far_call(pcsx_mtc0);
3460     if(copr==9||copr==11||copr==12||copr==13) {
3461       emit_readword(&Count,HOST_CCREG);
3462       emit_readword(&next_interupt,HOST_TEMPREG);
3463       emit_addimm(HOST_CCREG,-ccadj_,HOST_CCREG);
3464       emit_sub(HOST_CCREG,HOST_TEMPREG,HOST_CCREG);
3465       emit_writeword(HOST_TEMPREG,&last_count);
3466       emit_storereg(CCREG,HOST_CCREG);
3467     }
3468     if(copr==12||copr==13) {
3469       assert(!is_delayslot);
3470       emit_readword(&pending_exception,14);
3471       emit_test(14,14);
3472       void *jaddr = out;
3473       emit_jeq(0);
3474       emit_readword(&pcaddr, 0);
3475       emit_addimm(HOST_CCREG,2,HOST_CCREG);
3476       emit_far_call(ndrc_get_addr_ht);
3477       emit_jmpreg(0);
3478       set_jump_target(jaddr, out);
3479     }
3480     emit_loadreg(dops[i].rs1,s);
3481   }
3482   else
3483   {
3484     assert(dops[i].opcode2==0x10);
3485     //if((source[i]&0x3f)==0x10) // RFE
3486     {
3487       emit_readword(&Status,0);
3488       emit_andimm(0,0x3c,1);
3489       emit_andimm(0,~0xf,0);
3490       emit_orrshr_imm(1,2,0);
3491       emit_writeword(0,&Status);
3492     }
3493   }
3494 }
3495
3496 static void cop1_unusable(int i, const struct regstat *i_regs)
3497 {
3498   // XXX: should just just do the exception instead
3499   //if(!cop1_usable)
3500   {
3501     void *jaddr=out;
3502     emit_jmp(0);
3503     add_stub_r(FP_STUB,jaddr,out,i,0,i_regs,is_delayslot,0);
3504   }
3505 }
3506
3507 static void cop1_assemble(int i, const struct regstat *i_regs)
3508 {
3509   cop1_unusable(i, i_regs);
3510 }
3511
3512 static void c1ls_assemble(int i, const struct regstat *i_regs)
3513 {
3514   cop1_unusable(i, i_regs);
3515 }
3516
3517 // FP_STUB
3518 static void do_cop1stub(int n)
3519 {
3520   literal_pool(256);
3521   assem_debug("do_cop1stub %x\n",start+stubs[n].a*4);
3522   set_jump_target(stubs[n].addr, out);
3523   int i=stubs[n].a;
3524 //  int rs=stubs[n].b;
3525   struct regstat *i_regs=(struct regstat *)stubs[n].c;
3526   int ds=stubs[n].d;
3527   if(!ds) {
3528     load_all_consts(regs[i].regmap_entry,regs[i].wasdirty,i);
3529     //if(i_regs!=&regs[i]) printf("oops: regs[i]=%x i_regs=%x",(int)&regs[i],(int)i_regs);
3530   }
3531   //else {printf("fp exception in delay slot\n");}
3532   wb_dirtys(i_regs->regmap_entry,i_regs->wasdirty);
3533   if(regs[i].regmap_entry[HOST_CCREG]!=CCREG) emit_loadreg(CCREG,HOST_CCREG);
3534   emit_movimm(start+(i-ds)*4,EAX); // Get PC
3535   emit_addimm(HOST_CCREG,ccadj[i],HOST_CCREG); // CHECK: is this right?  There should probably be an extra cycle...
3536   emit_far_jump(ds?fp_exception_ds:fp_exception);
3537 }
3538
3539 static int cop2_is_stalling_op(int i, int *cycles)
3540 {
3541   if (dops[i].opcode == 0x3a) { // SWC2
3542     *cycles = 0;
3543     return 1;
3544   }
3545   if (dops[i].itype == COP2 && (dops[i].opcode2 == 0 || dops[i].opcode2 == 2)) { // MFC2/CFC2
3546     *cycles = 0;
3547     return 1;
3548   }
3549   if (dops[i].itype == C2OP) {
3550     *cycles = gte_cycletab[source[i] & 0x3f];
3551     return 1;
3552   }
3553   // ... what about MTC2/CTC2/LWC2?
3554   return 0;
3555 }
3556
3557 #if 0
3558 static void log_gte_stall(int stall, u_int cycle)
3559 {
3560   if ((u_int)stall <= 44)
3561     printf("x    stall %2d %u\n", stall, cycle + last_count);
3562 }
3563
3564 static void emit_log_gte_stall(int i, int stall, u_int reglist)
3565 {
3566   save_regs(reglist);
3567   if (stall > 0)
3568     emit_movimm(stall, 0);
3569   else
3570     emit_mov(HOST_TEMPREG, 0);
3571   emit_addimm(HOST_CCREG, ccadj[i], 1);
3572   emit_far_call(log_gte_stall);
3573   restore_regs(reglist);
3574 }
3575 #endif
3576
3577 static void cop2_do_stall_check(u_int op, int i, const struct regstat *i_regs, u_int reglist)
3578 {
3579   int j = i, other_gte_op_cycles = -1, stall = -MAXBLOCK, cycles_passed;
3580   int rtmp = reglist_find_free(reglist);
3581
3582   if (HACK_ENABLED(NDHACK_NO_STALLS))
3583     return;
3584   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3585     // happens occasionally... cc evicted? Don't bother then
3586     //printf("no cc %08x\n", start + i*4);
3587     return;
3588   }
3589   if (!dops[i].bt) {
3590     for (j = i - 1; j >= 0; j--) {
3591       //if (dops[j].is_ds) break;
3592       if (cop2_is_stalling_op(j, &other_gte_op_cycles) || dops[j].bt)
3593         break;
3594       if (j > 0 && ccadj[j - 1] > ccadj[j])
3595         break;
3596     }
3597     j = max(j, 0);
3598   }
3599   cycles_passed = ccadj[i] - ccadj[j];
3600   if (other_gte_op_cycles >= 0)
3601     stall = other_gte_op_cycles - cycles_passed;
3602   else if (cycles_passed >= 44)
3603     stall = 0; // can't stall
3604   if (stall == -MAXBLOCK && rtmp >= 0) {
3605     // unknown stall, do the expensive runtime check
3606     assem_debug("; cop2_do_stall_check\n");
3607 #if 0 // too slow
3608     save_regs(reglist);
3609     emit_movimm(gte_cycletab[op], 0);
3610     emit_addimm(HOST_CCREG, ccadj[i], 1);
3611     emit_far_call(call_gteStall);
3612     restore_regs(reglist);
3613 #else
3614     host_tempreg_acquire();
3615     emit_readword(&psxRegs.gteBusyCycle, rtmp);
3616     emit_addimm(rtmp, -ccadj[i], rtmp);
3617     emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3618     emit_cmpimm(HOST_TEMPREG, 44);
3619     emit_cmovb_reg(rtmp, HOST_CCREG);
3620     //emit_log_gte_stall(i, 0, reglist);
3621     host_tempreg_release();
3622 #endif
3623   }
3624   else if (stall > 0) {
3625     //emit_log_gte_stall(i, stall, reglist);
3626     emit_addimm(HOST_CCREG, stall, HOST_CCREG);
3627   }
3628
3629   // save gteBusyCycle, if needed
3630   if (gte_cycletab[op] == 0)
3631     return;
3632   other_gte_op_cycles = -1;
3633   for (j = i + 1; j < slen; j++) {
3634     if (cop2_is_stalling_op(j, &other_gte_op_cycles))
3635       break;
3636     if (dops[j].is_jump) {
3637       // check ds
3638       if (j + 1 < slen && cop2_is_stalling_op(j + 1, &other_gte_op_cycles))
3639         j++;
3640       break;
3641     }
3642   }
3643   if (other_gte_op_cycles >= 0)
3644     // will handle stall when assembling that op
3645     return;
3646   cycles_passed = ccadj[min(j, slen -1)] - ccadj[i];
3647   if (cycles_passed >= 44)
3648     return;
3649   assem_debug("; save gteBusyCycle\n");
3650   host_tempreg_acquire();
3651 #if 0
3652   emit_readword(&last_count, HOST_TEMPREG);
3653   emit_add(HOST_TEMPREG, HOST_CCREG, HOST_TEMPREG);
3654   emit_addimm(HOST_TEMPREG, ccadj[i], HOST_TEMPREG);
3655   emit_addimm(HOST_TEMPREG, gte_cycletab[op]), HOST_TEMPREG);
3656   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3657 #else
3658   emit_addimm(HOST_CCREG, ccadj[i] + gte_cycletab[op], HOST_TEMPREG);
3659   emit_writeword(HOST_TEMPREG, &psxRegs.gteBusyCycle);
3660 #endif
3661   host_tempreg_release();
3662 }
3663
3664 static int is_mflohi(int i)
3665 {
3666   return (dops[i].itype == MOV && (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG));
3667 }
3668
3669 static int check_multdiv(int i, int *cycles)
3670 {
3671   if (dops[i].itype != MULTDIV)
3672     return 0;
3673   if (dops[i].opcode2 == 0x18 || dops[i].opcode2 == 0x19) // MULT(U)
3674     *cycles = 11; // approx from 7 11 14
3675   else
3676     *cycles = 37;
3677   return 1;
3678 }
3679
3680 static void multdiv_prepare_stall(int i, const struct regstat *i_regs, int ccadj_)
3681 {
3682   int j, found = 0, c = 0;
3683   if (HACK_ENABLED(NDHACK_NO_STALLS))
3684     return;
3685   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG) {
3686     // happens occasionally... cc evicted? Don't bother then
3687     return;
3688   }
3689   for (j = i + 1; j < slen; j++) {
3690     if (dops[j].bt)
3691       break;
3692     if ((found = is_mflohi(j)))
3693       break;
3694     if (dops[j].is_jump) {
3695       // check ds
3696       if (j + 1 < slen && (found = is_mflohi(j + 1)))
3697         j++;
3698       break;
3699     }
3700   }
3701   if (found)
3702     // handle all in multdiv_do_stall()
3703     return;
3704   check_multdiv(i, &c);
3705   assert(c > 0);
3706   assem_debug("; muldiv prepare stall %d\n", c);
3707   host_tempreg_acquire();
3708   emit_addimm(HOST_CCREG, ccadj_ + c, HOST_TEMPREG);
3709   emit_writeword(HOST_TEMPREG, &psxRegs.muldivBusyCycle);
3710   host_tempreg_release();
3711 }
3712
3713 static void multdiv_do_stall(int i, const struct regstat *i_regs)
3714 {
3715   int j, known_cycles = 0;
3716   u_int reglist = get_host_reglist(i_regs->regmap);
3717   int rtmp = get_reg_temp(i_regs->regmap);
3718   if (rtmp < 0)
3719     rtmp = reglist_find_free(reglist);
3720   if (HACK_ENABLED(NDHACK_NO_STALLS))
3721     return;
3722   if (get_reg(i_regs->regmap, CCREG) != HOST_CCREG || rtmp < 0) {
3723     // happens occasionally... cc evicted? Don't bother then
3724     //printf("no cc/rtmp %08x\n", start + i*4);
3725     return;
3726   }
3727   if (!dops[i].bt) {
3728     for (j = i - 1; j >= 0; j--) {
3729       if (dops[j].is_ds) break;
3730       if (check_multdiv(j, &known_cycles))
3731         break;
3732       if (is_mflohi(j))
3733         // already handled by this op
3734         return;
3735       if (dops[j].bt || (j > 0 && ccadj[j - 1] > ccadj[j]))
3736         break;
3737     }
3738     j = max(j, 0);
3739   }
3740   if (known_cycles > 0) {
3741     known_cycles -= ccadj[i] - ccadj[j];
3742     assem_debug("; muldiv stall resolved %d\n", known_cycles);
3743     if (known_cycles > 0)
3744       emit_addimm(HOST_CCREG, known_cycles, HOST_CCREG);
3745     return;
3746   }
3747   assem_debug("; muldiv stall unresolved\n");
3748   host_tempreg_acquire();
3749   emit_readword(&psxRegs.muldivBusyCycle, rtmp);
3750   emit_addimm(rtmp, -ccadj[i], rtmp);
3751   emit_sub(rtmp, HOST_CCREG, HOST_TEMPREG);
3752   emit_cmpimm(HOST_TEMPREG, 37);
3753   emit_cmovb_reg(rtmp, HOST_CCREG);
3754   //emit_log_gte_stall(i, 0, reglist);
3755   host_tempreg_release();
3756 }
3757
3758 static void cop2_get_dreg(u_int copr,signed char tl,signed char temp)
3759 {
3760   switch (copr) {
3761     case 1:
3762     case 3:
3763     case 5:
3764     case 8:
3765     case 9:
3766     case 10:
3767     case 11:
3768       emit_readword(&reg_cop2d[copr],tl);
3769       emit_signextend16(tl,tl);
3770       emit_writeword(tl,&reg_cop2d[copr]); // hmh
3771       break;
3772     case 7:
3773     case 16:
3774     case 17:
3775     case 18:
3776     case 19:
3777       emit_readword(&reg_cop2d[copr],tl);
3778       emit_andimm(tl,0xffff,tl);
3779       emit_writeword(tl,&reg_cop2d[copr]);
3780       break;
3781     case 15:
3782       emit_readword(&reg_cop2d[14],tl); // SXY2
3783       emit_writeword(tl,&reg_cop2d[copr]);
3784       break;
3785     case 28:
3786     case 29:
3787       c2op_mfc2_29_assemble(tl,temp);
3788       break;
3789     default:
3790       emit_readword(&reg_cop2d[copr],tl);
3791       break;
3792   }
3793 }
3794
3795 static void cop2_put_dreg(u_int copr,signed char sl,signed char temp)
3796 {
3797   switch (copr) {
3798     case 15:
3799       emit_readword(&reg_cop2d[13],temp);  // SXY1
3800       emit_writeword(sl,&reg_cop2d[copr]);
3801       emit_writeword(temp,&reg_cop2d[12]); // SXY0
3802       emit_readword(&reg_cop2d[14],temp);  // SXY2
3803       emit_writeword(sl,&reg_cop2d[14]);
3804       emit_writeword(temp,&reg_cop2d[13]); // SXY1
3805       break;
3806     case 28:
3807       emit_andimm(sl,0x001f,temp);
3808       emit_shlimm(temp,7,temp);
3809       emit_writeword(temp,&reg_cop2d[9]);
3810       emit_andimm(sl,0x03e0,temp);
3811       emit_shlimm(temp,2,temp);
3812       emit_writeword(temp,&reg_cop2d[10]);
3813       emit_andimm(sl,0x7c00,temp);
3814       emit_shrimm(temp,3,temp);
3815       emit_writeword(temp,&reg_cop2d[11]);
3816       emit_writeword(sl,&reg_cop2d[28]);
3817       break;
3818     case 30:
3819       emit_xorsar_imm(sl,sl,31,temp);
3820 #if defined(HAVE_ARMV5) || defined(__aarch64__)
3821       emit_clz(temp,temp);
3822 #else
3823       emit_movs(temp,HOST_TEMPREG);
3824       emit_movimm(0,temp);
3825       emit_jeq((int)out+4*4);
3826       emit_addpl_imm(temp,1,temp);
3827       emit_lslpls_imm(HOST_TEMPREG,1,HOST_TEMPREG);
3828       emit_jns((int)out-2*4);
3829 #endif
3830       emit_writeword(sl,&reg_cop2d[30]);
3831       emit_writeword(temp,&reg_cop2d[31]);
3832       break;
3833     case 31:
3834       break;
3835     default:
3836       emit_writeword(sl,&reg_cop2d[copr]);
3837       break;
3838   }
3839 }
3840
3841 static void c2ls_assemble(int i, const struct regstat *i_regs, int ccadj_)
3842 {
3843   int s,tl;
3844   int ar;
3845   int offset;
3846   int memtarget=0,c=0;
3847   void *jaddr2=NULL;
3848   enum stub_type type;
3849   int agr=AGEN1+(i&1);
3850   int offset_reg = -1;
3851   int fastio_reg_override = -1;
3852   u_int reglist=get_host_reglist(i_regs->regmap);
3853   u_int copr=(source[i]>>16)&0x1f;
3854   s=get_reg(i_regs->regmap,dops[i].rs1);
3855   tl=get_reg(i_regs->regmap,FTEMP);
3856   offset=imm[i];
3857   assert(dops[i].rs1>0);
3858   assert(tl>=0);
3859
3860   if(i_regs->regmap[HOST_CCREG]==CCREG)
3861     reglist&=~(1<<HOST_CCREG);
3862
3863   // get the address
3864   if (dops[i].opcode==0x3a) { // SWC2
3865     ar=get_reg(i_regs->regmap,agr);
3866     if(ar<0) ar=get_reg_temp(i_regs->regmap);
3867     reglist|=1<<ar;
3868   } else { // LWC2
3869     ar=tl;
3870   }
3871   if(s>=0) c=(i_regs->wasconst>>s)&1;
3872   memtarget=c&&(((signed int)(constmap[i][s]+offset))<(signed int)0x80000000+RAM_SIZE);
3873   if (!offset&&!c&&s>=0) ar=s;
3874   assert(ar>=0);
3875
3876   cop2_do_stall_check(0, i, i_regs, reglist);
3877
3878   if (dops[i].opcode==0x3a) { // SWC2
3879     cop2_get_dreg(copr,tl,-1);
3880     type=STOREW_STUB;
3881   }
3882   else
3883     type=LOADW_STUB;
3884
3885   if(c&&!memtarget) {
3886     jaddr2=out;
3887     emit_jmp(0); // inline_readstub/inline_writestub?
3888   }
3889   else {
3890     if(!c) {
3891       jaddr2 = emit_fastpath_cmp_jump(i, i_regs, ar,
3892                 &offset_reg, &fastio_reg_override);
3893     }
3894     else if (ram_offset && memtarget) {
3895       offset_reg = get_ro_reg(i_regs, 0);
3896     }
3897     switch (dops[i].opcode) {
3898     case 0x32: { // LWC2
3899       int a = ar;
3900       if (fastio_reg_override >= 0)
3901         a = fastio_reg_override;
3902       do_load_word(a, tl, offset_reg);
3903       break;
3904     }
3905     case 0x3a: { // SWC2
3906       #ifdef DESTRUCTIVE_SHIFT
3907       if(!offset&&!c&&s>=0) emit_mov(s,ar);
3908       #endif
3909       int a = ar;
3910       if (fastio_reg_override >= 0)
3911         a = fastio_reg_override;
3912       do_store_word(a, 0, tl, offset_reg, 1);
3913       break;
3914     }
3915     default:
3916       assert(0);
3917     }
3918   }
3919   if (fastio_reg_override == HOST_TEMPREG || offset_reg == HOST_TEMPREG)
3920     host_tempreg_release();
3921   if(jaddr2)
3922     add_stub_r(type,jaddr2,out,i,ar,i_regs,ccadj_,reglist);
3923   if(dops[i].opcode==0x3a) // SWC2
3924   if(!(i_regs->waswritten&(1<<dops[i].rs1)) && !HACK_ENABLED(NDHACK_NO_SMC_CHECK)) {
3925 #if defined(HOST_IMM8)
3926     int ir=get_reg(i_regs->regmap,INVCP);
3927     assert(ir>=0);
3928     emit_cmpmem_indexedsr12_reg(ir,ar,1);
3929 #else
3930     emit_cmpmem_indexedsr12_imm(invalid_code,ar,1);
3931 #endif
3932     #ifdef INVALIDATE_USE_COND_CALL
3933     emit_callne(invalidate_addr_reg[ar]);
3934     #else
3935     void *jaddr3 = out;
3936     emit_jne(0);
3937     add_stub(INVCODE_STUB,jaddr3,out,reglist|(1<<HOST_CCREG),ar,0,0,0);
3938     #endif
3939   }
3940   if (dops[i].opcode==0x32) { // LWC2
3941     host_tempreg_acquire();
3942     cop2_put_dreg(copr,tl,HOST_TEMPREG);
3943     host_tempreg_release();
3944   }
3945 }
3946
3947 static void cop2_assemble(int i, const struct regstat *i_regs)
3948 {
3949   u_int copr = (source[i]>>11) & 0x1f;
3950   signed char temp = get_reg_temp(i_regs->regmap);
3951
3952   if (!HACK_ENABLED(NDHACK_NO_STALLS)) {
3953     u_int reglist = reglist_exclude(get_host_reglist(i_regs->regmap), temp, -1);
3954     if (dops[i].opcode2 == 0 || dops[i].opcode2 == 2) { // MFC2/CFC2
3955       signed char tl = get_reg(i_regs->regmap, dops[i].rt1);
3956       reglist = reglist_exclude(reglist, tl, -1);
3957     }
3958     cop2_do_stall_check(0, i, i_regs, reglist);
3959   }
3960   if (dops[i].opcode2==0) { // MFC2
3961     signed char tl=get_reg(i_regs->regmap,dops[i].rt1);
3962     if(tl>=0&&dops[i].rt1!=0)
3963       cop2_get_dreg(copr,tl,temp);
3964   }
3965   else if (dops[i].opcode2==4) { // MTC2
3966     signed char sl=get_reg(i_regs->regmap,dops[i].rs1);
3967     cop2_put_dreg(copr,sl,temp);
3968   }
3969   else if (dops[i].opcode2==2) // CFC2
3970   {
3971     signed char tl=get_reg(i_regs->regmap,dops[i].rt1);
3972     if(tl>=0&&dops[i].rt1!=0)
3973       emit_readword(&reg_cop2c[copr],tl);
3974   }
3975   else if (dops[i].opcode2==6) // CTC2
3976   {
3977     signed char sl=get_reg(i_regs->regmap,dops[i].rs1);
3978     switch(copr) {
3979       case 4:
3980       case 12:
3981       case 20:
3982       case 26:
3983       case 27:
3984       case 29:
3985       case 30:
3986         emit_signextend16(sl,temp);
3987         break;
3988       case 31:
3989         c2op_ctc2_31_assemble(sl,temp);
3990         break;
3991       default:
3992         temp=sl;
3993         break;
3994     }
3995     emit_writeword(temp,&reg_cop2c[copr]);
3996     assert(sl>=0);
3997   }
3998 }
3999
4000 static void do_unalignedwritestub(int n)
4001 {
4002   assem_debug("do_unalignedwritestub %x\n",start+stubs[n].a*4);
4003   literal_pool(256);
4004   set_jump_target(stubs[n].addr, out);
4005
4006   int i=stubs[n].a;
4007   struct regstat *i_regs=(struct regstat *)stubs[n].c;
4008   int addr=stubs[n].b;
4009   u_int reglist=stubs[n].e;
4010   signed char *i_regmap=i_regs->regmap;
4011   int temp2=get_reg(i_regmap,FTEMP);
4012   int rt;
4013   rt=get_reg(i_regmap,dops[i].rs2);
4014   assert(rt>=0);
4015   assert(addr>=0);
4016   assert(dops[i].opcode==0x2a||dops[i].opcode==0x2e); // SWL/SWR only implemented
4017   reglist|=(1<<addr);
4018   reglist&=~(1<<temp2);
4019
4020   // don't bother with it and call write handler
4021   save_regs(reglist);
4022   pass_args(addr,rt);
4023   int cc=get_reg(i_regmap,CCREG);
4024   if(cc<0)
4025     emit_loadreg(CCREG,2);
4026   emit_addimm(cc<0?2:cc,(int)stubs[n].d+1,2);
4027   emit_far_call((dops[i].opcode==0x2a?jump_handle_swl:jump_handle_swr));
4028   emit_addimm(0,-((int)stubs[n].d+1),cc<0?2:cc);
4029   if(cc<0)
4030     emit_storereg(CCREG,2);
4031   restore_regs(reglist);
4032   emit_jmp(stubs[n].retaddr); // return address
4033 }
4034
4035 #ifndef multdiv_assemble
4036 void multdiv_assemble(int i,struct regstat *i_regs)
4037 {
4038   printf("Need multdiv_assemble for this architecture.\n");
4039   abort();
4040 }
4041 #endif
4042
4043 static void mov_assemble(int i, const struct regstat *i_regs)
4044 {
4045   //if(dops[i].opcode2==0x10||dops[i].opcode2==0x12) { // MFHI/MFLO
4046   //if(dops[i].opcode2==0x11||dops[i].opcode2==0x13) { // MTHI/MTLO
4047   if(dops[i].rt1) {
4048     signed char sl,tl;
4049     tl=get_reg(i_regs->regmap,dops[i].rt1);
4050     //assert(tl>=0);
4051     if(tl>=0) {
4052       sl=get_reg(i_regs->regmap,dops[i].rs1);
4053       if(sl>=0) emit_mov(sl,tl);
4054       else emit_loadreg(dops[i].rs1,tl);
4055     }
4056   }
4057   if (dops[i].rs1 == HIREG || dops[i].rs1 == LOREG) // MFHI/MFLO
4058     multdiv_do_stall(i, i_regs);
4059 }
4060
4061 // call interpreter, exception handler, things that change pc/regs/cycles ...
4062 static void call_c_cpu_handler(int i, const struct regstat *i_regs, int ccadj_, u_int pc, void *func)
4063 {
4064   signed char ccreg=get_reg(i_regs->regmap,CCREG);
4065   assert(ccreg==HOST_CCREG);
4066   assert(!is_delayslot);
4067   (void)ccreg;
4068
4069   emit_movimm(pc,3); // Get PC
4070   emit_readword(&last_count,2);
4071   emit_writeword(3,&psxRegs.pc);
4072   emit_addimm(HOST_CCREG,ccadj_,HOST_CCREG);
4073   emit_add(2,HOST_CCREG,2);
4074   emit_writeword(2,&psxRegs.cycle);
4075   emit_far_call(func);
4076   emit_far_jump(jump_to_new_pc);
4077 }
4078
4079 static void syscall_assemble(int i, const struct regstat *i_regs, int ccadj_)
4080 {
4081   // 'break' tends to be littered around to catch things like
4082   // division by 0 and is almost never executed, so don't emit much code here
4083   void *func = (dops[i].opcode2 == 0x0C)
4084     ? (is_delayslot ? jump_syscall_ds : jump_syscall)
4085     : (is_delayslot ? jump_break_ds : jump_break);
4086   assert(get_reg(i_regs->regmap, CCREG) == HOST_CCREG);
4087   emit_movimm(start + i*4, 2); // pc
4088   emit_addimm(HOST_CCREG, ccadj_ + CLOCK_ADJUST(1), HOST_CCREG);
4089   emit_far_jump(func);
4090 }
4091
4092 static void hlecall_assemble(int i, const struct regstat *i_regs, int ccadj_)
4093 {
4094   void *hlefunc = psxNULL;
4095   uint32_t hleCode = source[i] & 0x03ffffff;
4096   if (hleCode < ARRAY_SIZE(psxHLEt))
4097     hlefunc = psxHLEt[hleCode];
4098
4099   call_c_cpu_handler(i, i_regs, ccadj_, start + i*4+4, hlefunc);
4100 }
4101
4102 static void intcall_assemble(int i, const struct regstat *i_regs, int ccadj_)
4103 {
4104   call_c_cpu_handler(i, i_regs, ccadj_, start + i*4, execI);
4105 }
4106
4107 static void speculate_mov(int rs,int rt)
4108 {
4109   if(rt!=0) {
4110     smrv_strong_next|=1<<rt;
4111     smrv[rt]=smrv[rs];
4112   }
4113 }
4114
4115 static void speculate_mov_weak(int rs,int rt)
4116 {
4117   if(rt!=0) {
4118     smrv_weak_next|=1<<rt;
4119     smrv[rt]=smrv[rs];
4120   }
4121 }
4122
4123 static void speculate_register_values(int i)
4124 {
4125   if(i==0) {
4126     memcpy(smrv,psxRegs.GPR.r,sizeof(smrv));
4127     // gp,sp are likely to stay the same throughout the block
4128     smrv_strong_next=(1<<28)|(1<<29)|(1<<30);
4129     smrv_weak_next=~smrv_strong_next;
4130     //printf(" llr %08x\n", smrv[4]);
4131   }
4132   smrv_strong=smrv_strong_next;
4133   smrv_weak=smrv_weak_next;
4134   switch(dops[i].itype) {
4135     case ALU:
4136       if     ((smrv_strong>>dops[i].rs1)&1) speculate_mov(dops[i].rs1,dops[i].rt1);
4137       else if((smrv_strong>>dops[i].rs2)&1) speculate_mov(dops[i].rs2,dops[i].rt1);
4138       else if((smrv_weak>>dops[i].rs1)&1) speculate_mov_weak(dops[i].rs1,dops[i].rt1);
4139       else if((smrv_weak>>dops[i].rs2)&1) speculate_mov_weak(dops[i].rs2,dops[i].rt1);
4140       else {
4141         smrv_strong_next&=~(1<<dops[i].rt1);
4142         smrv_weak_next&=~(1<<dops[i].rt1);
4143       }
4144       break;
4145     case SHIFTIMM:
4146       smrv_strong_next&=~(1<<dops[i].rt1);
4147       smrv_weak_next&=~(1<<dops[i].rt1);
4148       // fallthrough
4149     case IMM16:
4150       if(dops[i].rt1&&is_const(&regs[i],dops[i].rt1)) {
4151         int value,hr=get_reg(regs[i].regmap,dops[i].rt1);
4152         if(hr>=0) {
4153           if(get_final_value(hr,i,&value))
4154                smrv[dops[i].rt1]=value;
4155           else smrv[dops[i].rt1]=constmap[i][hr];
4156           smrv_strong_next|=1<<dops[i].rt1;
4157         }
4158       }
4159       else {
4160         if     ((smrv_strong>>dops[i].rs1)&1) speculate_mov(dops[i].rs1,dops[i].rt1);
4161         else if((smrv_weak>>dops[i].rs1)&1) speculate_mov_weak(dops[i].rs1,dops[i].rt1);
4162       }
4163       break;
4164     case LOAD:
4165       if(start<0x2000&&(dops[i].rt1==26||(smrv[dops[i].rt1]>>24)==0xa0)) {
4166         // special case for BIOS
4167         smrv[dops[i].rt1]=0xa0000000;
4168         smrv_strong_next|=1<<dops[i].rt1;
4169         break;
4170       }
4171       // fallthrough
4172     case SHIFT:
4173     case LOADLR:
4174     case MOV:
4175       smrv_strong_next&=~(1<<dops[i].rt1);
4176       smrv_weak_next&=~(1<<dops[i].rt1);
4177       break;
4178     case COP0:
4179     case COP2:
4180       if(dops[i].opcode2==0||dops[i].opcode2==2) { // MFC/CFC
4181         smrv_strong_next&=~(1<<dops[i].rt1);
4182         smrv_weak_next&=~(1<<dops[i].rt1);
4183       }
4184       break;
4185     case C2LS:
4186       if (dops[i].opcode==0x32) { // LWC2
4187         smrv_strong_next&=~(1<<dops[i].rt1);
4188         smrv_weak_next&=~(1<<dops[i].rt1);
4189       }
4190       break;
4191   }
4192 #if 0
4193   int r=4;
4194   printf("x %08x %08x %d %d c %08x %08x\n",smrv[r],start+i*4,
4195     ((smrv_strong>>r)&1),(smrv_weak>>r)&1,regs[i].isconst,regs[i].wasconst);
4196 #endif
4197 }
4198
4199 static void ujump_assemble(int i, const struct regstat *i_regs);
4200 static void rjump_assemble(int i, const struct regstat *i_regs);
4201 static void cjump_assemble(int i, const struct regstat *i_regs);
4202 static void sjump_assemble(int i, const struct regstat *i_regs);
4203
4204 static int assemble(int i, const struct regstat *i_regs, int ccadj_)
4205 {
4206   int ds = 0;
4207   switch (dops[i].itype) {
4208     case ALU:
4209       alu_assemble(i, i_regs);
4210       break;
4211     case IMM16:
4212       imm16_assemble(i, i_regs);
4213       break;
4214     case SHIFT:
4215       shift_assemble(i, i_regs);
4216       break;
4217     case SHIFTIMM:
4218       shiftimm_assemble(i, i_regs);
4219       break;
4220     case LOAD:
4221       load_assemble(i, i_regs, ccadj_);
4222       break;
4223     case LOADLR:
4224       loadlr_assemble(i, i_regs, ccadj_);
4225       break;
4226     case STORE:
4227       store_assemble(i, i_regs, ccadj_);
4228       break;
4229     case STORELR:
4230       storelr_assemble(i, i_regs, ccadj_);
4231       break;
4232     case COP0:
4233       cop0_assemble(i, i_regs, ccadj_);
4234       break;
4235     case COP1:
4236       cop1_assemble(i, i_regs);
4237       break;
4238     case C1LS:
4239       c1ls_assemble(i, i_regs);
4240       break;
4241     case COP2:
4242       cop2_assemble(i, i_regs);
4243       break;
4244     case C2LS:
4245       c2ls_assemble(i, i_regs, ccadj_);
4246       break;
4247     case C2OP:
4248       c2op_assemble(i, i_regs);
4249       break;
4250     case MULTDIV:
4251       multdiv_assemble(i, i_regs);
4252       multdiv_prepare_stall(i, i_regs, ccadj_);
4253       break;
4254     case MOV:
4255       mov_assemble(i, i_regs);
4256       break;
4257     case SYSCALL:
4258       syscall_assemble(i, i_regs, ccadj_);
4259       break;
4260     case HLECALL:
4261       hlecall_assemble(i, i_regs, ccadj_);
4262       break;
4263     case INTCALL:
4264       intcall_assemble(i, i_regs, ccadj_);
4265       break;
4266     case UJUMP:
4267       ujump_assemble(i, i_regs);
4268       ds = 1;
4269       break;
4270     case RJUMP:
4271       rjump_assemble(i, i_regs);
4272       ds = 1;
4273       break;
4274     case CJUMP:
4275       cjump_assemble(i, i_regs);
4276       ds = 1;
4277       break;
4278     case SJUMP:
4279       sjump_assemble(i, i_regs);
4280       ds = 1;
4281       break;
4282     case NOP:
4283     case OTHER:
4284     case NI:
4285       // not handled, just skip
4286       break;
4287     default:
4288       assert(0);
4289   }
4290   return ds;
4291 }
4292
4293 static void ds_assemble(int i, const struct regstat *i_regs)
4294 {
4295   speculate_register_values(i);
4296   is_delayslot = 1;
4297   switch (dops[i].itype) {
4298     case SYSCALL:
4299     case HLECALL:
4300     case INTCALL:
4301     case UJUMP:
4302     case RJUMP:
4303     case CJUMP:
4304     case SJUMP:
4305       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4306       break;
4307     default:
4308       assemble(i, i_regs, ccadj[i]);
4309   }
4310   is_delayslot = 0;
4311 }
4312
4313 // Is the branch target a valid internal jump?
4314 static int internal_branch(int addr)
4315 {
4316   if(addr&1) return 0; // Indirect (register) jump
4317   if(addr>=start && addr<start+slen*4-4)
4318   {
4319     return 1;
4320   }
4321   return 0;
4322 }
4323
4324 static void wb_invalidate(signed char pre[],signed char entry[],uint64_t dirty,uint64_t u)
4325 {
4326   int hr;
4327   for(hr=0;hr<HOST_REGS;hr++) {
4328     if(hr!=EXCLUDE_REG) {
4329       if(pre[hr]!=entry[hr]) {
4330         if(pre[hr]>=0) {
4331           if((dirty>>hr)&1) {
4332             if(get_reg(entry,pre[hr])<0) {
4333               assert(pre[hr]<64);
4334               if(!((u>>pre[hr])&1))
4335                 emit_storereg(pre[hr],hr);
4336             }
4337           }
4338         }
4339       }
4340     }
4341   }
4342   // Move from one register to another (no writeback)
4343   for(hr=0;hr<HOST_REGS;hr++) {
4344     if(hr!=EXCLUDE_REG) {
4345       if(pre[hr]!=entry[hr]) {
4346         if(pre[hr]>=0&&pre[hr]<TEMPREG) {
4347           int nr;
4348           if((nr=get_reg(entry,pre[hr]))>=0) {
4349             emit_mov(hr,nr);
4350           }
4351         }
4352       }
4353     }
4354   }
4355 }
4356
4357 // Load the specified registers
4358 // This only loads the registers given as arguments because
4359 // we don't want to load things that will be overwritten
4360 static inline void load_reg(signed char entry[], signed char regmap[], int rs)
4361 {
4362   int hr = get_reg(regmap, rs);
4363   if (hr >= 0 && entry[hr] != regmap[hr])
4364     emit_loadreg(regmap[hr], hr);
4365 }
4366
4367 static void load_regs(signed char entry[], signed char regmap[], int rs1, int rs2)
4368 {
4369   load_reg(entry, regmap, rs1);
4370   if (rs1 != rs2)
4371     load_reg(entry, regmap, rs2);
4372 }
4373
4374 // Load registers prior to the start of a loop
4375 // so that they are not loaded within the loop
4376 static void loop_preload(signed char pre[],signed char entry[])
4377 {
4378   int hr;
4379   for (hr = 0; hr < HOST_REGS; hr++) {
4380     int r = entry[hr];
4381     if (r >= 0 && pre[hr] != r && get_reg(pre, r) < 0) {
4382       assem_debug("loop preload:\n");
4383       if (r < TEMPREG)
4384         emit_loadreg(r, hr);
4385     }
4386   }
4387 }
4388
4389 // Generate address for load/store instruction
4390 // goes to AGEN for writes, FTEMP for LOADLR and cop1/2 loads
4391 static void address_generation(int i, const struct regstat *i_regs, signed char entry[])
4392 {
4393   if (dops[i].is_load || dops[i].is_store) {
4394     int ra=-1;
4395     int agr=AGEN1+(i&1);
4396     if(dops[i].itype==LOAD) {
4397       ra=get_reg(i_regs->regmap,dops[i].rt1);
4398       if(ra<0) ra=get_reg_temp(i_regs->regmap);
4399       assert(ra>=0);
4400     }
4401     if(dops[i].itype==LOADLR) {
4402       ra=get_reg(i_regs->regmap,FTEMP);
4403     }
4404     if(dops[i].itype==STORE||dops[i].itype==STORELR) {
4405       ra=get_reg(i_regs->regmap,agr);
4406       if(ra<0) ra=get_reg_temp(i_regs->regmap);
4407     }
4408     if(dops[i].itype==C2LS) {
4409       if ((dops[i].opcode&0x3b)==0x31||(dops[i].opcode&0x3b)==0x32) // LWC1/LDC1/LWC2/LDC2
4410         ra=get_reg(i_regs->regmap,FTEMP);
4411       else { // SWC1/SDC1/SWC2/SDC2
4412         ra=get_reg(i_regs->regmap,agr);
4413         if(ra<0) ra=get_reg_temp(i_regs->regmap);
4414       }
4415     }
4416     int rs=get_reg(i_regs->regmap,dops[i].rs1);
4417     if(ra>=0) {
4418       int offset=imm[i];
4419       int c=(i_regs->wasconst>>rs)&1;
4420       if(dops[i].rs1==0) {
4421         // Using r0 as a base address
4422         if(!entry||entry[ra]!=agr) {
4423           if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
4424             emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4425           }else if (dops[i].opcode==0x1a||dops[i].opcode==0x1b) {
4426             emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4427           }else{
4428             emit_movimm(offset,ra);
4429           }
4430         } // else did it in the previous cycle
4431       }
4432       else if(rs<0) {
4433         if(!entry||entry[ra]!=dops[i].rs1)
4434           emit_loadreg(dops[i].rs1,ra);
4435         //if(!entry||entry[ra]!=dops[i].rs1)
4436         //  printf("poor load scheduling!\n");
4437       }
4438       else if(c) {
4439         if(dops[i].rs1!=dops[i].rt1||dops[i].itype!=LOAD) {
4440           if(!entry||entry[ra]!=agr) {
4441             if (dops[i].opcode==0x22||dops[i].opcode==0x26) {
4442               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4443             }else if (dops[i].opcode==0x1a||dops[i].opcode==0x1b) {
4444               emit_movimm((constmap[i][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4445             }else{
4446               emit_movimm(constmap[i][rs]+offset,ra);
4447               regs[i].loadedconst|=1<<ra;
4448             }
4449           } // else did it in the previous cycle
4450         } // else load_consts already did it
4451       }
4452       if(offset&&!c&&dops[i].rs1) {
4453         if(rs>=0) {
4454           emit_addimm(rs,offset,ra);
4455         }else{
4456           emit_addimm(ra,offset,ra);
4457         }
4458       }
4459     }
4460   }
4461   // Preload constants for next instruction
4462   if (dops[i+1].is_load || dops[i+1].is_store) {
4463     int agr,ra;
4464     // Actual address
4465     agr=AGEN1+((i+1)&1);
4466     ra=get_reg(i_regs->regmap,agr);
4467     if(ra>=0) {
4468       int rs=get_reg(regs[i+1].regmap,dops[i+1].rs1);
4469       int offset=imm[i+1];
4470       int c=(regs[i+1].wasconst>>rs)&1;
4471       if(c&&(dops[i+1].rs1!=dops[i+1].rt1||dops[i+1].itype!=LOAD)) {
4472         if (dops[i+1].opcode==0x22||dops[i+1].opcode==0x26) {
4473           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFFC,ra); // LWL/LWR
4474         }else if (dops[i+1].opcode==0x1a||dops[i+1].opcode==0x1b) {
4475           emit_movimm((constmap[i+1][rs]+offset)&0xFFFFFFF8,ra); // LDL/LDR
4476         }else{
4477           emit_movimm(constmap[i+1][rs]+offset,ra);
4478           regs[i+1].loadedconst|=1<<ra;
4479         }
4480       }
4481       else if(dops[i+1].rs1==0) {
4482         // Using r0 as a base address
4483         if (dops[i+1].opcode==0x22||dops[i+1].opcode==0x26) {
4484           emit_movimm(offset&0xFFFFFFFC,ra); // LWL/LWR
4485         }else if (dops[i+1].opcode==0x1a||dops[i+1].opcode==0x1b) {
4486           emit_movimm(offset&0xFFFFFFF8,ra); // LDL/LDR
4487         }else{
4488           emit_movimm(offset,ra);
4489         }
4490       }
4491     }
4492   }
4493 }
4494
4495 static int get_final_value(int hr, int i, int *value)
4496 {
4497   int reg=regs[i].regmap[hr];
4498   while(i<slen-1) {
4499     if(regs[i+1].regmap[hr]!=reg) break;
4500     if(!((regs[i+1].isconst>>hr)&1)) break;
4501     if(dops[i+1].bt) break;
4502     i++;
4503   }
4504   if(i<slen-1) {
4505     if (dops[i].is_jump) {
4506       *value=constmap[i][hr];
4507       return 1;
4508     }
4509     if(!dops[i+1].bt) {
4510       if (dops[i+1].is_jump) {
4511         // Load in delay slot, out-of-order execution
4512         if(dops[i+2].itype==LOAD&&dops[i+2].rs1==reg&&dops[i+2].rt1==reg&&((regs[i+1].wasconst>>hr)&1))
4513         {
4514           // Precompute load address
4515           *value=constmap[i][hr]+imm[i+2];
4516           return 1;
4517         }
4518       }
4519       if(dops[i+1].itype==LOAD&&dops[i+1].rs1==reg&&dops[i+1].rt1==reg)
4520       {
4521         // Precompute load address
4522         *value=constmap[i][hr]+imm[i+1];
4523         //printf("c=%x imm=%lx\n",(long)constmap[i][hr],imm[i+1]);
4524         return 1;
4525       }
4526     }
4527   }
4528   *value=constmap[i][hr];
4529   //printf("c=%lx\n",(long)constmap[i][hr]);
4530   if(i==slen-1) return 1;
4531   assert(reg < 64);
4532   return !((unneeded_reg[i+1]>>reg)&1);
4533 }
4534
4535 // Load registers with known constants
4536 static void load_consts(signed char pre[],signed char regmap[],int i)
4537 {
4538   int hr,hr2;
4539   // propagate loaded constant flags
4540   if(i==0||dops[i].bt)
4541     regs[i].loadedconst=0;
4542   else {
4543     for(hr=0;hr<HOST_REGS;hr++) {
4544       if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((regs[i-1].isconst>>hr)&1)&&pre[hr]==regmap[hr]
4545          &&regmap[hr]==regs[i-1].regmap[hr]&&((regs[i-1].loadedconst>>hr)&1))
4546       {
4547         regs[i].loadedconst|=1<<hr;
4548       }
4549     }
4550   }
4551   // Load 32-bit regs
4552   for(hr=0;hr<HOST_REGS;hr++) {
4553     if(hr!=EXCLUDE_REG&&regmap[hr]>=0) {
4554       //if(entry[hr]!=regmap[hr]) {
4555       if(!((regs[i].loadedconst>>hr)&1)) {
4556         assert(regmap[hr]<64);
4557         if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4558           int value,similar=0;
4559           if(get_final_value(hr,i,&value)) {
4560             // see if some other register has similar value
4561             for(hr2=0;hr2<HOST_REGS;hr2++) {
4562               if(hr2!=EXCLUDE_REG&&((regs[i].loadedconst>>hr2)&1)) {
4563                 if(is_similar_value(value,constmap[i][hr2])) {
4564                   similar=1;
4565                   break;
4566                 }
4567               }
4568             }
4569             if(similar) {
4570               int value2;
4571               if(get_final_value(hr2,i,&value2)) // is this needed?
4572                 emit_movimm_from(value2,hr2,value,hr);
4573               else
4574                 emit_movimm(value,hr);
4575             }
4576             else if(value==0) {
4577               emit_zeroreg(hr);
4578             }
4579             else {
4580               emit_movimm(value,hr);
4581             }
4582           }
4583           regs[i].loadedconst|=1<<hr;
4584         }
4585       }
4586     }
4587   }
4588 }
4589
4590 static void load_all_consts(const signed char regmap[], u_int dirty, int i)
4591 {
4592   int hr;
4593   // Load 32-bit regs
4594   for(hr=0;hr<HOST_REGS;hr++) {
4595     if(hr!=EXCLUDE_REG&&regmap[hr]>=0&&((dirty>>hr)&1)) {
4596       assert(regmap[hr] < 64);
4597       if(((regs[i].isconst>>hr)&1)&&regmap[hr]>0) {
4598         int value=constmap[i][hr];
4599         if(value==0) {
4600           emit_zeroreg(hr);
4601         }
4602         else {
4603           emit_movimm(value,hr);
4604         }
4605       }
4606     }
4607   }
4608 }
4609
4610 // Write out all dirty registers (except cycle count)
4611 static void wb_dirtys(const signed char i_regmap[], uint64_t i_dirty)
4612 {
4613   int hr;
4614   for(hr=0;hr<HOST_REGS;hr++) {
4615     if(hr!=EXCLUDE_REG) {
4616       if(i_regmap[hr]>0) {
4617         if(i_regmap[hr]!=CCREG) {
4618           if((i_dirty>>hr)&1) {
4619             assert(i_regmap[hr]<64);
4620             emit_storereg(i_regmap[hr],hr);
4621           }
4622         }
4623       }
4624     }
4625   }
4626 }
4627
4628 // Write out dirty registers that we need to reload (pair with load_needed_regs)
4629 // This writes the registers not written by store_regs_bt
4630 static void wb_needed_dirtys(const signed char i_regmap[], uint64_t i_dirty, int addr)
4631 {
4632   int hr;
4633   int t=(addr-start)>>2;
4634   for(hr=0;hr<HOST_REGS;hr++) {
4635     if(hr!=EXCLUDE_REG) {
4636       if(i_regmap[hr]>0) {
4637         if(i_regmap[hr]!=CCREG) {
4638           if(i_regmap[hr]==regs[t].regmap_entry[hr] && ((regs[t].dirty>>hr)&1)) {
4639             if((i_dirty>>hr)&1) {
4640               assert(i_regmap[hr]<64);
4641               emit_storereg(i_regmap[hr],hr);
4642             }
4643           }
4644         }
4645       }
4646     }
4647   }
4648 }
4649
4650 // Load all registers (except cycle count)
4651 static void load_all_regs(const signed char i_regmap[])
4652 {
4653   int hr;
4654   for(hr=0;hr<HOST_REGS;hr++) {
4655     if(hr!=EXCLUDE_REG) {
4656       if(i_regmap[hr]==0) {
4657         emit_zeroreg(hr);
4658       }
4659       else
4660       if(i_regmap[hr]>0 && i_regmap[hr]<TEMPREG && i_regmap[hr]!=CCREG)
4661       {
4662         emit_loadreg(i_regmap[hr],hr);
4663       }
4664     }
4665   }
4666 }
4667
4668 // Load all current registers also needed by next instruction
4669 static void load_needed_regs(const signed char i_regmap[], const signed char next_regmap[])
4670 {
4671   int hr;
4672   for(hr=0;hr<HOST_REGS;hr++) {
4673     if(hr!=EXCLUDE_REG) {
4674       if(get_reg(next_regmap,i_regmap[hr])>=0) {
4675         if(i_regmap[hr]==0) {
4676           emit_zeroreg(hr);
4677         }
4678         else
4679         if(i_regmap[hr]>0 && i_regmap[hr]<TEMPREG && i_regmap[hr]!=CCREG)
4680         {
4681           emit_loadreg(i_regmap[hr],hr);
4682         }
4683       }
4684     }
4685   }
4686 }
4687
4688 // Load all regs, storing cycle count if necessary
4689 static void load_regs_entry(int t)
4690 {
4691   int hr;
4692   if(dops[t].is_ds) emit_addimm(HOST_CCREG,CLOCK_ADJUST(1),HOST_CCREG);
4693   else if(ccadj[t]) emit_addimm(HOST_CCREG,-ccadj[t],HOST_CCREG);
4694   if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4695     emit_storereg(CCREG,HOST_CCREG);
4696   }
4697   // Load 32-bit regs
4698   for(hr=0;hr<HOST_REGS;hr++) {
4699     if(regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4700       if(regs[t].regmap_entry[hr]==0) {
4701         emit_zeroreg(hr);
4702       }
4703       else if(regs[t].regmap_entry[hr]!=CCREG)
4704       {
4705         emit_loadreg(regs[t].regmap_entry[hr],hr);
4706       }
4707     }
4708   }
4709 }
4710
4711 // Store dirty registers prior to branch
4712 static void store_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4713 {
4714   if(internal_branch(addr))
4715   {
4716     int t=(addr-start)>>2;
4717     int hr;
4718     for(hr=0;hr<HOST_REGS;hr++) {
4719       if(hr!=EXCLUDE_REG) {
4720         if(i_regmap[hr]>0 && i_regmap[hr]!=CCREG) {
4721           if(i_regmap[hr]!=regs[t].regmap_entry[hr] || !((regs[t].dirty>>hr)&1)) {
4722             if((i_dirty>>hr)&1) {
4723               assert(i_regmap[hr]<64);
4724               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4725                 emit_storereg(i_regmap[hr],hr);
4726             }
4727           }
4728         }
4729       }
4730     }
4731   }
4732   else
4733   {
4734     // Branch out of this block, write out all dirty regs
4735     wb_dirtys(i_regmap,i_dirty);
4736   }
4737 }
4738
4739 // Load all needed registers for branch target
4740 static void load_regs_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4741 {
4742   //if(addr>=start && addr<(start+slen*4))
4743   if(internal_branch(addr))
4744   {
4745     int t=(addr-start)>>2;
4746     int hr;
4747     // Store the cycle count before loading something else
4748     if(i_regmap[HOST_CCREG]!=CCREG) {
4749       assert(i_regmap[HOST_CCREG]==-1);
4750     }
4751     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) {
4752       emit_storereg(CCREG,HOST_CCREG);
4753     }
4754     // Load 32-bit regs
4755     for(hr=0;hr<HOST_REGS;hr++) {
4756       if(hr!=EXCLUDE_REG&&regs[t].regmap_entry[hr]>=0&&regs[t].regmap_entry[hr]<TEMPREG) {
4757         if(i_regmap[hr]!=regs[t].regmap_entry[hr]) {
4758           if(regs[t].regmap_entry[hr]==0) {
4759             emit_zeroreg(hr);
4760           }
4761           else if(regs[t].regmap_entry[hr]!=CCREG)
4762           {
4763             emit_loadreg(regs[t].regmap_entry[hr],hr);
4764           }
4765         }
4766       }
4767     }
4768   }
4769 }
4770
4771 static int match_bt(signed char i_regmap[],uint64_t i_dirty,int addr)
4772 {
4773   if(addr>=start && addr<start+slen*4-4)
4774   {
4775     int t=(addr-start)>>2;
4776     int hr;
4777     if(regs[t].regmap_entry[HOST_CCREG]!=CCREG) return 0;
4778     for(hr=0;hr<HOST_REGS;hr++)
4779     {
4780       if(hr!=EXCLUDE_REG)
4781       {
4782         if(i_regmap[hr]!=regs[t].regmap_entry[hr])
4783         {
4784           if(regs[t].regmap_entry[hr]>=0&&(regs[t].regmap_entry[hr]|64)<TEMPREG+64)
4785           {
4786             return 0;
4787           }
4788           else
4789           if((i_dirty>>hr)&1)
4790           {
4791             if(i_regmap[hr]<TEMPREG)
4792             {
4793               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4794                 return 0;
4795             }
4796             else if(i_regmap[hr]>=64&&i_regmap[hr]<TEMPREG+64)
4797             {
4798               assert(0);
4799             }
4800           }
4801         }
4802         else // Same register but is it 32-bit or dirty?
4803         if(i_regmap[hr]>=0)
4804         {
4805           if(!((regs[t].dirty>>hr)&1))
4806           {
4807             if((i_dirty>>hr)&1)
4808             {
4809               if(!((unneeded_reg[t]>>i_regmap[hr])&1))
4810               {
4811                 //printf("%x: dirty no match\n",addr);
4812                 return 0;
4813               }
4814             }
4815           }
4816         }
4817       }
4818     }
4819     // Delay slots are not valid branch targets
4820     //if(t>0&&(dops[t-1].is_jump) return 0;
4821     // Delay slots require additional processing, so do not match
4822     if(dops[t].is_ds) return 0;
4823   }
4824   else
4825   {
4826     int hr;
4827     for(hr=0;hr<HOST_REGS;hr++)
4828     {
4829       if(hr!=EXCLUDE_REG)
4830       {
4831         if(i_regmap[hr]>=0)
4832         {
4833           if(hr!=HOST_CCREG||i_regmap[hr]!=CCREG)
4834           {
4835             if((i_dirty>>hr)&1)
4836             {
4837               return 0;
4838             }
4839           }
4840         }
4841       }
4842     }
4843   }
4844   return 1;
4845 }
4846
4847 #ifdef DRC_DBG
4848 static void drc_dbg_emit_do_cmp(int i, int ccadj_)
4849 {
4850   extern void do_insn_cmp();
4851   //extern int cycle;
4852   u_int hr, reglist = get_host_reglist(regs[i].regmap);
4853
4854   assem_debug("//do_insn_cmp %08x\n", start+i*4);
4855   save_regs(reglist);
4856   // write out changed consts to match the interpreter
4857   if (i > 0 && !dops[i].bt) {
4858     for (hr = 0; hr < HOST_REGS; hr++) {
4859       int reg = regs[i].regmap_entry[hr]; // regs[i-1].regmap[hr];
4860       if (hr == EXCLUDE_REG || reg < 0)
4861         continue;
4862       if (!((regs[i-1].isconst >> hr) & 1))
4863         continue;
4864       if (i > 1 && reg == regs[i-2].regmap[hr] && constmap[i-1][hr] == constmap[i-2][hr])
4865         continue;
4866       emit_movimm(constmap[i-1][hr],0);
4867       emit_storereg(reg, 0);
4868     }
4869   }
4870   emit_movimm(start+i*4,0);
4871   emit_writeword(0,&pcaddr);
4872   int cc = get_reg(regs[i].regmap_entry, CCREG);
4873   if (cc < 0)
4874     emit_loadreg(CCREG, cc = 0);
4875   emit_addimm(cc, ccadj_, 0);
4876   emit_writeword(0, &psxRegs.cycle);
4877   emit_far_call(do_insn_cmp);
4878   //emit_readword(&cycle,0);
4879   //emit_addimm(0,2,0);
4880   //emit_writeword(0,&cycle);
4881   (void)get_reg2;
4882   restore_regs(reglist);
4883   assem_debug("\\\\do_insn_cmp\n");
4884 }
4885 #else
4886 #define drc_dbg_emit_do_cmp(x,y)
4887 #endif
4888
4889 // Used when a branch jumps into the delay slot of another branch
4890 static void ds_assemble_entry(int i)
4891 {
4892   int t = (ba[i] - start) >> 2;
4893   int ccadj_ = -CLOCK_ADJUST(1);
4894   if (!instr_addr[t])
4895     instr_addr[t] = out;
4896   assem_debug("Assemble delay slot at %x\n",ba[i]);
4897   assem_debug("<->\n");
4898   drc_dbg_emit_do_cmp(t, ccadj_);
4899   if(regs[t].regmap_entry[HOST_CCREG]==CCREG&&regs[t].regmap[HOST_CCREG]!=CCREG)
4900     wb_register(CCREG,regs[t].regmap_entry,regs[t].wasdirty);
4901   load_regs(regs[t].regmap_entry,regs[t].regmap,dops[t].rs1,dops[t].rs2);
4902   address_generation(t,&regs[t],regs[t].regmap_entry);
4903   if (ram_offset && (dops[t].is_load || dops[t].is_store))
4904     load_reg(regs[t].regmap_entry,regs[t].regmap,ROREG);
4905   if (dops[t].is_store)
4906     load_reg(regs[t].regmap_entry,regs[t].regmap,INVCP);
4907   is_delayslot=0;
4908   switch (dops[t].itype) {
4909     case SYSCALL:
4910     case HLECALL:
4911     case INTCALL:
4912     case UJUMP:
4913     case RJUMP:
4914     case CJUMP:
4915     case SJUMP:
4916       SysPrintf("Jump in the delay slot.  This is probably a bug.\n");
4917       break;
4918     default:
4919       assemble(t, &regs[t], ccadj_);
4920   }
4921   store_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4922   load_regs_bt(regs[t].regmap,regs[t].dirty,ba[i]+4);
4923   if(internal_branch(ba[i]+4))
4924     assem_debug("branch: internal\n");
4925   else
4926     assem_debug("branch: external\n");
4927   assert(internal_branch(ba[i]+4));
4928   add_to_linker(out,ba[i]+4,internal_branch(ba[i]+4));
4929   emit_jmp(0);
4930 }
4931
4932 // Load 2 immediates optimizing for small code size
4933 static void emit_mov2imm_compact(int imm1,u_int rt1,int imm2,u_int rt2)
4934 {
4935   emit_movimm(imm1,rt1);
4936   emit_movimm_from(imm1,rt1,imm2,rt2);
4937 }
4938
4939 static void do_cc(int i, const signed char i_regmap[], int *adj,
4940   int addr, int taken, int invert)
4941 {
4942   int count, count_plus2;
4943   void *jaddr;
4944   void *idle=NULL;
4945   int t=0;
4946   if(dops[i].itype==RJUMP)
4947   {
4948     *adj=0;
4949   }
4950   //if(ba[i]>=start && ba[i]<(start+slen*4))
4951   if(internal_branch(ba[i]))
4952   {
4953     t=(ba[i]-start)>>2;
4954     if(dops[t].is_ds) *adj=-CLOCK_ADJUST(1); // Branch into delay slot adds an extra cycle
4955     else *adj=ccadj[t];
4956   }
4957   else
4958   {
4959     *adj=0;
4960   }
4961   count = ccadj[i];
4962   count_plus2 = count + CLOCK_ADJUST(2);
4963   if(taken==TAKEN && i==(ba[i]-start)>>2 && source[i+1]==0) {
4964     // Idle loop
4965     if(count&1) emit_addimm_and_set_flags(2*(count+2),HOST_CCREG);
4966     idle=out;
4967     //emit_subfrommem(&idlecount,HOST_CCREG); // Count idle cycles
4968     emit_andimm(HOST_CCREG,3,HOST_CCREG);
4969     jaddr=out;
4970     emit_jmp(0);
4971   }
4972   else if(*adj==0||invert) {
4973     int cycles = count_plus2;
4974     // faster loop HACK
4975 #if 0
4976     if (t&&*adj) {
4977       int rel=t-i;
4978       if(-NO_CYCLE_PENALTY_THR<rel&&rel<0)
4979         cycles=*adj+count+2-*adj;
4980     }
4981 #endif
4982     emit_addimm_and_set_flags(cycles, HOST_CCREG);
4983     jaddr = out;
4984     emit_jns(0);
4985   }
4986   else
4987   {
4988     emit_cmpimm(HOST_CCREG, -count_plus2);
4989     jaddr = out;
4990     emit_jns(0);
4991   }
4992   add_stub(CC_STUB,jaddr,idle?idle:out,(*adj==0||invert||idle)?0:count_plus2,i,addr,taken,0);
4993 }
4994
4995 static void do_ccstub(int n)
4996 {
4997   literal_pool(256);
4998   assem_debug("do_ccstub %x\n",start+(u_int)stubs[n].b*4);
4999   set_jump_target(stubs[n].addr, out);
5000   int i=stubs[n].b;
5001   if(stubs[n].d==NULLDS) {
5002     // Delay slot instruction is nullified ("likely" branch)
5003     wb_dirtys(regs[i].regmap,regs[i].dirty);
5004   }
5005   else if(stubs[n].d!=TAKEN) {
5006     wb_dirtys(branch_regs[i].regmap,branch_regs[i].dirty);
5007   }
5008   else {
5009     if(internal_branch(ba[i]))
5010       wb_needed_dirtys(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5011   }
5012   if(stubs[n].c!=-1)
5013   {
5014     // Save PC as return address
5015     emit_movimm(stubs[n].c,EAX);
5016     emit_writeword(EAX,&pcaddr);
5017   }
5018   else
5019   {
5020     // Return address depends on which way the branch goes
5021     if(dops[i].itype==CJUMP||dops[i].itype==SJUMP)
5022     {
5023       int s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5024       int s2l=get_reg(branch_regs[i].regmap,dops[i].rs2);
5025       if(dops[i].rs1==0)
5026       {
5027         s1l=s2l;
5028         s2l=-1;
5029       }
5030       else if(dops[i].rs2==0)
5031       {
5032         s2l=-1;
5033       }
5034       assert(s1l>=0);
5035       #ifdef DESTRUCTIVE_WRITEBACK
5036       if(dops[i].rs1) {
5037         if((branch_regs[i].dirty>>s1l)&&1)
5038           emit_loadreg(dops[i].rs1,s1l);
5039       }
5040       else {
5041         if((branch_regs[i].dirty>>s1l)&1)
5042           emit_loadreg(dops[i].rs2,s1l);
5043       }
5044       if(s2l>=0)
5045         if((branch_regs[i].dirty>>s2l)&1)
5046           emit_loadreg(dops[i].rs2,s2l);
5047       #endif
5048       int hr=0;
5049       int addr=-1,alt=-1,ntaddr=-1;
5050       while(hr<HOST_REGS)
5051       {
5052         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5053            branch_regs[i].regmap[hr]!=dops[i].rs1 &&
5054            branch_regs[i].regmap[hr]!=dops[i].rs2 )
5055         {
5056           addr=hr++;break;
5057         }
5058         hr++;
5059       }
5060       while(hr<HOST_REGS)
5061       {
5062         if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5063            branch_regs[i].regmap[hr]!=dops[i].rs1 &&
5064            branch_regs[i].regmap[hr]!=dops[i].rs2 )
5065         {
5066           alt=hr++;break;
5067         }
5068         hr++;
5069       }
5070       if((dops[i].opcode&0x2E)==6) // BLEZ/BGTZ needs another register
5071       {
5072         while(hr<HOST_REGS)
5073         {
5074           if(hr!=EXCLUDE_REG && hr!=HOST_CCREG &&
5075              branch_regs[i].regmap[hr]!=dops[i].rs1 &&
5076              branch_regs[i].regmap[hr]!=dops[i].rs2 )
5077           {
5078             ntaddr=hr;break;
5079           }
5080           hr++;
5081         }
5082         assert(hr<HOST_REGS);
5083       }
5084       if((dops[i].opcode&0x2f)==4) // BEQ
5085       {
5086         #ifdef HAVE_CMOV_IMM
5087         if(s2l>=0) emit_cmp(s1l,s2l);
5088         else emit_test(s1l,s1l);
5089         emit_cmov2imm_e_ne_compact(ba[i],start+i*4+8,addr);
5090         #else
5091         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5092         if(s2l>=0) emit_cmp(s1l,s2l);
5093         else emit_test(s1l,s1l);
5094         emit_cmovne_reg(alt,addr);
5095         #endif
5096       }
5097       if((dops[i].opcode&0x2f)==5) // BNE
5098       {
5099         #ifdef HAVE_CMOV_IMM
5100         if(s2l>=0) emit_cmp(s1l,s2l);
5101         else emit_test(s1l,s1l);
5102         emit_cmov2imm_e_ne_compact(start+i*4+8,ba[i],addr);
5103         #else
5104         emit_mov2imm_compact(start+i*4+8,addr,ba[i],alt);
5105         if(s2l>=0) emit_cmp(s1l,s2l);
5106         else emit_test(s1l,s1l);
5107         emit_cmovne_reg(alt,addr);
5108         #endif
5109       }
5110       if((dops[i].opcode&0x2f)==6) // BLEZ
5111       {
5112         //emit_movimm(ba[i],alt);
5113         //emit_movimm(start+i*4+8,addr);
5114         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5115         emit_cmpimm(s1l,1);
5116         emit_cmovl_reg(alt,addr);
5117       }
5118       if((dops[i].opcode&0x2f)==7) // BGTZ
5119       {
5120         //emit_movimm(ba[i],addr);
5121         //emit_movimm(start+i*4+8,ntaddr);
5122         emit_mov2imm_compact(ba[i],addr,start+i*4+8,ntaddr);
5123         emit_cmpimm(s1l,1);
5124         emit_cmovl_reg(ntaddr,addr);
5125       }
5126       if((dops[i].opcode==1)&&(dops[i].opcode2&0x2D)==0) // BLTZ
5127       {
5128         //emit_movimm(ba[i],alt);
5129         //emit_movimm(start+i*4+8,addr);
5130         emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5131         emit_test(s1l,s1l);
5132         emit_cmovs_reg(alt,addr);
5133       }
5134       if((dops[i].opcode==1)&&(dops[i].opcode2&0x2D)==1) // BGEZ
5135       {
5136         //emit_movimm(ba[i],addr);
5137         //emit_movimm(start+i*4+8,alt);
5138         emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5139         emit_test(s1l,s1l);
5140         emit_cmovs_reg(alt,addr);
5141       }
5142       if(dops[i].opcode==0x11 && dops[i].opcode2==0x08 ) {
5143         if(source[i]&0x10000) // BC1T
5144         {
5145           //emit_movimm(ba[i],alt);
5146           //emit_movimm(start+i*4+8,addr);
5147           emit_mov2imm_compact(ba[i],alt,start+i*4+8,addr);
5148           emit_testimm(s1l,0x800000);
5149           emit_cmovne_reg(alt,addr);
5150         }
5151         else // BC1F
5152         {
5153           //emit_movimm(ba[i],addr);
5154           //emit_movimm(start+i*4+8,alt);
5155           emit_mov2imm_compact(ba[i],addr,start+i*4+8,alt);
5156           emit_testimm(s1l,0x800000);
5157           emit_cmovne_reg(alt,addr);
5158         }
5159       }
5160       emit_writeword(addr,&pcaddr);
5161     }
5162     else
5163     if(dops[i].itype==RJUMP)
5164     {
5165       int r=get_reg(branch_regs[i].regmap,dops[i].rs1);
5166       if (ds_writes_rjump_rs(i)) {
5167         r=get_reg(branch_regs[i].regmap,RTEMP);
5168       }
5169       emit_writeword(r,&pcaddr);
5170     }
5171     else {SysPrintf("Unknown branch type in do_ccstub\n");abort();}
5172   }
5173   // Update cycle count
5174   assert(branch_regs[i].regmap[HOST_CCREG]==CCREG||branch_regs[i].regmap[HOST_CCREG]==-1);
5175   if(stubs[n].a) emit_addimm(HOST_CCREG,(int)stubs[n].a,HOST_CCREG);
5176   emit_far_call(cc_interrupt);
5177   if(stubs[n].a) emit_addimm(HOST_CCREG,-(int)stubs[n].a,HOST_CCREG);
5178   if(stubs[n].d==TAKEN) {
5179     if(internal_branch(ba[i]))
5180       load_needed_regs(branch_regs[i].regmap,regs[(ba[i]-start)>>2].regmap_entry);
5181     else if(dops[i].itype==RJUMP) {
5182       if(get_reg(branch_regs[i].regmap,RTEMP)>=0)
5183         emit_readword(&pcaddr,get_reg(branch_regs[i].regmap,RTEMP));
5184       else
5185         emit_loadreg(dops[i].rs1,get_reg(branch_regs[i].regmap,dops[i].rs1));
5186     }
5187   }else if(stubs[n].d==NOTTAKEN) {
5188     if(i<slen-2) load_needed_regs(branch_regs[i].regmap,regmap_pre[i+2]);
5189     else load_all_regs(branch_regs[i].regmap);
5190   }else if(stubs[n].d==NULLDS) {
5191     // Delay slot instruction is nullified ("likely" branch)
5192     if(i<slen-2) load_needed_regs(regs[i].regmap,regmap_pre[i+2]);
5193     else load_all_regs(regs[i].regmap);
5194   }else{
5195     load_all_regs(branch_regs[i].regmap);
5196   }
5197   if (stubs[n].retaddr)
5198     emit_jmp(stubs[n].retaddr);
5199   else
5200     do_jump_vaddr(stubs[n].e);
5201 }
5202
5203 static void add_to_linker(void *addr, u_int target, int is_internal)
5204 {
5205   assert(linkcount < ARRAY_SIZE(link_addr));
5206   link_addr[linkcount].addr = addr;
5207   link_addr[linkcount].target = target;
5208   link_addr[linkcount].internal = is_internal;
5209   linkcount++;
5210 }
5211
5212 static void ujump_assemble_write_ra(int i)
5213 {
5214   int rt;
5215   unsigned int return_address;
5216   rt=get_reg(branch_regs[i].regmap,31);
5217   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]);
5218   //assert(rt>=0);
5219   return_address=start+i*4+8;
5220   if(rt>=0) {
5221     #ifdef USE_MINI_HT
5222     if(internal_branch(return_address)&&dops[i+1].rt1!=31) {
5223       int temp=-1; // note: must be ds-safe
5224       #ifdef HOST_TEMPREG
5225       temp=HOST_TEMPREG;
5226       #endif
5227       if(temp>=0) do_miniht_insert(return_address,rt,temp);
5228       else emit_movimm(return_address,rt);
5229     }
5230     else
5231     #endif
5232     {
5233       #ifdef REG_PREFETCH
5234       if(temp>=0)
5235       {
5236         if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5237       }
5238       #endif
5239       emit_movimm(return_address,rt); // PC into link register
5240       #ifdef IMM_PREFETCH
5241       emit_prefetch(hash_table_get(return_address));
5242       #endif
5243     }
5244   }
5245 }
5246
5247 static void ujump_assemble(int i, const struct regstat *i_regs)
5248 {
5249   int ra_done=0;
5250   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5251   address_generation(i+1,i_regs,regs[i].regmap_entry);
5252   #ifdef REG_PREFETCH
5253   int temp=get_reg(branch_regs[i].regmap,PTEMP);
5254   if(dops[i].rt1==31&&temp>=0)
5255   {
5256     signed char *i_regmap=i_regs->regmap;
5257     int return_address=start+i*4+8;
5258     if(get_reg(branch_regs[i].regmap,31)>0)
5259     if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5260   }
5261   #endif
5262   if(dops[i].rt1==31&&(dops[i].rt1==dops[i+1].rs1||dops[i].rt1==dops[i+1].rs2)) {
5263     ujump_assemble_write_ra(i); // writeback ra for DS
5264     ra_done=1;
5265   }
5266   ds_assemble(i+1,i_regs);
5267   uint64_t bc_unneeded=branch_regs[i].u;
5268   bc_unneeded|=1|(1LL<<dops[i].rt1);
5269   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5270   load_reg(regs[i].regmap,branch_regs[i].regmap,CCREG);
5271   if(!ra_done&&dops[i].rt1==31)
5272     ujump_assemble_write_ra(i);
5273   int cc,adj;
5274   cc=get_reg(branch_regs[i].regmap,CCREG);
5275   assert(cc==HOST_CCREG);
5276   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5277   #ifdef REG_PREFETCH
5278   if(dops[i].rt1==31&&temp>=0) emit_prefetchreg(temp);
5279   #endif
5280   do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5281   if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5282   load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5283   if(internal_branch(ba[i]))
5284     assem_debug("branch: internal\n");
5285   else
5286     assem_debug("branch: external\n");
5287   if (internal_branch(ba[i]) && dops[(ba[i]-start)>>2].is_ds) {
5288     ds_assemble_entry(i);
5289   }
5290   else {
5291     add_to_linker(out,ba[i],internal_branch(ba[i]));
5292     emit_jmp(0);
5293   }
5294 }
5295
5296 static void rjump_assemble_write_ra(int i)
5297 {
5298   int rt,return_address;
5299   assert(dops[i+1].rt1!=dops[i].rt1);
5300   assert(dops[i+1].rt2!=dops[i].rt1);
5301   rt=get_reg(branch_regs[i].regmap,dops[i].rt1);
5302   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]);
5303   assert(rt>=0);
5304   return_address=start+i*4+8;
5305   #ifdef REG_PREFETCH
5306   if(temp>=0)
5307   {
5308     if(i_regmap[temp]!=PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5309   }
5310   #endif
5311   emit_movimm(return_address,rt); // PC into link register
5312   #ifdef IMM_PREFETCH
5313   emit_prefetch(hash_table_get(return_address));
5314   #endif
5315 }
5316
5317 static void rjump_assemble(int i, const struct regstat *i_regs)
5318 {
5319   int temp;
5320   int rs,cc;
5321   int ra_done=0;
5322   rs=get_reg(branch_regs[i].regmap,dops[i].rs1);
5323   assert(rs>=0);
5324   if (ds_writes_rjump_rs(i)) {
5325     // Delay slot abuse, make a copy of the branch address register
5326     temp=get_reg(branch_regs[i].regmap,RTEMP);
5327     assert(temp>=0);
5328     assert(regs[i].regmap[temp]==RTEMP);
5329     emit_mov(rs,temp);
5330     rs=temp;
5331   }
5332   address_generation(i+1,i_regs,regs[i].regmap_entry);
5333   #ifdef REG_PREFETCH
5334   if(dops[i].rt1==31)
5335   {
5336     if((temp=get_reg(branch_regs[i].regmap,PTEMP))>=0) {
5337       signed char *i_regmap=i_regs->regmap;
5338       int return_address=start+i*4+8;
5339       if(i_regmap[temp]==PTEMP) emit_movimm((uintptr_t)hash_table_get(return_address),temp);
5340     }
5341   }
5342   #endif
5343   #ifdef USE_MINI_HT
5344   if(dops[i].rs1==31) {
5345     int rh=get_reg(regs[i].regmap,RHASH);
5346     if(rh>=0) do_preload_rhash(rh);
5347   }
5348   #endif
5349   if(dops[i].rt1!=0&&(dops[i].rt1==dops[i+1].rs1||dops[i].rt1==dops[i+1].rs2)) {
5350     rjump_assemble_write_ra(i);
5351     ra_done=1;
5352   }
5353   ds_assemble(i+1,i_regs);
5354   uint64_t bc_unneeded=branch_regs[i].u;
5355   bc_unneeded|=1|(1LL<<dops[i].rt1);
5356   bc_unneeded&=~(1LL<<dops[i].rs1);
5357   wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5358   load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,CCREG);
5359   if(!ra_done&&dops[i].rt1!=0)
5360     rjump_assemble_write_ra(i);
5361   cc=get_reg(branch_regs[i].regmap,CCREG);
5362   assert(cc==HOST_CCREG);
5363   (void)cc;
5364   #ifdef USE_MINI_HT
5365   int rh=get_reg(branch_regs[i].regmap,RHASH);
5366   int ht=get_reg(branch_regs[i].regmap,RHTBL);
5367   if(dops[i].rs1==31) {
5368     if(regs[i].regmap[rh]!=RHASH) do_preload_rhash(rh);
5369     do_preload_rhtbl(ht);
5370     do_rhash(rs,rh);
5371   }
5372   #endif
5373   store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5374   #ifdef DESTRUCTIVE_WRITEBACK
5375   if((branch_regs[i].dirty>>rs)&1) {
5376     if(dops[i].rs1!=dops[i+1].rt1&&dops[i].rs1!=dops[i+1].rt2) {
5377       emit_loadreg(dops[i].rs1,rs);
5378     }
5379   }
5380   #endif
5381   #ifdef REG_PREFETCH
5382   if(dops[i].rt1==31&&temp>=0) emit_prefetchreg(temp);
5383   #endif
5384   #ifdef USE_MINI_HT
5385   if(dops[i].rs1==31) {
5386     do_miniht_load(ht,rh);
5387   }
5388   #endif
5389   //do_cc(i,branch_regs[i].regmap,&adj,-1,TAKEN);
5390   //if(adj) emit_addimm(cc,2*(ccadj[i]+2-adj),cc); // ??? - Shouldn't happen
5391   //assert(adj==0);
5392   emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
5393   add_stub(CC_STUB,out,NULL,0,i,-1,TAKEN,rs);
5394   if(dops[i+1].itype==COP0 && dops[i+1].opcode2==0x10)
5395     // special case for RFE
5396     emit_jmp(0);
5397   else
5398     emit_jns(0);
5399   //load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,-1);
5400   #ifdef USE_MINI_HT
5401   if(dops[i].rs1==31) {
5402     do_miniht_jump(rs,rh,ht);
5403   }
5404   else
5405   #endif
5406   {
5407     do_jump_vaddr(rs);
5408   }
5409   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5410   if(dops[i].rt1!=31&&i<slen-2&&(((u_int)out)&7)) emit_mov(13,13);
5411   #endif
5412 }
5413
5414 static void cjump_assemble(int i, const struct regstat *i_regs)
5415 {
5416   const signed char *i_regmap = i_regs->regmap;
5417   int cc;
5418   int match;
5419   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5420   assem_debug("match=%d\n",match);
5421   int s1l,s2l;
5422   int unconditional=0,nop=0;
5423   int invert=0;
5424   int internal=internal_branch(ba[i]);
5425   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5426   if(!match) invert=1;
5427   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5428   if(i>(ba[i]-start)>>2) invert=1;
5429   #endif
5430   #ifdef __aarch64__
5431   invert=1; // because of near cond. branches
5432   #endif
5433
5434   if(dops[i].ooo) {
5435     s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5436     s2l=get_reg(branch_regs[i].regmap,dops[i].rs2);
5437   }
5438   else {
5439     s1l=get_reg(i_regmap,dops[i].rs1);
5440     s2l=get_reg(i_regmap,dops[i].rs2);
5441   }
5442   if(dops[i].rs1==0&&dops[i].rs2==0)
5443   {
5444     if(dops[i].opcode&1) nop=1;
5445     else unconditional=1;
5446     //assert(dops[i].opcode!=5);
5447     //assert(dops[i].opcode!=7);
5448     //assert(dops[i].opcode!=0x15);
5449     //assert(dops[i].opcode!=0x17);
5450   }
5451   else if(dops[i].rs1==0)
5452   {
5453     s1l=s2l;
5454     s2l=-1;
5455   }
5456   else if(dops[i].rs2==0)
5457   {
5458     s2l=-1;
5459   }
5460
5461   if(dops[i].ooo) {
5462     // Out of order execution (delay slot first)
5463     //printf("OOOE\n");
5464     address_generation(i+1,i_regs,regs[i].regmap_entry);
5465     ds_assemble(i+1,i_regs);
5466     int adj;
5467     uint64_t bc_unneeded=branch_regs[i].u;
5468     bc_unneeded&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
5469     bc_unneeded|=1;
5470     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5471     load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,dops[i].rs2);
5472     load_reg(regs[i].regmap,branch_regs[i].regmap,CCREG);
5473     cc=get_reg(branch_regs[i].regmap,CCREG);
5474     assert(cc==HOST_CCREG);
5475     if(unconditional)
5476       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5477     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5478     //assem_debug("cycle count (adj)\n");
5479     if(unconditional) {
5480       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5481       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5482         if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5483         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5484         if(internal)
5485           assem_debug("branch: internal\n");
5486         else
5487           assem_debug("branch: external\n");
5488         if (internal && dops[(ba[i]-start)>>2].is_ds) {
5489           ds_assemble_entry(i);
5490         }
5491         else {
5492           add_to_linker(out,ba[i],internal);
5493           emit_jmp(0);
5494         }
5495         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5496         if(((u_int)out)&7) emit_addnop(0);
5497         #endif
5498       }
5499     }
5500     else if(nop) {
5501       emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5502       void *jaddr=out;
5503       emit_jns(0);
5504       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5505     }
5506     else {
5507       void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5508       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5509       if(adj&&!invert) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5510
5511       //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]);
5512       assert(s1l>=0);
5513       if(dops[i].opcode==4) // BEQ
5514       {
5515         if(s2l>=0) emit_cmp(s1l,s2l);
5516         else emit_test(s1l,s1l);
5517         if(invert){
5518           nottaken=out;
5519           emit_jne(DJT_1);
5520         }else{
5521           add_to_linker(out,ba[i],internal);
5522           emit_jeq(0);
5523         }
5524       }
5525       if(dops[i].opcode==5) // BNE
5526       {
5527         if(s2l>=0) emit_cmp(s1l,s2l);
5528         else emit_test(s1l,s1l);
5529         if(invert){
5530           nottaken=out;
5531           emit_jeq(DJT_1);
5532         }else{
5533           add_to_linker(out,ba[i],internal);
5534           emit_jne(0);
5535         }
5536       }
5537       if(dops[i].opcode==6) // BLEZ
5538       {
5539         emit_cmpimm(s1l,1);
5540         if(invert){
5541           nottaken=out;
5542           emit_jge(DJT_1);
5543         }else{
5544           add_to_linker(out,ba[i],internal);
5545           emit_jl(0);
5546         }
5547       }
5548       if(dops[i].opcode==7) // BGTZ
5549       {
5550         emit_cmpimm(s1l,1);
5551         if(invert){
5552           nottaken=out;
5553           emit_jl(DJT_1);
5554         }else{
5555           add_to_linker(out,ba[i],internal);
5556           emit_jge(0);
5557         }
5558       }
5559       if(invert) {
5560         if(taken) set_jump_target(taken, out);
5561         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5562         if (match && (!internal || !dops[(ba[i]-start)>>2].is_ds)) {
5563           if(adj) {
5564             emit_addimm(cc,-adj,cc);
5565             add_to_linker(out,ba[i],internal);
5566           }else{
5567             emit_addnop(13);
5568             add_to_linker(out,ba[i],internal*2);
5569           }
5570           emit_jmp(0);
5571         }else
5572         #endif
5573         {
5574           if(adj) emit_addimm(cc,-adj,cc);
5575           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5576           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5577           if(internal)
5578             assem_debug("branch: internal\n");
5579           else
5580             assem_debug("branch: external\n");
5581           if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5582             ds_assemble_entry(i);
5583           }
5584           else {
5585             add_to_linker(out,ba[i],internal);
5586             emit_jmp(0);
5587           }
5588         }
5589         set_jump_target(nottaken, out);
5590       }
5591
5592       if(nottaken1) set_jump_target(nottaken1, out);
5593       if(adj) {
5594         if(!invert) emit_addimm(cc,adj,cc);
5595       }
5596     } // (!unconditional)
5597   } // if(ooo)
5598   else
5599   {
5600     // In-order execution (branch first)
5601     void *taken = NULL, *nottaken = NULL, *nottaken1 = NULL;
5602     if(!unconditional&&!nop) {
5603       //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]);
5604       assert(s1l>=0);
5605       if((dops[i].opcode&0x2f)==4) // BEQ
5606       {
5607         if(s2l>=0) emit_cmp(s1l,s2l);
5608         else emit_test(s1l,s1l);
5609         nottaken=out;
5610         emit_jne(DJT_2);
5611       }
5612       if((dops[i].opcode&0x2f)==5) // BNE
5613       {
5614         if(s2l>=0) emit_cmp(s1l,s2l);
5615         else emit_test(s1l,s1l);
5616         nottaken=out;
5617         emit_jeq(DJT_2);
5618       }
5619       if((dops[i].opcode&0x2f)==6) // BLEZ
5620       {
5621         emit_cmpimm(s1l,1);
5622         nottaken=out;
5623         emit_jge(DJT_2);
5624       }
5625       if((dops[i].opcode&0x2f)==7) // BGTZ
5626       {
5627         emit_cmpimm(s1l,1);
5628         nottaken=out;
5629         emit_jl(DJT_2);
5630       }
5631     } // if(!unconditional)
5632     int adj;
5633     uint64_t ds_unneeded=branch_regs[i].u;
5634     ds_unneeded&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
5635     ds_unneeded|=1;
5636     // branch taken
5637     if(!nop) {
5638       if(taken) set_jump_target(taken, out);
5639       assem_debug("1:\n");
5640       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5641       // load regs
5642       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5643       address_generation(i+1,&branch_regs[i],0);
5644       if (ram_offset)
5645         load_reg(regs[i].regmap,branch_regs[i].regmap,ROREG);
5646       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5647       ds_assemble(i+1,&branch_regs[i]);
5648       cc=get_reg(branch_regs[i].regmap,CCREG);
5649       if(cc==-1) {
5650         emit_loadreg(CCREG,cc=HOST_CCREG);
5651         // CHECK: Is the following instruction (fall thru) allocated ok?
5652       }
5653       assert(cc==HOST_CCREG);
5654       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5655       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5656       assem_debug("cycle count (adj)\n");
5657       if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5658       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5659       if(internal)
5660         assem_debug("branch: internal\n");
5661       else
5662         assem_debug("branch: external\n");
5663       if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5664         ds_assemble_entry(i);
5665       }
5666       else {
5667         add_to_linker(out,ba[i],internal);
5668         emit_jmp(0);
5669       }
5670     }
5671     // branch not taken
5672     if(!unconditional) {
5673       if(nottaken1) set_jump_target(nottaken1, out);
5674       set_jump_target(nottaken, out);
5675       assem_debug("2:\n");
5676       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5677       // load regs
5678       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5679       address_generation(i+1,&branch_regs[i],0);
5680       if (ram_offset)
5681         load_reg(regs[i].regmap,branch_regs[i].regmap,ROREG);
5682       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5683       ds_assemble(i+1,&branch_regs[i]);
5684       cc=get_reg(branch_regs[i].regmap,CCREG);
5685       if (cc == -1) {
5686         // Cycle count isn't in a register, temporarily load it then write it out
5687         emit_loadreg(CCREG,HOST_CCREG);
5688         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
5689         void *jaddr=out;
5690         emit_jns(0);
5691         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5692         emit_storereg(CCREG,HOST_CCREG);
5693       }
5694       else{
5695         cc=get_reg(i_regmap,CCREG);
5696         assert(cc==HOST_CCREG);
5697         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5698         void *jaddr=out;
5699         emit_jns(0);
5700         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5701       }
5702     }
5703   }
5704 }
5705
5706 static void sjump_assemble(int i, const struct regstat *i_regs)
5707 {
5708   const signed char *i_regmap = i_regs->regmap;
5709   int cc;
5710   int match;
5711   match=match_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5712   assem_debug("smatch=%d ooo=%d\n", match, dops[i].ooo);
5713   int s1l;
5714   int unconditional=0,nevertaken=0;
5715   int invert=0;
5716   int internal=internal_branch(ba[i]);
5717   if(i==(ba[i]-start)>>2) assem_debug("idle loop\n");
5718   if(!match) invert=1;
5719   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5720   if(i>(ba[i]-start)>>2) invert=1;
5721   #endif
5722   #ifdef __aarch64__
5723   invert=1; // because of near cond. branches
5724   #endif
5725
5726   //if(dops[i].opcode2>=0x10) return; // FIXME (BxxZAL)
5727   //assert(dops[i].opcode2<0x10||dops[i].rs1==0); // FIXME (BxxZAL)
5728
5729   if(dops[i].ooo) {
5730     s1l=get_reg(branch_regs[i].regmap,dops[i].rs1);
5731   }
5732   else {
5733     s1l=get_reg(i_regmap,dops[i].rs1);
5734   }
5735   if(dops[i].rs1==0)
5736   {
5737     if(dops[i].opcode2&1) unconditional=1;
5738     else nevertaken=1;
5739     // These are never taken (r0 is never less than zero)
5740     //assert(dops[i].opcode2!=0);
5741     //assert(dops[i].opcode2!=2);
5742     //assert(dops[i].opcode2!=0x10);
5743     //assert(dops[i].opcode2!=0x12);
5744   }
5745
5746   if(dops[i].ooo) {
5747     // Out of order execution (delay slot first)
5748     //printf("OOOE\n");
5749     address_generation(i+1,i_regs,regs[i].regmap_entry);
5750     ds_assemble(i+1,i_regs);
5751     int adj;
5752     uint64_t bc_unneeded=branch_regs[i].u;
5753     bc_unneeded&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
5754     bc_unneeded|=1;
5755     wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,bc_unneeded);
5756     load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i].rs1,dops[i].rs1);
5757     load_reg(regs[i].regmap,branch_regs[i].regmap,CCREG);
5758     if(dops[i].rt1==31) {
5759       int rt,return_address;
5760       rt=get_reg(branch_regs[i].regmap,31);
5761       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]);
5762       if(rt>=0) {
5763         // Save the PC even if the branch is not taken
5764         return_address=start+i*4+8;
5765         emit_movimm(return_address,rt); // PC into link register
5766         #ifdef IMM_PREFETCH
5767         if(!nevertaken) emit_prefetch(hash_table_get(return_address));
5768         #endif
5769       }
5770     }
5771     cc=get_reg(branch_regs[i].regmap,CCREG);
5772     assert(cc==HOST_CCREG);
5773     if(unconditional)
5774       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5775     //do_cc(i,branch_regs[i].regmap,&adj,unconditional?ba[i]:-1,unconditional);
5776     assem_debug("cycle count (adj)\n");
5777     if(unconditional) {
5778       do_cc(i,branch_regs[i].regmap,&adj,ba[i],TAKEN,0);
5779       if(i!=(ba[i]-start)>>2 || source[i+1]!=0) {
5780         if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5781         load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5782         if(internal)
5783           assem_debug("branch: internal\n");
5784         else
5785           assem_debug("branch: external\n");
5786         if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5787           ds_assemble_entry(i);
5788         }
5789         else {
5790           add_to_linker(out,ba[i],internal);
5791           emit_jmp(0);
5792         }
5793         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5794         if(((u_int)out)&7) emit_addnop(0);
5795         #endif
5796       }
5797     }
5798     else if(nevertaken) {
5799       emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5800       void *jaddr=out;
5801       emit_jns(0);
5802       add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5803     }
5804     else {
5805       void *nottaken = NULL;
5806       do_cc(i,branch_regs[i].regmap,&adj,-1,0,invert);
5807       if(adj&&!invert) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5808       {
5809         assert(s1l>=0);
5810         if((dops[i].opcode2&0xf)==0) // BLTZ/BLTZAL
5811         {
5812           emit_test(s1l,s1l);
5813           if(invert){
5814             nottaken=out;
5815             emit_jns(DJT_1);
5816           }else{
5817             add_to_linker(out,ba[i],internal);
5818             emit_js(0);
5819           }
5820         }
5821         if((dops[i].opcode2&0xf)==1) // BGEZ/BLTZAL
5822         {
5823           emit_test(s1l,s1l);
5824           if(invert){
5825             nottaken=out;
5826             emit_js(DJT_1);
5827           }else{
5828             add_to_linker(out,ba[i],internal);
5829             emit_jns(0);
5830           }
5831         }
5832       }
5833
5834       if(invert) {
5835         #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
5836         if (match && (!internal || !dops[(ba[i] - start) >> 2].is_ds)) {
5837           if(adj) {
5838             emit_addimm(cc,-adj,cc);
5839             add_to_linker(out,ba[i],internal);
5840           }else{
5841             emit_addnop(13);
5842             add_to_linker(out,ba[i],internal*2);
5843           }
5844           emit_jmp(0);
5845         }else
5846         #endif
5847         {
5848           if(adj) emit_addimm(cc,-adj,cc);
5849           store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5850           load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5851           if(internal)
5852             assem_debug("branch: internal\n");
5853           else
5854             assem_debug("branch: external\n");
5855           if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5856             ds_assemble_entry(i);
5857           }
5858           else {
5859             add_to_linker(out,ba[i],internal);
5860             emit_jmp(0);
5861           }
5862         }
5863         set_jump_target(nottaken, out);
5864       }
5865
5866       if(adj) {
5867         if(!invert) emit_addimm(cc,adj,cc);
5868       }
5869     } // (!unconditional)
5870   } // if(ooo)
5871   else
5872   {
5873     // In-order execution (branch first)
5874     //printf("IOE\n");
5875     void *nottaken = NULL;
5876     if(dops[i].rt1==31) {
5877       int rt,return_address;
5878       rt=get_reg(branch_regs[i].regmap,31);
5879       if(rt>=0) {
5880         // Save the PC even if the branch is not taken
5881         return_address=start+i*4+8;
5882         emit_movimm(return_address,rt); // PC into link register
5883         #ifdef IMM_PREFETCH
5884         emit_prefetch(hash_table_get(return_address));
5885         #endif
5886       }
5887     }
5888     if(!unconditional) {
5889       //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]);
5890         assert(s1l>=0);
5891         if((dops[i].opcode2&0x0d)==0) // BLTZ/BLTZL/BLTZAL/BLTZALL
5892         {
5893           emit_test(s1l,s1l);
5894           nottaken=out;
5895           emit_jns(DJT_1);
5896         }
5897         if((dops[i].opcode2&0x0d)==1) // BGEZ/BGEZL/BGEZAL/BGEZALL
5898         {
5899           emit_test(s1l,s1l);
5900           nottaken=out;
5901           emit_js(DJT_1);
5902         }
5903     } // if(!unconditional)
5904     int adj;
5905     uint64_t ds_unneeded=branch_regs[i].u;
5906     ds_unneeded&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
5907     ds_unneeded|=1;
5908     // branch taken
5909     if(!nevertaken) {
5910       //assem_debug("1:\n");
5911       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5912       // load regs
5913       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5914       address_generation(i+1,&branch_regs[i],0);
5915       if (ram_offset)
5916         load_reg(regs[i].regmap,branch_regs[i].regmap,ROREG);
5917       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5918       ds_assemble(i+1,&branch_regs[i]);
5919       cc=get_reg(branch_regs[i].regmap,CCREG);
5920       if(cc==-1) {
5921         emit_loadreg(CCREG,cc=HOST_CCREG);
5922         // CHECK: Is the following instruction (fall thru) allocated ok?
5923       }
5924       assert(cc==HOST_CCREG);
5925       store_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5926       do_cc(i,i_regmap,&adj,ba[i],TAKEN,0);
5927       assem_debug("cycle count (adj)\n");
5928       if(adj) emit_addimm(cc, ccadj[i] + CLOCK_ADJUST(2) - adj, cc);
5929       load_regs_bt(branch_regs[i].regmap,branch_regs[i].dirty,ba[i]);
5930       if(internal)
5931         assem_debug("branch: internal\n");
5932       else
5933         assem_debug("branch: external\n");
5934       if (internal && dops[(ba[i] - start) >> 2].is_ds) {
5935         ds_assemble_entry(i);
5936       }
5937       else {
5938         add_to_linker(out,ba[i],internal);
5939         emit_jmp(0);
5940       }
5941     }
5942     // branch not taken
5943     if(!unconditional) {
5944       set_jump_target(nottaken, out);
5945       assem_debug("1:\n");
5946       wb_invalidate(regs[i].regmap,branch_regs[i].regmap,regs[i].dirty,ds_unneeded);
5947       load_regs(regs[i].regmap,branch_regs[i].regmap,dops[i+1].rs1,dops[i+1].rs2);
5948       address_generation(i+1,&branch_regs[i],0);
5949       if (ram_offset)
5950         load_reg(regs[i].regmap,branch_regs[i].regmap,ROREG);
5951       load_regs(regs[i].regmap,branch_regs[i].regmap,CCREG,INVCP);
5952       ds_assemble(i+1,&branch_regs[i]);
5953       cc=get_reg(branch_regs[i].regmap,CCREG);
5954       if (cc == -1) {
5955         // Cycle count isn't in a register, temporarily load it then write it out
5956         emit_loadreg(CCREG,HOST_CCREG);
5957         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), HOST_CCREG);
5958         void *jaddr=out;
5959         emit_jns(0);
5960         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5961         emit_storereg(CCREG,HOST_CCREG);
5962       }
5963       else{
5964         cc=get_reg(i_regmap,CCREG);
5965         assert(cc==HOST_CCREG);
5966         emit_addimm_and_set_flags(ccadj[i] + CLOCK_ADJUST(2), cc);
5967         void *jaddr=out;
5968         emit_jns(0);
5969         add_stub(CC_STUB,jaddr,out,0,i,start+i*4+8,NOTTAKEN,0);
5970       }
5971     }
5972   }
5973 }
5974
5975 static void check_regmap(signed char *regmap)
5976 {
5977 #ifndef NDEBUG
5978   int i,j;
5979   for (i = 0; i < HOST_REGS; i++) {
5980     if (regmap[i] < 0)
5981       continue;
5982     for (j = i + 1; j < HOST_REGS; j++)
5983       assert(regmap[i] != regmap[j]);
5984   }
5985 #endif
5986 }
5987
5988 #ifdef DISASM
5989 #include <inttypes.h>
5990 static char insn[MAXBLOCK][10];
5991
5992 #define set_mnemonic(i_, n_) \
5993   strcpy(insn[i_], n_)
5994
5995 void print_regmap(const char *name, const signed char *regmap)
5996 {
5997   char buf[5];
5998   int i, l;
5999   fputs(name, stdout);
6000   for (i = 0; i < HOST_REGS; i++) {
6001     l = 0;
6002     if (regmap[i] >= 0)
6003       l = snprintf(buf, sizeof(buf), "$%d", regmap[i]);
6004     for (; l < 3; l++)
6005       buf[l] = ' ';
6006     buf[l] = 0;
6007     printf(" r%d=%s", i, buf);
6008   }
6009   fputs("\n", stdout);
6010 }
6011
6012   /* disassembly */
6013 void disassemble_inst(int i)
6014 {
6015     if (dops[i].bt) printf("*"); else printf(" ");
6016     switch(dops[i].itype) {
6017       case UJUMP:
6018         printf (" %x: %s %8x\n",start+i*4,insn[i],ba[i]);break;
6019       case CJUMP:
6020         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;
6021       case SJUMP:
6022         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;
6023       case RJUMP:
6024         if (dops[i].opcode==0x9&&dops[i].rt1!=31)
6025           printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1);
6026         else
6027           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rs1);
6028         break;
6029       case IMM16:
6030         if(dops[i].opcode==0xf) //LUI
6031           printf (" %x: %s r%d,%4x0000\n",start+i*4,insn[i],dops[i].rt1,imm[i]&0xffff);
6032         else
6033           printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6034         break;
6035       case LOAD:
6036       case LOADLR:
6037         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6038         break;
6039       case STORE:
6040       case STORELR:
6041         printf (" %x: %s r%d,r%d+%x\n",start+i*4,insn[i],dops[i].rs2,dops[i].rs1,imm[i]);
6042         break;
6043       case ALU:
6044       case SHIFT:
6045         printf (" %x: %s r%d,r%d,r%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,dops[i].rs2);
6046         break;
6047       case MULTDIV:
6048         printf (" %x: %s r%d,r%d\n",start+i*4,insn[i],dops[i].rs1,dops[i].rs2);
6049         break;
6050       case SHIFTIMM:
6051         printf (" %x: %s r%d,r%d,%d\n",start+i*4,insn[i],dops[i].rt1,dops[i].rs1,imm[i]);
6052         break;
6053       case MOV:
6054         if((dops[i].opcode2&0x1d)==0x10)
6055           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rt1);
6056         else if((dops[i].opcode2&0x1d)==0x11)
6057           printf (" %x: %s r%d\n",start+i*4,insn[i],dops[i].rs1);
6058         else
6059           printf (" %x: %s\n",start+i*4,insn[i]);
6060         break;
6061       case COP0:
6062         if(dops[i].opcode2==0)
6063           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC0
6064         else if(dops[i].opcode2==4)
6065           printf (" %x: %s r%d,cpr0[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC0
6066         else printf (" %x: %s\n",start+i*4,insn[i]);
6067         break;
6068       case COP1:
6069         if(dops[i].opcode2<3)
6070           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC1
6071         else if(dops[i].opcode2>3)
6072           printf (" %x: %s r%d,cpr1[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC1
6073         else printf (" %x: %s\n",start+i*4,insn[i]);
6074         break;
6075       case COP2:
6076         if(dops[i].opcode2<3)
6077           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],dops[i].rt1,(source[i]>>11)&0x1f); // MFC2
6078         else if(dops[i].opcode2>3)
6079           printf (" %x: %s r%d,cpr2[%d]\n",start+i*4,insn[i],dops[i].rs1,(source[i]>>11)&0x1f); // MTC2
6080         else printf (" %x: %s\n",start+i*4,insn[i]);
6081         break;
6082       case C1LS:
6083         printf (" %x: %s cpr1[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,dops[i].rs1,imm[i]);
6084         break;
6085       case C2LS:
6086         printf (" %x: %s cpr2[%d],r%d+%x\n",start+i*4,insn[i],(source[i]>>16)&0x1f,dops[i].rs1,imm[i]);
6087         break;
6088       case INTCALL:
6089         printf (" %x: %s (INTCALL)\n",start+i*4,insn[i]);
6090         break;
6091       default:
6092         //printf (" %s %8x\n",insn[i],source[i]);
6093         printf (" %x: %s\n",start+i*4,insn[i]);
6094     }
6095     return;
6096     printf("D: %"PRIu64"  WD: %"PRIu64"  U: %"PRIu64"\n",
6097       regs[i].dirty, regs[i].wasdirty, unneeded_reg[i]);
6098     print_regmap("pre:   ", regmap_pre[i]);
6099     print_regmap("entry: ", regs[i].regmap_entry);
6100     print_regmap("map:   ", regs[i].regmap);
6101     if (dops[i].is_jump) {
6102       print_regmap("bentry:", branch_regs[i].regmap_entry);
6103       print_regmap("bmap:  ", branch_regs[i].regmap);
6104     }
6105 }
6106 #else
6107 #define set_mnemonic(i_, n_)
6108 static void disassemble_inst(int i) {}
6109 #endif // DISASM
6110
6111 #define DRC_TEST_VAL 0x74657374
6112
6113 static noinline void new_dynarec_test(void)
6114 {
6115   int (*testfunc)(void);
6116   void *beginning;
6117   int ret[2];
6118   size_t i;
6119
6120   // check structure linkage
6121   if ((u_char *)rcnts - (u_char *)&psxRegs != sizeof(psxRegs))
6122   {
6123     SysPrintf("linkage_arm* miscompilation/breakage detected.\n");
6124   }
6125
6126   SysPrintf("(%p) testing if we can run recompiled code @%p...\n",
6127     new_dynarec_test, out);
6128   ((volatile u_int *)NDRC_WRITE_OFFSET(out))[0]++; // make the cache dirty
6129
6130   for (i = 0; i < ARRAY_SIZE(ret); i++) {
6131     out = ndrc->translation_cache;
6132     beginning = start_block();
6133     emit_movimm(DRC_TEST_VAL + i, 0); // test
6134     emit_ret();
6135     literal_pool(0);
6136     end_block(beginning);
6137     testfunc = beginning;
6138     ret[i] = testfunc();
6139   }
6140
6141   if (ret[0] == DRC_TEST_VAL && ret[1] == DRC_TEST_VAL + 1)
6142     SysPrintf("test passed.\n");
6143   else
6144     SysPrintf("test failed, will likely crash soon (r=%08x %08x)\n", ret[0], ret[1]);
6145   out = ndrc->translation_cache;
6146 }
6147
6148 // clear the state completely, instead of just marking
6149 // things invalid like invalidate_all_pages() does
6150 void new_dynarec_clear_full(void)
6151 {
6152   int n;
6153   out = ndrc->translation_cache;
6154   memset(invalid_code,1,sizeof(invalid_code));
6155   memset(hash_table,0xff,sizeof(hash_table));
6156   memset(mini_ht,-1,sizeof(mini_ht));
6157   memset(shadow,0,sizeof(shadow));
6158   copy=shadow;
6159   expirep = EXPIRITY_OFFSET;
6160   pending_exception=0;
6161   literalcount=0;
6162   stop_after_jal=0;
6163   inv_code_start=inv_code_end=~0;
6164   hack_addr=0;
6165   f1_hack=0;
6166   for (n = 0; n < ARRAY_SIZE(blocks); n++)
6167     blocks_clear(&blocks[n]);
6168   for (n = 0; n < ARRAY_SIZE(jumps); n++) {
6169     free(jumps[n]);
6170     jumps[n] = NULL;
6171   }
6172   stat_clear(stat_blocks);
6173   stat_clear(stat_links);
6174
6175   cycle_multiplier_old = cycle_multiplier;
6176   new_dynarec_hacks_old = new_dynarec_hacks;
6177 }
6178
6179 void new_dynarec_init(void)
6180 {
6181   SysPrintf("Init new dynarec, ndrc size %x\n", (int)sizeof(*ndrc));
6182
6183 #ifdef _3DS
6184   check_rosalina();
6185 #endif
6186 #ifdef BASE_ADDR_DYNAMIC
6187   #ifdef VITA
6188   sceBlock = getVMBlock(); //sceKernelAllocMemBlockForVM("code", sizeof(*ndrc));
6189   if (sceBlock <= 0)
6190     SysPrintf("sceKernelAllocMemBlockForVM failed: %x\n", sceBlock);
6191   int ret = sceKernelGetMemBlockBase(sceBlock, (void **)&ndrc);
6192   if (ret < 0)
6193     SysPrintf("sceKernelGetMemBlockBase failed: %x\n", ret);
6194   sceKernelOpenVMDomain();
6195   sceClibPrintf("translation_cache = 0x%08lx\n ", (long)ndrc->translation_cache);
6196   #elif defined(_MSC_VER)
6197   ndrc = VirtualAlloc(NULL, sizeof(*ndrc), MEM_COMMIT | MEM_RESERVE,
6198     PAGE_EXECUTE_READWRITE);
6199   #elif defined(HAVE_LIBNX)
6200   Result rc = jitCreate(&g_jit, sizeof(*ndrc));
6201   if (R_FAILED(rc))
6202     SysPrintf("jitCreate failed: %08x\n", rc);
6203   SysPrintf("jitCreate: RX: %p RW: %p type: %d\n", g_jit.rx_addr, g_jit.rw_addr, g_jit.type);
6204   jitTransitionToWritable(&g_jit);
6205   ndrc = g_jit.rx_addr;
6206   ndrc_write_ofs = (char *)g_jit.rw_addr - (char *)ndrc;
6207   memset(NDRC_WRITE_OFFSET(&ndrc->tramp), 0, sizeof(ndrc->tramp));
6208   #else
6209   uintptr_t desired_addr = 0;
6210   int prot = PROT_READ | PROT_WRITE | PROT_EXEC;
6211   int flags = MAP_PRIVATE | MAP_ANONYMOUS;
6212   int fd = -1;
6213   #ifdef __ELF__
6214   extern char _end;
6215   desired_addr = ((uintptr_t)&_end + 0xffffff) & ~0xffffffl;
6216   #endif
6217   #ifdef TC_WRITE_OFFSET
6218   // mostly for testing
6219   fd = open("/dev/shm/pcsxr", O_CREAT | O_RDWR, 0600);
6220   ftruncate(fd, sizeof(*ndrc));
6221   void *mw = mmap(NULL, sizeof(*ndrc), PROT_READ | PROT_WRITE,
6222                   (flags = MAP_SHARED), fd, 0);
6223   assert(mw != MAP_FAILED);
6224   prot = PROT_READ | PROT_EXEC;
6225   #endif
6226   ndrc = mmap((void *)desired_addr, sizeof(*ndrc), prot, flags, fd, 0);
6227   if (ndrc == MAP_FAILED) {
6228     SysPrintf("mmap() failed: %s\n", strerror(errno));
6229     abort();
6230   }
6231   #ifdef TC_WRITE_OFFSET
6232   ndrc_write_ofs = (char *)mw - (char *)ndrc;
6233   #endif
6234   #endif
6235 #else
6236   #ifndef NO_WRITE_EXEC
6237   // not all systems allow execute in data segment by default
6238   // size must be 4K aligned for 3DS?
6239   if (mprotect(ndrc, sizeof(*ndrc),
6240                PROT_READ | PROT_WRITE | PROT_EXEC) != 0)
6241     SysPrintf("mprotect() failed: %s\n", strerror(errno));
6242   #endif
6243 #endif
6244   out = ndrc->translation_cache;
6245   cycle_multiplier=200;
6246   new_dynarec_clear_full();
6247 #ifdef HOST_IMM8
6248   // Copy this into local area so we don't have to put it in every literal pool
6249   invc_ptr=invalid_code;
6250 #endif
6251   arch_init();
6252   new_dynarec_test();
6253   ram_offset=(uintptr_t)rdram-0x80000000;
6254   if (ram_offset!=0)
6255     SysPrintf("warning: RAM is not directly mapped, performance will suffer\n");
6256   SysPrintf("Mapped (RAM/scrp/ROM/LUTs/TC):\n");
6257   SysPrintf("%p/%p/%p/%p/%p\n", psxM, psxH, psxR, mem_rtab, out);
6258 }
6259
6260 void new_dynarec_cleanup(void)
6261 {
6262   int n;
6263 #ifdef BASE_ADDR_DYNAMIC
6264   #ifdef VITA
6265   // sceBlock is managed by retroarch's bootstrap code
6266   //sceKernelFreeMemBlock(sceBlock);
6267   //sceBlock = -1;
6268   #elif defined(HAVE_LIBNX)
6269   jitClose(&g_jit);
6270   ndrc = NULL;
6271   #else
6272   if (munmap(ndrc, sizeof(*ndrc)) < 0)
6273     SysPrintf("munmap() failed\n");
6274   ndrc = NULL;
6275   #endif
6276 #endif
6277   for (n = 0; n < ARRAY_SIZE(blocks); n++)
6278     blocks_clear(&blocks[n]);
6279   for (n = 0; n < ARRAY_SIZE(jumps); n++) {
6280     free(jumps[n]);
6281     jumps[n] = NULL;
6282   }
6283   stat_clear(stat_blocks);
6284   stat_clear(stat_links);
6285   new_dynarec_print_stats();
6286 }
6287
6288 static u_int *get_source_start(u_int addr, u_int *limit)
6289 {
6290   if (addr < 0x00200000 ||
6291     (0xa0000000 <= addr && addr < 0xa0200000))
6292   {
6293     // used for BIOS calls mostly?
6294     *limit = (addr&0xa0000000)|0x00200000;
6295     return (u_int *)(rdram + (addr&0x1fffff));
6296   }
6297   else if (!Config.HLE && (
6298     /* (0x9fc00000 <= addr && addr < 0x9fc80000) ||*/
6299     (0xbfc00000 <= addr && addr < 0xbfc80000)))
6300   {
6301     // BIOS. The multiplier should be much higher as it's uncached 8bit mem,
6302     // but timings in PCSX are too tied to the interpreter's BIAS
6303     if (!HACK_ENABLED(NDHACK_OVERRIDE_CYCLE_M))
6304       cycle_multiplier_active = 200;
6305
6306     *limit = (addr & 0xfff00000) | 0x80000;
6307     return (u_int *)((u_char *)psxR + (addr&0x7ffff));
6308   }
6309   else if (addr >= 0x80000000 && addr < 0x80000000+RAM_SIZE) {
6310     *limit = (addr & 0x80600000) + 0x00200000;
6311     return (u_int *)(rdram + (addr&0x1fffff));
6312   }
6313   return NULL;
6314 }
6315
6316 static u_int scan_for_ret(u_int addr)
6317 {
6318   u_int limit = 0;
6319   u_int *mem;
6320
6321   mem = get_source_start(addr, &limit);
6322   if (mem == NULL)
6323     return addr;
6324
6325   if (limit > addr + 0x1000)
6326     limit = addr + 0x1000;
6327   for (; addr < limit; addr += 4, mem++) {
6328     if (*mem == 0x03e00008) // jr $ra
6329       return addr + 8;
6330   }
6331   return addr;
6332 }
6333
6334 struct savestate_block {
6335   uint32_t addr;
6336   uint32_t regflags;
6337 };
6338
6339 static int addr_cmp(const void *p1_, const void *p2_)
6340 {
6341   const struct savestate_block *p1 = p1_, *p2 = p2_;
6342   return p1->addr - p2->addr;
6343 }
6344
6345 int new_dynarec_save_blocks(void *save, int size)
6346 {
6347   struct savestate_block *sblocks = save;
6348   int maxcount = size / sizeof(sblocks[0]);
6349   struct savestate_block tmp_blocks[1024];
6350   struct block_info *block;
6351   int p, s, d, o, bcnt;
6352   u_int addr;
6353
6354   o = 0;
6355   for (p = 0; p < ARRAY_SIZE(blocks); p++) {
6356     bcnt = 0;
6357     for (block = blocks[p]; block != NULL; block = block->next) {
6358       if (block->is_dirty)
6359         continue;
6360       tmp_blocks[bcnt].addr = block->start;
6361       tmp_blocks[bcnt].regflags = block->reg_sv_flags;
6362       bcnt++;
6363     }
6364     if (bcnt < 1)
6365       continue;
6366     qsort(tmp_blocks, bcnt, sizeof(tmp_blocks[0]), addr_cmp);
6367
6368     addr = tmp_blocks[0].addr;
6369     for (s = d = 0; s < bcnt; s++) {
6370       if (tmp_blocks[s].addr < addr)
6371         continue;
6372       if (d == 0 || tmp_blocks[d-1].addr != tmp_blocks[s].addr)
6373         tmp_blocks[d++] = tmp_blocks[s];
6374       addr = scan_for_ret(tmp_blocks[s].addr);
6375     }
6376
6377     if (o + d > maxcount)
6378       d = maxcount - o;
6379     memcpy(&sblocks[o], tmp_blocks, d * sizeof(sblocks[0]));
6380     o += d;
6381   }
6382
6383   return o * sizeof(sblocks[0]);
6384 }
6385
6386 void new_dynarec_load_blocks(const void *save, int size)
6387 {
6388   const struct savestate_block *sblocks = save;
6389   int count = size / sizeof(sblocks[0]);
6390   struct block_info *block;
6391   u_int regs_save[32];
6392   u_int page;
6393   uint32_t f;
6394   int i, b;
6395
6396   // restore clean blocks, if any
6397   for (page = 0, b = i = 0; page < ARRAY_SIZE(blocks); page++) {
6398     for (block = blocks[page]; block != NULL; block = block->next, b++) {
6399       if (!block->is_dirty)
6400         continue;
6401       assert(block->source && block->copy);
6402       if (memcmp(block->source, block->copy, block->len))
6403         continue;
6404
6405       // see try_restore_block
6406       block->is_dirty = 0;
6407       mark_invalid_code(block->start, block->len, 0);
6408       i++;
6409     }
6410   }
6411   inv_debug("load_blocks: %d/%d clean blocks\n", i, b);
6412
6413   // change GPRs for speculation to at least partially work..
6414   memcpy(regs_save, &psxRegs.GPR, sizeof(regs_save));
6415   for (i = 1; i < 32; i++)
6416     psxRegs.GPR.r[i] = 0x80000000;
6417
6418   for (b = 0; b < count; b++) {
6419     for (f = sblocks[b].regflags, i = 0; f; f >>= 1, i++) {
6420       if (f & 1)
6421         psxRegs.GPR.r[i] = 0x1f800000;
6422     }
6423
6424     ndrc_get_addr_ht(sblocks[b].addr);
6425
6426     for (f = sblocks[b].regflags, i = 0; f; f >>= 1, i++) {
6427       if (f & 1)
6428         psxRegs.GPR.r[i] = 0x80000000;
6429     }
6430   }
6431
6432   memcpy(&psxRegs.GPR, regs_save, sizeof(regs_save));
6433 }
6434
6435 void new_dynarec_print_stats(void)
6436 {
6437 #ifdef STAT_PRINT
6438   printf("cc %3d,%3d,%3d lu%6d,%3d,%3d c%3d inv%3d,%3d tc_offs %zu b %u,%u\n",
6439     stat_bc_pre, stat_bc_direct, stat_bc_restore,
6440     stat_ht_lookups, stat_jump_in_lookups, stat_restore_tries,
6441     stat_restore_compares, stat_inv_addr_calls, stat_inv_hits,
6442     out - ndrc->translation_cache, stat_blocks, stat_links);
6443   stat_bc_direct = stat_bc_pre = stat_bc_restore =
6444   stat_ht_lookups = stat_jump_in_lookups = stat_restore_tries =
6445   stat_restore_compares = stat_inv_addr_calls = stat_inv_hits = 0;
6446 #endif
6447 }
6448
6449 static int apply_hacks(void)
6450 {
6451   int i;
6452   if (HACK_ENABLED(NDHACK_NO_COMPAT_HACKS))
6453     return 0;
6454   /* special hack(s) */
6455   for (i = 0; i < slen - 4; i++)
6456   {
6457     // lui a4, 0xf200; jal <rcnt_read>; addu a0, 2; slti v0, 28224
6458     if (source[i] == 0x3c04f200 && dops[i+1].itype == UJUMP
6459         && source[i+2] == 0x34840002 && dops[i+3].opcode == 0x0a
6460         && imm[i+3] == 0x6e40 && dops[i+3].rs1 == 2)
6461     {
6462       SysPrintf("PE2 hack @%08x\n", start + (i+3)*4);
6463       dops[i + 3].itype = NOP;
6464     }
6465   }
6466   i = slen;
6467   if (i > 10 && source[i-1] == 0 && source[i-2] == 0x03e00008
6468       && source[i-4] == 0x8fbf0018 && source[i-6] == 0x00c0f809
6469       && dops[i-7].itype == STORE)
6470   {
6471     i = i-8;
6472     if (dops[i].itype == IMM16)
6473       i--;
6474     // swl r2, 15(r6); swr r2, 12(r6); sw r6, *; jalr r6
6475     if (dops[i].itype == STORELR && dops[i].rs1 == 6
6476       && dops[i-1].itype == STORELR && dops[i-1].rs1 == 6)
6477     {
6478       SysPrintf("F1 hack from %08x, old dst %08x\n", start, hack_addr);
6479       f1_hack = 1;
6480       return 1;
6481     }
6482   }
6483   return 0;
6484 }
6485
6486 static noinline void pass1_disassemble(u_int pagelimit)
6487 {
6488   int i, j, done = 0, ni_count = 0;
6489   unsigned int type,op,op2;
6490
6491   for (i = 0; !done; i++)
6492   {
6493     memset(&dops[i], 0, sizeof(dops[i]));
6494     op2=0;
6495     minimum_free_regs[i]=0;
6496     dops[i].opcode=op=source[i]>>26;
6497     switch(op)
6498     {
6499       case 0x00: set_mnemonic(i, "special"); type=NI;
6500         op2=source[i]&0x3f;
6501         switch(op2)
6502         {
6503           case 0x00: set_mnemonic(i, "SLL"); type=SHIFTIMM; break;
6504           case 0x02: set_mnemonic(i, "SRL"); type=SHIFTIMM; break;
6505           case 0x03: set_mnemonic(i, "SRA"); type=SHIFTIMM; break;
6506           case 0x04: set_mnemonic(i, "SLLV"); type=SHIFT; break;
6507           case 0x06: set_mnemonic(i, "SRLV"); type=SHIFT; break;
6508           case 0x07: set_mnemonic(i, "SRAV"); type=SHIFT; break;
6509           case 0x08: set_mnemonic(i, "JR"); type=RJUMP; break;
6510           case 0x09: set_mnemonic(i, "JALR"); type=RJUMP; break;
6511           case 0x0C: set_mnemonic(i, "SYSCALL"); type=SYSCALL; break;
6512           case 0x0D: set_mnemonic(i, "BREAK"); type=SYSCALL; break;
6513           case 0x0F: set_mnemonic(i, "SYNC"); type=OTHER; break;
6514           case 0x10: set_mnemonic(i, "MFHI"); type=MOV; break;
6515           case 0x11: set_mnemonic(i, "MTHI"); type=MOV; break;
6516           case 0x12: set_mnemonic(i, "MFLO"); type=MOV; break;
6517           case 0x13: set_mnemonic(i, "MTLO"); type=MOV; break;
6518           case 0x18: set_mnemonic(i, "MULT"); type=MULTDIV; break;
6519           case 0x19: set_mnemonic(i, "MULTU"); type=MULTDIV; break;
6520           case 0x1A: set_mnemonic(i, "DIV"); type=MULTDIV; break;
6521           case 0x1B: set_mnemonic(i, "DIVU"); type=MULTDIV; break;
6522           case 0x20: set_mnemonic(i, "ADD"); type=ALU; break;
6523           case 0x21: set_mnemonic(i, "ADDU"); type=ALU; break;
6524           case 0x22: set_mnemonic(i, "SUB"); type=ALU; break;
6525           case 0x23: set_mnemonic(i, "SUBU"); type=ALU; break;
6526           case 0x24: set_mnemonic(i, "AND"); type=ALU; break;
6527           case 0x25: set_mnemonic(i, "OR"); type=ALU; break;
6528           case 0x26: set_mnemonic(i, "XOR"); type=ALU; break;
6529           case 0x27: set_mnemonic(i, "NOR"); type=ALU; break;
6530           case 0x2A: set_mnemonic(i, "SLT"); type=ALU; break;
6531           case 0x2B: set_mnemonic(i, "SLTU"); type=ALU; break;
6532           case 0x30: set_mnemonic(i, "TGE"); type=NI; break;
6533           case 0x31: set_mnemonic(i, "TGEU"); type=NI; break;
6534           case 0x32: set_mnemonic(i, "TLT"); type=NI; break;
6535           case 0x33: set_mnemonic(i, "TLTU"); type=NI; break;
6536           case 0x34: set_mnemonic(i, "TEQ"); type=NI; break;
6537           case 0x36: set_mnemonic(i, "TNE"); type=NI; break;
6538 #if 0
6539           case 0x14: set_mnemonic(i, "DSLLV"); type=SHIFT; break;
6540           case 0x16: set_mnemonic(i, "DSRLV"); type=SHIFT; break;
6541           case 0x17: set_mnemonic(i, "DSRAV"); type=SHIFT; break;
6542           case 0x1C: set_mnemonic(i, "DMULT"); type=MULTDIV; break;
6543           case 0x1D: set_mnemonic(i, "DMULTU"); type=MULTDIV; break;
6544           case 0x1E: set_mnemonic(i, "DDIV"); type=MULTDIV; break;
6545           case 0x1F: set_mnemonic(i, "DDIVU"); type=MULTDIV; break;
6546           case 0x2C: set_mnemonic(i, "DADD"); type=ALU; break;
6547           case 0x2D: set_mnemonic(i, "DADDU"); type=ALU; break;
6548           case 0x2E: set_mnemonic(i, "DSUB"); type=ALU; break;
6549           case 0x2F: set_mnemonic(i, "DSUBU"); type=ALU; break;
6550           case 0x38: set_mnemonic(i, "DSLL"); type=SHIFTIMM; break;
6551           case 0x3A: set_mnemonic(i, "DSRL"); type=SHIFTIMM; break;
6552           case 0x3B: set_mnemonic(i, "DSRA"); type=SHIFTIMM; break;
6553           case 0x3C: set_mnemonic(i, "DSLL32"); type=SHIFTIMM; break;
6554           case 0x3E: set_mnemonic(i, "DSRL32"); type=SHIFTIMM; break;
6555           case 0x3F: set_mnemonic(i, "DSRA32"); type=SHIFTIMM; break;
6556 #endif
6557         }
6558         break;
6559       case 0x01: set_mnemonic(i, "regimm"); type=NI;
6560         op2=(source[i]>>16)&0x1f;
6561         switch(op2)
6562         {
6563           case 0x00: set_mnemonic(i, "BLTZ"); type=SJUMP; break;
6564           case 0x01: set_mnemonic(i, "BGEZ"); type=SJUMP; break;
6565           //case 0x02: set_mnemonic(i, "BLTZL"); type=SJUMP; break;
6566           //case 0x03: set_mnemonic(i, "BGEZL"); type=SJUMP; break;
6567           //case 0x08: set_mnemonic(i, "TGEI"); type=NI; break;
6568           //case 0x09: set_mnemonic(i, "TGEIU"); type=NI; break;
6569           //case 0x0A: set_mnemonic(i, "TLTI"); type=NI; break;
6570           //case 0x0B: set_mnemonic(i, "TLTIU"); type=NI; break;
6571           //case 0x0C: set_mnemonic(i, "TEQI"); type=NI; break;
6572           //case 0x0E: set_mnemonic(i, "TNEI"); type=NI; break;
6573           case 0x10: set_mnemonic(i, "BLTZAL"); type=SJUMP; break;
6574           case 0x11: set_mnemonic(i, "BGEZAL"); type=SJUMP; break;
6575           //case 0x12: set_mnemonic(i, "BLTZALL"); type=SJUMP; break;
6576           //case 0x13: set_mnemonic(i, "BGEZALL"); type=SJUMP; break;
6577         }
6578         break;
6579       case 0x02: set_mnemonic(i, "J"); type=UJUMP; break;
6580       case 0x03: set_mnemonic(i, "JAL"); type=UJUMP; break;
6581       case 0x04: set_mnemonic(i, "BEQ"); type=CJUMP; break;
6582       case 0x05: set_mnemonic(i, "BNE"); type=CJUMP; break;
6583       case 0x06: set_mnemonic(i, "BLEZ"); type=CJUMP; break;
6584       case 0x07: set_mnemonic(i, "BGTZ"); type=CJUMP; break;
6585       case 0x08: set_mnemonic(i, "ADDI"); type=IMM16; break;
6586       case 0x09: set_mnemonic(i, "ADDIU"); type=IMM16; break;
6587       case 0x0A: set_mnemonic(i, "SLTI"); type=IMM16; break;
6588       case 0x0B: set_mnemonic(i, "SLTIU"); type=IMM16; break;
6589       case 0x0C: set_mnemonic(i, "ANDI"); type=IMM16; break;
6590       case 0x0D: set_mnemonic(i, "ORI"); type=IMM16; break;
6591       case 0x0E: set_mnemonic(i, "XORI"); type=IMM16; break;
6592       case 0x0F: set_mnemonic(i, "LUI"); type=IMM16; break;
6593       case 0x10: set_mnemonic(i, "cop0"); type=NI;
6594         op2=(source[i]>>21)&0x1f;
6595         switch(op2)
6596         {
6597           case 0x00: set_mnemonic(i, "MFC0"); type=COP0; break;
6598           case 0x02: set_mnemonic(i, "CFC0"); type=COP0; break;
6599           case 0x04: set_mnemonic(i, "MTC0"); type=COP0; break;
6600           case 0x06: set_mnemonic(i, "CTC0"); type=COP0; break;
6601           case 0x10: set_mnemonic(i, "RFE"); type=COP0; break;
6602         }
6603         break;
6604       case 0x11: set_mnemonic(i, "cop1"); type=COP1;
6605         op2=(source[i]>>21)&0x1f;
6606         break;
6607 #if 0
6608       case 0x14: set_mnemonic(i, "BEQL"); type=CJUMP; break;
6609       case 0x15: set_mnemonic(i, "BNEL"); type=CJUMP; break;
6610       case 0x16: set_mnemonic(i, "BLEZL"); type=CJUMP; break;
6611       case 0x17: set_mnemonic(i, "BGTZL"); type=CJUMP; break;
6612       case 0x18: set_mnemonic(i, "DADDI"); type=IMM16; break;
6613       case 0x19: set_mnemonic(i, "DADDIU"); type=IMM16; break;
6614       case 0x1A: set_mnemonic(i, "LDL"); type=LOADLR; break;
6615       case 0x1B: set_mnemonic(i, "LDR"); type=LOADLR; break;
6616 #endif
6617       case 0x20: set_mnemonic(i, "LB"); type=LOAD; break;
6618       case 0x21: set_mnemonic(i, "LH"); type=LOAD; break;
6619       case 0x22: set_mnemonic(i, "LWL"); type=LOADLR; break;
6620       case 0x23: set_mnemonic(i, "LW"); type=LOAD; break;
6621       case 0x24: set_mnemonic(i, "LBU"); type=LOAD; break;
6622       case 0x25: set_mnemonic(i, "LHU"); type=LOAD; break;
6623       case 0x26: set_mnemonic(i, "LWR"); type=LOADLR; break;
6624 #if 0
6625       case 0x27: set_mnemonic(i, "LWU"); type=LOAD; break;
6626 #endif
6627       case 0x28: set_mnemonic(i, "SB"); type=STORE; break;
6628       case 0x29: set_mnemonic(i, "SH"); type=STORE; break;
6629       case 0x2A: set_mnemonic(i, "SWL"); type=STORELR; break;
6630       case 0x2B: set_mnemonic(i, "SW"); type=STORE; break;
6631 #if 0
6632       case 0x2C: set_mnemonic(i, "SDL"); type=STORELR; break;
6633       case 0x2D: set_mnemonic(i, "SDR"); type=STORELR; break;
6634 #endif
6635       case 0x2E: set_mnemonic(i, "SWR"); type=STORELR; break;
6636       case 0x2F: set_mnemonic(i, "CACHE"); type=NOP; break;
6637       case 0x30: set_mnemonic(i, "LL"); type=NI; break;
6638       case 0x31: set_mnemonic(i, "LWC1"); type=C1LS; break;
6639 #if 0
6640       case 0x34: set_mnemonic(i, "LLD"); type=NI; break;
6641       case 0x35: set_mnemonic(i, "LDC1"); type=C1LS; break;
6642       case 0x37: set_mnemonic(i, "LD"); type=LOAD; break;
6643 #endif
6644       case 0x38: set_mnemonic(i, "SC"); type=NI; break;
6645       case 0x39: set_mnemonic(i, "SWC1"); type=C1LS; break;
6646 #if 0
6647       case 0x3C: set_mnemonic(i, "SCD"); type=NI; break;
6648       case 0x3D: set_mnemonic(i, "SDC1"); type=C1LS; break;
6649       case 0x3F: set_mnemonic(i, "SD"); type=STORE; break;
6650 #endif
6651       case 0x12: set_mnemonic(i, "COP2"); type=NI;
6652         op2=(source[i]>>21)&0x1f;
6653         //if (op2 & 0x10)
6654         if (source[i]&0x3f) { // use this hack to support old savestates with patched gte insns
6655           if (gte_handlers[source[i]&0x3f]!=NULL) {
6656 #ifdef DISASM
6657             if (gte_regnames[source[i]&0x3f]!=NULL)
6658               strcpy(insn[i],gte_regnames[source[i]&0x3f]);
6659             else
6660               snprintf(insn[i], sizeof(insn[i]), "COP2 %x", source[i]&0x3f);
6661 #endif
6662             type=C2OP;
6663           }
6664         }
6665         else switch(op2)
6666         {
6667           case 0x00: set_mnemonic(i, "MFC2"); type=COP2; break;
6668           case 0x02: set_mnemonic(i, "CFC2"); type=COP2; break;
6669           case 0x04: set_mnemonic(i, "MTC2"); type=COP2; break;
6670           case 0x06: set_mnemonic(i, "CTC2"); type=COP2; break;
6671         }
6672         break;
6673       case 0x32: set_mnemonic(i, "LWC2"); type=C2LS; break;
6674       case 0x3A: set_mnemonic(i, "SWC2"); type=C2LS; break;
6675       case 0x3B: set_mnemonic(i, "HLECALL"); type=HLECALL; break;
6676       default: set_mnemonic(i, "???"); type=NI;
6677         SysPrintf("NI %08x @%08x (%08x)\n", source[i], start + i*4, start);
6678         break;
6679     }
6680     dops[i].itype=type;
6681     dops[i].opcode2=op2;
6682     /* Get registers/immediates */
6683     dops[i].use_lt1=0;
6684     gte_rs[i]=gte_rt[i]=0;
6685     switch(type) {
6686       case LOAD:
6687         dops[i].rs1=(source[i]>>21)&0x1f;
6688         dops[i].rs2=0;
6689         dops[i].rt1=(source[i]>>16)&0x1f;
6690         dops[i].rt2=0;
6691         imm[i]=(short)source[i];
6692         break;
6693       case STORE:
6694       case STORELR:
6695         dops[i].rs1=(source[i]>>21)&0x1f;
6696         dops[i].rs2=(source[i]>>16)&0x1f;
6697         dops[i].rt1=0;
6698         dops[i].rt2=0;
6699         imm[i]=(short)source[i];
6700         break;
6701       case LOADLR:
6702         // LWL/LWR only load part of the register,
6703         // therefore the target register must be treated as a source too
6704         dops[i].rs1=(source[i]>>21)&0x1f;
6705         dops[i].rs2=(source[i]>>16)&0x1f;
6706         dops[i].rt1=(source[i]>>16)&0x1f;
6707         dops[i].rt2=0;
6708         imm[i]=(short)source[i];
6709         break;
6710       case IMM16:
6711         if (op==0x0f) dops[i].rs1=0; // LUI instruction has no source register
6712         else dops[i].rs1=(source[i]>>21)&0x1f;
6713         dops[i].rs2=0;
6714         dops[i].rt1=(source[i]>>16)&0x1f;
6715         dops[i].rt2=0;
6716         if(op>=0x0c&&op<=0x0e) { // ANDI/ORI/XORI
6717           imm[i]=(unsigned short)source[i];
6718         }else{
6719           imm[i]=(short)source[i];
6720         }
6721         break;
6722       case UJUMP:
6723         dops[i].rs1=0;
6724         dops[i].rs2=0;
6725         dops[i].rt1=0;
6726         dops[i].rt2=0;
6727         // The JAL instruction writes to r31.
6728         if (op&1) {
6729           dops[i].rt1=31;
6730         }
6731         dops[i].rs2=CCREG;
6732         break;
6733       case RJUMP:
6734         dops[i].rs1=(source[i]>>21)&0x1f;
6735         dops[i].rs2=0;
6736         dops[i].rt1=0;
6737         dops[i].rt2=0;
6738         // The JALR instruction writes to rd.
6739         if (op2&1) {
6740           dops[i].rt1=(source[i]>>11)&0x1f;
6741         }
6742         dops[i].rs2=CCREG;
6743         break;
6744       case CJUMP:
6745         dops[i].rs1=(source[i]>>21)&0x1f;
6746         dops[i].rs2=(source[i]>>16)&0x1f;
6747         dops[i].rt1=0;
6748         dops[i].rt2=0;
6749         if(op&2) { // BGTZ/BLEZ
6750           dops[i].rs2=0;
6751         }
6752         break;
6753       case SJUMP:
6754         dops[i].rs1=(source[i]>>21)&0x1f;
6755         dops[i].rs2=CCREG;
6756         dops[i].rt1=0;
6757         dops[i].rt2=0;
6758         if(op2&0x10) { // BxxAL
6759           dops[i].rt1=31;
6760           // NOTE: If the branch is not taken, r31 is still overwritten
6761         }
6762         break;
6763       case ALU:
6764         dops[i].rs1=(source[i]>>21)&0x1f; // source
6765         dops[i].rs2=(source[i]>>16)&0x1f; // subtract amount
6766         dops[i].rt1=(source[i]>>11)&0x1f; // destination
6767         dops[i].rt2=0;
6768         break;
6769       case MULTDIV:
6770         dops[i].rs1=(source[i]>>21)&0x1f; // source
6771         dops[i].rs2=(source[i]>>16)&0x1f; // divisor
6772         dops[i].rt1=HIREG;
6773         dops[i].rt2=LOREG;
6774         break;
6775       case MOV:
6776         dops[i].rs1=0;
6777         dops[i].rs2=0;
6778         dops[i].rt1=0;
6779         dops[i].rt2=0;
6780         if(op2==0x10) dops[i].rs1=HIREG; // MFHI
6781         if(op2==0x11) dops[i].rt1=HIREG; // MTHI
6782         if(op2==0x12) dops[i].rs1=LOREG; // MFLO
6783         if(op2==0x13) dops[i].rt1=LOREG; // MTLO
6784         if((op2&0x1d)==0x10) dops[i].rt1=(source[i]>>11)&0x1f; // MFxx
6785         if((op2&0x1d)==0x11) dops[i].rs1=(source[i]>>21)&0x1f; // MTxx
6786         break;
6787       case SHIFT:
6788         dops[i].rs1=(source[i]>>16)&0x1f; // target of shift
6789         dops[i].rs2=(source[i]>>21)&0x1f; // shift amount
6790         dops[i].rt1=(source[i]>>11)&0x1f; // destination
6791         dops[i].rt2=0;
6792         break;
6793       case SHIFTIMM:
6794         dops[i].rs1=(source[i]>>16)&0x1f;
6795         dops[i].rs2=0;
6796         dops[i].rt1=(source[i]>>11)&0x1f;
6797         dops[i].rt2=0;
6798         imm[i]=(source[i]>>6)&0x1f;
6799         // DSxx32 instructions
6800         if(op2>=0x3c) imm[i]|=0x20;
6801         break;
6802       case COP0:
6803         dops[i].rs1=0;
6804         dops[i].rs2=0;
6805         dops[i].rt1=0;
6806         dops[i].rt2=0;
6807         if(op2==0||op2==2) dops[i].rt1=(source[i]>>16)&0x1F; // MFC0/CFC0
6808         if(op2==4||op2==6) dops[i].rs1=(source[i]>>16)&0x1F; // MTC0/CTC0
6809         if(op2==4&&((source[i]>>11)&0x1f)==12) dops[i].rt2=CSREG; // Status
6810         if(op2==16) if((source[i]&0x3f)==0x18) dops[i].rs2=CCREG; // ERET
6811         break;
6812       case COP1:
6813         dops[i].rs1=0;
6814         dops[i].rs2=0;
6815         dops[i].rt1=0;
6816         dops[i].rt2=0;
6817         if(op2<3) dops[i].rt1=(source[i]>>16)&0x1F; // MFC1/DMFC1/CFC1
6818         if(op2>3) dops[i].rs1=(source[i]>>16)&0x1F; // MTC1/DMTC1/CTC1
6819         dops[i].rs2=CSREG;
6820         break;
6821       case COP2:
6822         dops[i].rs1=0;
6823         dops[i].rs2=0;
6824         dops[i].rt1=0;
6825         dops[i].rt2=0;
6826         if(op2<3) dops[i].rt1=(source[i]>>16)&0x1F; // MFC2/CFC2
6827         if(op2>3) dops[i].rs1=(source[i]>>16)&0x1F; // MTC2/CTC2
6828         dops[i].rs2=CSREG;
6829         int gr=(source[i]>>11)&0x1F;
6830         switch(op2)
6831         {
6832           case 0x00: gte_rs[i]=1ll<<gr; break; // MFC2
6833           case 0x04: gte_rt[i]=1ll<<gr; break; // MTC2
6834           case 0x02: gte_rs[i]=1ll<<(gr+32); break; // CFC2
6835           case 0x06: gte_rt[i]=1ll<<(gr+32); break; // CTC2
6836         }
6837         break;
6838       case C1LS:
6839         dops[i].rs1=(source[i]>>21)&0x1F;
6840         dops[i].rs2=CSREG;
6841         dops[i].rt1=0;
6842         dops[i].rt2=0;
6843         imm[i]=(short)source[i];
6844         break;
6845       case C2LS:
6846         dops[i].rs1=(source[i]>>21)&0x1F;
6847         dops[i].rs2=0;
6848         dops[i].rt1=0;
6849         dops[i].rt2=0;
6850         imm[i]=(short)source[i];
6851         if(op==0x32) gte_rt[i]=1ll<<((source[i]>>16)&0x1F); // LWC2
6852         else gte_rs[i]=1ll<<((source[i]>>16)&0x1F); // SWC2
6853         break;
6854       case C2OP:
6855         dops[i].rs1=0;
6856         dops[i].rs2=0;
6857         dops[i].rt1=0;
6858         dops[i].rt2=0;
6859         gte_rs[i]=gte_reg_reads[source[i]&0x3f];
6860         gte_rt[i]=gte_reg_writes[source[i]&0x3f];
6861         gte_rt[i]|=1ll<<63; // every op changes flags
6862         if((source[i]&0x3f)==GTE_MVMVA) {
6863           int v = (source[i] >> 15) & 3;
6864           gte_rs[i]&=~0xe3fll;
6865           if(v==3) gte_rs[i]|=0xe00ll;
6866           else gte_rs[i]|=3ll<<(v*2);
6867         }
6868         break;
6869       case SYSCALL:
6870       case HLECALL:
6871       case INTCALL:
6872         dops[i].rs1=CCREG;
6873         dops[i].rs2=0;
6874         dops[i].rt1=0;
6875         dops[i].rt2=0;
6876         break;
6877       default:
6878         dops[i].rs1=0;
6879         dops[i].rs2=0;
6880         dops[i].rt1=0;
6881         dops[i].rt2=0;
6882     }
6883     /* Calculate branch target addresses */
6884     if(type==UJUMP)
6885       ba[i]=((start+i*4+4)&0xF0000000)|(((unsigned int)source[i]<<6)>>4);
6886     else if(type==CJUMP&&dops[i].rs1==dops[i].rs2&&(op&1))
6887       ba[i]=start+i*4+8; // Ignore never taken branch
6888     else if(type==SJUMP&&dops[i].rs1==0&&!(op2&1))
6889       ba[i]=start+i*4+8; // Ignore never taken branch
6890     else if(type==CJUMP||type==SJUMP)
6891       ba[i]=start+i*4+4+((signed int)((unsigned int)source[i]<<16)>>14);
6892     else ba[i]=-1;
6893
6894     /* simplify always (not)taken branches */
6895     if (type == CJUMP && dops[i].rs1 == dops[i].rs2) {
6896       dops[i].rs1 = dops[i].rs2 = 0;
6897       if (!(op & 1)) {
6898         dops[i].itype = type = UJUMP;
6899         dops[i].rs2 = CCREG;
6900       }
6901     }
6902     else if (type == SJUMP && dops[i].rs1 == 0 && (op2 & 1))
6903       dops[i].itype = type = UJUMP;
6904
6905     dops[i].is_jump = (dops[i].itype == RJUMP || dops[i].itype == UJUMP || dops[i].itype == CJUMP || dops[i].itype == SJUMP);
6906     dops[i].is_ujump = (dops[i].itype == RJUMP || dops[i].itype == UJUMP); // || (source[i] >> 16) == 0x1000 // beq r0,r0
6907     dops[i].is_load = (dops[i].itype == LOAD || dops[i].itype == LOADLR || op == 0x32); // LWC2
6908     dops[i].is_store = (dops[i].itype == STORE || dops[i].itype == STORELR || op == 0x3a); // SWC2
6909
6910     /* messy cases to just pass over to the interpreter */
6911     if (i > 0 && dops[i-1].is_jump) {
6912       int do_in_intrp=0;
6913       // branch in delay slot?
6914       if (dops[i].is_jump) {
6915         // don't handle first branch and call interpreter if it's hit
6916         SysPrintf("branch in delay slot @%08x (%08x)\n", start + i*4, start);
6917         do_in_intrp=1;
6918       }
6919       // basic load delay detection
6920       else if((type==LOAD||type==LOADLR||type==COP0||type==COP2||type==C2LS)&&dops[i].rt1!=0) {
6921         int t=(ba[i-1]-start)/4;
6922         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) {
6923           // jump target wants DS result - potential load delay effect
6924           SysPrintf("load delay @%08x (%08x)\n", start + i*4, start);
6925           do_in_intrp=1;
6926           dops[t+1].bt=1; // expected return from interpreter
6927         }
6928         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&&
6929               !(i>=3&&dops[i-3].is_jump)) {
6930           // v0 overwrite like this is a sign of trouble, bail out
6931           SysPrintf("v0 overwrite @%08x (%08x)\n", start + i*4, start);
6932           do_in_intrp=1;
6933         }
6934       }
6935       if (do_in_intrp) {
6936         memset(&dops[i-1], 0, sizeof(dops[i-1]));
6937         dops[i-1].itype = INTCALL;
6938         dops[i-1].rs1 = CCREG;
6939         ba[i-1] = -1;
6940         done = 2;
6941         i--; // don't compile the DS
6942       }
6943     }
6944
6945     /* Is this the end of the block? */
6946     if (i > 0 && dops[i-1].is_ujump) {
6947       if (dops[i-1].rt1 == 0) { // not jal
6948         int found_bbranch = 0, t = (ba[i-1] - start) / 4;
6949         if ((u_int)(t - i) < 64 && start + (t+64)*4 < pagelimit) {
6950           // scan for a branch back to i+1
6951           for (j = t; j < t + 64; j++) {
6952             int tmpop = source[j] >> 26;
6953             if (tmpop == 1 || ((tmpop & ~3) == 4)) {
6954               int t2 = j + 1 + (int)(signed short)source[j];
6955               if (t2 == i + 1) {
6956                 //printf("blk expand %08x<-%08x\n", start + (i+1)*4, start + j*4);
6957                 found_bbranch = 1;
6958                 break;
6959               }
6960             }
6961           }
6962         }
6963         if (!found_bbranch)
6964           done = 2;
6965       }
6966       else {
6967         if(stop_after_jal) done=1;
6968         // Stop on BREAK
6969         if((source[i+1]&0xfc00003f)==0x0d) done=1;
6970       }
6971       // Don't recompile stuff that's already compiled
6972       if(check_addr(start+i*4+4)) done=1;
6973       // Don't get too close to the limit
6974       if(i>MAXBLOCK/2) done=1;
6975     }
6976     if (dops[i].itype == SYSCALL || dops[i].itype == HLECALL || dops[i].itype == INTCALL)
6977       done = stop_after_jal ? 1 : 2;
6978     if (done == 2) {
6979       // Does the block continue due to a branch?
6980       for(j=i-1;j>=0;j--)
6981       {
6982         if(ba[j]==start+i*4) done=j=0; // Branch into delay slot
6983         if(ba[j]==start+i*4+4) done=j=0;
6984         if(ba[j]==start+i*4+8) done=j=0;
6985       }
6986     }
6987     //assert(i<MAXBLOCK-1);
6988     if(start+i*4==pagelimit-4) done=1;
6989     assert(start+i*4<pagelimit);
6990     if (i==MAXBLOCK-1) done=1;
6991     // Stop if we're compiling junk
6992     if(dops[i].itype == NI && (++ni_count > 8 || dops[i].opcode == 0x11)) {
6993       done=stop_after_jal=1;
6994       SysPrintf("Disabled speculative precompilation\n");
6995     }
6996   }
6997   while (i > 0 && dops[i-1].is_jump)
6998     i--;
6999   assert(i > 0);
7000   assert(!dops[i-1].is_jump);
7001   slen = i;
7002 }
7003
7004 // Basic liveness analysis for MIPS registers
7005 static noinline void pass2_unneeded_regs(int istart,int iend,int r)
7006 {
7007   int i;
7008   uint64_t u,gte_u,b,gte_b;
7009   uint64_t temp_u,temp_gte_u=0;
7010   uint64_t gte_u_unknown=0;
7011   if (HACK_ENABLED(NDHACK_GTE_UNNEEDED))
7012     gte_u_unknown=~0ll;
7013   if(iend==slen-1) {
7014     u=1;
7015     gte_u=gte_u_unknown;
7016   }else{
7017     //u=unneeded_reg[iend+1];
7018     u=1;
7019     gte_u=gte_unneeded[iend+1];
7020   }
7021
7022   for (i=iend;i>=istart;i--)
7023   {
7024     //printf("unneeded registers i=%d (%d,%d) r=%d\n",i,istart,iend,r);
7025     if(dops[i].is_jump)
7026     {
7027       // If subroutine call, flag return address as a possible branch target
7028       if(dops[i].rt1==31 && i<slen-2) dops[i+2].bt=1;
7029
7030       if(ba[i]<start || ba[i]>=(start+slen*4))
7031       {
7032         // Branch out of this block, flush all regs
7033         u=1;
7034         gte_u=gte_u_unknown;
7035         branch_unneeded_reg[i]=u;
7036         // Merge in delay slot
7037         u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
7038         u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7039         u|=1;
7040         gte_u|=gte_rt[i+1];
7041         gte_u&=~gte_rs[i+1];
7042       }
7043       else
7044       {
7045         // Internal branch, flag target
7046         dops[(ba[i]-start)>>2].bt=1;
7047         if(ba[i]<=start+i*4) {
7048           // Backward branch
7049           if(dops[i].is_ujump)
7050           {
7051             // Unconditional branch
7052             temp_u=1;
7053             temp_gte_u=0;
7054           } else {
7055             // Conditional branch (not taken case)
7056             temp_u=unneeded_reg[i+2];
7057             temp_gte_u&=gte_unneeded[i+2];
7058           }
7059           // Merge in delay slot
7060           temp_u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
7061           temp_u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7062           temp_u|=1;
7063           temp_gte_u|=gte_rt[i+1];
7064           temp_gte_u&=~gte_rs[i+1];
7065           temp_u|=(1LL<<dops[i].rt1)|(1LL<<dops[i].rt2);
7066           temp_u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7067           temp_u|=1;
7068           temp_gte_u|=gte_rt[i];
7069           temp_gte_u&=~gte_rs[i];
7070           unneeded_reg[i]=temp_u;
7071           gte_unneeded[i]=temp_gte_u;
7072           // Only go three levels deep.  This recursion can take an
7073           // excessive amount of time if there are a lot of nested loops.
7074           if(r<2) {
7075             pass2_unneeded_regs((ba[i]-start)>>2,i-1,r+1);
7076           }else{
7077             unneeded_reg[(ba[i]-start)>>2]=1;
7078             gte_unneeded[(ba[i]-start)>>2]=gte_u_unknown;
7079           }
7080         } /*else*/ if(1) {
7081           if (dops[i].is_ujump)
7082           {
7083             // Unconditional branch
7084             u=unneeded_reg[(ba[i]-start)>>2];
7085             gte_u=gte_unneeded[(ba[i]-start)>>2];
7086             branch_unneeded_reg[i]=u;
7087             // Merge in delay slot
7088             u|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
7089             u&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7090             u|=1;
7091             gte_u|=gte_rt[i+1];
7092             gte_u&=~gte_rs[i+1];
7093           } else {
7094             // Conditional branch
7095             b=unneeded_reg[(ba[i]-start)>>2];
7096             gte_b=gte_unneeded[(ba[i]-start)>>2];
7097             branch_unneeded_reg[i]=b;
7098             // Branch delay slot
7099             b|=(1LL<<dops[i+1].rt1)|(1LL<<dops[i+1].rt2);
7100             b&=~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7101             b|=1;
7102             gte_b|=gte_rt[i+1];
7103             gte_b&=~gte_rs[i+1];
7104             u&=b;
7105             gte_u&=gte_b;
7106             if(i<slen-1) {
7107               branch_unneeded_reg[i]&=unneeded_reg[i+2];
7108             } else {
7109               branch_unneeded_reg[i]=1;
7110             }
7111           }
7112         }
7113       }
7114     }
7115     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
7116     {
7117       // SYSCALL instruction (software interrupt)
7118       u=1;
7119     }
7120     else if(dops[i].itype==COP0 && dops[i].opcode2==0x10)
7121     {
7122       // RFE
7123       u=1;
7124     }
7125     //u=1; // DEBUG
7126     // Written registers are unneeded
7127     u|=1LL<<dops[i].rt1;
7128     u|=1LL<<dops[i].rt2;
7129     gte_u|=gte_rt[i];
7130     // Accessed registers are needed
7131     u&=~(1LL<<dops[i].rs1);
7132     u&=~(1LL<<dops[i].rs2);
7133     gte_u&=~gte_rs[i];
7134     if(gte_rs[i]&&dops[i].rt1&&(unneeded_reg[i+1]&(1ll<<dops[i].rt1)))
7135       gte_u|=gte_rs[i]&gte_unneeded[i+1]; // MFC2/CFC2 to dead register, unneeded
7136     // Source-target dependencies
7137     // R0 is always unneeded
7138     u|=1;
7139     // Save it
7140     unneeded_reg[i]=u;
7141     gte_unneeded[i]=gte_u;
7142     /*
7143     printf("ur (%d,%d) %x: ",istart,iend,start+i*4);
7144     printf("U:");
7145     int r;
7146     for(r=1;r<=CCREG;r++) {
7147       if((unneeded_reg[i]>>r)&1) {
7148         if(r==HIREG) printf(" HI");
7149         else if(r==LOREG) printf(" LO");
7150         else printf(" r%d",r);
7151       }
7152     }
7153     printf("\n");
7154     */
7155   }
7156 }
7157
7158 static noinline void pass3_register_alloc(u_int addr)
7159 {
7160   struct regstat current; // Current register allocations/status
7161   clear_all_regs(current.regmap_entry);
7162   clear_all_regs(current.regmap);
7163   current.wasdirty = current.dirty = 0;
7164   current.u = unneeded_reg[0];
7165   alloc_reg(&current, 0, CCREG);
7166   dirty_reg(&current, CCREG);
7167   current.wasconst = 0;
7168   current.isconst = 0;
7169   current.loadedconst = 0;
7170   current.waswritten = 0;
7171   int ds=0;
7172   int cc=0;
7173   int hr;
7174   int i, j;
7175
7176   if (addr & 1) {
7177     // First instruction is delay slot
7178     cc=-1;
7179     dops[1].bt=1;
7180     ds=1;
7181     unneeded_reg[0]=1;
7182     current.regmap[HOST_BTREG]=BTREG;
7183   }
7184
7185   for(i=0;i<slen;i++)
7186   {
7187     if(dops[i].bt)
7188     {
7189       for(hr=0;hr<HOST_REGS;hr++)
7190       {
7191         // Is this really necessary?
7192         if(current.regmap[hr]==0) current.regmap[hr]=-1;
7193       }
7194       current.isconst=0;
7195       current.waswritten=0;
7196     }
7197
7198     memcpy(regmap_pre[i],current.regmap,sizeof(current.regmap));
7199     regs[i].wasconst=current.isconst;
7200     regs[i].wasdirty=current.dirty;
7201     regs[i].dirty=0;
7202     regs[i].u=0;
7203     regs[i].isconst=0;
7204     regs[i].loadedconst=0;
7205     if (!dops[i].is_jump) {
7206       if(i+1<slen) {
7207         current.u=unneeded_reg[i+1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7208         current.u|=1;
7209       } else {
7210         current.u=1;
7211       }
7212     } else {
7213       if(i+1<slen) {
7214         current.u=branch_unneeded_reg[i]&~((1LL<<dops[i+1].rs1)|(1LL<<dops[i+1].rs2));
7215         current.u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7216         current.u|=1;
7217       } else {
7218         SysPrintf("oops, branch at end of block with no delay slot @%08x\n", start + i*4);
7219         abort();
7220       }
7221     }
7222     dops[i].is_ds=ds;
7223     if(ds) {
7224       ds=0; // Skip delay slot, already allocated as part of branch
7225       // ...but we need to alloc it in case something jumps here
7226       if(i+1<slen) {
7227         current.u=branch_unneeded_reg[i-1]&unneeded_reg[i+1];
7228       }else{
7229         current.u=branch_unneeded_reg[i-1];
7230       }
7231       current.u&=~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7232       current.u|=1;
7233       struct regstat temp;
7234       memcpy(&temp,&current,sizeof(current));
7235       temp.wasdirty=temp.dirty;
7236       // TODO: Take into account unconditional branches, as below
7237       delayslot_alloc(&temp,i);
7238       memcpy(regs[i].regmap,temp.regmap,sizeof(temp.regmap));
7239       regs[i].wasdirty=temp.wasdirty;
7240       regs[i].dirty=temp.dirty;
7241       regs[i].isconst=0;
7242       regs[i].wasconst=0;
7243       current.isconst=0;
7244       // Create entry (branch target) regmap
7245       for(hr=0;hr<HOST_REGS;hr++)
7246       {
7247         int r=temp.regmap[hr];
7248         if(r>=0) {
7249           if(r!=regmap_pre[i][hr]) {
7250             regs[i].regmap_entry[hr]=-1;
7251           }
7252           else
7253           {
7254               assert(r < 64);
7255               if((current.u>>r)&1) {
7256                 regs[i].regmap_entry[hr]=-1;
7257                 regs[i].regmap[hr]=-1;
7258                 //Don't clear regs in the delay slot as the branch might need them
7259                 //current.regmap[hr]=-1;
7260               }else
7261                 regs[i].regmap_entry[hr]=r;
7262           }
7263         } else {
7264           // First instruction expects CCREG to be allocated
7265           if(i==0&&hr==HOST_CCREG)
7266             regs[i].regmap_entry[hr]=CCREG;
7267           else
7268             regs[i].regmap_entry[hr]=-1;
7269         }
7270       }
7271     }
7272     else { // Not delay slot
7273       switch(dops[i].itype) {
7274         case UJUMP:
7275           //current.isconst=0; // DEBUG
7276           //current.wasconst=0; // DEBUG
7277           //regs[i].wasconst=0; // DEBUG
7278           clear_const(&current,dops[i].rt1);
7279           alloc_cc(&current,i);
7280           dirty_reg(&current,CCREG);
7281           if (dops[i].rt1==31) {
7282             alloc_reg(&current,i,31);
7283             dirty_reg(&current,31);
7284             //assert(dops[i+1].rs1!=31&&dops[i+1].rs2!=31);
7285             //assert(dops[i+1].rt1!=dops[i].rt1);
7286             #ifdef REG_PREFETCH
7287             alloc_reg(&current,i,PTEMP);
7288             #endif
7289           }
7290           dops[i].ooo=1;
7291           delayslot_alloc(&current,i+1);
7292           //current.isconst=0; // DEBUG
7293           ds=1;
7294           //printf("i=%d, isconst=%x\n",i,current.isconst);
7295           break;
7296         case RJUMP:
7297           //current.isconst=0;
7298           //current.wasconst=0;
7299           //regs[i].wasconst=0;
7300           clear_const(&current,dops[i].rs1);
7301           clear_const(&current,dops[i].rt1);
7302           alloc_cc(&current,i);
7303           dirty_reg(&current,CCREG);
7304           if (!ds_writes_rjump_rs(i)) {
7305             alloc_reg(&current,i,dops[i].rs1);
7306             if (dops[i].rt1!=0) {
7307               alloc_reg(&current,i,dops[i].rt1);
7308               dirty_reg(&current,dops[i].rt1);
7309               assert(dops[i+1].rs1!=dops[i].rt1&&dops[i+1].rs2!=dops[i].rt1);
7310               assert(dops[i+1].rt1!=dops[i].rt1);
7311               #ifdef REG_PREFETCH
7312               alloc_reg(&current,i,PTEMP);
7313               #endif
7314             }
7315             #ifdef USE_MINI_HT
7316             if(dops[i].rs1==31) { // JALR
7317               alloc_reg(&current,i,RHASH);
7318               alloc_reg(&current,i,RHTBL);
7319             }
7320             #endif
7321             delayslot_alloc(&current,i+1);
7322           } else {
7323             // The delay slot overwrites our source register,
7324             // allocate a temporary register to hold the old value.
7325             current.isconst=0;
7326             current.wasconst=0;
7327             regs[i].wasconst=0;
7328             delayslot_alloc(&current,i+1);
7329             current.isconst=0;
7330             alloc_reg(&current,i,RTEMP);
7331           }
7332           //current.isconst=0; // DEBUG
7333           dops[i].ooo=1;
7334           ds=1;
7335           break;
7336         case CJUMP:
7337           //current.isconst=0;
7338           //current.wasconst=0;
7339           //regs[i].wasconst=0;
7340           clear_const(&current,dops[i].rs1);
7341           clear_const(&current,dops[i].rs2);
7342           if((dops[i].opcode&0x3E)==4) // BEQ/BNE
7343           {
7344             alloc_cc(&current,i);
7345             dirty_reg(&current,CCREG);
7346             if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7347             if(dops[i].rs2) alloc_reg(&current,i,dops[i].rs2);
7348             if((dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2))||
7349                (dops[i].rs2&&(dops[i].rs2==dops[i+1].rt1||dops[i].rs2==dops[i+1].rt2))) {
7350               // The delay slot overwrites one of our conditions.
7351               // Allocate the branch condition registers instead.
7352               current.isconst=0;
7353               current.wasconst=0;
7354               regs[i].wasconst=0;
7355               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7356               if(dops[i].rs2) alloc_reg(&current,i,dops[i].rs2);
7357             }
7358             else
7359             {
7360               dops[i].ooo=1;
7361               delayslot_alloc(&current,i+1);
7362             }
7363           }
7364           else
7365           if((dops[i].opcode&0x3E)==6) // BLEZ/BGTZ
7366           {
7367             alloc_cc(&current,i);
7368             dirty_reg(&current,CCREG);
7369             alloc_reg(&current,i,dops[i].rs1);
7370             if(dops[i].rs1&&(dops[i].rs1==dops[i+1].rt1||dops[i].rs1==dops[i+1].rt2)) {
7371               // The delay slot overwrites one of our conditions.
7372               // Allocate the branch condition registers instead.
7373               current.isconst=0;
7374               current.wasconst=0;
7375               regs[i].wasconst=0;
7376               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7377             }
7378             else
7379             {
7380               dops[i].ooo=1;
7381               delayslot_alloc(&current,i+1);
7382             }
7383           }
7384           else
7385           // Don't alloc the delay slot yet because we might not execute it
7386           if((dops[i].opcode&0x3E)==0x14) // BEQL/BNEL
7387           {
7388             current.isconst=0;
7389             current.wasconst=0;
7390             regs[i].wasconst=0;
7391             alloc_cc(&current,i);
7392             dirty_reg(&current,CCREG);
7393             alloc_reg(&current,i,dops[i].rs1);
7394             alloc_reg(&current,i,dops[i].rs2);
7395           }
7396           else
7397           if((dops[i].opcode&0x3E)==0x16) // BLEZL/BGTZL
7398           {
7399             current.isconst=0;
7400             current.wasconst=0;
7401             regs[i].wasconst=0;
7402             alloc_cc(&current,i);
7403             dirty_reg(&current,CCREG);
7404             alloc_reg(&current,i,dops[i].rs1);
7405           }
7406           ds=1;
7407           //current.isconst=0;
7408           break;
7409         case SJUMP:
7410           //current.isconst=0;
7411           //current.wasconst=0;
7412           //regs[i].wasconst=0;
7413           clear_const(&current,dops[i].rs1);
7414           clear_const(&current,dops[i].rt1);
7415           //if((dops[i].opcode2&0x1E)==0x0) // BLTZ/BGEZ
7416           if((dops[i].opcode2&0x0E)==0x0) // BLTZ/BGEZ
7417           {
7418             alloc_cc(&current,i);
7419             dirty_reg(&current,CCREG);
7420             alloc_reg(&current,i,dops[i].rs1);
7421             if (dops[i].rt1==31) { // BLTZAL/BGEZAL
7422               alloc_reg(&current,i,31);
7423               dirty_reg(&current,31);
7424               //#ifdef REG_PREFETCH
7425               //alloc_reg(&current,i,PTEMP);
7426               //#endif
7427             }
7428             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.
7429                ||(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
7430               // Allocate the branch condition registers instead.
7431               current.isconst=0;
7432               current.wasconst=0;
7433               regs[i].wasconst=0;
7434               if(dops[i].rs1) alloc_reg(&current,i,dops[i].rs1);
7435             }
7436             else
7437             {
7438               dops[i].ooo=1;
7439               delayslot_alloc(&current,i+1);
7440             }
7441           }
7442           else
7443           // Don't alloc the delay slot yet because we might not execute it
7444           if((dops[i].opcode2&0x1E)==0x2) // BLTZL/BGEZL
7445           {
7446             current.isconst=0;
7447             current.wasconst=0;
7448             regs[i].wasconst=0;
7449             alloc_cc(&current,i);
7450             dirty_reg(&current,CCREG);
7451             alloc_reg(&current,i,dops[i].rs1);
7452           }
7453           ds=1;
7454           //current.isconst=0;
7455           break;
7456         case IMM16:
7457           imm16_alloc(&current,i);
7458           break;
7459         case LOAD:
7460         case LOADLR:
7461           load_alloc(&current,i);
7462           break;
7463         case STORE:
7464         case STORELR:
7465           store_alloc(&current,i);
7466           break;
7467         case ALU:
7468           alu_alloc(&current,i);
7469           break;
7470         case SHIFT:
7471           shift_alloc(&current,i);
7472           break;
7473         case MULTDIV:
7474           multdiv_alloc(&current,i);
7475           break;
7476         case SHIFTIMM:
7477           shiftimm_alloc(&current,i);
7478           break;
7479         case MOV:
7480           mov_alloc(&current,i);
7481           break;
7482         case COP0:
7483           cop0_alloc(&current,i);
7484           break;
7485         case COP1:
7486           break;
7487         case COP2:
7488           cop2_alloc(&current,i);
7489           break;
7490         case C1LS:
7491           c1ls_alloc(&current,i);
7492           break;
7493         case C2LS:
7494           c2ls_alloc(&current,i);
7495           break;
7496         case C2OP:
7497           c2op_alloc(&current,i);
7498           break;
7499         case SYSCALL:
7500         case HLECALL:
7501         case INTCALL:
7502           syscall_alloc(&current,i);
7503           break;
7504       }
7505
7506       // Create entry (branch target) regmap
7507       for(hr=0;hr<HOST_REGS;hr++)
7508       {
7509         int r,or;
7510         r=current.regmap[hr];
7511         if(r>=0) {
7512           if(r!=regmap_pre[i][hr]) {
7513             // TODO: delay slot (?)
7514             or=get_reg(regmap_pre[i],r); // Get old mapping for this register
7515             if(or<0||r>=TEMPREG){
7516               regs[i].regmap_entry[hr]=-1;
7517             }
7518             else
7519             {
7520               // Just move it to a different register
7521               regs[i].regmap_entry[hr]=r;
7522               // If it was dirty before, it's still dirty
7523               if((regs[i].wasdirty>>or)&1) dirty_reg(&current,r);
7524             }
7525           }
7526           else
7527           {
7528             // Unneeded
7529             if(r==0){
7530               regs[i].regmap_entry[hr]=0;
7531             }
7532             else
7533             {
7534               assert(r<64);
7535               if((current.u>>r)&1) {
7536                 regs[i].regmap_entry[hr]=-1;
7537                 //regs[i].regmap[hr]=-1;
7538                 current.regmap[hr]=-1;
7539               }else
7540                 regs[i].regmap_entry[hr]=r;
7541             }
7542           }
7543         } else {
7544           // Branches expect CCREG to be allocated at the target
7545           if(regmap_pre[i][hr]==CCREG)
7546             regs[i].regmap_entry[hr]=CCREG;
7547           else
7548             regs[i].regmap_entry[hr]=-1;
7549         }
7550       }
7551       memcpy(regs[i].regmap,current.regmap,sizeof(current.regmap));
7552     }
7553
7554     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)
7555       current.waswritten|=1<<dops[i-1].rs1;
7556     current.waswritten&=~(1<<dops[i].rt1);
7557     current.waswritten&=~(1<<dops[i].rt2);
7558     if((dops[i].itype==STORE||dops[i].itype==STORELR||(dops[i].itype==C2LS&&dops[i].opcode==0x3a))&&(u_int)imm[i]>=0x800)
7559       current.waswritten&=~(1<<dops[i].rs1);
7560
7561     /* Branch post-alloc */
7562     if(i>0)
7563     {
7564       current.wasdirty=current.dirty;
7565       switch(dops[i-1].itype) {
7566         case UJUMP:
7567           memcpy(&branch_regs[i-1],&current,sizeof(current));
7568           branch_regs[i-1].isconst=0;
7569           branch_regs[i-1].wasconst=0;
7570           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
7571           alloc_cc(&branch_regs[i-1],i-1);
7572           dirty_reg(&branch_regs[i-1],CCREG);
7573           if(dops[i-1].rt1==31) { // JAL
7574             alloc_reg(&branch_regs[i-1],i-1,31);
7575             dirty_reg(&branch_regs[i-1],31);
7576           }
7577           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7578           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7579           break;
7580         case RJUMP:
7581           memcpy(&branch_regs[i-1],&current,sizeof(current));
7582           branch_regs[i-1].isconst=0;
7583           branch_regs[i-1].wasconst=0;
7584           branch_regs[i-1].u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
7585           alloc_cc(&branch_regs[i-1],i-1);
7586           dirty_reg(&branch_regs[i-1],CCREG);
7587           alloc_reg(&branch_regs[i-1],i-1,dops[i-1].rs1);
7588           if(dops[i-1].rt1!=0) { // JALR
7589             alloc_reg(&branch_regs[i-1],i-1,dops[i-1].rt1);
7590             dirty_reg(&branch_regs[i-1],dops[i-1].rt1);
7591           }
7592           #ifdef USE_MINI_HT
7593           if(dops[i-1].rs1==31) { // JALR
7594             alloc_reg(&branch_regs[i-1],i-1,RHASH);
7595             alloc_reg(&branch_regs[i-1],i-1,RHTBL);
7596           }
7597           #endif
7598           memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7599           memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7600           break;
7601         case CJUMP:
7602           if((dops[i-1].opcode&0x3E)==4) // BEQ/BNE
7603           {
7604             alloc_cc(&current,i-1);
7605             dirty_reg(&current,CCREG);
7606             if((dops[i-1].rs1&&(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2))||
7607                (dops[i-1].rs2&&(dops[i-1].rs2==dops[i].rt1||dops[i-1].rs2==dops[i].rt2))) {
7608               // The delay slot overwrote one of our conditions
7609               // Delay slot goes after the test (in order)
7610               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7611               current.u|=1;
7612               delayslot_alloc(&current,i);
7613               current.isconst=0;
7614             }
7615             else
7616             {
7617               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i-1].rs1)|(1LL<<dops[i-1].rs2));
7618               // Alloc the branch condition registers
7619               if(dops[i-1].rs1) alloc_reg(&current,i-1,dops[i-1].rs1);
7620               if(dops[i-1].rs2) alloc_reg(&current,i-1,dops[i-1].rs2);
7621             }
7622             memcpy(&branch_regs[i-1],&current,sizeof(current));
7623             branch_regs[i-1].isconst=0;
7624             branch_regs[i-1].wasconst=0;
7625             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
7626             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7627           }
7628           else
7629           if((dops[i-1].opcode&0x3E)==6) // BLEZ/BGTZ
7630           {
7631             alloc_cc(&current,i-1);
7632             dirty_reg(&current,CCREG);
7633             if(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2) {
7634               // The delay slot overwrote the branch condition
7635               // Delay slot goes after the test (in order)
7636               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7637               current.u|=1;
7638               delayslot_alloc(&current,i);
7639               current.isconst=0;
7640             }
7641             else
7642             {
7643               current.u=branch_unneeded_reg[i-1]&~(1LL<<dops[i-1].rs1);
7644               // Alloc the branch condition register
7645               alloc_reg(&current,i-1,dops[i-1].rs1);
7646             }
7647             memcpy(&branch_regs[i-1],&current,sizeof(current));
7648             branch_regs[i-1].isconst=0;
7649             branch_regs[i-1].wasconst=0;
7650             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
7651             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7652           }
7653           else
7654           // Alloc the delay slot in case the branch is taken
7655           if((dops[i-1].opcode&0x3E)==0x14) // BEQL/BNEL
7656           {
7657             memcpy(&branch_regs[i-1],&current,sizeof(current));
7658             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;
7659             alloc_cc(&branch_regs[i-1],i);
7660             dirty_reg(&branch_regs[i-1],CCREG);
7661             delayslot_alloc(&branch_regs[i-1],i);
7662             branch_regs[i-1].isconst=0;
7663             alloc_reg(&current,i,CCREG); // Not taken path
7664             dirty_reg(&current,CCREG);
7665             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7666           }
7667           else
7668           if((dops[i-1].opcode&0x3E)==0x16) // BLEZL/BGTZL
7669           {
7670             memcpy(&branch_regs[i-1],&current,sizeof(current));
7671             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;
7672             alloc_cc(&branch_regs[i-1],i);
7673             dirty_reg(&branch_regs[i-1],CCREG);
7674             delayslot_alloc(&branch_regs[i-1],i);
7675             branch_regs[i-1].isconst=0;
7676             alloc_reg(&current,i,CCREG); // Not taken path
7677             dirty_reg(&current,CCREG);
7678             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7679           }
7680           break;
7681         case SJUMP:
7682           //if((dops[i-1].opcode2&0x1E)==0) // BLTZ/BGEZ
7683           if((dops[i-1].opcode2&0x0E)==0) // BLTZ/BGEZ
7684           {
7685             alloc_cc(&current,i-1);
7686             dirty_reg(&current,CCREG);
7687             if(dops[i-1].rs1==dops[i].rt1||dops[i-1].rs1==dops[i].rt2) {
7688               // The delay slot overwrote the branch condition
7689               // Delay slot goes after the test (in order)
7690               current.u=branch_unneeded_reg[i-1]&~((1LL<<dops[i].rs1)|(1LL<<dops[i].rs2));
7691               current.u|=1;
7692               delayslot_alloc(&current,i);
7693               current.isconst=0;
7694             }
7695             else
7696             {
7697               current.u=branch_unneeded_reg[i-1]&~(1LL<<dops[i-1].rs1);
7698               // Alloc the branch condition register
7699               alloc_reg(&current,i-1,dops[i-1].rs1);
7700             }
7701             memcpy(&branch_regs[i-1],&current,sizeof(current));
7702             branch_regs[i-1].isconst=0;
7703             branch_regs[i-1].wasconst=0;
7704             memcpy(&branch_regs[i-1].regmap_entry,&current.regmap,sizeof(current.regmap));
7705             memcpy(constmap[i],constmap[i-1],sizeof(constmap[i]));
7706           }
7707           else
7708           // Alloc the delay slot in case the branch is taken
7709           if((dops[i-1].opcode2&0x1E)==2) // BLTZL/BGEZL
7710           {
7711             memcpy(&branch_regs[i-1],&current,sizeof(current));
7712             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;
7713             alloc_cc(&branch_regs[i-1],i);
7714             dirty_reg(&branch_regs[i-1],CCREG);
7715             delayslot_alloc(&branch_regs[i-1],i);
7716             branch_regs[i-1].isconst=0;
7717             alloc_reg(&current,i,CCREG); // Not taken path
7718             dirty_reg(&current,CCREG);
7719             memcpy(&branch_regs[i-1].regmap_entry,&branch_regs[i-1].regmap,sizeof(current.regmap));
7720           }
7721           // FIXME: BLTZAL/BGEZAL
7722           if(dops[i-1].opcode2&0x10) { // BxxZAL
7723             alloc_reg(&branch_regs[i-1],i-1,31);
7724             dirty_reg(&branch_regs[i-1],31);
7725           }
7726           break;
7727       }
7728
7729       if (dops[i-1].is_ujump)
7730       {
7731         if(dops[i-1].rt1==31) // JAL/JALR
7732         {
7733           // Subroutine call will return here, don't alloc any registers
7734           current.dirty=0;
7735           clear_all_regs(current.regmap);
7736           alloc_reg(&current,i,CCREG);
7737           dirty_reg(&current,CCREG);
7738         }
7739         else if(i+1<slen)
7740         {
7741           // Internal branch will jump here, match registers to caller
7742           current.dirty=0;
7743           clear_all_regs(current.regmap);
7744           alloc_reg(&current,i,CCREG);
7745           dirty_reg(&current,CCREG);
7746           for(j=i-1;j>=0;j--)
7747           {
7748             if(ba[j]==start+i*4+4) {
7749               memcpy(current.regmap,branch_regs[j].regmap,sizeof(current.regmap));
7750               current.dirty=branch_regs[j].dirty;
7751               break;
7752             }
7753           }
7754           while(j>=0) {
7755             if(ba[j]==start+i*4+4) {
7756               for(hr=0;hr<HOST_REGS;hr++) {
7757                 if(current.regmap[hr]!=branch_regs[j].regmap[hr]) {
7758                   current.regmap[hr]=-1;
7759                 }
7760                 current.dirty&=branch_regs[j].dirty;
7761               }
7762             }
7763             j--;
7764           }
7765         }
7766       }
7767     }
7768
7769     // Count cycles in between branches
7770     ccadj[i] = CLOCK_ADJUST(cc);
7771     if (i > 0 && (dops[i-1].is_jump || dops[i].itype == SYSCALL || dops[i].itype == HLECALL))
7772     {
7773       cc=0;
7774     }
7775 #if !defined(DRC_DBG)
7776     else if(dops[i].itype==C2OP&&gte_cycletab[source[i]&0x3f]>2)
7777     {
7778       // this should really be removed since the real stalls have been implemented,
7779       // but doing so causes sizeable perf regression against the older version
7780       u_int gtec = gte_cycletab[source[i] & 0x3f];
7781       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? gtec/2 : 2;
7782     }
7783     else if(i>1&&dops[i].itype==STORE&&dops[i-1].itype==STORE&&dops[i-2].itype==STORE&&!dops[i].bt)
7784     {
7785       cc+=4;
7786     }
7787     else if(dops[i].itype==C2LS)
7788     {
7789       // same as with C2OP
7790       cc += HACK_ENABLED(NDHACK_NO_STALLS) ? 4 : 2;
7791     }
7792 #endif
7793     else
7794     {
7795       cc++;
7796     }
7797
7798     if(!dops[i].is_ds) {
7799       regs[i].dirty=current.dirty;
7800       regs[i].isconst=current.isconst;
7801       memcpy(constmap[i],current_constmap,sizeof(constmap[i]));
7802     }
7803     for(hr=0;hr<HOST_REGS;hr++) {
7804       if(hr!=EXCLUDE_REG&&regs[i].regmap[hr]>=0) {
7805         if(regmap_pre[i][hr]!=regs[i].regmap[hr]) {
7806           regs[i].wasconst&=~(1<<hr);
7807         }
7808       }
7809     }
7810     if(current.regmap[HOST_BTREG]==BTREG) current.regmap[HOST_BTREG]=-1;
7811     regs[i].waswritten=current.waswritten;
7812   }
7813 }
7814
7815 static noinline void pass4_cull_unused_regs(void)
7816 {
7817   u_int last_needed_regs[4] = {0,0,0,0};
7818   u_int nr=0;
7819   int i;
7820
7821   for (i=slen-1;i>=0;i--)
7822   {
7823     int hr;
7824     __builtin_prefetch(regs[i-2].regmap);
7825     if(dops[i].is_jump)
7826     {
7827       if(ba[i]<start || ba[i]>=(start+slen*4))
7828       {
7829         // Branch out of this block, don't need anything
7830         nr=0;
7831       }
7832       else
7833       {
7834         // Internal branch
7835         // Need whatever matches the target
7836         nr=0;
7837         int t=(ba[i]-start)>>2;
7838         for(hr=0;hr<HOST_REGS;hr++)
7839         {
7840           if(regs[i].regmap_entry[hr]>=0) {
7841             if(regs[i].regmap_entry[hr]==regs[t].regmap_entry[hr]) nr|=1<<hr;
7842           }
7843         }
7844       }
7845       // Conditional branch may need registers for following instructions
7846       if (!dops[i].is_ujump)
7847       {
7848         if(i<slen-2) {
7849           nr |= last_needed_regs[(i+2) & 3];
7850           for(hr=0;hr<HOST_REGS;hr++)
7851           {
7852             if(regmap_pre[i+2][hr]>=0&&get_reg(regs[i+2].regmap_entry,regmap_pre[i+2][hr])<0) nr&=~(1<<hr);
7853             //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]);
7854           }
7855         }
7856       }
7857       // Don't need stuff which is overwritten
7858       //if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
7859       //if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
7860       // Merge in delay slot
7861       if (dops[i+1].rt1) nr &= ~get_regm(regs[i].regmap, dops[i+1].rt1);
7862       if (dops[i+1].rt2) nr &= ~get_regm(regs[i].regmap, dops[i+1].rt2);
7863       nr |= get_regm(regmap_pre[i], dops[i+1].rs1);
7864       nr |= get_regm(regmap_pre[i], dops[i+1].rs2);
7865       nr |= get_regm(regs[i].regmap_entry, dops[i+1].rs1);
7866       nr |= get_regm(regs[i].regmap_entry, dops[i+1].rs2);
7867       if (ram_offset && (dops[i+1].is_load || dops[i+1].is_store)) {
7868         nr |= get_regm(regmap_pre[i], ROREG);
7869         nr |= get_regm(regs[i].regmap_entry, ROREG);
7870       }
7871       if (dops[i+1].is_store) {
7872         nr |= get_regm(regmap_pre[i], INVCP);
7873         nr |= get_regm(regs[i].regmap_entry, INVCP);
7874       }
7875     }
7876     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
7877     {
7878       // SYSCALL instruction (software interrupt)
7879       nr=0;
7880     }
7881     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
7882     {
7883       // ERET instruction (return from interrupt)
7884       nr=0;
7885     }
7886     else // Non-branch
7887     {
7888       if(i<slen-1) {
7889         for(hr=0;hr<HOST_REGS;hr++) {
7890           if(regmap_pre[i+1][hr]>=0&&get_reg(regs[i+1].regmap_entry,regmap_pre[i+1][hr])<0) nr&=~(1<<hr);
7891           if(regs[i].regmap[hr]!=regmap_pre[i+1][hr]) nr&=~(1<<hr);
7892           if(regs[i].regmap[hr]!=regmap_pre[i][hr]) nr&=~(1<<hr);
7893           if(regs[i].regmap[hr]<0) nr&=~(1<<hr);
7894         }
7895       }
7896     }
7897     // Overwritten registers are not needed
7898     if (dops[i].rt1) nr &= ~get_regm(regs[i].regmap, dops[i].rt1);
7899     if (dops[i].rt2) nr &= ~get_regm(regs[i].regmap, dops[i].rt2);
7900     nr &= ~get_regm(regs[i].regmap, FTEMP);
7901     // Source registers are needed
7902     nr |= get_regm(regmap_pre[i], dops[i].rs1);
7903     nr |= get_regm(regmap_pre[i], dops[i].rs2);
7904     nr |= get_regm(regs[i].regmap_entry, dops[i].rs1);
7905     nr |= get_regm(regs[i].regmap_entry, dops[i].rs2);
7906     if (ram_offset && (dops[i].is_load || dops[i].is_store)) {
7907       nr |= get_regm(regmap_pre[i], ROREG);
7908       nr |= get_regm(regs[i].regmap_entry, ROREG);
7909     }
7910     if (dops[i].is_store) {
7911       nr |= get_regm(regmap_pre[i], INVCP);
7912       nr |= get_regm(regs[i].regmap_entry, INVCP);
7913     }
7914
7915     if (i > 0 && !dops[i].bt && regs[i].wasdirty)
7916     for(hr=0;hr<HOST_REGS;hr++)
7917     {
7918       // Don't store a register immediately after writing it,
7919       // may prevent dual-issue.
7920       // But do so if this is a branch target, otherwise we
7921       // might have to load the register before the branch.
7922       if((regs[i].wasdirty>>hr)&1) {
7923         if((regmap_pre[i][hr]>0&&!((unneeded_reg[i]>>regmap_pre[i][hr])&1))) {
7924           if(dops[i-1].rt1==regmap_pre[i][hr]) nr|=1<<hr;
7925           if(dops[i-1].rt2==regmap_pre[i][hr]) nr|=1<<hr;
7926         }
7927         if((regs[i].regmap_entry[hr]>0&&!((unneeded_reg[i]>>regs[i].regmap_entry[hr])&1))) {
7928           if(dops[i-1].rt1==regs[i].regmap_entry[hr]) nr|=1<<hr;
7929           if(dops[i-1].rt2==regs[i].regmap_entry[hr]) nr|=1<<hr;
7930         }
7931       }
7932     }
7933     // Cycle count is needed at branches.  Assume it is needed at the target too.
7934     if(i==0||dops[i].bt||dops[i].itype==CJUMP) {
7935       if(regmap_pre[i][HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
7936       if(regs[i].regmap_entry[HOST_CCREG]==CCREG) nr|=1<<HOST_CCREG;
7937     }
7938     // Save it
7939     last_needed_regs[i & 3] = nr;
7940
7941     // Deallocate unneeded registers
7942     for(hr=0;hr<HOST_REGS;hr++)
7943     {
7944       if(!((nr>>hr)&1)) {
7945         if(regs[i].regmap_entry[hr]!=CCREG) regs[i].regmap_entry[hr]=-1;
7946         if(dops[i].is_jump)
7947         {
7948           int map1 = 0, map2 = 0, temp = 0; // or -1 ??
7949           if (dops[i+1].is_load || dops[i+1].is_store)
7950             map1 = ROREG;
7951           if (dops[i+1].is_store)
7952             map2 = INVCP;
7953           if(dops[i+1].itype==LOADLR || dops[i+1].itype==STORELR || dops[i+1].itype==C2LS)
7954             temp = FTEMP;
7955           if(regs[i].regmap[hr]!=dops[i].rs1 && regs[i].regmap[hr]!=dops[i].rs2 &&
7956              regs[i].regmap[hr]!=dops[i].rt1 && regs[i].regmap[hr]!=dops[i].rt2 &&
7957              regs[i].regmap[hr]!=dops[i+1].rt1 && regs[i].regmap[hr]!=dops[i+1].rt2 &&
7958              regs[i].regmap[hr]!=dops[i+1].rs1 && regs[i].regmap[hr]!=dops[i+1].rs2 &&
7959              regs[i].regmap[hr]!=temp && regs[i].regmap[hr]!=PTEMP &&
7960              regs[i].regmap[hr]!=RHASH && regs[i].regmap[hr]!=RHTBL &&
7961              regs[i].regmap[hr]!=RTEMP && regs[i].regmap[hr]!=CCREG &&
7962              regs[i].regmap[hr]!=map1 && regs[i].regmap[hr]!=map2)
7963           {
7964             regs[i].regmap[hr]=-1;
7965             regs[i].isconst&=~(1<<hr);
7966             regs[i].dirty&=~(1<<hr);
7967             regs[i+1].wasdirty&=~(1<<hr);
7968             if(branch_regs[i].regmap[hr]!=dops[i].rs1 && branch_regs[i].regmap[hr]!=dops[i].rs2 &&
7969                branch_regs[i].regmap[hr]!=dops[i].rt1 && branch_regs[i].regmap[hr]!=dops[i].rt2 &&
7970                branch_regs[i].regmap[hr]!=dops[i+1].rt1 && branch_regs[i].regmap[hr]!=dops[i+1].rt2 &&
7971                branch_regs[i].regmap[hr]!=dops[i+1].rs1 && branch_regs[i].regmap[hr]!=dops[i+1].rs2 &&
7972                branch_regs[i].regmap[hr]!=temp && branch_regs[i].regmap[hr]!=PTEMP &&
7973                branch_regs[i].regmap[hr]!=RHASH && branch_regs[i].regmap[hr]!=RHTBL &&
7974                branch_regs[i].regmap[hr]!=RTEMP && branch_regs[i].regmap[hr]!=CCREG &&
7975                branch_regs[i].regmap[hr]!=map1 && branch_regs[i].regmap[hr]!=map2)
7976             {
7977               branch_regs[i].regmap[hr]=-1;
7978               branch_regs[i].regmap_entry[hr]=-1;
7979               if (!dops[i].is_ujump)
7980               {
7981                 if (i < slen-2) {
7982                   regmap_pre[i+2][hr]=-1;
7983                   regs[i+2].wasconst&=~(1<<hr);
7984                 }
7985               }
7986             }
7987           }
7988         }
7989         else
7990         {
7991           // Non-branch
7992           if(i>0)
7993           {
7994             int map1 = -1, map2 = -1, temp=-1;
7995             if (dops[i].is_load || dops[i].is_store)
7996               map1 = ROREG;
7997             if (dops[i].is_store)
7998               map2 = INVCP;
7999             if (dops[i].itype==LOADLR || dops[i].itype==STORELR || dops[i].itype==C2LS)
8000               temp = FTEMP;
8001             if(regs[i].regmap[hr]!=dops[i].rt1 && regs[i].regmap[hr]!=dops[i].rt2 &&
8002                regs[i].regmap[hr]!=dops[i].rs1 && regs[i].regmap[hr]!=dops[i].rs2 &&
8003                regs[i].regmap[hr]!=temp && regs[i].regmap[hr]!=map1 && regs[i].regmap[hr]!=map2 &&
8004                //(dops[i].itype!=SPAN||regs[i].regmap[hr]!=CCREG)
8005                regs[i].regmap[hr] != CCREG)
8006             {
8007               if(i<slen-1&&!dops[i].is_ds) {
8008                 assert(regs[i].regmap[hr]<64);
8009                 if(regmap_pre[i+1][hr]!=-1 || regs[i].regmap[hr]>0)
8010                 if(regmap_pre[i+1][hr]!=regs[i].regmap[hr])
8011                 {
8012                   SysPrintf("fail: %x (%d %d!=%d)\n",start+i*4,hr,regmap_pre[i+1][hr],regs[i].regmap[hr]);
8013                   assert(regmap_pre[i+1][hr]==regs[i].regmap[hr]);
8014                 }
8015                 regmap_pre[i+1][hr]=-1;
8016                 if(regs[i+1].regmap_entry[hr]==CCREG) regs[i+1].regmap_entry[hr]=-1;
8017                 regs[i+1].wasconst&=~(1<<hr);
8018               }
8019               regs[i].regmap[hr]=-1;
8020               regs[i].isconst&=~(1<<hr);
8021               regs[i].dirty&=~(1<<hr);
8022               regs[i+1].wasdirty&=~(1<<hr);
8023             }
8024           }
8025         }
8026       } // if needed
8027     } // for hr
8028   }
8029 }
8030
8031 // If a register is allocated during a loop, try to allocate it for the
8032 // entire loop, if possible.  This avoids loading/storing registers
8033 // inside of the loop.
8034 static noinline void pass5a_preallocate1(void)
8035 {
8036   int i, j, hr;
8037   signed char f_regmap[HOST_REGS];
8038   clear_all_regs(f_regmap);
8039   for(i=0;i<slen-1;i++)
8040   {
8041     if(dops[i].itype==UJUMP||dops[i].itype==CJUMP||dops[i].itype==SJUMP)
8042     {
8043       if(ba[i]>=start && ba[i]<(start+i*4))
8044       if(dops[i+1].itype==NOP||dops[i+1].itype==MOV||dops[i+1].itype==ALU
8045       ||dops[i+1].itype==SHIFTIMM||dops[i+1].itype==IMM16||dops[i+1].itype==LOAD
8046       ||dops[i+1].itype==STORE||dops[i+1].itype==STORELR||dops[i+1].itype==C1LS
8047       ||dops[i+1].itype==SHIFT||dops[i+1].itype==COP1
8048       ||dops[i+1].itype==COP2||dops[i+1].itype==C2LS||dops[i+1].itype==C2OP)
8049       {
8050         int t=(ba[i]-start)>>2;
8051         if(t > 0 && !dops[t-1].is_jump) // loop_preload can't handle jumps into delay slots
8052         if(t<2||(dops[t-2].itype!=UJUMP&&dops[t-2].itype!=RJUMP)||dops[t-2].rt1!=31) // call/ret assumes no registers allocated
8053         for(hr=0;hr<HOST_REGS;hr++)
8054         {
8055           if(regs[i].regmap[hr]>=0) {
8056             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8057               // dealloc old register
8058               int n;
8059               for(n=0;n<HOST_REGS;n++)
8060               {
8061                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8062               }
8063               // and alloc new one
8064               f_regmap[hr]=regs[i].regmap[hr];
8065             }
8066           }
8067           if(branch_regs[i].regmap[hr]>=0) {
8068             if(f_regmap[hr]!=branch_regs[i].regmap[hr]) {
8069               // dealloc old register
8070               int n;
8071               for(n=0;n<HOST_REGS;n++)
8072               {
8073                 if(f_regmap[n]==branch_regs[i].regmap[hr]) {f_regmap[n]=-1;}
8074               }
8075               // and alloc new one
8076               f_regmap[hr]=branch_regs[i].regmap[hr];
8077             }
8078           }
8079           if(dops[i].ooo) {
8080             if(count_free_regs(regs[i].regmap)<=minimum_free_regs[i+1])
8081               f_regmap[hr]=branch_regs[i].regmap[hr];
8082           }else{
8083             if(count_free_regs(branch_regs[i].regmap)<=minimum_free_regs[i+1])
8084               f_regmap[hr]=branch_regs[i].regmap[hr];
8085           }
8086           // Avoid dirty->clean transition
8087           #ifdef DESTRUCTIVE_WRITEBACK
8088           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;
8089           #endif
8090           // This check is only strictly required in the DESTRUCTIVE_WRITEBACK
8091           // case above, however it's always a good idea.  We can't hoist the
8092           // load if the register was already allocated, so there's no point
8093           // wasting time analyzing most of these cases.  It only "succeeds"
8094           // when the mapping was different and the load can be replaced with
8095           // a mov, which is of negligible benefit.  So such cases are
8096           // skipped below.
8097           if(f_regmap[hr]>0) {
8098             if(regs[t].regmap[hr]==f_regmap[hr]||(regs[t].regmap_entry[hr]<0&&get_reg(regmap_pre[t],f_regmap[hr])<0)) {
8099               int r=f_regmap[hr];
8100               for(j=t;j<=i;j++)
8101               {
8102                 //printf("Test %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8103                 if(r<34&&((unneeded_reg[j]>>r)&1)) break;
8104                 assert(r < 64);
8105                 if(regs[j].regmap[hr]==f_regmap[hr]&&f_regmap[hr]<TEMPREG) {
8106                   //printf("Hit %x -> %x, %x %d/%d\n",start+i*4,ba[i],start+j*4,hr,r);
8107                   int k;
8108                   if(regs[i].regmap[hr]==-1&&branch_regs[i].regmap[hr]==-1) {
8109                     if(get_reg(regs[i].regmap,f_regmap[hr])>=0) break;
8110                     if(get_reg(regs[i+2].regmap,f_regmap[hr])>=0) break;
8111                     k=i;
8112                     while(k>1&&regs[k-1].regmap[hr]==-1) {
8113                       if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8114                         //printf("no free regs for store %x\n",start+(k-1)*4);
8115                         break;
8116                       }
8117                       if(get_reg(regs[k-1].regmap,f_regmap[hr])>=0) {
8118                         //printf("no-match due to different register\n");
8119                         break;
8120                       }
8121                       if (dops[k-2].is_jump) {
8122                         //printf("no-match due to branch\n");
8123                         break;
8124                       }
8125                       // call/ret fast path assumes no registers allocated
8126                       if(k>2&&(dops[k-3].itype==UJUMP||dops[k-3].itype==RJUMP)&&dops[k-3].rt1==31) {
8127                         break;
8128                       }
8129                       k--;
8130                     }
8131                     if(regs[k-1].regmap[hr]==f_regmap[hr]&&regmap_pre[k][hr]==f_regmap[hr]) {
8132                       //printf("Extend r%d, %x ->\n",hr,start+k*4);
8133                       while(k<i) {
8134                         regs[k].regmap_entry[hr]=f_regmap[hr];
8135                         regs[k].regmap[hr]=f_regmap[hr];
8136                         regmap_pre[k+1][hr]=f_regmap[hr];
8137                         regs[k].wasdirty&=~(1<<hr);
8138                         regs[k].dirty&=~(1<<hr);
8139                         regs[k].wasdirty|=(1<<hr)&regs[k-1].dirty;
8140                         regs[k].dirty|=(1<<hr)&regs[k].wasdirty;
8141                         regs[k].wasconst&=~(1<<hr);
8142                         regs[k].isconst&=~(1<<hr);
8143                         k++;
8144                       }
8145                     }
8146                     else {
8147                       //printf("Fail Extend r%d, %x ->\n",hr,start+k*4);
8148                       break;
8149                     }
8150                     assert(regs[i-1].regmap[hr]==f_regmap[hr]);
8151                     if(regs[i-1].regmap[hr]==f_regmap[hr]&&regmap_pre[i][hr]==f_regmap[hr]) {
8152                       //printf("OK fill %x (r%d)\n",start+i*4,hr);
8153                       regs[i].regmap_entry[hr]=f_regmap[hr];
8154                       regs[i].regmap[hr]=f_regmap[hr];
8155                       regs[i].wasdirty&=~(1<<hr);
8156                       regs[i].dirty&=~(1<<hr);
8157                       regs[i].wasdirty|=(1<<hr)&regs[i-1].dirty;
8158                       regs[i].dirty|=(1<<hr)&regs[i-1].dirty;
8159                       regs[i].wasconst&=~(1<<hr);
8160                       regs[i].isconst&=~(1<<hr);
8161                       branch_regs[i].regmap_entry[hr]=f_regmap[hr];
8162                       branch_regs[i].wasdirty&=~(1<<hr);
8163                       branch_regs[i].wasdirty|=(1<<hr)&regs[i].dirty;
8164                       branch_regs[i].regmap[hr]=f_regmap[hr];
8165                       branch_regs[i].dirty&=~(1<<hr);
8166                       branch_regs[i].dirty|=(1<<hr)&regs[i].dirty;
8167                       branch_regs[i].wasconst&=~(1<<hr);
8168                       branch_regs[i].isconst&=~(1<<hr);
8169                       if (!dops[i].is_ujump) {
8170                         regmap_pre[i+2][hr]=f_regmap[hr];
8171                         regs[i+2].wasdirty&=~(1<<hr);
8172                         regs[i+2].wasdirty|=(1<<hr)&regs[i].dirty;
8173                       }
8174                     }
8175                   }
8176                   for(k=t;k<j;k++) {
8177                     // Alloc register clean at beginning of loop,
8178                     // but may dirty it in pass 6
8179                     regs[k].regmap_entry[hr]=f_regmap[hr];
8180                     regs[k].regmap[hr]=f_regmap[hr];
8181                     regs[k].dirty&=~(1<<hr);
8182                     regs[k].wasconst&=~(1<<hr);
8183                     regs[k].isconst&=~(1<<hr);
8184                     if (dops[k].is_jump) {
8185                       branch_regs[k].regmap_entry[hr]=f_regmap[hr];
8186                       branch_regs[k].regmap[hr]=f_regmap[hr];
8187                       branch_regs[k].dirty&=~(1<<hr);
8188                       branch_regs[k].wasconst&=~(1<<hr);
8189                       branch_regs[k].isconst&=~(1<<hr);
8190                       if (!dops[k].is_ujump) {
8191                         regmap_pre[k+2][hr]=f_regmap[hr];
8192                         regs[k+2].wasdirty&=~(1<<hr);
8193                       }
8194                     }
8195                     else
8196                     {
8197                       regmap_pre[k+1][hr]=f_regmap[hr];
8198                       regs[k+1].wasdirty&=~(1<<hr);
8199                     }
8200                   }
8201                   if(regs[j].regmap[hr]==f_regmap[hr])
8202                     regs[j].regmap_entry[hr]=f_regmap[hr];
8203                   break;
8204                 }
8205                 if(j==i) break;
8206                 if(regs[j].regmap[hr]>=0)
8207                   break;
8208                 if(get_reg(regs[j].regmap,f_regmap[hr])>=0) {
8209                   //printf("no-match due to different register\n");
8210                   break;
8211                 }
8212                 if (dops[j].is_ujump)
8213                 {
8214                   // Stop on unconditional branch
8215                   break;
8216                 }
8217                 if(dops[j].itype==CJUMP||dops[j].itype==SJUMP)
8218                 {
8219                   if(dops[j].ooo) {
8220                     if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j+1])
8221                       break;
8222                   }else{
8223                     if(count_free_regs(branch_regs[j].regmap)<=minimum_free_regs[j+1])
8224                       break;
8225                   }
8226                   if(get_reg(branch_regs[j].regmap,f_regmap[hr])>=0) {
8227                     //printf("no-match due to different register (branch)\n");
8228                     break;
8229                   }
8230                 }
8231                 if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8232                   //printf("No free regs for store %x\n",start+j*4);
8233                   break;
8234                 }
8235                 assert(f_regmap[hr]<64);
8236               }
8237             }
8238           }
8239         }
8240       }
8241     }else{
8242       // Non branch or undetermined branch target
8243       for(hr=0;hr<HOST_REGS;hr++)
8244       {
8245         if(hr!=EXCLUDE_REG) {
8246           if(regs[i].regmap[hr]>=0) {
8247             if(f_regmap[hr]!=regs[i].regmap[hr]) {
8248               // dealloc old register
8249               int n;
8250               for(n=0;n<HOST_REGS;n++)
8251               {
8252                 if(f_regmap[n]==regs[i].regmap[hr]) {f_regmap[n]=-1;}
8253               }
8254               // and alloc new one
8255               f_regmap[hr]=regs[i].regmap[hr];
8256             }
8257           }
8258         }
8259       }
8260       // Try to restore cycle count at branch targets
8261       if(dops[i].bt) {
8262         for(j=i;j<slen-1;j++) {
8263           if(regs[j].regmap[HOST_CCREG]!=-1) break;
8264           if(count_free_regs(regs[j].regmap)<=minimum_free_regs[j]) {
8265             //printf("no free regs for store %x\n",start+j*4);
8266             break;
8267           }
8268         }
8269         if(regs[j].regmap[HOST_CCREG]==CCREG) {
8270           int k=i;
8271           //printf("Extend CC, %x -> %x\n",start+k*4,start+j*4);
8272           while(k<j) {
8273             regs[k].regmap_entry[HOST_CCREG]=CCREG;
8274             regs[k].regmap[HOST_CCREG]=CCREG;
8275             regmap_pre[k+1][HOST_CCREG]=CCREG;
8276             regs[k+1].wasdirty|=1<<HOST_CCREG;
8277             regs[k].dirty|=1<<HOST_CCREG;
8278             regs[k].wasconst&=~(1<<HOST_CCREG);
8279             regs[k].isconst&=~(1<<HOST_CCREG);
8280             k++;
8281           }
8282           regs[j].regmap_entry[HOST_CCREG]=CCREG;
8283         }
8284         // Work backwards from the branch target
8285         if(j>i&&f_regmap[HOST_CCREG]==CCREG)
8286         {
8287           //printf("Extend backwards\n");
8288           int k;
8289           k=i;
8290           while(regs[k-1].regmap[HOST_CCREG]==-1) {
8291             if(count_free_regs(regs[k-1].regmap)<=minimum_free_regs[k-1]) {
8292               //printf("no free regs for store %x\n",start+(k-1)*4);
8293               break;
8294             }
8295             k--;
8296           }
8297           if(regs[k-1].regmap[HOST_CCREG]==CCREG) {
8298             //printf("Extend CC, %x ->\n",start+k*4);
8299             while(k<=i) {
8300               regs[k].regmap_entry[HOST_CCREG]=CCREG;
8301               regs[k].regmap[HOST_CCREG]=CCREG;
8302               regmap_pre[k+1][HOST_CCREG]=CCREG;
8303               regs[k+1].wasdirty|=1<<HOST_CCREG;
8304               regs[k].dirty|=1<<HOST_CCREG;
8305               regs[k].wasconst&=~(1<<HOST_CCREG);
8306               regs[k].isconst&=~(1<<HOST_CCREG);
8307               k++;
8308             }
8309           }
8310           else {
8311             //printf("Fail Extend CC, %x ->\n",start+k*4);
8312           }
8313         }
8314       }
8315       if(dops[i].itype!=STORE&&dops[i].itype!=STORELR&&dops[i].itype!=C1LS&&dops[i].itype!=SHIFT&&
8316          dops[i].itype!=NOP&&dops[i].itype!=MOV&&dops[i].itype!=ALU&&dops[i].itype!=SHIFTIMM&&
8317          dops[i].itype!=IMM16&&dops[i].itype!=LOAD&&dops[i].itype!=COP1)
8318       {
8319         memcpy(f_regmap,regs[i].regmap,sizeof(f_regmap));
8320       }
8321     }
8322   }
8323 }
8324
8325 // This allocates registers (if possible) one instruction prior
8326 // to use, which can avoid a load-use penalty on certain CPUs.
8327 static noinline void pass5b_preallocate2(void)
8328 {
8329   int i, hr;
8330   for(i=0;i<slen-1;i++)
8331   {
8332     if (!i || !dops[i-1].is_jump)
8333     {
8334       if(!dops[i+1].bt)
8335       {
8336         if(dops[i].itype==ALU||dops[i].itype==MOV||dops[i].itype==LOAD||dops[i].itype==SHIFTIMM||dops[i].itype==IMM16
8337            ||((dops[i].itype==COP1||dops[i].itype==COP2)&&dops[i].opcode2<3))
8338         {
8339           if(dops[i+1].rs1) {
8340             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rs1))>=0)
8341             {
8342               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8343               {
8344                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8345                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8346                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8347                 regs[i].isconst&=~(1<<hr);
8348                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8349                 constmap[i][hr]=constmap[i+1][hr];
8350                 regs[i+1].wasdirty&=~(1<<hr);
8351                 regs[i].dirty&=~(1<<hr);
8352               }
8353             }
8354           }
8355           if(dops[i+1].rs2) {
8356             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rs2))>=0)
8357             {
8358               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8359               {
8360                 regs[i].regmap[hr]=regs[i+1].regmap[hr];
8361                 regmap_pre[i+1][hr]=regs[i+1].regmap[hr];
8362                 regs[i+1].regmap_entry[hr]=regs[i+1].regmap[hr];
8363                 regs[i].isconst&=~(1<<hr);
8364                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8365                 constmap[i][hr]=constmap[i+1][hr];
8366                 regs[i+1].wasdirty&=~(1<<hr);
8367                 regs[i].dirty&=~(1<<hr);
8368               }
8369             }
8370           }
8371           // Preload target address for load instruction (non-constant)
8372           if(dops[i+1].itype==LOAD&&dops[i+1].rs1&&get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8373             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rt1))>=0)
8374             {
8375               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8376               {
8377                 regs[i].regmap[hr]=dops[i+1].rs1;
8378                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8379                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8380                 regs[i].isconst&=~(1<<hr);
8381                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8382                 constmap[i][hr]=constmap[i+1][hr];
8383                 regs[i+1].wasdirty&=~(1<<hr);
8384                 regs[i].dirty&=~(1<<hr);
8385               }
8386             }
8387           }
8388           // Load source into target register
8389           if(dops[i+1].use_lt1&&get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8390             if((hr=get_reg(regs[i+1].regmap,dops[i+1].rt1))>=0)
8391             {
8392               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8393               {
8394                 regs[i].regmap[hr]=dops[i+1].rs1;
8395                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8396                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8397                 regs[i].isconst&=~(1<<hr);
8398                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8399                 constmap[i][hr]=constmap[i+1][hr];
8400                 regs[i+1].wasdirty&=~(1<<hr);
8401                 regs[i].dirty&=~(1<<hr);
8402               }
8403             }
8404           }
8405           // Address for store instruction (non-constant)
8406           if(dops[i+1].itype==STORE||dops[i+1].itype==STORELR
8407              ||(dops[i+1].opcode&0x3b)==0x39||(dops[i+1].opcode&0x3b)==0x3a) { // SB/SH/SW/SD/SWC1/SDC1/SWC2/SDC2
8408             if(get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8409               hr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1);
8410               if(hr<0) hr=get_reg_temp(regs[i+1].regmap);
8411               else {
8412                 regs[i+1].regmap[hr]=AGEN1+((i+1)&1);
8413                 regs[i+1].isconst&=~(1<<hr);
8414               }
8415               assert(hr>=0);
8416               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8417               {
8418                 regs[i].regmap[hr]=dops[i+1].rs1;
8419                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8420                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8421                 regs[i].isconst&=~(1<<hr);
8422                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8423                 constmap[i][hr]=constmap[i+1][hr];
8424                 regs[i+1].wasdirty&=~(1<<hr);
8425                 regs[i].dirty&=~(1<<hr);
8426               }
8427             }
8428           }
8429           if(dops[i+1].itype==LOADLR||(dops[i+1].opcode&0x3b)==0x31||(dops[i+1].opcode&0x3b)==0x32) { // LWC1/LDC1, LWC2/LDC2
8430             if(get_reg(regs[i+1].regmap,dops[i+1].rs1)<0) {
8431               int nr;
8432               hr=get_reg(regs[i+1].regmap,FTEMP);
8433               assert(hr>=0);
8434               if(regs[i].regmap[hr]<0&&regs[i+1].regmap_entry[hr]<0)
8435               {
8436                 regs[i].regmap[hr]=dops[i+1].rs1;
8437                 regmap_pre[i+1][hr]=dops[i+1].rs1;
8438                 regs[i+1].regmap_entry[hr]=dops[i+1].rs1;
8439                 regs[i].isconst&=~(1<<hr);
8440                 regs[i].isconst|=regs[i+1].isconst&(1<<hr);
8441                 constmap[i][hr]=constmap[i+1][hr];
8442                 regs[i+1].wasdirty&=~(1<<hr);
8443                 regs[i].dirty&=~(1<<hr);
8444               }
8445               else if((nr=get_reg2(regs[i].regmap,regs[i+1].regmap,-1))>=0)
8446               {
8447                 // move it to another register
8448                 regs[i+1].regmap[hr]=-1;
8449                 regmap_pre[i+2][hr]=-1;
8450                 regs[i+1].regmap[nr]=FTEMP;
8451                 regmap_pre[i+2][nr]=FTEMP;
8452                 regs[i].regmap[nr]=dops[i+1].rs1;
8453                 regmap_pre[i+1][nr]=dops[i+1].rs1;
8454                 regs[i+1].regmap_entry[nr]=dops[i+1].rs1;
8455                 regs[i].isconst&=~(1<<nr);
8456                 regs[i+1].isconst&=~(1<<nr);
8457                 regs[i].dirty&=~(1<<nr);
8458                 regs[i+1].wasdirty&=~(1<<nr);
8459                 regs[i+1].dirty&=~(1<<nr);
8460                 regs[i+2].wasdirty&=~(1<<nr);
8461               }
8462             }
8463           }
8464           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*/) {
8465             hr = -1;
8466             if(dops[i+1].itype==LOAD)
8467               hr=get_reg(regs[i+1].regmap,dops[i+1].rt1);
8468             if(dops[i+1].itype==LOADLR||(dops[i+1].opcode&0x3b)==0x31||(dops[i+1].opcode&0x3b)==0x32) // LWC1/LDC1, LWC2/LDC2
8469               hr=get_reg(regs[i+1].regmap,FTEMP);
8470             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
8471               hr=get_reg(regs[i+1].regmap,AGEN1+((i+1)&1));
8472               if(hr<0) hr=get_reg_temp(regs[i+1].regmap);
8473             }
8474             if(hr>=0&&regs[i].regmap[hr]<0) {
8475               int rs=get_reg(regs[i+1].regmap,dops[i+1].rs1);
8476               if(rs>=0&&((regs[i+1].wasconst>>rs)&1)) {
8477                 regs[i].regmap[hr]=AGEN1+((i+1)&1);
8478                 regmap_pre[i+1][hr]=AGEN1+((i+1)&1);
8479                 regs[i+1].regmap_entry[hr]=AGEN1+((i+1)&1);
8480                 regs[i].isconst&=~(1<<hr);
8481                 regs[i+1].wasdirty&=~(1<<hr);
8482                 regs[i].dirty&=~(1<<hr);
8483               }
8484             }
8485           }
8486         }
8487       }
8488     }
8489   }
8490 }
8491
8492 // Write back dirty registers as soon as we will no longer modify them,
8493 // so that we don't end up with lots of writes at the branches.
8494 static noinline void pass6_clean_registers(int istart, int iend, int wr)
8495 {
8496   static u_int wont_dirty[MAXBLOCK];
8497   static u_int will_dirty[MAXBLOCK];
8498   int i;
8499   int r;
8500   u_int will_dirty_i,will_dirty_next,temp_will_dirty;
8501   u_int wont_dirty_i,wont_dirty_next,temp_wont_dirty;
8502   if(iend==slen-1) {
8503     will_dirty_i=will_dirty_next=0;
8504     wont_dirty_i=wont_dirty_next=0;
8505   }else{
8506     will_dirty_i=will_dirty_next=will_dirty[iend+1];
8507     wont_dirty_i=wont_dirty_next=wont_dirty[iend+1];
8508   }
8509   for (i=iend;i>=istart;i--)
8510   {
8511     signed char rregmap_i[RRMAP_SIZE];
8512     u_int hr_candirty = 0;
8513     assert(HOST_REGS < 32);
8514     make_rregs(regs[i].regmap, rregmap_i, &hr_candirty);
8515     __builtin_prefetch(regs[i-1].regmap);
8516     if(dops[i].is_jump)
8517     {
8518       signed char branch_rregmap_i[RRMAP_SIZE];
8519       u_int branch_hr_candirty = 0;
8520       make_rregs(branch_regs[i].regmap, branch_rregmap_i, &branch_hr_candirty);
8521       if(ba[i]<start || ba[i]>=(start+slen*4))
8522       {
8523         // Branch out of this block, flush all regs
8524         will_dirty_i = 0;
8525         will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8526         will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8527         will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8528         will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8529         will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8530         will_dirty_i &= branch_hr_candirty;
8531         if (dops[i].is_ujump)
8532         {
8533           // Unconditional branch
8534           wont_dirty_i = 0;
8535           // Merge in delay slot (will dirty)
8536           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8537           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8538           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8539           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8540           will_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8541           will_dirty_i &= hr_candirty;
8542         }
8543         else
8544         {
8545           // Conditional branch
8546           wont_dirty_i = wont_dirty_next;
8547           // Merge in delay slot (will dirty)
8548           // (the original code had no explanation why these 2 are commented out)
8549           //will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8550           //will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8551           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8552           will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8553           will_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8554           will_dirty_i &= hr_candirty;
8555         }
8556         // Merge in delay slot (wont dirty)
8557         wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8558         wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8559         wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8560         wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8561         wont_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8562         wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8563         wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8564         wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8565         wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8566         wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8567         wont_dirty_i &= ~(1u << 31);
8568         if(wr) {
8569           #ifndef DESTRUCTIVE_WRITEBACK
8570           branch_regs[i].dirty&=wont_dirty_i;
8571           #endif
8572           branch_regs[i].dirty|=will_dirty_i;
8573         }
8574       }
8575       else
8576       {
8577         // Internal branch
8578         if(ba[i]<=start+i*4) {
8579           // Backward branch
8580           if (dops[i].is_ujump)
8581           {
8582             // Unconditional branch
8583             temp_will_dirty=0;
8584             temp_wont_dirty=0;
8585             // Merge in delay slot (will dirty)
8586             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8587             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8588             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8589             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8590             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8591             temp_will_dirty &= branch_hr_candirty;
8592             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8593             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8594             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8595             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8596             temp_will_dirty |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8597             temp_will_dirty &= hr_candirty;
8598           } else {
8599             // Conditional branch (not taken case)
8600             temp_will_dirty=will_dirty_next;
8601             temp_wont_dirty=wont_dirty_next;
8602             // Merge in delay slot (will dirty)
8603             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8604             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8605             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8606             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8607             temp_will_dirty |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8608             temp_will_dirty &= branch_hr_candirty;
8609             //temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8610             //temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8611             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8612             temp_will_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8613             temp_will_dirty |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8614             temp_will_dirty &= hr_candirty;
8615           }
8616           // Merge in delay slot (wont dirty)
8617           temp_wont_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8618           temp_wont_dirty |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8619           temp_wont_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8620           temp_wont_dirty |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8621           temp_wont_dirty |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8622           temp_wont_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8623           temp_wont_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8624           temp_wont_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8625           temp_wont_dirty |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8626           temp_wont_dirty |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8627           temp_wont_dirty &= ~(1u << 31);
8628           // Deal with changed mappings
8629           if(i<iend) {
8630             for(r=0;r<HOST_REGS;r++) {
8631               if(r!=EXCLUDE_REG) {
8632                 if(regs[i].regmap[r]!=regmap_pre[i][r]) {
8633                   temp_will_dirty&=~(1<<r);
8634                   temp_wont_dirty&=~(1<<r);
8635                   if(regmap_pre[i][r]>0 && regmap_pre[i][r]<34) {
8636                     temp_will_dirty|=((unneeded_reg[i]>>regmap_pre[i][r])&1)<<r;
8637                     temp_wont_dirty|=((unneeded_reg[i]>>regmap_pre[i][r])&1)<<r;
8638                   } else {
8639                     temp_will_dirty|=1<<r;
8640                     temp_wont_dirty|=1<<r;
8641                   }
8642                 }
8643               }
8644             }
8645           }
8646           if(wr) {
8647             will_dirty[i]=temp_will_dirty;
8648             wont_dirty[i]=temp_wont_dirty;
8649             pass6_clean_registers((ba[i]-start)>>2,i-1,0);
8650           }else{
8651             // Limit recursion.  It can take an excessive amount
8652             // of time if there are a lot of nested loops.
8653             will_dirty[(ba[i]-start)>>2]=0;
8654             wont_dirty[(ba[i]-start)>>2]=-1;
8655           }
8656         }
8657         /*else*/ if(1)
8658         {
8659           if (dops[i].is_ujump)
8660           {
8661             // Unconditional branch
8662             will_dirty_i=0;
8663             wont_dirty_i=0;
8664           //if(ba[i]>start+i*4) { // Disable recursion (for debugging)
8665             for(r=0;r<HOST_REGS;r++) {
8666               if(r!=EXCLUDE_REG) {
8667                 if(branch_regs[i].regmap[r]==regs[(ba[i]-start)>>2].regmap_entry[r]) {
8668                   will_dirty_i|=will_dirty[(ba[i]-start)>>2]&(1<<r);
8669                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
8670                 }
8671                 if(branch_regs[i].regmap[r]>=0) {
8672                   will_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>branch_regs[i].regmap[r])&1)<<r;
8673                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>branch_regs[i].regmap[r])&1)<<r;
8674                 }
8675               }
8676             }
8677           //}
8678             // Merge in delay slot
8679             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8680             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8681             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8682             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8683             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8684             will_dirty_i &= branch_hr_candirty;
8685             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8686             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8687             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8688             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8689             will_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8690             will_dirty_i &= hr_candirty;
8691           } else {
8692             // Conditional branch
8693             will_dirty_i=will_dirty_next;
8694             wont_dirty_i=wont_dirty_next;
8695           //if(ba[i]>start+i*4) // Disable recursion (for debugging)
8696             for(r=0;r<HOST_REGS;r++) {
8697               if(r!=EXCLUDE_REG) {
8698                 signed char target_reg=branch_regs[i].regmap[r];
8699                 if(target_reg==regs[(ba[i]-start)>>2].regmap_entry[r]) {
8700                   will_dirty_i&=will_dirty[(ba[i]-start)>>2]&(1<<r);
8701                   wont_dirty_i|=wont_dirty[(ba[i]-start)>>2]&(1<<r);
8702                 }
8703                 else if(target_reg>=0) {
8704                   will_dirty_i&=((unneeded_reg[(ba[i]-start)>>2]>>target_reg)&1)<<r;
8705                   wont_dirty_i|=((unneeded_reg[(ba[i]-start)>>2]>>target_reg)&1)<<r;
8706                 }
8707               }
8708             }
8709             // Merge in delay slot
8710             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8711             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8712             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8713             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8714             will_dirty_i |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8715             will_dirty_i &= branch_hr_candirty;
8716             //will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8717             //will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8718             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8719             will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8720             will_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8721             will_dirty_i &= hr_candirty;
8722           }
8723           // Merge in delay slot (won't dirty)
8724           wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8725           wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8726           wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt1) & 31);
8727           wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i+1].rt2) & 31);
8728           wont_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8729           wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt1) & 31);
8730           wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i].rt2) & 31);
8731           wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt1) & 31);
8732           wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, dops[i+1].rt2) & 31);
8733           wont_dirty_i |= 1u << (get_rreg(branch_rregmap_i, CCREG) & 31);
8734           wont_dirty_i &= ~(1u << 31);
8735           if(wr) {
8736             #ifndef DESTRUCTIVE_WRITEBACK
8737             branch_regs[i].dirty&=wont_dirty_i;
8738             #endif
8739             branch_regs[i].dirty|=will_dirty_i;
8740           }
8741         }
8742       }
8743     }
8744     else if(dops[i].itype==SYSCALL||dops[i].itype==HLECALL||dops[i].itype==INTCALL)
8745     {
8746       // SYSCALL instruction (software interrupt)
8747       will_dirty_i=0;
8748       wont_dirty_i=0;
8749     }
8750     else if(dops[i].itype==COP0 && (source[i]&0x3f)==0x18)
8751     {
8752       // ERET instruction (return from interrupt)
8753       will_dirty_i=0;
8754       wont_dirty_i=0;
8755     }
8756     will_dirty_next=will_dirty_i;
8757     wont_dirty_next=wont_dirty_i;
8758     will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8759     will_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8760     will_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8761     will_dirty_i &= hr_candirty;
8762     wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt1) & 31);
8763     wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i].rt2) & 31);
8764     wont_dirty_i |= 1u << (get_rreg(rregmap_i, CCREG) & 31);
8765     wont_dirty_i &= ~(1u << 31);
8766     if (i > istart && !dops[i].is_jump) {
8767       // Don't store a register immediately after writing it,
8768       // may prevent dual-issue.
8769       wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i-1].rt1) & 31);
8770       wont_dirty_i |= 1u << (get_rreg(rregmap_i, dops[i-1].rt2) & 31);
8771     }
8772     // Save it
8773     will_dirty[i]=will_dirty_i;
8774     wont_dirty[i]=wont_dirty_i;
8775     // Mark registers that won't be dirtied as not dirty
8776     if(wr) {
8777         regs[i].dirty|=will_dirty_i;
8778         #ifndef DESTRUCTIVE_WRITEBACK
8779         regs[i].dirty&=wont_dirty_i;
8780         if(dops[i].is_jump)
8781         {
8782           if (i < iend-1 && !dops[i].is_ujump) {
8783             for(r=0;r<HOST_REGS;r++) {
8784               if(r!=EXCLUDE_REG) {
8785                 if(regs[i].regmap[r]==regmap_pre[i+2][r]) {
8786                   regs[i+2].wasdirty&=wont_dirty_i|~(1<<r);
8787                 }else {/*printf("i: %x (%d) mismatch(+2): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
8788               }
8789             }
8790           }
8791         }
8792         else
8793         {
8794           if(i<iend) {
8795             for(r=0;r<HOST_REGS;r++) {
8796               if(r!=EXCLUDE_REG) {
8797                 if(regs[i].regmap[r]==regmap_pre[i+1][r]) {
8798                   regs[i+1].wasdirty&=wont_dirty_i|~(1<<r);
8799                 }else {/*printf("i: %x (%d) mismatch(+1): %d\n",start+i*4,i,r);assert(!((wont_dirty_i>>r)&1));*/}
8800               }
8801             }
8802           }
8803         }
8804         #endif
8805     }
8806     // Deal with changed mappings
8807     temp_will_dirty=will_dirty_i;
8808     temp_wont_dirty=wont_dirty_i;
8809     for(r=0;r<HOST_REGS;r++) {
8810       if(r!=EXCLUDE_REG) {
8811         int nr;
8812         if(regs[i].regmap[r]==regmap_pre[i][r]) {
8813           if(wr) {
8814             #ifndef DESTRUCTIVE_WRITEBACK
8815             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
8816             #endif
8817             regs[i].wasdirty|=will_dirty_i&(1<<r);
8818           }
8819         }
8820         else if(regmap_pre[i][r]>=0&&(nr=get_rreg(rregmap_i,regmap_pre[i][r]))>=0) {
8821           // Register moved to a different register
8822           will_dirty_i&=~(1<<r);
8823           wont_dirty_i&=~(1<<r);
8824           will_dirty_i|=((temp_will_dirty>>nr)&1)<<r;
8825           wont_dirty_i|=((temp_wont_dirty>>nr)&1)<<r;
8826           if(wr) {
8827             #ifndef DESTRUCTIVE_WRITEBACK
8828             regs[i].wasdirty&=wont_dirty_i|~(1<<r);
8829             #endif
8830             regs[i].wasdirty|=will_dirty_i&(1<<r);
8831           }
8832         }
8833         else {
8834           will_dirty_i&=~(1<<r);
8835           wont_dirty_i&=~(1<<r);
8836           if(regmap_pre[i][r]>0 && regmap_pre[i][r]<34) {
8837             will_dirty_i|=((unneeded_reg[i]>>regmap_pre[i][r])&1)<<r;
8838             wont_dirty_i|=((unneeded_reg[i]>>regmap_pre[i][r])&1)<<r;
8839           } else {
8840             wont_dirty_i|=1<<r;
8841             /*printf("i: %x (%d) mismatch: %d\n",start+i*4,i,r);assert(!((will_dirty>>r)&1));*/
8842           }
8843         }
8844       }
8845     }
8846   }
8847 }
8848
8849 static noinline void pass10_expire_blocks(void)
8850 {
8851   u_int step = MAX_OUTPUT_BLOCK_SIZE / PAGE_COUNT / 2;
8852   // not sizeof(ndrc->translation_cache) due to vita hack
8853   u_int step_mask = ((1u << TARGET_SIZE_2) - 1u) & ~(step - 1u);
8854   u_int end = (out - ndrc->translation_cache + EXPIRITY_OFFSET) & step_mask;
8855   u_int base_shift = __builtin_ctz(MAX_OUTPUT_BLOCK_SIZE);
8856   int hit;
8857
8858   for (; expirep != end; expirep = ((expirep + step) & step_mask))
8859   {
8860     u_int base_offs = expirep & ~(MAX_OUTPUT_BLOCK_SIZE - 1);
8861     u_int block_i = expirep / step & (PAGE_COUNT - 1);
8862     u_int phase = (expirep >> (base_shift - 1)) & 1u;
8863     if (!(expirep & (MAX_OUTPUT_BLOCK_SIZE / 2 - 1))) {
8864       inv_debug("EXP: base_offs %x/%x phase %u\n", base_offs,
8865         out - ndrc->translation_cache, phase);
8866     }
8867
8868     if (!phase) {
8869       hit = blocks_remove_matching_addrs(&blocks[block_i], base_offs, base_shift);
8870       if (hit) {
8871         do_clear_cache();
8872         #ifdef USE_MINI_HT
8873         memset(mini_ht, -1, sizeof(mini_ht));
8874         #endif
8875       }
8876     }
8877     else
8878       unlink_jumps_tc_range(jumps[block_i], base_offs, base_shift);
8879   }
8880 }
8881
8882 static struct block_info *new_block_info(u_int start, u_int len,
8883   const void *source, const void *copy, u_char *beginning, u_short jump_in_count)
8884 {
8885   struct block_info **b_pptr;
8886   struct block_info *block;
8887   u_int page = get_page(start);
8888
8889   block = malloc(sizeof(*block) + jump_in_count * sizeof(block->jump_in[0]));
8890   assert(block);
8891   assert(jump_in_count > 0);
8892   block->source = source;
8893   block->copy = copy;
8894   block->start = start;
8895   block->len = len;
8896   block->reg_sv_flags = 0;
8897   block->tc_offs = beginning - ndrc->translation_cache;
8898   //block->tc_len = out - beginning;
8899   block->is_dirty = 0;
8900   block->inv_near_misses = 0;
8901   block->jump_in_cnt = jump_in_count;
8902
8903   // insert sorted by start mirror-unmasked vaddr
8904   for (b_pptr = &blocks[page]; ; b_pptr = &((*b_pptr)->next)) {
8905     if (*b_pptr == NULL || (*b_pptr)->start >= start) {
8906       block->next = *b_pptr;
8907       *b_pptr = block;
8908       break;
8909     }
8910   }
8911   stat_inc(stat_blocks);
8912   return block;
8913 }
8914
8915 static int new_recompile_block(u_int addr)
8916 {
8917   u_int pagelimit = 0;
8918   u_int state_rflags = 0;
8919   int i;
8920
8921   assem_debug("NOTCOMPILED: addr = %x -> %p\n", addr, out);
8922
8923   // this is just for speculation
8924   for (i = 1; i < 32; i++) {
8925     if ((psxRegs.GPR.r[i] & 0xffff0000) == 0x1f800000)
8926       state_rflags |= 1 << i;
8927   }
8928
8929   assert(!(addr & 3));
8930   start = addr & ~3;
8931   new_dynarec_did_compile=1;
8932   if (Config.HLE && start == 0x80001000) // hlecall
8933   {
8934     // XXX: is this enough? Maybe check hleSoftCall?
8935     void *beginning = start_block();
8936
8937     emit_movimm(start,0);
8938     emit_writeword(0,&pcaddr);
8939     emit_far_jump(new_dyna_leave);
8940     literal_pool(0);
8941     end_block(beginning);
8942     struct block_info *block = new_block_info(start, 4, NULL, NULL, beginning, 1);
8943     block->jump_in[0].vaddr = start;
8944     block->jump_in[0].addr = beginning;
8945     return 0;
8946   }
8947   else if (f1_hack && hack_addr == 0) {
8948     void *beginning = start_block();
8949     emit_movimm(start, 0);
8950     emit_writeword(0, &hack_addr);
8951     emit_readword(&psxRegs.GPR.n.sp, 0);
8952     emit_readptr(&mem_rtab, 1);
8953     emit_shrimm(0, 12, 2);
8954     emit_readptr_dualindexedx_ptrlen(1, 2, 1);
8955     emit_addimm(0, 0x18, 0);
8956     emit_adds_ptr(1, 1, 1);
8957     emit_ldr_dualindexed(1, 0, 0);
8958     emit_writeword(0, &psxRegs.GPR.r[26]); // lw k0, 0x18(sp)
8959     emit_far_call(ndrc_get_addr_ht);
8960     emit_jmpreg(0); // jr k0
8961     literal_pool(0);
8962     end_block(beginning);
8963
8964     struct block_info *block = new_block_info(start, 4, NULL, NULL, beginning, 1);
8965     block->jump_in[0].vaddr = start;
8966     block->jump_in[0].addr = beginning;
8967     SysPrintf("F1 hack to   %08x\n", start);
8968     return 0;
8969   }
8970
8971   cycle_multiplier_active = cycle_multiplier_override && cycle_multiplier == CYCLE_MULT_DEFAULT
8972     ? cycle_multiplier_override : cycle_multiplier;
8973
8974   source = get_source_start(start, &pagelimit);
8975   if (source == NULL) {
8976     if (addr != hack_addr) {
8977       SysPrintf("Compile at bogus memory address: %08x\n", addr);
8978       hack_addr = addr;
8979     }
8980     //abort();
8981     return -1;
8982   }
8983
8984   /* Pass 1: disassemble */
8985   /* Pass 2: register dependencies, branch targets */
8986   /* Pass 3: register allocation */
8987   /* Pass 4: branch dependencies */
8988   /* Pass 5: pre-alloc */
8989   /* Pass 6: optimize clean/dirty state */
8990   /* Pass 7: flag 32-bit registers */
8991   /* Pass 8: assembly */
8992   /* Pass 9: linker */
8993   /* Pass 10: garbage collection / free memory */
8994
8995   /* Pass 1 disassembly */
8996
8997   pass1_disassemble(pagelimit);
8998
8999   int clear_hack_addr = apply_hacks();
9000
9001   /* Pass 2 - Register dependencies and branch targets */
9002
9003   pass2_unneeded_regs(0,slen-1,0);
9004
9005   /* Pass 3 - Register allocation */
9006
9007   pass3_register_alloc(addr);
9008
9009   /* Pass 4 - Cull unused host registers */
9010
9011   pass4_cull_unused_regs();
9012
9013   /* Pass 5 - Pre-allocate registers */
9014
9015   pass5a_preallocate1();
9016   pass5b_preallocate2();
9017
9018   /* Pass 6 - Optimize clean/dirty state */
9019   pass6_clean_registers(0, slen-1, 1);
9020
9021   /* Pass 7 - Identify 32-bit registers */
9022   for (i=slen-1;i>=0;i--)
9023   {
9024     if(dops[i].itype==CJUMP||dops[i].itype==SJUMP)
9025     {
9026       // Conditional branch
9027       if((source[i]>>16)!=0x1000&&i<slen-2) {
9028         // Mark this address as a branch target since it may be called
9029         // upon return from interrupt
9030         dops[i+2].bt=1;
9031       }
9032     }
9033   }
9034
9035   /* Pass 8 - Assembly */
9036   linkcount=0;stubcount=0;
9037   is_delayslot=0;
9038   u_int dirty_pre=0;
9039   void *beginning=start_block();
9040   void *instr_addr0_override = NULL;
9041   int ds = 0;
9042
9043   if (start == 0x80030000) {
9044     // nasty hack for the fastbios thing
9045     // override block entry to this code
9046     instr_addr0_override = out;
9047     emit_movimm(start,0);
9048     // abuse io address var as a flag that we
9049     // have already returned here once
9050     emit_readword(&address,1);
9051     emit_writeword(0,&pcaddr);
9052     emit_writeword(0,&address);
9053     emit_cmp(0,1);
9054     #ifdef __aarch64__
9055     emit_jeq(out + 4*2);
9056     emit_far_jump(new_dyna_leave);
9057     #else
9058     emit_jne(new_dyna_leave);
9059     #endif
9060   }
9061   for(i=0;i<slen;i++)
9062   {
9063     __builtin_prefetch(regs[i+1].regmap);
9064     check_regmap(regmap_pre[i]);
9065     check_regmap(regs[i].regmap_entry);
9066     check_regmap(regs[i].regmap);
9067     //if(ds) printf("ds: ");
9068     disassemble_inst(i);
9069     if(ds) {
9070       ds=0; // Skip delay slot
9071       if(dops[i].bt) assem_debug("OOPS - branch into delay slot\n");
9072       instr_addr[i] = NULL;
9073     } else {
9074       speculate_register_values(i);
9075       #ifndef DESTRUCTIVE_WRITEBACK
9076       if (i < 2 || !dops[i-2].is_ujump)
9077       {
9078         wb_valid(regmap_pre[i],regs[i].regmap_entry,dirty_pre,regs[i].wasdirty,unneeded_reg[i]);
9079       }
9080       if((dops[i].itype==CJUMP||dops[i].itype==SJUMP)) {
9081         dirty_pre=branch_regs[i].dirty;
9082       }else{
9083         dirty_pre=regs[i].dirty;
9084       }
9085       #endif
9086       // write back
9087       if (i < 2 || !dops[i-2].is_ujump)
9088       {
9089         wb_invalidate(regmap_pre[i],regs[i].regmap_entry,regs[i].wasdirty,unneeded_reg[i]);
9090         loop_preload(regmap_pre[i],regs[i].regmap_entry);
9091       }
9092       // branch target entry point
9093       instr_addr[i] = out;
9094       assem_debug("<->\n");
9095       drc_dbg_emit_do_cmp(i, ccadj[i]);
9096       if (clear_hack_addr) {
9097         emit_movimm(0, 0);
9098         emit_writeword(0, &hack_addr);
9099         clear_hack_addr = 0;
9100       }
9101
9102       // load regs
9103       if(regs[i].regmap_entry[HOST_CCREG]==CCREG&&regs[i].regmap[HOST_CCREG]!=CCREG)
9104         wb_register(CCREG,regs[i].regmap_entry,regs[i].wasdirty);
9105       load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i].rs1,dops[i].rs2);
9106       address_generation(i,&regs[i],regs[i].regmap_entry);
9107       load_consts(regmap_pre[i],regs[i].regmap,i);
9108       if(dops[i].is_jump)
9109       {
9110         // Load the delay slot registers if necessary
9111         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))
9112           load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs1,dops[i+1].rs1);
9113         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))
9114           load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs2,dops[i+1].rs2);
9115         if (ram_offset && (dops[i+1].is_load || dops[i+1].is_store))
9116           load_reg(regs[i].regmap_entry,regs[i].regmap,ROREG);
9117         if (dops[i+1].is_store)
9118           load_reg(regs[i].regmap_entry,regs[i].regmap,INVCP);
9119       }
9120       else if(i+1<slen)
9121       {
9122         // Preload registers for following instruction
9123         if(dops[i+1].rs1!=dops[i].rs1&&dops[i+1].rs1!=dops[i].rs2)
9124           if(dops[i+1].rs1!=dops[i].rt1&&dops[i+1].rs1!=dops[i].rt2)
9125             load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs1,dops[i+1].rs1);
9126         if(dops[i+1].rs2!=dops[i+1].rs1&&dops[i+1].rs2!=dops[i].rs1&&dops[i+1].rs2!=dops[i].rs2)
9127           if(dops[i+1].rs2!=dops[i].rt1&&dops[i+1].rs2!=dops[i].rt2)
9128             load_regs(regs[i].regmap_entry,regs[i].regmap,dops[i+1].rs2,dops[i+1].rs2);
9129       }
9130       // TODO: if(is_ooo(i)) address_generation(i+1);
9131       if (!dops[i].is_jump || dops[i].itype == CJUMP)
9132         load_reg(regs[i].regmap_entry,regs[i].regmap,CCREG);
9133       if (ram_offset && (dops[i].is_load || dops[i].is_store))
9134         load_reg(regs[i].regmap_entry,regs[i].regmap,ROREG);
9135       if (dops[i].is_store)
9136         load_reg(regs[i].regmap_entry,regs[i].regmap,INVCP);
9137
9138       ds = assemble(i, &regs[i], ccadj[i]);
9139
9140       if (dops[i].is_ujump)
9141         literal_pool(1024);
9142       else
9143         literal_pool_jumpover(256);
9144     }
9145   }
9146
9147   assert(slen > 0);
9148   if (slen > 0 && dops[slen-1].itype == INTCALL) {
9149     // no ending needed for this block since INTCALL never returns
9150   }
9151   // If the block did not end with an unconditional branch,
9152   // add a jump to the next instruction.
9153   else if (i > 1) {
9154     if (!dops[i-2].is_ujump) {
9155       assert(!dops[i-1].is_jump);
9156       assert(i==slen);
9157       if(dops[i-2].itype!=CJUMP&&dops[i-2].itype!=SJUMP) {
9158         store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9159         if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9160           emit_loadreg(CCREG,HOST_CCREG);
9161         emit_addimm(HOST_CCREG, ccadj[i-1] + CLOCK_ADJUST(1), HOST_CCREG);
9162       }
9163       else
9164       {
9165         store_regs_bt(branch_regs[i-2].regmap,branch_regs[i-2].dirty,start+i*4);
9166         assert(branch_regs[i-2].regmap[HOST_CCREG]==CCREG);
9167       }
9168       add_to_linker(out,start+i*4,0);
9169       emit_jmp(0);
9170     }
9171   }
9172   else
9173   {
9174     assert(i>0);
9175     assert(!dops[i-1].is_jump);
9176     store_regs_bt(regs[i-1].regmap,regs[i-1].dirty,start+i*4);
9177     if(regs[i-1].regmap[HOST_CCREG]!=CCREG)
9178       emit_loadreg(CCREG,HOST_CCREG);
9179     emit_addimm(HOST_CCREG, ccadj[i-1] + CLOCK_ADJUST(1), HOST_CCREG);
9180     add_to_linker(out,start+i*4,0);
9181     emit_jmp(0);
9182   }
9183
9184   // TODO: delay slot stubs?
9185   // Stubs
9186   for(i=0;i<stubcount;i++)
9187   {
9188     switch(stubs[i].type)
9189     {
9190       case LOADB_STUB:
9191       case LOADH_STUB:
9192       case LOADW_STUB:
9193       case LOADD_STUB:
9194       case LOADBU_STUB:
9195       case LOADHU_STUB:
9196         do_readstub(i);break;
9197       case STOREB_STUB:
9198       case STOREH_STUB:
9199       case STOREW_STUB:
9200       case STORED_STUB:
9201         do_writestub(i);break;
9202       case CC_STUB:
9203         do_ccstub(i);break;
9204       case INVCODE_STUB:
9205         do_invstub(i);break;
9206       case FP_STUB:
9207         do_cop1stub(i);break;
9208       case STORELR_STUB:
9209         do_unalignedwritestub(i);break;
9210     }
9211   }
9212
9213   if (instr_addr0_override)
9214     instr_addr[0] = instr_addr0_override;
9215
9216 #if 0
9217   /* check for improper expiration */
9218   for (i = 0; i < ARRAY_SIZE(jumps); i++) {
9219     int j;
9220     if (!jumps[i])
9221       continue;
9222     for (j = 0; j < jumps[i]->count; j++)
9223       assert(jumps[i]->e[j].stub < beginning || (u_char *)jumps[i]->e[j].stub > out);
9224   }
9225 #endif
9226
9227   /* Pass 9 - Linker */
9228   for(i=0;i<linkcount;i++)
9229   {
9230     assem_debug("%p -> %8x\n",link_addr[i].addr,link_addr[i].target);
9231     literal_pool(64);
9232     if (!link_addr[i].internal)
9233     {
9234       void *stub = out;
9235       void *addr = check_addr(link_addr[i].target);
9236       emit_extjump(link_addr[i].addr, link_addr[i].target);
9237       if (addr) {
9238         set_jump_target(link_addr[i].addr, addr);
9239         ndrc_add_jump_out(link_addr[i].target,stub);
9240       }
9241       else
9242         set_jump_target(link_addr[i].addr, stub);
9243     }
9244     else
9245     {
9246       // Internal branch
9247       int target=(link_addr[i].target-start)>>2;
9248       assert(target>=0&&target<slen);
9249       assert(instr_addr[target]);
9250       //#ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9251       //set_jump_target_fillslot(link_addr[i].addr,instr_addr[target],link_addr[i].ext>>1);
9252       //#else
9253       set_jump_target(link_addr[i].addr, instr_addr[target]);
9254       //#endif
9255     }
9256   }
9257
9258   u_int source_len = slen*4;
9259   if (dops[slen-1].itype == INTCALL && source_len > 4)
9260     // no need to treat the last instruction as compiled
9261     // as interpreter fully handles it
9262     source_len -= 4;
9263
9264   if ((u_char *)copy + source_len > (u_char *)shadow + sizeof(shadow))
9265     copy = shadow;
9266
9267   // External Branch Targets (jump_in)
9268   int jump_in_count = 1;
9269   assert(instr_addr[0]);
9270   for (i = 1; i < slen; i++)
9271   {
9272     if (dops[i].bt && instr_addr[i])
9273       jump_in_count++;
9274   }
9275
9276   struct block_info *block =
9277     new_block_info(start, slen * 4, source, copy, beginning, jump_in_count);
9278   block->reg_sv_flags = state_rflags;
9279
9280   int jump_in_i = 0;
9281   for (i = 0; i < slen; i++)
9282   {
9283     if ((i == 0 || dops[i].bt) && instr_addr[i])
9284     {
9285       assem_debug("%p (%d) <- %8x\n", instr_addr[i], i, start + i*4);
9286       u_int vaddr = start + i*4;
9287
9288       literal_pool(256);
9289       void *entry = out;
9290       load_regs_entry(i);
9291       if (entry == out)
9292         entry = instr_addr[i];
9293       else
9294         emit_jmp(instr_addr[i]);
9295
9296       block->jump_in[jump_in_i].vaddr = vaddr;
9297       block->jump_in[jump_in_i].addr = entry;
9298       jump_in_i++;
9299     }
9300   }
9301   assert(jump_in_i == jump_in_count);
9302   hash_table_add(block->jump_in[0].vaddr, block->jump_in[0].addr);
9303   // Write out the literal pool if necessary
9304   literal_pool(0);
9305   #ifdef CORTEX_A8_BRANCH_PREDICTION_HACK
9306   // Align code
9307   if(((u_int)out)&7) emit_addnop(13);
9308   #endif
9309   assert(out - (u_char *)beginning < MAX_OUTPUT_BLOCK_SIZE);
9310   //printf("shadow buffer: %p-%p\n",copy,(u_char *)copy+slen*4);
9311   memcpy(copy, source, source_len);
9312   copy += source_len;
9313
9314   end_block(beginning);
9315
9316   // If we're within 256K of the end of the buffer,
9317   // start over from the beginning. (Is 256K enough?)
9318   if (out > ndrc->translation_cache + sizeof(ndrc->translation_cache) - MAX_OUTPUT_BLOCK_SIZE)
9319     out = ndrc->translation_cache;
9320
9321   // Trap writes to any of the pages we compiled
9322   mark_invalid_code(start, slen*4, 0);
9323
9324   /* Pass 10 - Free memory by expiring oldest blocks */
9325
9326   pass10_expire_blocks();
9327
9328 #ifdef ASSEM_PRINT
9329   fflush(stdout);
9330 #endif
9331   stat_inc(stat_bc_direct);
9332   return 0;
9333 }
9334
9335 // vim:shiftwidth=2:expandtab