Source

pypy / pypy / jit / backend / ppc / ppcgen / ppc_assembler.py

Full commit
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
import os
import struct
from pypy.jit.backend.ppc.ppcgen.ppc_form import PPCForm as Form
from pypy.jit.backend.ppc.ppcgen.ppc_field import ppc_fields
from pypy.jit.backend.ppc.ppcgen.regalloc import (TempInt, PPCFrameManager,
                                                  Regalloc)
from pypy.jit.backend.ppc.ppcgen.assembler import Assembler
from pypy.jit.backend.ppc.ppcgen.opassembler import OpAssembler
from pypy.jit.backend.ppc.ppcgen.symbol_lookup import lookup
from pypy.jit.backend.ppc.ppcgen.codebuilder import PPCBuilder
from pypy.jit.backend.ppc.ppcgen.arch import (IS_PPC_32, WORD, NONVOLATILES,
                                              GPR_SAVE_AREA)
from pypy.jit.backend.ppc.ppcgen.helper.assembler import (gen_emit_cmp_op, 
                                                          encode32, decode32)
import pypy.jit.backend.ppc.ppcgen.register as r
import pypy.jit.backend.ppc.ppcgen.condition as c
from pypy.jit.metainterp.history import (Const, ConstPtr, LoopToken,
                                         AbstractFailDescr)
from pypy.jit.backend.llsupport.asmmemmgr import (BlockBuilderMixin, 
                                                  AsmMemoryManager,
                                                  MachineDataBlockWrapper)
from pypy.jit.backend.llsupport.regalloc import (RegisterManager, 
                                                 compute_vars_longevity)
from pypy.jit.backend.llsupport import symbolic
from pypy.jit.backend.model import CompiledLoopToken
from pypy.rpython.lltypesystem import lltype, rffi, rstr, llmemory
from pypy.jit.metainterp.resoperation import rop
from pypy.jit.metainterp.history import (BoxInt, ConstInt, ConstPtr,
                                         ConstFloat, Box, INT, REF, FLOAT)
from pypy.jit.backend.x86.support import values_array
from pypy.rlib import rgc
from pypy.rpython.annlowlevel import llhelper

memcpy_fn = rffi.llexternal('memcpy', [llmemory.Address, llmemory.Address,
                                       rffi.SIZE_T], lltype.Void,
                            sandboxsafe=True, _nowrapper=True)
def hi(w):
    return w >> 16

def ha(w):
    if (w >> 15) & 1:
        return (w >> 16) + 1
    else:
        return w >> 16

def lo(w):
    return w & 0x0000FFFF

def la(w):
    v = w & 0x0000FFFF
    if v & 0x8000:
        return -((v ^ 0xFFFF) + 1) # "sign extend" to 32 bits
    return v

def highest(w):
    return w >> 48

def higher(w):
    return (w >> 32) & 0x0000FFFF

def high(w):
    return (w >> 16) & 0x0000FFFF

