Example #1
0
 def visit_Instruction(self, instr):
     if instr.type == ir.IntType(64):
         if instr.opname in ['srem', 'urem', 'sdiv', 'udiv']:
             name = 'numba_{op}'.format(op=instr.opname)
             fn = self.module.globals.get(name)
             # Declare the function if it doesn't already exist
             if fn is None:
                 opty = instr.type
                 sdivfnty = ir.FunctionType(opty, [opty, opty])
                 fn = ir.Function(self.module, sdivfnty, name=name)
             # Replace the operation with a call to the builtin
             repl = ir.CallInstr(parent=instr.parent,
                                 func=fn,
                                 args=instr.operands,
                                 name=instr.name)
             instr.parent.replace(instr, repl)
Example #2
0
 def externfuncdecl(self, name, node):
     for func in self.module.functions:
         if func.name == name:
             self.define(name, func, 1)
             return
     return_type = node.return_type
     parameters = node.parameters
     varargs = node.varargs
     ret_type = type_map[return_type.value]
     args = [type_map[param.value] for param in parameters.values()]
     func_type = ir.FunctionType(ret_type, args, varargs)
     func_type.parameters = parameters
     if hasattr(return_type, 'func_ret_type') and return_type.func_ret_type:
         func_type.return_type = func_type.return_type(type_map[return_type.func_ret_type.value], [return_type.func_ret_type.value]).as_pointer()
     func = ir.Function(self.module, func_type, name)
     self.define(name, func, 1)
Example #3
0
    def generateCode(self, breakBlock=None):
        #print "generating code for funcdecl",self.name, self.arglist

        argtypelist = []
        argnamelist = []
        for arg in self.arglist:
            try:
                argType = makeArgumentType(arg.typestr)
            except ValueError:
                print "in funcDecl", self.name
                raise
            argtypelist.append(argType)
            argnamelist.append(arg.name)

        functype = ir.FunctionType(self.rettype, argtypelist)

        foundDup = False
        for f in gLlvmModule.functions:
            if self.name == f.name:
                foundDup = True
                funcobj = f
                break

        if not foundDup:
            funcobj = ir.Function(gLlvmModule, functype, name=self.name)
            #print "made a function declaration for name:", self.name

        self.llvmNode = funcobj
        if funcobj.name != self.name:
            # something already exists
            # don't allow redef or redecl
            #funcobj.delete()
            funcobj = gLlvmModule.get_function_named(self.name)

            # if the function already has a body, this is bad.
            if not funcobj.is_declaration:
                raise RuntimeError('Redefinition of function: ' + self.name)

            # if f took a different number of args, that's bad (callee?)
            if len(funcobj.args) != len(self.arglist):
                raise RuntimeError('wrong args')

        for arg, argName in zip(funcobj.args, argnamelist):
            #print "assigning",argName,arg
            arg.name = argName
            gNamedValues[argName] = arg
        return funcobj
Example #4
0
def build_initial_ir(symbol_table: SymbolTable, context: CodegenContext):
    assert 'free' not in symbol_table
    for type_identifier, builtin_type in SLEEPY_TYPES.items():
        assert type_identifier not in symbol_table
        symbol_table[
            type_identifier] = TypeTemplateSymbol.make_concrete_type_symbol(
                builtin_type)
        if builtin_type == SLEEPY_UNIT:
            continue

        # add destructor
        destructor_signature = BuiltinOperationFunctionSignature(
            identifier='free',
            placeholder_template_types=[],
            return_type=SLEEPY_UNIT,
            arg_identifiers=['var'],
            arg_types=[builtin_type],
            arg_type_narrowings=[SLEEPY_NEVER],
            instruction=lambda builder, value: SLEEPY_UNIT.unit_constant())
        symbol_table.add_overload('free', destructor_signature)

    if context.emits_ir:
        context.ir_func_malloc = ir.Function(context.module,
                                             ir.FunctionType(
                                                 LLVM_VOID_POINTER_TYPE,
                                                 [LLVM_SIZE_TYPE]),
                                             name='malloc')

    # TODO: currently, some builtin free() functions are not inlined.
    # This means that we need to add debug information to these functions, but they do not have any line numbers.
    # We use this dummy here.
    builtin_pos = TreePosition('', 0, 0)

    builtin_symbols = {
        'Str': _make_str_symbol,
        'Ptr': _make_ptr_symbol,
        'RawPtr': _make_raw_ptr_symbol,
        'Ref': _make_ref_symbol,
        'bitcast': _make_bitcast_symbol
    }
    with context.use_pos(builtin_pos):
        for symbol_identifier, setup_func in builtin_symbols.items():
            assert symbol_identifier not in symbol_table
            symbol = setup_func(symbol_table=symbol_table, context=context)
            symbol_table[symbol_identifier] = symbol

        _make_builtin_operator_functions(symbol_table)
