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