Beispiel #1
0
def _setup_mt_rand_init(ctx, state_ty, init_scalar):
    seed_ty = state_ty.elements[0].element
    builder = _setup_builtin_func_builder(ctx, "mt_rand_init",
                                          (state_ty.as_pointer(), seed_ty))
    state, seed = builder.function.args

    default_seed = seed.type(19650218)
    builder.call(init_scalar, [state, default_seed])

    # python considers everything to be an array
    key_array = builder.alloca(ir.ArrayType(seed.type, 1))
    key_p = builder.gep(key_array, [ctx.int32_ty(0), ctx.int32_ty(0)])
    builder.store(seed, key_p)

    pi = builder.alloca(ctx.int32_ty)
    builder.store(ctx.int32_ty(1), pi)
    pj = builder.alloca(ctx.int32_ty)
    builder.store(ctx.int32_ty(0), pj)
    array = builder.gep(state, [ctx.int32_ty(0), ctx.int32_ty(0)])
    a_0 = builder.gep(array, [ctx.int32_ty(0), ctx.int32_ty(0)])

    # This loop should go from max(N, len(key)) -> 0,
    # but we know the key length so we can hardcode it
    with helpers.for_loop_zero_inc(builder, ctx.int32_ty(_MERSENNE_N),
                                   "add_key") as (b, _):
        i = builder.load(pi)
        i_m1 = b.sub(i, ctx.int32_ty(1))
        pa_i = b.gep(array, [ctx.int32_ty(0), i])
        pa_i_m1 = b.gep(array, [ctx.int32_ty(0), i_m1])

        # Load key element
        j = b.load(pj)
        pkey = b.gep(key_array, [ctx.int32_ty(0), j])

        # Update key index
        j_new = b.add(j, ctx.int32_ty(1))
        j_ovf = b.icmp_unsigned(">=", j_new, ctx.int32_ty(1))
        j_new = b.select(j_ovf, ctx.int32_ty(0), j_new)
        b.store(j_new, pj)

        # Mix in the key
        val = b.load(pa_i_m1)
        val = b.xor(val, b.lshr(val, val.type(30)))
        val = b.mul(val, val.type(1664525))
        val = b.xor(b.load(pa_i), val)
        val = b.add(val, b.load(pkey))
        val = b.add(val, b.zext(j, val.type))
        val = b.and_(val, val.type(0xffffffff))
        b.store(val, pa_i)

        # Update the index
        i = b.add(i, ctx.int32_ty(1))
        b.store(i, pi)
        i_ovf = b.icmp_unsigned(">=", i, ctx.int32_ty(_MERSENNE_N))
        with b.if_then(i_ovf, likely=False):
            b.store(ctx.int32_ty(1), pi)
            b.store(val, a_0)

    with helpers.for_loop_zero_inc(builder, ctx.int32_ty(_MERSENNE_N - 1),
                                   "second_shuffle") as (b, _):
        i = builder.load(pi)
        i_m1 = b.sub(i, ctx.int32_ty(1))
        pa_i = b.gep(array, [ctx.int32_ty(0), i])
        pa_i_m1 = b.gep(array, [ctx.int32_ty(0), i_m1])

        val = b.load(pa_i_m1)
        val = b.xor(val, b.lshr(val, val.type(30)))
        val = b.mul(val, val.type(1566083941))
        val = b.xor(b.load(pa_i), val)
        val = b.sub(val, b.zext(i, val.type))
        val = b.and_(val, val.type(0xffffffff))
        b.store(val, pa_i)

        # Update the index
        i = b.add(i, ctx.int32_ty(1))
        b.store(i, pi)
        i_ovf = b.icmp_unsigned(">=", i, ctx.int32_ty(_MERSENNE_N))
        with b.if_then(i_ovf, likely=False):
            b.store(ctx.int32_ty(1), pi)
            b.store(val, a_0)

    # set the 0th element to INT_MIN
    builder.store(a_0.type.pointee(0x80000000), a_0)
    builder.ret_void()

    return builder.function
Beispiel #2
0
 def __init__(self, dmm, fe_type):
     super(EphemeralArrayModel, self).__init__(dmm, fe_type)
     self._data_type = ir.ArrayType(self._pointee_be_type,
                                    self._fe_type.count)
Beispiel #3
0
 def __init__(self, dmm, fe_type):
     super(RecordModel, self).__init__(dmm, fe_type)
     self._models = [self._dmm.lookup(t) for _, t in fe_type.members]
     self._be_type = ir.ArrayType(ir.IntType(8), fe_type.size)
     self._be_ptr_type = self._be_type.as_pointer()