Example #5
0
def test_helper_is_close(mode):

    with pnlvm.LLVMBuilderContext() as ctx:
        double_ptr_ty = ctx.float_ty.as_pointer()
        func_ty = ir.FunctionType(ir.VoidType(), [double_ptr_ty, double_ptr_ty,
                                                  double_ptr_ty, ctx.int32_ty])

        # Create clamp function
        custom_name = ctx.get_unique_name("all_close")
        function = ir.Function(ctx.module, func_ty, name=custom_name)
        in1, in2, out, count = function.args
        block = function.append_basic_block(name="entry")
        builder = ir.IRBuilder(block)

        index = None
        with pnlvm.helpers.for_loop_zero_inc(builder, count, "compare") as (b1, index):
            val1_ptr = b1.gep(in1, [index])
            val2_ptr = b1.gep(in2, [index])
            val1 = b1.load(val1_ptr)
            val2 = b1.load(val2_ptr)
            close = pnlvm.helpers.is_close(b1, val1, val2)
            out_ptr = b1.gep(out, [index])
            out_val = b1.select(close, ctx.float_ty(1), ctx.float_ty(0))
            b1.store(out_val, out_ptr)

        builder.ret_void()
        
    vec1 = copy.deepcopy(vector)
    tmp = np.random.rand(DIM_X)
    tmp[0::2] = vec1[0::2]
    vec2 = np.asfarray(tmp)
    assert len(vec1) == len(vec2)
    res = np.empty_like(vec2)

    ref = np.isclose(vec1, vec2)
    bin_f = pnlvm.LLVMBinaryFunction.get(custom_name)
    if mode == 'CPU':
        ct_ty = pnlvm._convert_llvm_ir_to_ctype(double_ptr_ty)
        ct_vec1 = vec1.ctypes.data_as(ct_ty)
        ct_vec2 = vec2.ctypes.data_as(ct_ty)
        ct_res = res.ctypes.data_as(ct_ty)

        bin_f(ct_vec1, ct_vec2, ct_res, DIM_X)
    else:
        bin_f.cuda_wrap_call(vec1, vec2, res, np.int32(DIM_X))

    assert np.array_equal(res, ref)
Example #6
0
    def _codegenPrototypeAST(self, node):
        funcName = node.name
        # Create a function type
        funcType = ir.FunctionType(ir.DoubleType(),
                                   [ir.DoubleType()] * len(node.argNames))

        # If a function with this name already exists in the module...
        if funcName in self.module.globals:
            # We do not allow redeclaration yet. Potentially worth changing later...
            raise CodegenError('Function/Global name collision', funcName)
        else:
            func = ir.Function(self.module, funcType, funcName)
        # Set function argument names from AST
        for i, arg in enumerate(func.args):
            arg.name = node.argNames[i]
            self.functionSymbolTable[arg.name] = arg
        return func
Example #7
0
def gen_anonymous_function(ast, nst, ctx):
    params, _, body = ast
    fname = ast.fname
    nst.enterScope(fname)
    ftype = llvm_fun_type(ast.type, nst, ctx)
    print(ftype)
    func = ir.Function(ctx['mod'], ftype, name=fname)
    entry = func.append_basic_block('entry')
    for arg, name in zip(func.args, params.names):
        arg.name = name
        nst.currentScope[name].llvm_info = arg
    builder = ir.IRBuilder(entry)
    new_ctx = {'builder': builder, **ctx}
    codegen(params, nst, new_ctx)
    codegen(body, nst, new_ctx)
    nst.exitScope()
    return func
