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