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