Example #8
0
    def declare_functions(self, node):
        for fn_symbol in self.context.symbols:
            if isinstance(fn_symbol, FunctionSymbol):

                parameters = []

                for var_symbol in self.context.symbols:
                    if isinstance(
                            var_symbol, VarSymbol
                    ) and var_symbol.scope == fn_symbol.name and var_symbol.parameter:
                        parameters.append(
                            self.type_to_llvmlite_type(var_symbol.type_,
                                                       var_symbol.index_list))

                type_ = self.type_to_llvmlite_type(fn_symbol.type_, [])
                t_func = ir.FunctionType(type_, parameters)
                func = ir.Function(self.module, t_func, name=fn_symbol.name)
    def register_readln(self):
        read_type = ir.FunctionType(ir.VoidType(), (ir.IntType(32),))
        c_read_type = CFUNCTYPE(c_void_p, c_int32)
        c_read = c_read_type(wirte)
        read_address = cast(c_read, c_void_p).value

        read_func_type = ir.FunctionType(ir.VoidType(), (ir.IntType(32),))
        read_func = ir.Function(self.module, read_func_type, 'readln')
        builder = ir.IRBuilder(read_func.append_basic_block('entry'))
        read_f = builder.inttoptr(ir.Constant(ir.IntType(64), read_address),
                                  read_func_type.as_pointer(), name='read_f')
        arg = read_func.args[0]
        arg.name = 'arg0'
        call = builder.call(read_f, [arg])
        builder.ret_void()

        self.GenTable.add_function(func_name='readln', func_block=read_func, scope_id=self.scope_id)
Example #10
0
    def import_llvm_function(self, fun, *,
                             tags: frozenset = frozenset()) -> ir.Function:
        """
        Get function handle if function exists in current modele.
        Create function declaration if it exists in a older module.
        """
        if isinstance(fun, str):
            f = _find_llvm_function(fun, _all_modules | {self.module})
        else:
            f = self.gen_llvm_function(fun, tags=tags)

        # Add declaration to the current module
        if f.name not in self.module.globals:
            decl_f = ir.Function(self.module, f.type.pointee, f.name)
            assert decl_f.is_declaration
            return decl_f
        return f
Example #11
0
    def _headers(self):

        int8 = ir.IntType(8).as_pointer()

        fmt = "%i\n\0"
        c_fmt = ir.Constant(ir.ArrayType(ir.IntType(8), len(fmt)),
                            bytearray(fmt.encode("utf8")))
        global_fmt = ir.GlobalVariable(self.module, c_fmt.type, name="fstr")
        global_fmt.linkage = 'internal'
        global_fmt.global_constant = True
        global_fmt.initializer = c_fmt

        ty = ir.FunctionType(ir.IntType(32), [int8], var_arg=True)
        printf = ir.Function(self.module, ty, name="printf")

        self.env["ftm"] = global_fmt
        self.env["printf"] = printf
Example #12
0
    def visitCompilationUnit(self, ctx: SoLangParser.CompilationUnitContext):
        # global function table
        # functions[function-name] = function-pointer
        self.functions = {}
        # global variable table
        # variables[function-name][variable-name] = variable-pointer
        self.variables = {}
        self.current_function = ''

        # llvm init
        llvm.initialize()
        llvm.initialize_native_target()
        llvm.initialize_native_asmprinter()

        # set target
        target = llvm.Target.from_default_triple()

        # define types
        self.i64 = ir.IntType(64)
        self.f64 = ir.FloatType()

        self.module = ir.Module(name='sokoide_module')
        self.module.triple = target.triple
        # function prototype (external linkage implemented in builtin.c) for
        # void write(int64_t)
        ftype_write = ir.FunctionType(ir.VoidType(), [self.i64])
        self.fn_write = ir.Function(self.module, ftype_write, name='write')

        self.visitChildren(ctx)

        # generate code
        llvm_ir = str(self.module)
        llvm_ir_parsed = llvm.parse_assembly(llvm_ir)

        # optimizer
        if self.optimize:
            pmb = llvm.create_pass_manager_builder()
            pmb.opt_level = 1
            pm = llvm.create_module_pass_manager()
            pmb.populate(pm)
            pm.run(llvm_ir_parsed)

        with open('build/out.ll', 'w') as f:
            f.write(str(llvm_ir_parsed))

        return None