class AssemblerPPC(OpAssembler):

    FLOAT_TYPE = '\xED'
    REF_TYPE   = '\xEE'
    INT_TYPE   = '\xEF'

    STACK_LOC = '\xFC'
    IMM_LOC = '\xFD'
    # REG_LOC is empty
    EMPTY_LOC = '\xFE'
    END_OF_LOCS = '\xFF'

    def __init__(self, cpu, failargs_limit=1000):
        self.cpu = cpu
        self.fail_boxes_int = values_array(lltype.Signed, failargs_limit)
        self.fail_boxes_ptr = values_array(llmemory.GCREF, failargs_limit)
        self.mc = None
        self.datablockwrapper = None
        self.memcpy_addr = 0
        self.fail_boxes_count = 0

    def load_imm(self, rD, word):
        if word <= 32767 and word >= -32768:
            self.mc.li(rD, word)
        elif IS_PPC_32 or (word <= 2147483647 and word >= -2147483648):
            self.mc.lis(rD, hi(word))
            if word & 0xFFFF != 0:
                self.mc.ori(rD, rD, lo(word))
        else:
            self.mc.lis(rD, highest(word))
            self.mc.ori(rD, rD, higher(word))
            self.mc.sldi(rD, rD, 32)
            self.mc.oris(rD, rD, high(word))
            self.mc.ori(rD, rD, lo(word))

    def store_reg(self, source_reg, addr):
        self.load_imm(r.r0.value, addr)
        if IS_PPC_32:
            self.mc.stwx(source_reg.value, 0, 0)
        else:
            self.mc.stdx(source_reg.value, 0, 0)

    def _save_nonvolatiles(self):
        for i, reg in enumerate(NONVOLATILES):
            # save r31 later on
            if reg.value == r.SPP.value:
                continue
            if IS_PPC_32:
                self.mc.stw(reg.value, r.SPP.value, WORD + WORD * i)
            else:
                self.mc.std(reg.value, r.SPP.value, WORD + WORD * i)

    def _restore_nonvolatiles(self, mc, spp_reg):
        for i, reg in enumerate(NONVOLATILES):
            if IS_PPC_32:
                mc.lwz(reg.value, spp_reg.value, WORD + WORD * i)
            else:
                mc.ld(reg.value, spp_reg.value, WORD + WORD * i)

    # Fetches the identifier from a descr object.
    # If it has no identifier, then an unused identifier
    # is generated
    # XXX could be overwritten later on, better approach?
    def _get_identifier_from_descr(self, descr):
        try:
            identifier = descr.identifier
        except AttributeError:
            identifier = None
        if identifier is not None:
            return identifier
        keys = self.cpu.saved_descr.keys()
        if keys == []:
            return 1
        return max(keys) + 1

    def get_asmmemmgr_blocks(self, looptoken):
        clt = looptoken.compiled_loop_token
        if clt.asmmemmgr_blocks is None:
            clt.asmmemmgr = []
        return clt.asmmemmgr_blocks

    # XXX adjust for 64 bit
    def _make_prologue(self, target_pos, frame_depth):
        if IS_PPC_32:
            # save it in previous frame (Backchain)
            self.mc.stwu(r.SP.value, r.SP.value, -frame_depth)
            self.mc.mflr(r.r0.value)  # move old link register
            # save old link register in previous frame
            self.mc.stw(r.r0.value, r.SP.value, frame_depth + WORD) 
            # save r31 at the bottom of the stack frame
            self.mc.stw(r.SPP.value, r.SP.value, WORD)
        else:
            self.mc.stdu(r.SP.value, r.SP.value, -frame_depth)
            self.mc.mflr(r.r0.value)
            self.mc.std(r.r0.value, r.SP.value, frame_depth + 2 * WORD)
        offset = GPR_SAVE_AREA + WORD
        # compute spilling pointer (SPP)
        self.mc.addi(r.SPP.value, r.SP.value, frame_depth - offset)
        self._save_nonvolatiles()
        # save r31, use r30 as scratch register
        # this is safe because r30 has been saved already
        if IS_PPC_32:
            self.mc.lwz(r.r30.value, r.SP.value, WORD)
            self.mc.stw(r.r30.value, r.SPP.value, WORD * len(NONVOLATILES))
        else:
            self.mc.ld(r.r30.value, r.SP.value, WORD)
            self.mc.std(r.r30.value, r.SPP.value, WORD * len(NONVOLATILES))
        # branch to loop code
        curpos = self.mc.currpos()
        offset = target_pos - curpos
        self.mc.b(offset)

    def setup_failure_recovery(self):

        @rgc.no_collect
        def failure_recovery_func(mem_loc, frame_pointer, stack_pointer):
            """mem_loc is a structure in memory describing where the values for
            the failargs are stored.
            frame loc is the address of the frame pointer for the frame to be
            decoded frame """
            return self.decode_registers_and_descr(mem_loc, frame_pointer, stack_pointer)

        self.failure_recovery_func = failure_recovery_func

    recovery_func_sign = lltype.Ptr(lltype.FuncType([lltype.Signed, 
            lltype.Signed, lltype.Signed], lltype.Signed))

    @rgc.no_collect
    def decode_registers_and_descr(self, mem_loc, stack_loc, spp_loc):
        ''' 
            mem_loc     : pointer to encoded state
            stack_loc   : pointer to top of the stack
            spp_loc     : pointer to begin of the spilling area
            '''
        enc = rffi.cast(rffi.CCHARP, mem_loc)
        managed_size = WORD * len(r.MANAGED_REGS)
        spilling_depth = spp_loc - stack_loc + managed_size
        spilling_area = rffi.cast(rffi.CCHARP, stack_loc + managed_size)
        assert spilling_depth >= 0

        regs = rffi.cast(rffi.CCHARP, stack_loc)
        i = -1
        fail_index = -1
        while(True):
            i += 1
            fail_index += 1
            res = enc[i]
            if res == self.END_OF_LOCS:
                break
            if res == self.EMPTY_LOC:
                continue

            group = res
            i += 1
            res = enc[i]
            if res == self.IMM_LOC:
               # imm value
                if group == self.INT_TYPE or group == self.REF_TYPE:
                    value = decode32(enc, i+1)
                    i += 4
                else:
                    assert group == self.FLOAT_TYPE
                    adr = decode32(enc, i+1)
                    value = rffi.cast(rffi.CArrayPtr(longlong.FLOATSTORAGE), adr)[0]
                    self.fail_boxes_float.setitem(fail_index, value)
                    i += 4
                    continue
            elif res == self.STACK_LOC:
                stack_loc = decode32(enc, i+1)
                i += 4
                if group == self.FLOAT_TYPE:
                    value = decode64(stack, frame_depth - stack_loc*WORD)
                    self.fail_boxes_float.setitem(fail_index, value)
                    continue
                else:
                    value = decode32(spilling_area, spilling_area - stack_loc * WORD)
            else: # REG_LOC
                reg = ord(enc[i])
                if group == self.FLOAT_TYPE:
                    value = decode64(vfp_regs, reg*2*WORD)
                    self.fail_boxes_float.setitem(fail_index, value)
                    continue
                else:
                    value = decode32(regs, reg*WORD - 2 * WORD)

            if group == self.INT_TYPE:
                self.fail_boxes_int.setitem(fail_index, value)
            elif group == self.REF_TYPE:
                tgt = self.fail_boxes_ptr.get_addr_for_num(fail_index)
                rffi.cast(rffi.LONGP, tgt)[0] = value
            else:
                assert 0, 'unknown type'


        assert enc[i] == self.END_OF_LOCS
        descr = decode32(enc, i+1)
        self.fail_boxes_count = fail_index
        self.fail_force_index = spp_loc
        return descr

    def _gen_leave_jitted_hook_code(self, save_exc=False):
        mc = PPCBuilder()

        # PLAN:
        # =====
        # save caller save registers AND(!) r0 
        # (r0 contains address of state encoding)

        mc.b_abs(self.exit_code_adr)
        mc.prepare_insts_blocks()
        return mc.materialize(self.cpu.asmmemmgr, [],
                               self.cpu.gc_ll_descr.gcrootmap)

    # XXX 64 bit adjustment needed
    def _gen_exit_path(self):
        mc = PPCBuilder() 
        #
        self._save_managed_regs(mc)
        # adjust SP (r1)
        size = WORD * len(r.MANAGED_REGS)
        mc.addi(r.SP.value, r.SP.value, -size)
        #
        decode_func_addr = llhelper(self.recovery_func_sign,
                self.failure_recovery_func)
        addr = rffi.cast(lltype.Signed, decode_func_addr)
        #
        # load parameters into parameter registers
        mc.lwz(r.r3.value, r.SPP.value, 0)
        #mc.mr(r.r3.value, r.r0.value)          # address of state encoding 
        mc.mr(r.r4.value, r.SP.value)          # load stack pointer
        mc.mr(r.r5.value, r.SPP.value)         # load spilling pointer
        #
        # load address of decoding function into r0
        mc.load_imm(r.r0, addr)
        # ... and branch there
        mc.mtctr(r.r0.value)
        mc.bctrl()
        #
        mc.addi(r.SP.value, r.SP.value, size)
        # save SPP in r5
        # (assume that r5 has been written to failboxes)
        mc.mr(r.r5.value, r.SPP.value)
        self._restore_nonvolatiles(mc, r.r5)
        # load old backchain into r4
        if IS_PPC_32:
            mc.lwz(r.r4.value, r.r5.value, GPR_SAVE_AREA + 2 * WORD) 
        else:
            mc.ld(r.r4.value, r.r5.value, GPR_SAVE_AREA + 2 * WORD)
        mc.mtlr(r.r4.value)     # restore LR
        mc.addi(r.SP.value, r.r5.value, GPR_SAVE_AREA + WORD) # restore old SP
        mc.blr()
        mc.prepare_insts_blocks()
        return mc.materialize(self.cpu.asmmemmgr, [],
                                   self.cpu.gc_ll_descr.gcrootmap)

    # Save all registers which are managed by the register
    # allocator on top of the stack before decoding.
    # XXX adjust for 64 bit
    def _save_managed_regs(self, mc):
        for i in range(len(r.MANAGED_REGS) - 1, -1, -1):
            reg = r.MANAGED_REGS[i]
            if IS_PPC_32:
                mc.stw(reg.value, r.SP.value, -(len(r.MANAGED_REGS) - i) * WORD)
            else:
                assert 0, "not implemented yet"

    def gen_bootstrap_code(self, nonfloatlocs, inputargs):
        for i in range(len(nonfloatlocs)):
            loc = nonfloatlocs[i]
            arg = inputargs[i]
            assert arg.type != FLOAT
            if arg.type == INT:
                addr = self.fail_boxes_int.get_addr_for_num(i)
            elif arg.type == REF:
                addr = self.fail_boxes_ptr.get_addr_for_num(i)
            else:
                assert 0, "%s not supported" % arg.type
            if loc.is_reg():
                reg = loc
            else:
                reg = r.r0
            self.mc.load_from_addr(reg, addr)
            if loc.is_stack():
                self.regalloc_mov(r.r0, loc)

    def setup(self, looptoken, operations):
        operations = self.cpu.gc_ll_descr.rewrite_assembler(self.cpu, 
                                                            operations)
        assert self.memcpy_addr != 0
        self.current_clt = looptoken.compiled_loop_token
        self.mc = PPCBuilder()
        self.pending_guards = []
        assert self.datablockwrapper is None
        allblocks = self.get_asmmemmgr_blocks(looptoken)
        self.datablockwrapper = MachineDataBlockWrapper(self.cpu.asmmemmgr,
                                                        allblocks)

    def setup_once(self):
        self.memcpy_addr = self.cpu.cast_ptr_to_int(memcpy_fn)
        self.setup_failure_recovery()
        self.exit_code_adr = self._gen_exit_path()
        #self._leave_jitted_hook_save_exc = self._gen_leave_jitted_hook_code(True)
        self._leave_jitted_hook = self._gen_leave_jitted_hook_code(False)

    def assemble_loop(self, inputargs, operations, looptoken, log):

        clt = CompiledLoopToken(self.cpu, looptoken.number)
        looptoken.compiled_loop_token = clt

        self.setup(looptoken, operations)
        self.startpos = self.mc.currpos()

        longevity = compute_vars_longevity(inputargs, operations)
        regalloc = Regalloc(longevity, assembler=self,
                            frame_manager=PPCFrameManager())

        nonfloatlocs = regalloc.prepare_loop(inputargs, operations, looptoken)
        regalloc_head = self.mc.currpos()
        self.gen_bootstrap_code(nonfloatlocs, inputargs)

        loophead = self.mc.currpos()            # address of actual loop
        looptoken._ppc_loop_code = loophead
        looptoken._ppc_arglocs = [nonfloatlocs]
        looptoken._ppc_bootstrap_code = 0

        self._walk_operations(operations, regalloc)

        start_pos = self.mc.currpos()
        self.framesize = frame_depth = self.compute_frame_depth(regalloc)
        self._make_prologue(regalloc_head, frame_depth)
     
        self.write_pending_failure_recoveries()
        loop_start = self.materialize_loop(looptoken, False)
        looptoken.ppc_code = loop_start + start_pos
        self.process_pending_guards(loop_start)
        self._teardown()

    # For an explanation of the encoding, see
    # backend/arm/assembler.py
    def gen_descr_encoding(self, descr, args, arglocs):
        minsize = (len(arglocs) - 1) * 6 + 5
        memsize = self.align(minsize)
        memaddr = self.datablockwrapper.malloc_aligned(memsize, alignment=1)
        mem = rffi.cast(rffi.CArrayPtr(lltype.Char), memaddr)
        i = 0
        j = 0
        while i < len(args):
            if arglocs[i+1]:
                arg = args[i]
                loc = arglocs[i+1]
                if arg.type == INT:
                    mem[j] = self.INT_TYPE
                    j += 1
                elif arg.type == REF:
                    mem[j] = self.REF_TYPE
                    j += 1
                elif arg.type == FLOAT:
                    mem[j] = self.FLOAT_TYPE
                    j += 1
                else:
                    assert 0, 'unknown type'

                if loc.is_reg() or loc.is_vfp_reg():
                    mem[j] = chr(loc.value)
                    j += 1
                elif loc.is_imm() or loc.is_imm_float():
                    assert (arg.type == INT or arg.type == REF
                                or arg.type == FLOAT)
                    mem[j] = self.IMM_LOC
                    encode32(mem, j+1, loc.getint())
                    j += 5
                else:
                    mem[j] = self.STACK_LOC
                    encode32(mem, j+1, loc.position)
                    j += 5
            else:
                mem[j] = self.EMPTY_LOC
                j += 1
            i += 1
                # XXX 64 bit adjustment needed

        mem[j] = chr(0xFF)

        n = self.cpu.get_fail_descr_number(descr)
        encode32(mem, j+1, n)
        return memaddr

    def align(self, size):
        while size % 8 != 0:
            size += 1
        return size

    def _teardown(self):
        self.patch_list = None
        self.pending_guards = None
        self.current_clt = None
        self.mc = None

    def _walk_operations(self, operations, regalloc):
        while regalloc.position() < len(operations) - 1:
            regalloc.next_instruction()
            pos = regalloc.position()
            op = operations[pos]
            opnum = op.getopnum()
            if op.has_no_side_effect() and op.result not in regalloc.longevity:
                regalloc.possibly_free_vars_for_op(op)
            else:
                arglocs = regalloc.operations[opnum](regalloc, op)
                if arglocs is not None:
                    self.operations[opnum](self, op, arglocs, regalloc)
            if op.result:
                regalloc.possibly_free_var(op.result)
            regalloc.possibly_free_vars_for_op(op)
            regalloc._check_invariants()

    def compute_frame_depth(self, regalloc):
        frame_depth = (GPR_SAVE_AREA                        # GPR space
                       + WORD                               # FORCE INDEX
                       + regalloc.frame_manager.frame_depth * WORD)
        return frame_depth
    
    def materialize_loop(self, looptoken, show):
        self.mc.prepare_insts_blocks(show)
        self.datablockwrapper.done()
        self.datablockwrapper = None
        allblocks = self.get_asmmemmgr_blocks(looptoken)
        return self.mc.materialize(self.cpu.asmmemmgr, allblocks, 
                                   self.cpu.gc_ll_descr.gcrootmap)

    def write_pending_failure_recoveries(self):
        for tok in self.pending_guards:
            descr = tok.descr
            #generate the exit stub and the encoded representation
            pos = self.mc.currpos()
            tok.pos_recovery_stub = pos 

            memaddr = self.gen_exit_stub(descr, tok.failargs,
                                            tok.faillocs, save_exc=tok.save_exc)
            # store info on the descr
            descr._ppc_frame_depth = tok.faillocs[0].getint()
            descr._failure_recovery_code = memaddr
            descr._ppc_guard_pos = pos

    def gen_exit_stub(self, descr, args, arglocs, fcond=c.NE,
                               save_exc=False):
        memaddr = self.gen_descr_encoding(descr, args, arglocs)

        # store addr in force index field
        self.mc.load_imm(r.r0, memaddr)
        self.mc.stw(r.r0.value, r.SPP.value, 0)

        if save_exc:
            path = self._leave_jitted_hook_save_exc
        else:
            path = self._leave_jitted_hook
        self.branch_abs(path)
        return memaddr

    def process_pending_guards(self, block_start):
        clt = self.current_clt
        for tok in self.pending_guards:
            descr = tok.descr
            assert isinstance(descr, AbstractFailDescr)
            descr._ppc_block_start = block_start

            if not tok.is_invalidate:
                mc = PPCBuilder()
                offset = descr._ppc_guard_pos - tok.offset
                mc.b_cond_offset(offset, tok.fcond)
                mc.prepare_insts_blocks(True)
                mc.copy_to_raw_memory(block_start + tok.offset)
            else:
                assert 0, "not implemented yet"

    def get_asmmemmgr_blocks(self, looptoken):
        clt = looptoken.compiled_loop_token
        if clt.asmmemmgr_blocks is None:
            clt.asmmemmgr_blocks = []
        return clt.asmmemmgr_blocks

    # XXX fix for 64 bit
    def regalloc_mov(self, prev_loc, loc):
        if prev_loc.is_imm():
            value = prev_loc.getint()
            # move immediate value to register
            if loc.is_reg():
                reg = loc.as_key()
                self.mc.load_imm(reg, value)
                return
            # move immediate value to memory
            elif loc.is_stack():
                offset = loc.as_key() * WORD - WORD
                self.mc.load_imm(r.r0.value, value)
                self.mc.stw(r.r0.value, r.SPP.value, offset)
                return
            assert 0, "not supported location"
        elif prev_loc.is_stack():
            offset = prev_loc.as_key() * WORD - WORD
            # move from memory to register
            if loc.is_reg():
                reg = loc.as_key()
                self.mc.lwz(reg, r.SPP.value, offset)
                return
            # move in memory
            elif loc.is_stack():
                target_offset = loc.as_key() * WORD - WORD
                self.mc.lwz(r.r0.value, r.SPP.value, offset)
                self.mc.stw(r.r0.value, r.SPP.value, target_offset)
                return
            assert 0, "not supported location"
        elif prev_loc.is_reg():
            reg = prev_loc.as_key()
            # move to another register
            if loc.is_reg():
                other_reg = loc.as_key()
                self.mc.mr(other_reg, reg)
                return
            # move to memory
            elif loc.is_stack():
                offset = loc.as_key() * WORD - WORD
                self.mc.stw(reg, r.SPP.value, offset)
                return
            assert 0, "not supported location"
        assert 0, "not supported location"

def make_operations():
    def not_implemented(builder, trace_op, cpu, *rest_args):
        raise NotImplementedError, trace_op

    oplist = [None] * (rop._LAST + 1)
    for key, val in rop.__dict__.items():
        if key.startswith("_"):
            continue
        opname = key.lower()
        methname = "emit_%s" % opname
        if hasattr(AssemblerPPC, methname):
            oplist[val] = getattr(AssemblerPPC, methname).im_func
        else:
            oplist[val] = not_implemented
    return oplist

AssemblerPPC.operations = make_operations()