Beispiel #4
0
def _setup_mt_rand_init(ctx, state_ty, init_scalar):
    seed_ty = state_ty.elements[0].element
    init_ty = ir.FunctionType(ir.VoidType(), (state_ty.as_pointer(), seed_ty))
    # Create init_array function
    init = ir.Function(ctx.module, init_ty, name="__pnl_builtin_mt_rand_init")
    init.attributes.add('argmemonly')
    init.attributes.add('alwaysinline')

    block = init.append_basic_block(name="entry")
    builder = ir.IRBuilder(block)
    builder.debug_metadata = LLVMBuilderContext.get_debug_location(init, None)
    state, seed = init.args

    # Add function arg attributes
    state.attributes.add('nonnull')
    state.attributes.add('noalias')

    default_seed = seed.type(19650218)
    builder.call(init_scalar, [state, default_seed])

    # python considers everything to be an array
    key_array = builder.alloca(ir.ArrayType(seed.type, 1))
    key_p = builder.gep(key_array, [ctx.int32_ty(0), ctx.int32_ty(0)])
    builder.store(seed, key_p)

    pi = builder.alloca(ctx.int32_ty)
    builder.store(ctx.int32_ty(1), pi)
    pj = builder.alloca(ctx.int32_ty)
    builder.store(ctx.int32_ty(0), pj)
    array = builder.gep(state, [ctx.int32_ty(0), ctx.int32_ty(0)])
    a_0 = builder.gep(array, [ctx.int32_ty(0), ctx.int32_ty(0)])

    # This loop should go from max(N, len(key)) -> 0,
    # but we know the key length so we can hardcode it
    with helpers.for_loop_zero_inc(builder,
                                   ctx.int32_ty(_MERSENNE_N),
                                   "add_key") as (b, _):
        i = builder.load(pi)
        i_m1 = b.sub(i, ctx.int32_ty(1))
        pa_i = b.gep(array, [ctx.int32_ty(0), i])
        pa_i_m1 = b.gep(array, [ctx.int32_ty(0), i_m1])

        # Load key element
        j = b.load(pj)
        pkey = b.gep(key_array, [ctx.int32_ty(0), j])

        # Update key index
        j_new = b.add(j, ctx.int32_ty(1))
        j_ovf = b.icmp_unsigned(">=", j_new, ctx.int32_ty(1))
        j_new = b.select(j_ovf, ctx.int32_ty(0), j_new)
        b.store(j_new, pj)

        # Mix in the key
        val = b.load(pa_i_m1)
        val = b.xor(val, b.lshr(val, val.type(30)))
        val = b.mul(val, val.type(1664525))
        val = b.xor(b.load(pa_i), val)
        val = b.add(val, b.load(pkey))
        val = b.add(val, b.zext(j, val.type))
        val = b.and_(val, val.type(0xffffffff))
        b.store(val, pa_i)

        # Update the index
        i = b.add(i, ctx.int32_ty(1))
        b.store(i, pi)
        i_ovf = b.icmp_unsigned(">=", i, ctx.int32_ty(_MERSENNE_N))
        with b.if_then(i_ovf, likely=False):
            b.store(ctx.int32_ty(1), pi)
            b.store(val, a_0)


    with helpers.for_loop_zero_inc(builder,
                                   ctx.int32_ty(_MERSENNE_N - 1),
                                   "second_shuffle") as (b, _):
        i = builder.load(pi)
        i_m1 = b.sub(i, ctx.int32_ty(1))
        pa_i = b.gep(array, [ctx.int32_ty(0), i])
        pa_i_m1 = b.gep(array, [ctx.int32_ty(0), i_m1])

        val = b.load(pa_i_m1)
        val = b.xor(val, b.lshr(val, val.type(30)))
        val = b.mul(val, val.type(1566083941))
        val = b.xor(b.load(pa_i), val)
        val = b.sub(val, b.zext(i, val.type))
        val = b.and_(val, val.type(0xffffffff))
        b.store(val, pa_i)

        # Update the index
        i = b.add(i, ctx.int32_ty(1))
        b.store(i, pi)
        i_ovf = b.icmp_unsigned(">=", i, ctx.int32_ty(_MERSENNE_N))
        with b.if_then(i_ovf, likely=False):
            b.store(ctx.int32_ty(1), pi)
            b.store(val, a_0)

    # set the 0th element to INT_MIN
    builder.store(a_0.type.pointee(0x80000000), a_0)
    builder.ret_void()
    return init
Beispiel #5
0
def get_mersenne_twister_state_struct(ctx):
    return ir.LiteralStructType([
        ir.ArrayType(ctx.int32_ty, _MERSENNE_N), # array
        ctx.int32_ty, #index
        ctx.int32_ty, #last_gauss available
        ctx.float_ty]) #last_gauss
Beispiel #6
0
 def type(element_type: ir.Type, count: int) -> ir.Type:
     return ir.ArrayType(element_type, count)
Beispiel #7
0
 def array(typ, val):
     return ir.Constant(ir.ArrayType(typ, len(val)), val)