Example #13
0
def dynamic_array_length(self, dyn_array_ptr, array_type):
    # START
    dyn_array_length_type = ir.FunctionType(type_map[INT], [dyn_array_ptr])
    dyn_array_length = ir.Function(self.module, dyn_array_length_type,
                                   '{}_array_length'.format(array_type))
    dyn_array_length_entry = dyn_array_length.append_basic_block('entry')
    builder = ir.IRBuilder(dyn_array_length_entry)
    self.builder = builder
    builder.position_at_end(dyn_array_length_entry)
    array_ptr = builder.alloca(dyn_array_ptr)
    builder.store(dyn_array_length.args[0], array_ptr)

    size_ptr = builder.gep(builder.load(array_ptr), [zero_32, zero_32],
                           inbounds=True)

    # CLOSE
    builder.ret(builder.load(size_ptr))
Example #14
0
def test_fixed_dimensions__pnl_builtin_vxm(mode):
    # The original builtin mxv function
    binf = pnlvm.LLVMBinaryFunction.get("__pnl_builtin_vxm")
    orig_res = np.empty_like(llvm_res)
    if mode == 'CPU':
        ct_in_ty, ct_mat_ty, _, _, ct_res_ty = binf.byref_arg_types

        ct_vec = vector.ctypes.data_as(ctypes.POINTER(ct_in_ty))
        ct_mat = matrix.ctypes.data_as(ctypes.POINTER(ct_mat_ty))
        ct_res = orig_res.ctypes.data_as(ctypes.POINTER(ct_res_ty))

        binf.c_func(ct_vec, ct_mat, x, y, ct_res)
    else:
        binf.cuda_wrap_call(vector, matrix, np.int32(x), np.int32(y), orig_res)

    custom_name = None

    with pnlvm.LLVMBuilderContext() as ctx:
        custom_name = ctx.get_unique_name("vxsqm")
        double_ptr_ty = ctx.convert_python_struct_to_llvm_ir(1.0).as_pointer()
        func_ty = ir.FunctionType(
            ir.VoidType(), (double_ptr_ty, double_ptr_ty, double_ptr_ty))

        # get builtin IR
        builtin = ctx.import_llvm_function("__pnl_builtin_vxm")

        # Create square vector matrix multiply
        function = ir.Function(ctx.module, func_ty, name=custom_name)
        _x = ctx.int32_ty(x)
        _v, _m, _o = function.args
        block = function.append_basic_block(name="entry")
        builder = ir.IRBuilder(block)
        builder.call(builtin, [_v, _m, _x, _x, _o])
        builder.ret_void()

    binf2 = pnlvm.LLVMBinaryFunction.get(custom_name)
    new_res = np.empty_like(llvm_res)

    if mode == 'CPU':
        ct_res = new_res.ctypes.data_as(ctypes.POINTER(ct_res_ty))

        binf2(ct_vec, ct_mat, ct_res)
    else:
        binf2.cuda_wrap_call(vector, matrix, new_res)

    assert np.array_equal(orig_res, new_res)
Example #15
0
    def visit_JapycFunction(self, node):
        # hard coded return value, hardcoded 64 bit integers
        function_type = ir.FunctionType(ir.VoidType(),
                                        [ir.IntType(64) for _ in node.args])
        fn = ir.Function(self.module, function_type, name=node.name)
        block = fn.append_basic_block(name='entry')
        self.functions[node.name] = fn
        self.builder = ir.IRBuilder(block)
        # lookup table for function arguments
        self.function_arguments = {
            ast_arg.name: llvm_arg
            for ast_arg, llvm_arg in zip(node.args, fn.args)
        }

        self._recurse(node.body)

        self.builder.ret_void()
Example #16
0
    def llvm_declaracao_funcao(self, modulo, filho, nome, tipo_de_retorno):
        if nome == "principal":
            nome = "main"
        if tipo_de_retorno == "inteiro":
            tipo_de_retorno = ir.IntType(32)
        elif tipo_de_retorno == "flutuante":
            tipo_de_retorno = ir.FloatType()

        tipo_da_funcao = ir.FunctionType(tipo_de_retorno, [])
        funcao = ir.Function(modulo, tipo_da_funcao, name=nome)
        self.lista_ponteiros_funcoes.append(funcao)
        bloco_de_entrada = funcao.append_basic_block('%s.start' % nome)
        self.builder = ir.IRBuilder(bloco_de_entrada)
        retorna = self.builder.alloca(tipo_de_retorno, name='return')
        self.lista_ponteiros_variaveis.append(retorna)
        corpo = filho.child[1].child[1]
        self.resolve_corpo(corpo, modulo, self.builder)
