example_irbuilder.py 2.24 KB
Newer Older
Kunshan Wang's avatar
Kunshan Wang committed
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
from __future__ import division, absolute_import, print_function, unicode_literals

import sys

import ctypes, ctypes.util
from libmu import *

libc = ctypes.CDLL(ctypes.util.find_library("c"))
libc.write.restype = ctypes.c_ssize_t
libc.write.argtypes = [ctypes.c_int, ctypes.c_void_p, ctypes.c_size_t]

dll = MuRefImpl2StartDLL("../cbinding/libmurefimpl2start.so")
mu = dll.mu_refimpl2_new_ex(
        dumpBundle=True
        #vmLog="DEBUG"
        #vmLog="INFO"
        )

with mu.new_context() as ctx:
    # Perpare the C function pointers:
    puts_addr = ctypes.cast(libc.puts, ctypes.c_void_p).value
    print("puts = ", puts_addr, hex(puts_addr))

    # Building bundle...
    b = ctx.new_ir_builder()

    i32      = b.gen_sym("@i32")
    i8       = b.gen_sym("@i8")
    pi8      = b.gen_sym("@pi8")
    puts_sig = b.gen_sym("@puts.sig")
    puts_fp  = b.gen_sym("@puts.fp")
    puts     = b.gen_sym("@puts")

    b.new_type_int(i32, 32)
    b.new_type_int(i8, 8)
    b.new_type_uptr(pi8, i8)
    b.new_funcsig(puts_sig, [pi8], [i32])
    b.new_type_ufuncptr(puts_fp, puts_sig)
    b.new_const_int(puts, pi8, puts_addr)
    
    buf = ctypes.create_string_buffer("Hello python!".encode("ascii"))
    buf_addr = ctypes.cast(buf, ctypes.c_void_p).value
    print("buf_addr = ", buf_addr, hex(buf_addr))

    msg = b.gen_sym("@msg")
    b.new_const_int(msg, pi8, buf_addr)

    mumain_sig = b.gen_sym("@mumain.sig")
    mumain     = b.gen_sym("@mumain")
    fv         = b.gen_sym("@mumain.v1")
    entry      = b.gen_sym("@mumain.v1.entry")
    ccall      = b.gen_sym("@mumain.v1.entry.ccall")
    ccall_r    = b.gen_sym("@mumain.v1.entry.ccall_r")
    threadexit = b.gen_sym("@mumain.v1.entry.threadedit")

    b.new_funcsig(mumain_sig, [], [])
    b.new_func(mumain, mumain_sig)
    b.new_func_ver(fv, mumain, [entry])

    b.new_bb(entry, [], [], 0, [ccall, threadexit])

    b.new_ccall(ccall, [ccall_r], MuCallConv.DEFAULT, puts_fp, puts_sig, puts, [msg], None, None)

    b.new_comminst(threadexit, [], common_instruction_opcodes["@uvm.thread_exit"],
            [], [], [], [], None, None)

    b.load()

    hmumain = ctx.handle_from_func(mumain)
    st = ctx.new_stack(hmumain)
    th = ctx.new_thread(st, None, PassValues())

    mu.execute()

    print("Returned from Mu.")