Beispiel #8
0
  int B[1024];

  A[50] = A[49] + 5;

  B[0] = B[1] + 10;
    
  return 0;
}
'''

# Cria o módulo.
module = ir.Module('meu_modulo.bc')

# Array global de 1024 elementos.
typeA = ir.ArrayType(ir.IntType(64), 1024)

arrayA = ir.GlobalVariable(module, typeA, "A")
arrayA.initializer = ir.Constant.array(ir.IntType(64), 0)

# arrayA.initializer = ir.IntType(64)
arrayA.linkage = "common"
# arrayA.initializer = ir.Constant(ir.IntType(64), 0)
arrayA.align = 16

# Cria um valor zero para colocar no retorno.
Zero64 = ir.Constant(ir.IntType(64), 0)

# Declara o tipo do retorno da função main.
mainFnReturnType = ir.IntType(64)
# Cria a função main.
Beispiel #9
0
 def _codegen_String(node):
     return ir.Constant(
         ir.ArrayType(ir.IntType(4), len(str(node.value))),
         [ord(char) for char in node.value],
     )
Beispiel #10
0
	def print_string(self, string):
		stringz = self.stringz(string)
		str_ptr = self.alloc_and_store(stringz, ir.ArrayType(stringz.type.element, stringz.type.count))
		str_ptr = self.gep(str_ptr, [self.const(0), self.const(0)])
		str_ptr = self.builder.bitcast(str_ptr, type_map[INT].as_pointer())
		self.call('puts', [str_ptr])
Beispiel #11
0
	def stringz(string):
		n = len(string) + 1
		buf = bytearray((' ' * n).encode('ascii'))
		buf[-1] = 0
		buf[:-1] = string.encode('utf-8')
		return ir.Constant(ir.ArrayType(type_map[INT8], n), buf)
Beispiel #12
0
 def type(element_type, count):
     return ir.ArrayType(element_type, count)
Beispiel #13
0
def gen_code(tree, symbol_table, sema_success):
    # symbol = {
    #         "symbol_type": None,
    #         "name": None,
    #         "value_type": None,
    #         "scope": None,
    #         "parameters": [],
    #         "dimensions": [],
    #         "declared": True,
    #         "inicialized": False,
    #         "used": False
    #     }
    global module
    global info

    # Define Global Variables and Functions
    for symbol in symbol_table:
        if (symbol["symbol_type"] == "variable"
                and symbol["scope"] == "global"):
            var_type = symbol["value_type"]

            if (var_type == "inteiro"):
                if (len(symbol["dimensions"]) == 0):
                    g = ir.GlobalVariable(module, ir.IntType(32),
                                          symbol["name"])

                if (len(symbol["dimensions"]) == 1):
                    g_type = ir.ArrayType(ir.IntType(32),
                                          int(symbol["dimensions"][0]))
                    g = ir.GlobalVariable(module, g_type, symbol["name"])
                    info["global_variables"].append(g)

            elif (var_type == "flutuante"):

                if (len(symbol["dimensions"]) == 0):
                    g = ir.GlobalVariable(module, ir.FloatType(),
                                          symbol["name"])

                if (len(symbol["dimensions"]) == 1):
                    g_type = ir.ArrayType(ir.FloatType(),
                                          int(symbol["dimensions"][0]))
                    g = ir.GlobalVariable(module, g_type, symbol["name"])

            g.linkage = "common"
            g.align = 4
            info["global_variables"].append(g)

        elif (symbol["symbol_type"] == "function"):
            if (symbol["name"] == "principal"):
                symbol["name"] = "main"

            arguments_list = []

            if (len(symbol["parameters"]) > 0):
                for a in symbol["parameters"]:
                    if (a["par_type"] == "inteiro"):
                        arguments_list.append(ir.IntType(32))
                    else:
                        arguments_list.append(ir.FloatType())

            if (len(symbol["return"]) > 0):
                if (symbol["return"][0]["ret_type"] == "inteiro"):
                    f_ret = ir.IntType(32)
                else:
                    f_ret = ir.FloatType()

                f_func = ir.FunctionType(f_ret, arguments_list)
                f = ir.Function(module, f_func, name=symbol["name"])
                entryBlock = f.append_basic_block('entry')
                builder = ir.IRBuilder(entryBlock)

            else:
                f_func = ir.FunctionType(ir.VoidType(), arguments_list)
                f = ir.Function(module, f_func, name=symbol["name"])
                entryBlock = f.append_basic_block('entry')
                builder = ir.IRBuilder(entryBlock)

            for i in range(len(f.args)):
                f.args[i].name = symbol["parameters"][i]["par_name"]

            functions.append({
                "function": f,
                "builder": builder,
                "arguments": f.args
            })

    go_through_tree(tree, functions)

    file = open('module.ll', 'w')
    file.write(str(module))
    file.close()
    print(module)
Beispiel #14
0
def _setup_mt_rand_integer(ctx, state_ty):
    int64_ty = ir.IntType(64)
    # Generate random number generator function.
    # It produces random 32bit numberin a 64bit word
    builder = _setup_builtin_func_builder(
        ctx, "mt_rand_int32", (state_ty.as_pointer(), int64_ty.as_pointer()))
    state, out = builder.function.args

    array = builder.gep(state, [ctx.int32_ty(0), ctx.int32_ty(0)])
    pidx = builder.gep(state, [ctx.int32_ty(0), ctx.int32_ty(1)])
    idx = builder.load(pidx)

    cond = builder.icmp_signed(">=", idx, ctx.int32_ty(_MERSENNE_N))
    with builder.if_then(cond, likely=False):
        mag01 = ir.ArrayType(array.type.pointee.element, 2)([0, 0x9908b0df])
        pmag01 = builder.alloca(mag01.type)
        builder.store(mag01, pmag01)

        with helpers.for_loop_zero_inc(builder,
                                       ctx.int32_ty(_MERSENNE_N - _MERSENNE_M),
                                       "first_half") as (b, kk):
            pkk = b.gep(array, [ctx.int32_ty(0), kk])
            pkk_1 = b.gep(array, [ctx.int32_ty(0), b.add(kk, ctx.int32_ty(1))])

            val_kk = b.and_(b.load(pkk), pkk.type.pointee(0x80000000))
            val_kk_1 = b.and_(b.load(pkk_1), pkk_1.type.pointee(0x7fffffff))
            val = b.or_(val_kk, val_kk_1)

            val_1 = b.and_(val, val.type(1))
            pval_mag = b.gep(pmag01, [ctx.int32_ty(0), val_1])
            val_mag = b.load(pval_mag)

            val_shift = b.lshr(val, val.type(1))

            kk_m = b.add(kk, ctx.int32_ty(_MERSENNE_M))
            pval_kk_m = b.gep(array, [ctx.int32_ty(0), kk_m])
            val_kk_m = b.load(pval_kk_m)

            val = b.xor(val_kk_m, val_shift)
            val = b.xor(val, val_mag)

            b.store(val, pkk)

        with helpers.for_loop(builder, ctx.int32_ty(_MERSENNE_N - _MERSENNE_M),
                              ctx.int32_ty(_MERSENNE_N), ctx.int32_ty(1),
                              "second_half") as (b, kk):
            pkk = b.gep(array, [ctx.int32_ty(0), kk])
            is_last = b.icmp_unsigned("==", kk, ctx.int32_ty(_MERSENNE_N - 1))
            idx_1 = b.select(is_last, ctx.int32_ty(0),
                             b.add(kk, ctx.int32_ty(1)))
            pkk_1 = b.gep(array, [ctx.int32_ty(0), idx_1])

            val_kk = b.and_(b.load(pkk), pkk.type.pointee(0x80000000))
            val_kk_1 = b.and_(b.load(pkk_1), pkk.type.pointee(0x7fffffff))
            val = b.or_(val_kk, val_kk_1)

            val_1 = b.and_(val, val.type(1))
            pval_mag = b.gep(pmag01, [ctx.int32_ty(0), val_1])
            val_mag = b.load(pval_mag)

            val_shift = b.lshr(val, val.type(1))

            kk_m = b.add(kk, ctx.int32_ty(_MERSENNE_M - _MERSENNE_N))
            pval_kk_m = b.gep(array, [ctx.int32_ty(0), kk_m])
            val_kk_m = b.load(pval_kk_m)

            val = b.xor(val_kk_m, val_shift)
            val = b.xor(val, val_mag)

            b.store(val, pkk)

        builder.store(pidx.type.pointee(0), pidx)

    # Get pointer and update index
    idx = builder.load(pidx)
    pval = builder.gep(array, [ctx.int32_ty(0), idx])
    idx = builder.add(idx, idx.type(1))
    builder.store(idx, pidx)

    # Load and temper
    val = builder.load(pval)
    tmp = builder.lshr(val, val.type(11))
    val = builder.xor(val, tmp)

    tmp = builder.shl(val, val.type(7))
    tmp = builder.and_(tmp, tmp.type(0x9d2c5680))
    val = builder.xor(val, tmp)

    tmp = builder.shl(val, val.type(15))
    tmp = builder.and_(tmp, tmp.type(0xefc60000))
    val = builder.xor(val, tmp)

    tmp = builder.lshr(val, val.type(18))
    val = builder.xor(val, tmp)

    # val is now random 32bit integer
    val = builder.zext(val, out.type.pointee)
    builder.store(val, out)
    builder.ret_void()

    return builder.function
Beispiel #15
0
 def __init__(self, dmm, fe_type):
     super(CharSeq, self).__init__(dmm, fe_type)
     charty = ir.IntType(8)
     self._be_type = ir.ArrayType(charty, fe_type.count)
Beispiel #16
0
def arrayOpera(ast, builder, symblos):

    i32_0 = ir.Constant(i32, 0)

    if ast[c.op] == "+":

        if ast[c.var] in symblos:
            value_op = builder.load(symblos[ast[c.var]])

            if '#array' in symblos:

                array_poiter = builder.gep(symblos['#array'],
                                           [i32_0, value_op])
                array_i_value = builder.load(array_poiter)
                valor_somado = ir.Constant(i32, ast[c.value])

                new_value_index = builder.add(array_i_value,
                                              valor_somado,
                                              name="add")
                builder.store(new_value_index, array_poiter)
            else:
                array_example = [
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                ]
                #print(array_example)
                array_type = ir.ArrayType(
                    i32, len(array_example)
                )  #According to documentation, the second argument has to be an Python Integer. It can't be ir.Constant(i32, 3) for example.
                arr = ir.Constant(array_type, array_example)
                ptr = builder.alloca(array_type)  #allocate memory
                builder.store(arr, ptr)
                symblos['#array'] = ptr
                array_poiter = builder.gep(symblos['#array'],
                                           [i32_0, value_op])
                array_i_value = builder.load(array_poiter)
                valor_somado = ir.Constant(i32, ast[c.value])

                new_value_index = builder.add(array_i_value,
                                              valor_somado,
                                              name="add")
                builder.store(new_value_index, array_poiter)
        else:

            value_op = ir.Constant(i32, ast['var'])
            #builder.store(ast[c.var], value_op)

            if '#array' in symblos:

                array_poiter = builder.gep(symblos['#array'],
                                           [i32_0, value_op])
                array_i_value = builder.load(array_poiter)
                valor_somado = ir.Constant(i32, ast[c.value])

                new_value_index = builder.add(array_i_value,
                                              valor_somado,
                                              name="add")
                builder.store(new_value_index, array_poiter)
            else:
                array_example = [
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                ]
                #print(array_example)
                array_type = ir.ArrayType(
                    i32, len(array_example)
                )  #According to documentation, the second argument has to be an Python Integer. It can't be ir.Constant(i32, 3) for example.
                arr = ir.Constant(array_type, array_example)
                ptr = builder.alloca(array_type)  #allocate memory
                builder.store(arr, ptr)
                symblos['#array'] = ptr
                array_poiter = builder.gep(symblos['#array'],
                                           [i32_0, value_op])
                array_i_value = builder.load(array_poiter)
                valor_somado = ir.Constant(i32, ast[c.value])

                new_value_index = builder.add(array_i_value,
                                              valor_somado,
                                              name="add")
                builder.store(new_value_index, array_poiter)
    else:

        if ast[c.var] in symblos:
            value_op = builder.load(symblos[ast[c.var]])

            if '#array' in symblos:

                array_poiter = builder.gep(symblos['#array'],
                                           [i32_0, value_op])
                array_i_value = builder.load(array_poiter)
                valor_somado = ir.Constant(i32, ast[c.value])

                new_value_index = builder.sub(array_i_value,
                                              valor_somado,
                                              name="sub")
                builder.store(new_value_index, array_poiter)
            else:
                array_example = [
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                ]
                #print(array_example)
                array_type = ir.ArrayType(
                    i32, len(array_example)
                )  #According to documentation, the second argument has to be an Python Integer. It can't be ir.Constant(i32, 3) for example.
                arr = ir.Constant(array_type, array_example)
                ptr = builder.alloca(array_type)  #allocate memory
                builder.store(arr, ptr)
                symblos['#array'] = ptr
                array_poiter = builder.gep(symblos['#array'],
                                           [i32_0, value_op])
                array_i_value = builder.load(array_poiter)
                valor_somado = ir.Constant(i32, ast[c.value])

                new_value_index = builder.sub(array_i_value,
                                              valor_somado,
                                              name="sub")
                builder.store(new_value_index, array_poiter)
        else:

            value_op = ir.Constant(i32, ast[c.var])

            if '#array' in symblos:

                array_poiter = builder.gep(symblos['#array'],
                                           [i32_0, value_op])
                array_i_value = builder.load(array_poiter)
                valor_somado = ir.Constant(i32, ast[c.value])

                new_value_index = builder.sub(array_i_value,
                                              valor_somado,
                                              name="sub")
                builder.store(new_value_index, array_poiter)
            else:
                array_example = [
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
                ]
                #print(array_example)
                array_type = ir.ArrayType(
                    i32, len(array_example)
                )  #According to documentation, the second argument has to be an Python Integer. It can't be ir.Constant(i32, 3) for example.
                arr = ir.Constant(array_type, array_example)
                ptr = builder.alloca(array_type)  #allocate memory
                builder.store(arr, ptr)
                symblos['#array'] = ptr
                array_poiter = builder.gep(symblos['#array'],
                                           [i32_0, value_op])
                array_i_value = builder.load(array_poiter)
                valor_somado = ir.Constant(i32, ast[c.value])

                new_value_index = builder.sub(array_i_value,
                                              valor_somado,
                                              name="sub")
                builder.store(new_value_index, array_poiter)
Beispiel #17
0
def random_init():
    """
    Initialize the random states with system entropy.
    """
    global _pid
    if _pid != os.getpid():
        b = os.urandom(N * 4)
        for n in ('py_random_state', 'np_random_state'):
            _helperlib.rnd_seed(_helperlib.c_helpers[n], b)
        _pid = os.getpid()


# This is the same struct as rnd_state_t in _helperlib.c.
rnd_state_t = ir.LiteralStructType(
    [int32_t, ir.ArrayType(int32_t, N), int32_t, double])
rnd_state_ptr_t = ir.PointerType(rnd_state_t)


# Accessors
def get_index_ptr(builder, state_ptr):
    return cgutils.gep_inbounds(builder, state_ptr, 0, 0)


def get_array_ptr(builder, state_ptr):
    return cgutils.gep_inbounds(builder, state_ptr, 0, 1)


def get_has_gauss_ptr(builder, state_ptr):
    return cgutils.gep_inbounds(builder, state_ptr, 0, 2)
Beispiel #18
0
def array(ast, builder, symbols):

    if ast[c.array][c.value] == None:

        symbol_table = {}

        if '#array' in symbols:
            symbol_table['vetor'] = symbols['#array']

        else:

            array_example = [
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
            ]
            #print(array_example)
            array_type = ir.ArrayType(
                i32, len(array_example)
            )  #According to documentation, the second argument has to be an Python Integer. It can't be ir.Constant(i32, 3) for example.
            arr = ir.Constant(array_type, array_example)
            ptr = builder.alloca(array_type)  #allocate memory
            builder.store(arr, ptr)

            symbols['#array'] = ptr
            symbol_table['vetor'] = ptr

        i32_100 = ir.Constant(i32, 100)
        i32_0 = ir.Constant(i32, 0)
        i32_1 = ir.Constant(i32, 1)

        array_prime = [
            2, 3, 5, 7, 11, 13, 17, 19, 23, 31, 37, 41, 43, 47, 53, 59, 61, 67,
            71, 73, 79, 83, 97, 101, 103, 107, 109, 113, 127, 131, 137, 139,
            149, 151, 157, 163, 167, 173, 179, 181, 191, 193, 197, 199, 211,
            223, 227, 229, 233, 239, 241, 251, 257, 263, 269, 271, 277, 281,
            283, 293, 307, 311, 313, 317, 331, 337, 347, 349, 353, 359, 367,
            373, 379, 383, 389, 397, 401, 409, 419, 421, 431, 433, 439, 443,
            449, 457, 461, 463, 467, 479, 487, 491, 499, 503, 509, 521, 523,
            523, 541, 547
        ]

        array_type = ir.ArrayType(i32, 100)
        arr = ir.Constant(array_type, array_prime)
        ptr = builder.alloca(array_type)
        builder.store(arr, ptr)

        symbol_table["#array_prime"] = ptr

        value_array = builder.alloca(i32)
        builder.store(i32_1, value_array)

        symbol_table["value_array"] = value_array

        for_body_block = builder.append_basic_block("for_body_externo")
        for_after_block = builder.append_basic_block("for_after_externo")

        for_body_block_interno = builder.append_basic_block("for_body")
        for_after_block_interno = builder.append_basic_block("for_after")

        #iniciando o for(int i = 0; ...)

        i_ptr = builder.alloca(i32)
        i_value = ir.Constant(i32, 0)
        builder.store(i_value, i_ptr)

        symbol_table["i"] = i_ptr

        #Fazendo i< 28; Quando i =0

        current_i_value = builder.load(symbol_table["i"])

        cond_head = builder.icmp_signed('<',
                                        current_i_value,
                                        i32_100,
                                        name="lt")

        builder.cbranch(cond_head, for_body_block, for_after_block)
        builder.position_at_start(for_body_block)

        current_i_value = builder.load(symbol_table["i"])
        array_i_ponter = builder.gep(symbol_table["vetor"],
                                     [i32_0, current_i_value])
        max_j_value = builder.load(array_i_ponter)

        #operação do for

        # Aqui dentro tem q fazer o segundo for

        #iniciando o for(int i = 0; ...)

        j_ptr = builder.alloca(i32)
        j_value = ir.Constant(i32, 0)
        builder.store(j_value, j_ptr)

        symbol_table["j"] = j_ptr

        #Fazendo i< 28; Quando i =0

        current_j_value = builder.load(symbol_table["j"])

        cond_head_interno = builder.icmp_signed('<',
                                                current_j_value,
                                                max_j_value,
                                                name="lt")

        builder.cbranch(cond_head_interno, for_body_block_interno,
                        for_after_block_interno)
        builder.position_at_start(for_body_block_interno)

        value_atual = builder.load(symbol_table["value_array"])
        value_primo_pointer = builder.gep(symbol_table["#array_prime"],
                                          [i32_0, current_i_value])
        value_primo_prod = builder.load(value_primo_pointer)

        value_prod = builder.mul(value_atual, value_primo_prod, name="mul")
        builder.store(value_prod, symbol_table["value_array"])

        #Fim do for interno

        current_j_value = builder.load(symbol_table["j"])
        new_j_value = builder.add(current_j_value, i32_1, name="add")
        builder.store(new_j_value, symbol_table["j"])

        cond_body_interno = builder.icmp_signed('<',
                                                new_j_value,
                                                max_j_value,
                                                name="lt")
        builder.cbranch(cond_body_interno, for_body_block_interno,
                        for_after_block_interno)

        builder.position_at_start(for_after_block_interno)

        # Inicio da incremento no valor de i, for_externo

        new_i_value = builder.add(current_i_value, i32_1, name="add")
        builder.store(new_i_value, symbol_table["i"])
        cond_body = builder.icmp_signed('<', new_i_value, i32_100, name="lt")
        builder.cbranch(cond_body, for_body_block, for_after_block)

        builder.position_at_start(for_after_block)

        #Load do valor final e atribuição a variavel q chamou ele

        var_recebe = symbols[ast[c.var]]
        value_stored = builder.load(symbol_table["value_array"])
        builder.store(value_stored, var_recebe)

    elif ast[c.array][c.value] in symbols:

        var_name = symbols[ast[c.array][c.value]]

        if '#array' in symbols:

            ptr = symbols['#array']

            int_0 = ir.Constant(i32, 0)
            value = builder.load(var_name)

            # index out of range criar

            address = builder.gep(ptr, [int_0, value])
            valor_stored = builder.load(address)
            var_recebe = symbols[ast[c.var]]
            builder.store(valor_stored, var_recebe)
        else:
            array_example = array_example = [
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
            ]
            #print(array_example)
            array_type = ir.ArrayType(
                i32, len(array_example)
            )  #According to documentation, the second argument has to be an Python Integer. It can't be ir.Constant(i32, 3) for example.
            arr = ir.Constant(array_type, array_example)
            ptr = builder.alloca(array_type)  #allocate memory
            builder.store(arr, ptr)

            symbols['#array'] = ptr
            #print(symbols)
            int_0 = ir.Constant(i32, 0)
            value = builder.load(var_name)

            # index out of range criar

            address = builder.gep(ptr, [int_0, value])
            valor_stored = builder.load(address)

            var_recebe = symbols[ast[c.var]]

            builder.store(valor_stored, var_recebe)

    else:

        value_int = ast[c.array][c.value]

        # index out of range criar

        if '#array' in symbols:
            ptr = symbols['#array']

            int_0 = ir.Constant(i32, 0)
            value = ir.Constant(i32, value_int)
            address = builder.gep(ptr, [int_0, value])
            var_name = symbols[ast[c.var]]
            valor_stored = builder.load(address)
            builder.store(valor_stored, var_name)
        else:
            array_example = [
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
                0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
            ]

            #array_example = [3,5,8]
            array_type = ir.ArrayType(
                i32, len(array_example)
            )  #According to documentation, the second argument has to be an Python Integer. It can't be ir.Constant(i32, 3) for example.
            arr = ir.Constant(array_type, array_example)
            ptr = builder.alloca(array_type)  #allocate memory
            builder.store(arr, ptr)
            symbols['#array'] = ptr

            int_0 = ir.Constant(i32, 0)
            value = value = ir.Constant(i32, value_int)
            address = builder.gep(ptr, [int_0, value])
            valor_stored = builder.load(address)
            var_name = symbols[ast[c.var]]

            builder.store(valor_stored, var_name)
Beispiel #19
0
 def stringz(string):
     n = (len(string) + 1)
     buf = bytearray((' ' * n).encode('ascii'))
     buf[-1] = 0
     buf[:-1] = string.encode('utf-8')
     return ir.Constant(ir.ArrayType(ir.IntType(8), n), buf)
Beispiel #20
0
def make_bytearray(buf):
    b = bytearray(buf)
    n = len(b)
    return ir.Constant(ir.ArrayType(char_ty, n), b)
Beispiel #21
0
 def array(element, count):
     return ir.ArrayType(element, count)
Beispiel #22
0
 def get_data_type(self):
     return ir.ArrayType(self._pointee_be_type, self._fe_type.count)
Beispiel #23
0
def _setup_mt_rand_integer(ctx, state_ty):
    int64_ty = ir.IntType(64)
    # Generate random number generator function. It produces random 32bit numberin a 64bit word
    gen_ty = ir.FunctionType(ir.VoidType(), (state_ty.as_pointer(), int64_ty.as_pointer()))
    gen_int = ir.Function(ctx.module, gen_ty, name="__pnl_builtin_mt_rand_int32")
    gen_int.attributes.add('argmemonly')
    gen_int.attributes.add('alwaysinline')

    block = gen_int.append_basic_block(name="entry")
    builder = ir.IRBuilder(block)
    builder.debug_metadata = LLVMBuilderContext.get_debug_location(gen_int, None)
    state, out = gen_int.args

    # Add function arg attributes
    for a in state, out:
        a.attributes.add('nonnull')
        a.attributes.add('noalias')

    array = builder.gep(state, [ctx.int32_ty(0), ctx.int32_ty(0)])
    pidx = builder.gep(state, [ctx.int32_ty(0), ctx.int32_ty(1)])
    idx = builder.load(pidx)

    cond = builder.icmp_signed(">=", idx, ctx.int32_ty(_MERSENNE_N))
    with builder.if_then(cond, likely=False):
        mag01 = ir.ArrayType(array.type.pointee.element, 2)([0, 0x9908b0df])
        pmag01 = builder.alloca(mag01.type)
        builder.store(mag01, pmag01)

        with helpers.for_loop_zero_inc(builder,
                                       ctx.int32_ty(_MERSENNE_N - _MERSENNE_M),
                                       "first_half") as (b, kk):
            pkk = b.gep(array, [ctx.int32_ty(0), kk])
            pkk_1 = b.gep(array, [ctx.int32_ty(0), b.add(kk, ctx.int32_ty(1))])

            val_kk = b.and_(b.load(pkk), pkk.type.pointee(0x80000000))
            val_kk_1 = b.and_(b.load(pkk_1), pkk_1.type.pointee(0x7fffffff))
            val = b.or_(val_kk, val_kk_1)

            val_1 = b.and_(val, val.type(1))
            pval_mag = b.gep(pmag01, [ctx.int32_ty(0), val_1])
            val_mag = b.load(pval_mag)

            val_shift = b.lshr(val, val.type(1))

            kk_m = b.add(kk, ctx.int32_ty(_MERSENNE_M))
            pval_kk_m = b.gep(array, [ctx.int32_ty(0), kk_m])
            val_kk_m = b.load(pval_kk_m)

            val = b.xor(val_kk_m, val_shift)
            val = b.xor(val, val_mag)

            b.store(val, pkk)

        with helpers.for_loop(builder,
                              ctx.int32_ty(_MERSENNE_N - _MERSENNE_M),
                              ctx.int32_ty(_MERSENNE_N),
                              ctx.int32_ty(1), "second_half") as (b, kk):
            pkk = b.gep(array, [ctx.int32_ty(0), kk])
            is_last = b.icmp_unsigned( "==", kk, ctx.int32_ty(_MERSENNE_N - 1))
            idx_1 = b.select(is_last, ctx.int32_ty(0), b.add(kk, ctx.int32_ty(1)))
            pkk_1 = b.gep(array, [ctx.int32_ty(0), idx_1])

            val_kk = b.and_(b.load(pkk), pkk.type.pointee(0x80000000))
            val_kk_1 = b.and_(b.load(pkk_1), pkk.type.pointee(0x7fffffff))
            val = b.or_(val_kk, val_kk_1)

            val_1 = b.and_(val, val.type(1))
            pval_mag = b.gep(pmag01, [ctx.int32_ty(0), val_1])
            val_mag = b.load(pval_mag)

            val_shift = b.lshr(val, val.type(1))

            kk_m = b.add(kk, ctx.int32_ty(_MERSENNE_M - _MERSENNE_N))
            pval_kk_m = b.gep(array, [ctx.int32_ty(0), kk_m])
            val_kk_m = b.load(pval_kk_m)

            val = b.xor(val_kk_m, val_shift)
            val = b.xor(val, val_mag)

            b.store(val, pkk)

        builder.store(pidx.type.pointee(0), pidx)

    # Get pointer and update index
    idx = builder.load(pidx)
    pval = builder.gep(array, [ctx.int32_ty(0), idx])
    idx = builder.add(idx, idx.type(1))
    builder.store(idx, pidx)

    # Load and temper
    val = builder.load(pval)
    tmp = builder.lshr(val, val.type(11))
    val = builder.xor(val, tmp)

    tmp = builder.shl(val, val.type(7))
    tmp = builder.and_(tmp, tmp.type(0x9d2c5680))
    val = builder.xor(val, tmp)

    tmp = builder.shl(val, val.type(15))
    tmp = builder.and_(tmp, tmp.type(0xefc60000))
    val = builder.xor(val, tmp)

    tmp = builder.lshr(val, val.type(18))
    val = builder.xor(val, tmp)

    # val is now random 32bit integer
    val = builder.zext(val, out.type.pointee)
    builder.store(val, out)
    builder.ret_void()
    return gen_int
Beispiel #24
0
 def get_data_type(self):
     elem_type = self._elem_model.get_data_type()
     return ir.ArrayType(elem_type, self._count)
Beispiel #25
0
def const_int(x):
    return ir.Constant(int32_t, x)


double = ir.DoubleType()

N = 624
N_const = ir.Constant(int32_t, N)

# This is the same struct as rnd_state_t in _random.c.
rnd_state_t = ir.LiteralStructType([
    # index
    int32_t,
    # mt[N]
    ir.ArrayType(int32_t, N),
    # has_gauss
    int32_t,
    # gauss
    double,
    # is_initialized
    int32_t,
])
rnd_state_ptr_t = ir.PointerType(rnd_state_t)


def get_state_ptr(context, builder, name):
    """
    Get a pointer to the given thread-local random state
    (depending on *name*: "py" or "np").
    If the state isn't initialized, it is lazily initialized with
# 	return array;

# generate the IR code
######################################
# the initial part: define module, function, basic block, etc

i32 = ir.IntType(32)  #integer with 32 bits
i32_0 = ir.Constant(i32, 0)
i32_1 = ir.Constant(i32, 1)
i32_3 = ir.Constant(i32, 3)

#make a module
module = ir.Module(name="array_example")

# define function parameters for function "main"
return_type = ir.ArrayType(
    i32, 3)  #the return type is an array with 3 32-bit integers

argument_types = list()  #can add ir.IntType(#), ir.FloatType() for arguments
func_name = "main"

#make a function
fnty = ir.FunctionType(return_type, argument_types)
main_func = ir.Function(module, fnty, name=func_name)

# append basic block named 'entry', and make builder
# blocks generally have 1 entry and exit point, with no branches within the block
block = main_func.append_basic_block('entry')
builder = ir.IRBuilder(block)

########################################
#array = [3,5,8]
Beispiel #27
0
 def get_data_type(self):
     ret = ir.ArrayType(self._be_type, self._fe_type.nitems)
     return ret
    def gen_composition_exec(self, composition, simulation=False):
        with self._gen_composition_exec_context(
                composition, simulation) as (builder, data, params, cond_gen):
            state, _, comp_in, _, cond = builder.function.args
            # Call input CIM
            input_cim_w = composition._get_node_wrapper(composition.input_CIM)
            input_cim_f = self.import_llvm_function(input_cim_w)
            builder.call(input_cim_f, [state, params, comp_in, data, data])

            # Call parameter CIM
            param_cim_w = composition._get_node_wrapper(
                composition.parameter_CIM)
            param_cim_f = self.import_llvm_function(param_cim_w)
            builder.call(param_cim_f, [state, params, comp_in, data, data])

            if simulation is False and composition.enable_controller and \
               composition.controller_mode == BEFORE:
                assert composition.controller is not None
                controller = composition._get_node_wrapper(
                    composition.controller)
                controller_f = self.import_llvm_function(controller)
                builder.call(controller_f,
                             [state, params, comp_in, data, data])

            # Allocate run set structure
            run_set_type = ir.ArrayType(ir.IntType(1), len(composition.nodes))
            run_set_ptr = builder.alloca(run_set_type, name="run_set")
            builder.store(run_set_type(None), run_set_ptr)

            # Allocate temporary output storage
            output_storage = builder.alloca(data.type.pointee,
                                            name="output_storage")

            iter_ptr = builder.alloca(self.int32_ty, name="iter_counter")
            builder.store(self.int32_ty(0), iter_ptr)

            loop_condition = builder.append_basic_block(
                name="scheduling_loop_condition")
            builder.branch(loop_condition)

            # Generate a while not 'end condition' loop
            builder.position_at_end(loop_condition)
            run_cond = cond_gen.generate_sched_condition(
                builder, composition.termination_processing[TimeScale.TRIAL],
                cond, None)
            run_cond = builder.not_(run_cond, name="not_run_cond")

            loop_body = builder.append_basic_block(name="scheduling_loop_body")
            exit_block = builder.append_basic_block(name="exit")
            builder.cbranch(run_cond, loop_body, exit_block)

            # Generate loop body
            builder.position_at_end(loop_body)

            zero = self.int32_ty(0)
            any_cond = ir.IntType(1)(0)

            # Calculate execution set before running the mechanisms
            for idx, mech in enumerate(composition.nodes):
                run_set_mech_ptr = builder.gep(
                    run_set_ptr, [zero, self.int32_ty(idx)],
                    name="run_cond_ptr_" + mech.name)
                mech_cond = cond_gen.generate_sched_condition(
                    builder, composition._get_processing_condition_set(mech),
                    cond, mech)
                ran = cond_gen.generate_ran_this_pass(builder, cond, mech)
                mech_cond = builder.and_(mech_cond,
                                         builder.not_(ran),
                                         name="run_cond_" + mech.name)
                any_cond = builder.or_(any_cond,
                                       mech_cond,
                                       name="any_ran_cond")
                builder.store(mech_cond, run_set_mech_ptr)

            for idx, mech in enumerate(composition.nodes):
                run_set_mech_ptr = builder.gep(run_set_ptr,
                                               [zero, self.int32_ty(idx)])
                mech_cond = builder.load(run_set_mech_ptr,
                                         name="mech_" + mech.name +
                                         "_should_run")
                with builder.if_then(mech_cond):
                    mech_w = composition._get_node_wrapper(mech)
                    mech_f = self.import_llvm_function(mech_w)
                    builder.block.name = "invoke_" + mech_f.name
                    # Wrappers do proper indexing of all structures
                    if len(mech_f.args
                           ) == 5:  # Mechanism wrappers have 5 inputs
                        builder.call(
                            mech_f,
                            [state, params, comp_in, data, output_storage])
                    else:
                        builder.call(mech_f, [
                            state, params, comp_in, data, output_storage, cond
                        ])

                    cond_gen.generate_update_after_run(builder, cond, mech)
                builder.block.name = "post_invoke_" + mech_f.name

            # Writeback results
            for idx, mech in enumerate(composition.nodes):
                run_set_mech_ptr = builder.gep(run_set_ptr,
                                               [zero, self.int32_ty(idx)])
                mech_cond = builder.load(run_set_mech_ptr,
                                         name="mech_" + mech.name + "_ran")
                with builder.if_then(mech_cond):
                    out_ptr = builder.gep(
                        output_storage,
                        [zero, zero, self.int32_ty(idx)],
                        name="result_ptr_" + mech.name)
                    data_ptr = builder.gep(
                        data, [zero, zero, self.int32_ty(idx)],
                        name="data_result_" + mech.name)
                    builder.store(builder.load(out_ptr), data_ptr)

            # Update step counter
            with builder.if_then(any_cond):
                builder.block.name = "inc_step"
                cond_gen.bump_ts(builder, cond)

            builder.block.name = "update_iter_count"
            # Increment number of iterations
            iters = builder.load(iter_ptr, name="iterw")
            iters = builder.add(iters, self.int32_ty(1), name="iterw_inc")
            builder.store(iters, iter_ptr)

            max_iters = len(composition.scheduler.consideration_queue)
            completed_pass = builder.icmp_unsigned("==",
                                                   iters,
                                                   self.int32_ty(max_iters),
                                                   name="completed_pass")
            # Increment pass and reset time step
            with builder.if_then(completed_pass):
                builder.block.name = "inc_pass"
                builder.store(zero, iter_ptr)
                # Bumping automatically zeros lower elements
                cond_gen.bump_ts(builder, cond, (0, 1, 0))

            builder.branch(loop_condition)

            builder.position_at_end(exit_block)

            if simulation is False and composition.enable_controller and \
               composition.controller_mode == AFTER:
                assert composition.controller is not None
                controller = composition._get_node_wrapper(
                    composition.controller)
                controller_f = self.import_llvm_function(controller)
                builder.call(controller_f,
                             [state, params, comp_in, data, data])

            # Call output CIM
            output_cim_w = composition._get_node_wrapper(
                composition.output_CIM)
            output_cim_f = self.import_llvm_function(output_cim_w)
            builder.block.name = "invoke_" + output_cim_f.name
            builder.call(output_cim_f, [state, params, comp_in, data, data])

        return builder.function
Beispiel #29
0
 def __init__(self, dmm, fe_type):
     super(UnicodeCharSeq, self).__init__(dmm, fe_type)
     charty = ir.IntType(numpy_support.sizeof_unicode_char * 8)
     self._be_type = ir.ArrayType(charty, fe_type.count)
Beispiel #30
0
def gera_codigo(arvore, tabela_simbolos, sema_success):

    global modulo
    global info

    # Define as variáveis globais e funções
    for simbolo in tabela_simbolos:
        # Se o simbolo for uma variavel
        if (simbolo["simbolo_tipo"] == "variable"
                and simbolo["escopo"] == "global"):
            var_type = simbolo["tipo_valor"]

            # Verifica se o tipo é inteiro
            if (var_type == "inteiro"):
                if (len(simbolo["dimensoes"]) == 0):
                    g = ir.GlobalVariable(modulo, ir.IntType(32),
                                          simbolo["nome"])

                if (len(simbolo["dimensoes"]) == 1):
                    g_type = ir.ArrayType(ir.IntType(32),
                                          int(simbolo["dimensoes"][0]))
                    g = ir.GlobalVariable(modulo, g_type, simbolo["nome"])
                    info["variaveis_globais"].append(g)

            # Verifica se o tipo é flutuante
            elif (var_type == "flutuante"):

                if (len(simbolo["dimensoes"]) == 0):
                    g = ir.GlobalVariable(modulo, ir.FloatType(),
                                          simbolo["nome"])

                if (len(simbolo["dimensoes"]) == 1):
                    g_type = ir.ArrayType(ir.FloatType(),
                                          int(simbolo["dimensoes"][0]))
                    g = ir.GlobalVariable(modulo, g_type, simbolo["nome"])

            g.linkage = "common"
            g.align = 4
            info["variaveis_globais"].append(g)

        # Se o simbolo for uma funcao
        elif (simbolo["simbolo_tipo"] == "function"):
            if (simbolo["nome"] == "principal"):
                simbolo["nome"] = "main"

            # Lista de argumentos
            arguments_list = []

            if (len(simbolo["parametros"]) > 0):
                for a in simbolo["parametros"]:
                    if (a["par_type"] == "inteiro"):
                        arguments_list.append(ir.IntType(32))
                    else:
                        arguments_list.append(ir.FloatType())

            if (len(simbolo["return"]) > 0):
                if (simbolo["return"][0]["ret_type"] == "inteiro"):
                    f_ret = ir.IntType(32)
                else:
                    f_ret = ir.FloatType()

                f_func = ir.FunctionType(f_ret, arguments_list)
                f = ir.Function(modulo, f_func, name=simbolo["nome"])
                entryBlock = f.append_basic_block('entry')
                builder = ir.IRBuilder(entryBlock)

            else:
                f_func = ir.FunctionType(ir.VoidType(), arguments_list)
                f = ir.Function(modulo, f_func, name=simbolo["nome"])
                entryBlock = f.append_basic_block('entry')
                builder = ir.IRBuilder(entryBlock)

            for i in range(len(f.args)):
                f.args[i].name = simbolo["parametros"][i]["par_name"]

            funcoes.append({
                "function": f,
                "builder": builder,
                "arguments": f.args
            })

    # Chama a funcao recursiva que passa pela arvore
    passar_por_arvore(arvore, funcoes)

    file = open('modulo.ll', 'w')
    file.write(str(modulo))
    file.close()
    print(modulo)