Example #17
0
def make_lookup(name,ary):
   #build tables
   func = ir.Function(module, lfnty, name=name)
   func.attributes.personality = pers
   func.attributes.add("alwaysinline")
   func.attributes.add("uwtable")
   block = func.append_basic_block(name="entry")
   builder = ir.IRBuilder(block)

   g,v = emph.CreateMinimalPerfectHash({ary[i]:i for i in range(len(ary))})
   l = len(g)
   g = builder.bitcast(get_int_array(g),ir.ArrayType(int32,0).as_pointer())
   v = builder.bitcast(get_int_array(v),ir.ArrayType(int32,0).as_pointer())
   strs = builder.bitcast(get_constant(ary),make_tuple_type(0)[1])
   
   builder.ret(builder.call(local_lookup,(func.args[0],strs,g,v,int32(l))))
   return func
Example #18
0
def declaracao_funcao_main(modulo,
                           name,
                           funcao_soma,
                           tipo_retorno_funcao=ir.VoidType()):
    # Declarando função
    tipo_funcao = ir.FunctionType(tipo_retorno_funcao, [])
    funcao_declarada = ir.Function(modulo, tipo_funcao, name=name)

    bloco_inicio = funcao_declarada.append_basic_block('%s.start' % name)
    bloco_fim = funcao_declarada.append_basic_block('%s.end' % name)

    builder = ir.IRBuilder(bloco_inicio)

    # Entrando na função funcao_declarada
    with builder.goto_entry_block():
        # inteiro: a, b
        a = declara_local_var(builder, ir.IntType(32), 'a')
        b = declara_local_var(builder, ir.IntType(32), 'b')

        # leia(a)
        leia = declara_funcao_externa(modulo, 'scanf')
        args = [declara_string_global(modulo, '%d\0'), a]
        chama_funcao(builder, leia, args)

        # leia(b)
        leia = declara_funcao_externa(modulo, 'scanf')
        args = [declara_string_global(modulo, '%d\0'), b]
        chama_funcao(builder, leia, args)

        # escreva(soma(a,b))
        args = [builder.load(a), builder.load(b)]
        res = chama_funcao(builder, funcao_soma, args)

        escreva = declara_funcao_externa(modulo, 'printf')
        args = [declara_string_global(modulo, '%d\n\0'), res]
        chama_funcao(builder, escreva, args)

        # Vai para o final da função
        builder.branch(bloco_fim)

    # Finaliza a função funcao_declarada
    with builder.goto_block(bloco_fim):
        builder.ret_void()

    return funcao_declarada
Example #19
0
    def function_decl(self, node):
        name, paralist, ret = self.function_head(node.children[0])
        namelist = []
        ir_type_list = []
        for t in paralist:
            if t[0][0] == "var":
                for i in range(1, len(t[0])):
                    ir_type_list.append(t[1].as_pointer())
                    namelist.append(("var", t[0][i]))
            else:
                for i in range(1, len(t[0])):
                    ir_type_list.append(t[1])
                    namelist.append(("val", t[0][i]))

        ret_ir_type = type_t[
            node.children[0].children[-1].children[0].name.upper()]

        func_type = ir.FunctionType(ret_ir_type, ir_type_list)
        func = ir.Function(self.module, func_type, name=name)
        self.symbol_table.insert([name, func])
        self.symbol_table.create_tab()

        stored_builder = self.builder
        block = func.append_basic_block(name=name)
        self.builder = ir.IRBuilder(block)

        retaddr = self.builder.alloca(ret_ir_type)
        self.symbol_table.insert([name + "_return", retaddr])

        func_args = func.args
        for i in range(len(func_args)):
            if namelist[i][0] == "val":
                addr = self.builder.alloca(ir_type_list[i])
                self.builder.store(func_args[i], addr)
                self.symbol_table.insert([namelist[i][1], addr])
            if namelist[i][0] == "var":
                addr = func_args[i]
                self.symbol_table.insert([namelist[i][1], addr])

        self.subroutine(node.children[2])
        retval = self.builder.load(retaddr)
        self.builder.ret(retval)

        self.builder = stored_builder
        self.symbol_table.pop()
Example #20
0
def define_print(self, dyn_array_ptr):
    # START
    func_type = ir.FunctionType(type_map[VOID], [dyn_array_ptr])
    func = ir.Function(self.module, func_type, 'print')
    entry_block = func.append_basic_block('entry')
    builder = ir.IRBuilder(entry_block)
    self.builder = builder
    builder.position_at_end(entry_block)
    zero_length_check_block = func.append_basic_block('zero_length_check')
    non_zero_length_block = func.append_basic_block('non_zero_length')
    cond_block = func.append_basic_block('check_if_done')
    body_block = func.append_basic_block('print_it')
    exit_block = func.append_basic_block('exit')
    array_ptr = builder.alloca(dyn_array_ptr)
    builder.store(func.args[0], array_ptr)

    # BODY
    builder.position_at_end(entry_block)
    length = builder.call(self.module.get_global('i64.array.longitud'), [builder.load(array_ptr)])
    builder.branch(zero_length_check_block)

    builder.position_at_end(zero_length_check_block)
    cond = builder.icmp_signed(LESS_THAN_OR_EQUAL_TO, zero, length)
    builder.cbranch(cond, non_zero_length_block, exit_block)

    builder.position_at_end(non_zero_length_block)
    position_ptr = builder.alloca(type_map[INT])
    builder.store(zero, position_ptr)
    builder.branch(cond_block)

    builder.position_at_end(cond_block)
    cond = builder.icmp_signed(LESS_THAN, builder.load(position_ptr), length)
    builder.cbranch(cond, body_block, exit_block)

    builder.position_at_end(body_block)
    char = builder.call(self.module.get_global('i64.array.ver'), [builder.load(array_ptr), builder.load(position_ptr)])
    builder.call(self.module.get_global('putchar'), [char])
    add_one = builder.add(one, builder.load(position_ptr))
    builder.store(add_one, position_ptr)
    builder.branch(cond_block)

    # CLOSE
    builder.position_at_end(exit_block)
    builder.call(self.module.get_global('putchar'), [ten])
    builder.ret_void()
Example #21
0
    def define_variaveis_auxiliares(self):
        self.valores = {}
        self.valoresExpressoes = {}
        self.valoresLeia = {}
        self.valoresRetorno = {}
        self.valoresRepita = {}
        self.valoresStore = {}
        self.escopoVar = []
        self.builder = None
        self.escopo = "global"
        self.escopoRepita = None
        self.funcao = None
        self.var = None

        #self.leiaFlutuante = ir.Function(self.modulo, ir.FunctionType(ir.FloatType(), []), 'leiaFlutuante')
        self.leiaInteiro = ir.Function(self.modulo,
                                       ir.FunctionType(ir.IntType(32), []),
                                       'leiaInteiro')
Example #22
0
def fix_powi_calls(mod):
    """Replace llvm.powi.f64 intrinsic because we don't have compiler-rt.
    """
    orig = mod.globals.get('llvm.powi.f64')
    if orig is not None:
        # Build a wrapper function for powi() to re-direct the intrinsic call
        # to pow().
        powinstr = mod.declare_intrinsic('llvm.pow', [ir.DoubleType()])
        repl = ir.Function(mod, orig.function_type, name=".numba.powi_fix")
        repl.linkage = 'internal'
        builder = ir.IRBuilder(repl.append_basic_block())
        base, power = repl.args
        power = builder.sitofp(power, ir.DoubleType())
        call = builder.call(powinstr, [base, power])
        builder.ret(call)

        # Replace all calls in the module
        ir.replace_all_calls(mod, orig, repl)
Example #23
0
    def code_gen(self, module, bb=None):
        ret_type = get_llvm_prm_type(self.type)

        args_type = [get_llvm_prm_type(arg.type) for arg in self.args]
        ty_func = ir.FunctionType(ret_type, args_type)
        func = ir.Function(module, ty_func, self.name)

        self.func = func

        for i in range(len(self.args)):
            func.args[i].name = self.args[i].name
            self.args[i].ptr = func.args[i]

        bb = func.append_basic_block("entry")
        builder = ir.IRBuilder(bb)

        for op in self.order_operations:
            op.code_gen(func, builder)
Example #24
0
 def walk_ast(self, scope, builder):
     try:
         scope.add_callable(self)
     except ScopeException:
         Exit.REDECLARED_NAME_ERROR(self.lineno, self.globid)
     self.type = self.ret_type
     if self.decls:
         self.func_type = ir.FunctionType(
             self.ir_type, [decl.ir_type for decl in self.decls],
             var_arg=self.var_arg)
     else:
         self.func_type = ir.FunctionType(self.ir_type, [],
                                          var_arg=self.var_arg)
     self.ptr = ir.Function(builder, self.func_type, name=self.globid)
     scope.add_ptr(self.globid, self.ptr)
     if self.decls:
         self.decls.walk_ast(scope.copy(), builder)
     super().walk_ast(scope.copy(), builder)
Example #25
0
    def generate(self):
        func_name = self.name
        func_ty = ir.FunctionType(self.cg.int64,
                                  [self.cg.int64] * len(self.arg_names), False)
        if func_name in self.module.globals:
            func = self.module[func_name]
            if not isinstance(func, ir.Function):
                raise CodeGenError('Function / Global name collision',
                                   func_name)
            if not func.is_declaration():
                raise CodeGenError('Redefinition of {0}', func_name)
            if len(func.function_type.args) != len(self.arg_names):
                raise CodeGenError(
                    'Redefinition with different number of arguments')
        else:
            func = ir.Function(self.module, func_ty, func_name)

        return func
    def add_function(self, mir_function):
        """Add the specified function to the current module."""
        # Add only if it doesn't exist yet.
        try:
            if mir_function not in self.functions:
                self.functions.add(mir_function)

            mir_function.module = self

            fty = mir_function._llvm_type._ptr
            name = mir_function.name

            #llvm_func_def = self._ptr.add_function(fty, name)
            llvm_func_def = ir.Function(self._ptr, fty, name)

            mir_function._llvm_definition = llvm_func_def
        except Exception, err:
            raise MiddleIrModuleException(err)
Example #27
0
def externs(extern, module, *sysArgs):
    returnType = ir_type(extern["ret_type"])

    args = list()
    if "tdecls" in extern:
        for arg in extern["tdecls"]["types"]:
            args.append(ir_type(arg))

    if extern["globid"] == "getarg":
        getArg(module, *sysArgs)

    elif extern["globid"] == "getargf":
        getArgf(module, *sysArgs)
        pass

    else:
        fnty = ir.FunctionType(returnType, args)
        func = ir.Function(module, fnty, name=extern["globid"])
Example #28
0
def get_extract_func(high, low, bigwidth):
    smallwidth = high - low + 1
    t = (smallwidth, bigwidth)

    if t not in get_extract_func.funcs:
        typ = ir.FunctionType(
            ir.IntType(smallwidth),
            [ir.IntType(64),
             ir.IntType(64),
             ir.IntType(bigwidth)])
        func = ir.Function(module, typ,
                           "smt.extract.i%d.i%d" % (bigwidth, smallwidth))
        func.attributes.add("readnone")
        func.attributes.add("norecurse")
        func.attributes.add("nounwind")
        get_extract_func.funcs[t] = func

    return get_extract_func.funcs[t]
Example #29
0
    def __init__(self):
        ''' Initialize  llvm '''
        self.binding = binding
        self.binding.initialize()
        self.binding.initialize_native_target()
        self.binding.initialize_native_asmprinter()

        # Declare module
        self.module = ir.Module()
        self.module.triple = self.binding.get_default_triple()

        # Declare main function
        func_type = ir.FunctionType(ir.VoidType(), [], False)
        base_func = ir.Function(self.module, func_type, name='main')
        block = base_func.append_basic_block()

        # Declare builder
        self.builder = ir.IRBuilder(block)
Example #30
0
 def __init__(self,nome,module,returnType,returnValue):
     self.retValue=None
     self.functionType=None
     self.functionDeclaration=None
     self.entryBlock=None
     self.endBlock=None
     self.builder=None
     self.variables={}
     if returnType=="inteiro":
         self.retValue = ir.Constant(ir.IntType(32),returnValue)
         self.functionType = ir.FunctionType(ir.IntType(32),())
     elif returnType=="flutuante":
         self.retValue = ir.Constant(ir.FloatType(),returnValue)
         self.functionType = ir.FunctionType(ir.FloatType,())
     self.functionDeclaration = ir.Function(module,self.functionType,name=nome)
     self.entryBlock = self.functionDeclaration.append_basic_block('entry')
     self.endBlock = self.functionDeclaration.append_basic_block('exit')
     self.builder = ir.IRBuilder(self.entryBlock)