Ejemplo n.º 1
0
    def __init__(self, dmm, fe_type):
        super(GeneratorModel, self).__init__(dmm, fe_type)
        # XXX Fold this in DataPacker?
        self._arg_models = [
            self._dmm.lookup(t) for t in fe_type.arg_types
            if not isinstance(t, types.Omitted)
        ]
        self._state_models = [self._dmm.lookup(t) for t in fe_type.state_types]

        self._args_be_type = ir.LiteralStructType(
            [t.get_data_type() for t in self._arg_models])
        self._state_be_type = ir.LiteralStructType(
            [t.get_data_type() for t in self._state_models])
        # The whole generator closure
        self._be_type = ir.LiteralStructType([
            self._dmm.lookup(types.int32).get_value_type(), self._args_be_type,
            self._state_be_type
        ])
        self._be_ptr_type = self._be_type.as_pointer()
Ejemplo n.º 2
0
def make_anonymous_struct(builder, values, struct_type=None):
    """
    Create an anonymous struct containing the given LLVM *values*.
    """
    if struct_type is None:
        struct_type = ir.LiteralStructType([v.type for v in values])
    struct_val = struct_type(ir.Undefined)
    for i, v in enumerate(values):
        struct_val = builder.insert_value(struct_val, v, i)
    return struct_val
Ejemplo n.º 3
0
    def test_str(self):
        """
        Test the string representation of types.
        """
        self.assertEqual(str(int1), 'i1')
        self.assertEqual(str(ir.IntType(29)), 'i29')
        self.assertEqual(str(flt), 'float')
        self.assertEqual(str(dbl), 'double')
        self.assertEqual(str(ir.VoidType()), 'void')
        self.assertEqual(str(ir.FunctionType(int1, ())), 'i1 ()')
        self.assertEqual(str(ir.FunctionType(int1, (flt, ))), 'i1 (float)')
        self.assertEqual(str(ir.FunctionType(int1, (flt, dbl))),
                         'i1 (float, double)')
        self.assertEqual(str(ir.FunctionType(int1, (), var_arg=True)),
                         'i1 (...)')
        self.assertEqual(str(ir.FunctionType(int1, (flt, ), var_arg=True)),
                         'i1 (float, ...)')
        self.assertEqual(str(ir.FunctionType(int1, (flt, dbl), var_arg=True)),
                         'i1 (float, double, ...)')
        self.assertEqual(str(ir.PointerType(int32)), 'i32*')
        self.assertEqual(str(ir.PointerType(ir.PointerType(int32))), 'i32**')
        self.assertEqual(str(ir.ArrayType(int1, 5)), '[5 x i1]')
        self.assertEqual(str(ir.ArrayType(ir.PointerType(int1), 5)),
                         '[5 x i1*]')
        self.assertEqual(str(ir.PointerType(ir.ArrayType(int1, 5))),
                         '[5 x i1]*')
        self.assertEqual(str(ir.LiteralStructType((int1, ))), '{i1}')
        self.assertEqual(str(ir.LiteralStructType((int1, flt))), '{i1, float}')
        self.assertEqual(
            str(
                ir.LiteralStructType(
                    (ir.PointerType(int1), ir.LiteralStructType(
                        (int32, int8))))), '{i1*, {i32, i8}}')

        # Avoid polluting the namespace
        context = ir.Context()
        mytype = context.get_identified_type("MyType")
        self.assertEqual(str(mytype), "%\"MyType\"")
        mytype1 = context.get_identified_type("MyType\\")
        self.assertEqual(str(mytype1), "%\"MyType\\5c\"")
        mytype2 = context.get_identified_type("MyType\"")
        self.assertEqual(str(mytype2), "%\"MyType\\22\"")
Ejemplo n.º 4
0
Archivo: ir.py Proyecto: Delaunay/Kiwi
    def union(self, union: Union, depth=0) -> Any:
        types = {}

        for i, m in enumerate(union.members):
            members = [
                ir.IntType(32),
                self.visit(m.type, depth + 1, mode='type')
            ]
            types[m.name] = (i, ir.LiteralStructType(elems=members))

        return types
Ejemplo n.º 5
0
def ptx_match_all_sync(context, builder, sig, args):
    mask, value = args
    width = sig.args[1].bitwidth
    if sig.args[1] in types.real_domain:
        value = builder.bitcast(value, ir.IntType(width))
    fname = 'llvm.nvvm.match.all.sync.i{}'.format(width)
    lmod = builder.module
    fnty = ir.FunctionType(
        ir.LiteralStructType((ir.IntType(32), ir.IntType(1))),
        (ir.IntType(32), ir.IntType(width)))
    func = cgutils.get_or_insert_function(lmod, fnty, fname)
    return builder.call(func, (mask, value))
Ejemplo n.º 6
0
    def test_abi_alignment(self):
        td = llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128")

        def check(tp, expected):
            self.assertIn(tp.get_abi_alignment(td), expected)

        check(int8, (1, 2, 4))
        check(int32, (4, ))
        check(int64, (8, ))
        check(ir.ArrayType(int8, 5), (1, 2, 4))
        check(ir.ArrayType(int32, 5), (4, ))
        check(ir.LiteralStructType((dbl, flt, flt)), (8, ))
Ejemplo n.º 7
0
    def test_abi_size(self):
        td = llvm.create_target_data("e-m:e-i64:64-f80:128-n8:16:32:64-S128")

        def check(tp, expected):
            self.assertEqual(tp.get_abi_size(td), expected)

        check(int8, 1)
        check(int32, 4)
        check(int64, 8)
        check(ir.ArrayType(int8, 5), 5)
        check(ir.ArrayType(int32, 5), 20)
        check(ir.LiteralStructType((dbl, flt, flt)), 16)
Ejemplo n.º 8
0
    def visit_Tuple(self, node):
        elements = (self.visit(element) for element in node.elts)
        element_values = [self.builder.load(element) if helpers.is_pointer(element) else element for element in elements]
        element_types = [element.type for element in element_values]
        if len(element_types) > 0 and all(x == element_types[0] for x in element_types):
            result = ir.ArrayType(element_types[0], len(element_types))(ir.Undefined)
        else:
            result = ir.LiteralStructType(element_types)(ir.Undefined)

        for i, val in enumerate(element_values):
            result = self.builder.insert_value(result, val, i)

        return result
Ejemplo n.º 9
0
 def convert_python_struct_to_llvm_ir(self, t):
     self._stats["types_converted"] += 1
     if t is None:
         return ir.LiteralStructType([])
     elif type(t) is list:
         if len(t) == 0:
             return ir.LiteralStructType([])
         elems_t = [self.convert_python_struct_to_llvm_ir(x) for x in t]
         if all(x == elems_t[0] for x in elems_t):
             return ir.ArrayType(elems_t[0], len(elems_t))
         return ir.LiteralStructType(elems_t)
     elif type(t) is tuple:
         elems_t = [self.convert_python_struct_to_llvm_ir(x) for x in t]
         if len(elems_t) > 0 and all(x == elems_t[0] for x in elems_t):
             return ir.ArrayType(elems_t[0], len(elems_t))
         return ir.LiteralStructType(elems_t)
     elif isinstance(t, enum.Enum):
         # FIXME: Consider enums of non-int type
         assert all(round(x.value) == x.value for x in type(t))
         return self.int32_ty
     elif isinstance(t, (int, float, np.floating)):
         return self.float_ty
     elif isinstance(t, np.integer):
         # Python 'int' is handled above as it is the default type for '0'
         return ir.IntType(t.nbytes * 8)
     elif isinstance(t, np.ndarray):
         return self.convert_python_struct_to_llvm_ir(t.tolist())
     elif isinstance(t, np.random.RandomState):
         return pnlvm.builtins.get_mersenne_twister_state_struct(self)
     elif isinstance(t, Time):
         return ir.ArrayType(self.int32_ty, len(TimeScale))
     elif isinstance(t, SampleIterator):
         if isinstance(t.generator, list):
             return ir.ArrayType(self.float_ty, len(t.generator))
         # Generic iterator is {start, increment, count}
         return ir.LiteralStructType(
             (self.float_ty, self.float_ty, self.int32_ty))
     assert False, "Don't know how to convert {}".format(type(t))
Ejemplo n.º 10
0
 def test_comparisons(self):
     # A bunch of mutually unequal types
     types = [
         ir.LabelType(),
         ir.VoidType(),
         ir.FunctionType(int1, (int8, int8)),
         ir.FunctionType(int1, (int8, )),
         ir.FunctionType(int1, (int8, ), var_arg=True),
         ir.FunctionType(int8, (int8, )),
         int1,
         int8,
         int32,
         flt,
         dbl,
         ir.ArrayType(flt, 5),
         ir.ArrayType(dbl, 5),
         ir.ArrayType(dbl, 4),
         ir.LiteralStructType((int1, int8)),
         ir.LiteralStructType((int8, int1)),
     ]
     types.extend([
         ir.PointerType(tp) for tp in types
         if not isinstance(tp, ir.VoidType)
     ])
     for a, b in itertools.product(types, types):
         if a is not b:
             self.assertFalse(a == b, (a, b))
             self.assertTrue(a != b, (a, b))
     # We assume copy.copy() works fine here...
     for tp in types:
         other = copy.copy(tp)
         self.assertIsNot(other, tp)
         if isinstance(tp, ir.LabelType):
             self.assertFalse(tp == other, (tp, other))
             self.assertTrue(tp != other, (tp, other))
         else:
             self.assertTrue(tp == other, (tp, other))
             self.assertFalse(tp != other, (tp, other))
Ejemplo n.º 11
0
 def _param_struct(p):
     val = p.get(None)   # this should use defaults
     if hasattr(val, "_get_compilation_params") or \
        hasattr(val, "_get_param_struct_type"):
         return self.get_param_struct_type(val)
     if isinstance(val, ContentAddressableList):
         return ir.LiteralStructType(self.get_param_struct_type(x) for x in val)
     elif p.name == 'matrix':   # Flatten matrix
         val = np.asfarray(val).flatten()
     elif p.name == 'num_estimates':  # Should always be int
         val = np.int32(0) if val is None else np.int32(val)
     elif np.ndim(val) == 0 and component._is_param_modulated(p):
         val = [val]   # modulation adds array wrap
     return self.convert_python_struct_to_llvm_ir(val)
Ejemplo n.º 12
0
 def make_ir_type(self, compiler):
     if not self.fields:
         raise CodegenError("type {} has no defined field.".format(
             self.name))
     else:
         elems = []
         for field in self.fields:
             try:
                 field_type = compiler.types[field.type]
             except KeyError:
                 raise CodegenError("unknown field type: {}".format(
                     field.type))
             elems.append(field_type.ir_type)
         self.ir_type = ir.LiteralStructType(elems)
Ejemplo n.º 13
0
Archivo: context.py Proyecto: rjw57/rbc
    def __init__(self, target, machine):
        # Record target and machine
        self.target = target
        self.machine = machine

        # We choose the word type to be an integer with the same size as a
        # pointer to i8. The word size is expressed in bytes
        word_size = ir.IntType(8).as_pointer().get_abi_size(
            self.machine.target_data)

        # Define the word type and bytes-per-word appropriately
        self.word_type = ir.IntType(word_size * 8)
        self.bytes_per_word = word_size

        # Define the type used for constructor function records
        priority_type = ir.IntType(32)
        ctor_func_type = ir.FunctionType(ir.VoidType(), [])
        data_ptr_type = ir.PointerType(ir.IntType(8))
        self.ctor_record_type = ir.LiteralStructType(
            [priority_type,
             ctor_func_type.as_pointer(), data_ptr_type])

        # Initialise context attributes
        self.module = None
        self.global_scope = {}
        self.externals = {}
        self.scope = collections.ChainMap(self.global_scope)
        self.builder = None
        self.string_constants = {}
        self.ctor_records = []

        # Block at end of current switch/which statement
        self.break_block = None

        # LLVM Value of condition in current switch statement
        self.switch_val = None

        # Block which new switch tests should be appended to
        self.switch_block = None

        # Labels are mappings from names to.basic blocks A goto branches to the
        # block. The labels dict is only created within functions.
        self.labels = None

        # Callables which should be called after all code has been emitted
        self.post_emit_hooks = []

        # Flag to indicate when one is within the emitting_code() context.
        self._is_emitting = False
Ejemplo n.º 14
0
    def declare_type(self, symbol: Type) -> ir.Type:
        if symbol.is_generic:
            raise DiagnosticError(symbol.location, f'Conversion to LLVM for generic type is not allowed')

        if isinstance(symbol, BooleanType):
            return ir.IntType(1)
        elif isinstance(symbol, IntegerType):
            return ir.IntType(64)
        elif isinstance(symbol, VoidType):
            return ir.LiteralStructType([])
        elif isinstance(symbol, VoidType):
            return ir.LiteralStructType([])
        elif isinstance(symbol, StringType):
            return ir.IntType(8).as_pointer()
        elif isinstance(symbol, ClassType):
            return self.llvm_context.get_identified_type(symbol.mangled_name).as_pointer()
        elif isinstance(symbol, ArrayType):
            # {size_t, T*}
            llvm_size = self.llvm_size
            llvm_element = self.llvm_types[symbol.element_type]
            llvm_array = llvm_element.as_pointer()
            return ir.LiteralStructType([llvm_size, llvm_array]).as_pointer()

        raise DiagnosticError(symbol.location, f'Conversion to LLVM is not implemented: {type(symbol).__name__}')
Ejemplo n.º 15
0
    def get_state_struct_type(self, component):
        self._stats["state_structs_generated"] += 1
        if hasattr(component, '_get_state_struct_type'):
            return component._get_state_struct_type(self)

        def _state_struct(p):
            val = p.get(None)   # this should use defaults
            if hasattr(val, "_get_compilation_state") or \
               hasattr(val, "_get_state_struct_type"):
                return self.get_state_struct_type(val)
            if isinstance(val, ContentAddressableList):
                return ir.LiteralStructType(self.get_state_struct_type(x) for x in val)
            struct = self.convert_python_struct_to_llvm_ir(val)
            return ir.ArrayType(struct, p.history_min_length + 1)

        elements = map(_state_struct, component._get_compilation_state())
        return ir.LiteralStructType(elements)
Ejemplo n.º 16
0
 def visit_vardecl(self, node):
     typ = type_map[node.type.value] if node.type.value in type_map else self.search_scopes(node.type.value)
     if node.type.value == FUNC:
         if node.type.func_ret_type.value in type_map:
             func_ret_type = type_map[node.type.func_ret_type.value]
         else:
             func_ret_type = self.search_scopes(node.type.func_ret_type.value)
         func_parameters = self.get_args(node.type.func_params)
         func_ty = ir.FunctionType(func_ret_type, func_parameters, None).as_pointer()
         typ = func_ty
         self.alloc_and_define(node.value.value, typ)
     elif node.type.value in (LIST, TUPLE):
         array_type = node.type.func_params['0'].value
         typ = ir.LiteralStructType([type_map[INT], type_map[INT], type_map[array_type].as_pointer()])
         self.alloc_and_define(node.value.value, typ)
     else:
         self.alloc_and_define(node.value.value, typ)
Ejemplo n.º 17
0
 def var_decl(self, node):
     namelist = self.name_list(node.children[0])
     if (node.children[2].children[0].type == "simple_type_decl"):
         ir_type = self.type_decl(node.children[2])
         for name in namelist:
             # addr = self.builder.alloca(ir_type)
             # # addr = ir.GlobalVariable(self.module, ir_type, node.children[0].children[0].name)
             # # addr.initializer = ir.Constant(ir.IntType(32), 0)
             # self.symbol_table.insert([name, addr])
             if len(self.symbol_table.tables) > 1:
                 addr = self.builder.alloca(ir_type)
             else:
                 addr = ir.GlobalVariable(self.module, ir_type, name)
                 if ir_type.intrinsic_name == 'i32':
                     addr.initializer = ir.Constant(ir.IntType(32), 0)
                 elif ir_type.intrinsic_name == 'f64':
                     addr.initializer = ir.Constant(ir.DoubleType(), 0)
                 elif ir_type.intrinsic_name == 'i8':
                     addr.initializer = ir.Constant(ir.IntType(8), 0)
             self.symbol_table.insert([name, addr])
     elif (node.children[2].children[0].type == "array_type_decl"):
         array_list = self.type_decl(node.children[2])
         array_type = ir.ArrayType(array_list[1],
                                   int(array_list[2]) +
                                   1)  # x integers of element
         for name in namelist:
             addr = self.builder.alloca(array_type)  # pointer to array
             self.symbol_table.insert([name, addr])
     elif (node.children[2].children[0].type == "record_type_decl"):
         field_list = self.type_decl(node.children[2])
         i32 = ir.IntType(32)
         for name in namelist:
             field_body = [i32]
             count = 1
             for f in field_list[1]:
                 field_body += [f[1]]
                 index = ir.Constant(i32, count)
                 try:
                     self.symbol_table.insert([name + "." + f[0], index], 0)
                 except MultiDefinedError as error:
                     pass
                 count += 1
             str_list = ir.LiteralStructType(field_body)
             addr = self.builder.alloca(str_list)  # pointer to array
             self.symbol_table.insert([name, addr])
Ejemplo n.º 18
0
 def AddItem(self, Name, MemberList, TypeList):
     '''
     描述:添加一个元素
     参数:名称,成员列表,类型列表
     返回:成功{"result":"success"},失败{"result":"fail","reason":具体原因码}
     '''
     #todo:处理这个错误
     if Name in self.List:
         Result = {
             "result": "fail",
             "reason": Constants.ERROR_TYPE_REDEFINATION
         }
         return Result
     NewStruct = {}
     NewStruct["Members"] = MemberList
     NewStruct["Type"] = ir.LiteralStructType(TypeList)
     self.List[Name] = NewStruct
     return {"result": "success"}
Ejemplo n.º 19
0
def ptx_shfl_sync_i32(context, builder, sig, args):
    """
    The NVVM intrinsic for shfl only supports i32, but the cuda intrinsic
    function supports both 32 and 64 bit ints and floats, so for feature parity,
    i64, f32, and f64 are implemented. Floats by way of bitcasting the float to
    an int, then shuffling, then bitcasting back. And 64-bit values by packing
    them into 2 32bit values, shuffling thoose, and then packing back together.
    """
    mask, mode, value, index, clamp = args
    value_type = sig.args[2]
    if value_type in types.real_domain:
        value = builder.bitcast(value, ir.IntType(value_type.bitwidth))
    fname = 'llvm.nvvm.shfl.sync.i32'
    lmod = builder.module
    fnty = ir.FunctionType(
        ir.LiteralStructType((ir.IntType(32), ir.IntType(1))),
                            (ir.IntType(32), ir.IntType(32), ir.IntType(32),
                             ir.IntType(32), ir.IntType(32))
    )
    func = cgutils.get_or_insert_function(lmod, fnty, fname)
    if value_type.bitwidth == 32:
        ret = builder.call(func, (mask, mode, value, index, clamp))
        if value_type == types.float32:
            rv = builder.extract_value(ret, 0)
            pred = builder.extract_value(ret, 1)
            fv = builder.bitcast(rv, ir.FloatType())
            ret = cgutils.make_anonymous_struct(builder, (fv, pred))
    else:
        value1 = builder.trunc(value, ir.IntType(32))
        value_lshr = builder.lshr(value, context.get_constant(types.i8, 32))
        value2 = builder.trunc(value_lshr, ir.IntType(32))
        ret1 = builder.call(func, (mask, mode, value1, index, clamp))
        ret2 = builder.call(func, (mask, mode, value2, index, clamp))
        rv1 = builder.extract_value(ret1, 0)
        rv2 = builder.extract_value(ret2, 0)
        pred = builder.extract_value(ret1, 1)
        rv1_64 = builder.zext(rv1, ir.IntType(64))
        rv2_64 = builder.zext(rv2, ir.IntType(64))
        rv_shl = builder.shl(rv2_64, context.get_constant(types.i8, 32))
        rv = builder.or_(rv_shl, rv1_64)
        if value_type == types.float64:
            rv = builder.bitcast(rv, ir.DoubleType())
        ret = cgutils.make_anonymous_struct(builder, (rv, pred))
    return ret
Ejemplo n.º 20
0
    def create_in_global_ctor(self):
        current_block = self.current_block
        current_func = self.current_func
        current_struct = self.current_struct
        conditional_block = self.conditional_block
        end_block = self.end_block
        pos = self.builder is not None and self.builder._anchor or 0

        func = ParserState.module().get_global_safe('global_ctor')

        if func is None:
            func_type = self.create_function_type(ir.VoidType(), [], False)
            func = self.create_function_with_type('global_ctor', 'global_ctor', func_type, "internal", "ccc",
                                                  FunctionDefinition('void'))
            self.create_function_body(func, [])
            struct_type = ir.LiteralStructType([ir.IntType(32), func_type.as_pointer(), ir.IntType(8).as_pointer()])
            glob_value = ir.Constant(ir.ArrayType(struct_type, 1), [ir.Constant.literal_struct(
                [ir.Constant(ir.IntType(32), 65535), func, NULL])])
            glob_type = ir.ArrayType(struct_type, 1)

            self.gen_global("llvm.global_ctors", glob_value, glob_type, RIALAccessModifier.PRIVATE, "appending", False)
        else:
            self.builder.position_before(func.entry_basic_block.terminator)
            self.current_func = func
            self.current_block = create_llvm_block(func.entry_basic_block)

        self.current_struct = None
        self.conditional_block = None
        self.end_block = None

        yield

        self.finish_current_block()
        self.finish_current_func()

        self.current_block = current_block
        self.current_func = current_func
        self.current_struct = current_struct
        self.conditional_block = conditional_block
        self.end_block = end_block
        self.builder._anchor = pos
        self.builder._block = self.current_block is not None and self.current_block.block or None

        return
Ejemplo n.º 21
0
    def visit_Tuple(self, node):
        elements = [self.visit(element) for element in node.elts]

        elements = [
            self.builder.load(element)
            if helpers.is_pointer(element) else element for element in elements
        ]

        element_types = [element.type for element in elements]
        ret_list = self.builder.alloca(ir.LiteralStructType(element_types))

        for idx, element in enumerate(elements):
            self.builder.store(
                element,
                self.builder.gep(
                    ret_list, [self.ctx.int32_ty(0),
                               self.ctx.int32_ty(idx)]))

        return ret_list
Ejemplo n.º 22
0
def define_dynamic_array(compiler):
    # define a struct dynamic_array
    # 0: int size
    # 1: int capacity
    # 2: int *data  TODO: maybe make this a void pointer to allow any kind of data
    dyn_array_struct = ir.LiteralStructType(
        [type_map[INT], type_map[INT], type_map[INT].as_pointer()])
    compiler.define('Dynamic_Array', dyn_array_struct)
    dyn_array_struct_ptr = dyn_array_struct.as_pointer()

    dynamic_array_init(compiler, dyn_array_struct_ptr)
    dynamic_array_double_if_full(compiler, dyn_array_struct_ptr)
    dynamic_array_append(compiler, dyn_array_struct_ptr)
    dynamic_array_get(compiler, dyn_array_struct_ptr)
    dynamic_array_set(compiler, dyn_array_struct_ptr)
    dynamic_array_length(compiler, dyn_array_struct_ptr)
    define_create_range(compiler, dyn_array_struct_ptr)
    define_int_to_str(compiler, dyn_array_struct_ptr)
    define_bool_to_str(compiler, dyn_array_struct_ptr)
    define_print(compiler, dyn_array_struct_ptr)
Ejemplo n.º 23
0
    def visitStructDeclaration(self,
                               ctx: c2llvmParser.StructDeclarationContext):
        self.enter_scope()

        struct_name = ctx.getChild(0).getChild(1).getText()
        if struct_name in self.structures:
            logger.error("Struct Declaration Error")
            return

        member_types = []
        member_names = []
        for index in range(2, ctx.getChildCount() - 2):
            v_types, v_names = self.visit(ctx.getChild(index))
            member_types.extend(v_types)
            member_names.extend(v_names)

        self.structures[struct_name] = {
            'members': member_names,
            'struct': ir.LiteralStructType(member_types)
        }
        self.exit_scope()
Ejemplo n.º 24
0
 def type_definition(self, node):
     name = node.children[0].name
     if (node.children[2].children[0].type == "array_type_decl"):
         array_list = self.type_decl(node.children[2])
         array_type = ir.ArrayType(array_list[1],
                                   int(array_list[2]) +
                                   1)  # x integers of element
         addr = self.builder.alloca(array_type)  # pointer to array
         self.symbol_table.insert([name, addr])
     elif (node.children[2].children[0].type == "record_type_decl"):
         field_list = self.type_decl(node.children[2])
         i32 = ir.IntType(32)
         field_body = [i32]
         count = 1
         for f in field_list[1]:
             field_body += [f[1]]
             index = ir.Constant(i32, count)
             self.symbol_table.insert([name + "." + f[0], index])
             count += 1
         str_list = ir.LiteralStructType(field_body)
         addr = self.builder.alloca(str_list)  # pointer to array
         self.symbol_table.insert([name, addr])
Ejemplo n.º 25
0
def get_lpad(func):
   global pad_map, block_num
   if except_stack[-1] in pad_map:
     return pad_map[except_stack[-1]]
   lpad = func.append_basic_block(name="lpad" + str(block_num+1))
   block_num +=1 
   lbuilder = ir.IRBuilder(lpad) 
   lp = lbuilder.landingpad(ir.LiteralStructType([int8.as_pointer(),int64]), 'lp')
   lp.add_clause(ir.CatchClause(int8.as_pointer()(None)))

   lbuilder.call(begin_catch,[])
   lbuilder.call(end_catch,[])
   
   rpad = func.append_basic_block(name="lpad" + str(block_num+1) + "_tgt")
   lbuilder.branch(rpad)
   rbuilder = ir.IRBuilder(rpad)
   

   #lbuilder.call(resume,[lbuilder.extract_value(lp, 0)])
   #lbuilder.resume(lp)
   pad_map[except_stack[-1]] = (lpad,lbuilder,rpad,rbuilder)
   return pad_map[except_stack[-1]]
Ejemplo n.º 26
0
    def create_in_global_ctor(self):
        func = self.get_global_safe('global_ctor')

        if func is None:
            func_type = ir.FunctionType(ir.VoidType(), [], False)
            func = self.declare_function('global_ctor', 'global_ctor',
                                         func_type, "internal", "ccc",
                                         FunctionDefinition("Void"))
            struct_type = ir.LiteralStructType(
                [Int32,
                 func_type.as_pointer(),
                 ir.IntType(8).as_pointer()])
            glob_value = ir.Constant(
                ir.ArrayType(struct_type, 1),
                [ir.Constant.literal_struct([Int32(65535), func, NULL])])
            glob_type = ir.ArrayType(struct_type, 1)

            self.declare_global("llvm.global_ctors",
                                map_llvm_to_type(glob_type), glob_type,
                                "appending", glob_value)

        with self.create_or_enter_function_body(func):
            yield
Ejemplo n.º 27
0
def define_builtins(self):
    # 0: int size
    # 1: int capacity
    # 2: int *data
    str_struct = ir.LiteralStructType(
        [type_map[INT], type_map[INT], type_map[INT].as_pointer()])
    self.define('Str', str_struct)
    str_struct_ptr = str_struct.as_pointer()
    self.define('Str_ptr', str_struct_ptr)
    type_map[STR] = str_struct
    lint = str(type_map[INT])

    dynamic_array_init(self, str_struct_ptr, lint)
    dynamic_array_double_if_full(self, str_struct_ptr, lint)
    dynamic_array_append(self, str_struct_ptr, lint)
    dynamic_array_get(self, str_struct_ptr, lint)
    dynamic_array_set(self, str_struct_ptr, lint)
    dynamic_array_length(self, str_struct_ptr, lint)

    define_create_range(self, str_struct_ptr, lint)

    define_int_to_str(self, str_struct_ptr)
    define_bool_to_str(self, str_struct_ptr)
    define_print(self, str_struct_ptr)
Ejemplo n.º 28
0
    def codegen(context, builder, sig, args):
        vtablety = ir.LiteralStructType([
            ll_voidptr_type,  # item incref
            ll_voidptr_type,  # item decref
        ])
        setmethod_fnty = ir.FunctionType(
            ir.VoidType(),
            [ll_list_type, vtablety.as_pointer()]
        )
        setmethod_fn = ir.Function(
            builder.module,
            setmethod_fnty,
            name='numba_list_set_method_table',
        )
        dp = args[0]
        vtable = cgutils.alloca_once(builder, vtablety, zfill=True)

        # install item incref/decref
        item_incref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 0)
        item_decref_ptr = cgutils.gep_inbounds(builder, vtable, 0, 1)

        dm_item = context.data_model_manager[itemty.instance_type]
        if dm_item.contains_nrt_meminfo():
            item_incref, item_decref = _get_incref_decref(
                context, builder.module, dm_item, "list"
            )
            builder.store(
                builder.bitcast(item_incref, item_incref_ptr.type.pointee),
                item_incref_ptr,
            )
            builder.store(
                builder.bitcast(item_decref, item_decref_ptr.type.pointee),
                item_decref_ptr,
            )

        builder.call(setmethod_fn, [dp, vtable])
Ejemplo n.º 29
0
    def make_c_struct(cls, name_types):
        """Construct a Record type from a list of (name:str, type:Types).
        The layout of the structure will follow C.

        Note: only scalar types are supported currently.
        """
        from numba.core.registry import cpu_target

        ctx = cpu_target.target_context
        offset = 0
        fields = []
        lltypes = []
        for k, ty in name_types:
            if not isinstance(ty, (Number, NestedArray)):
                msg = "Only Number and NestedArray types are supported, found: {}. "
                raise TypeError(msg.format(ty))
            if isinstance(ty, NestedArray):
                datatype = ctx.data_model_manager[ty].as_storage_type()
            else:
                datatype = ctx.get_data_type(ty)
            lltypes.append(datatype)
            size = ctx.get_abi_sizeof(datatype)
            align = ctx.get_abi_alignment(datatype)
            # align
            misaligned = offset % align
            if misaligned:
                offset += align - misaligned
            fields.append((k, {
                'type': ty,
                'offset': offset,
                'alignment': align,
            }))
            offset += size
        # Adjust sizeof structure
        abi_size = ctx.get_abi_sizeof(ir.LiteralStructType(lltypes))
        return Record(fields, size=abi_size, aligned=True)
Ejemplo n.º 30
0
 def get_struct_type(self, struct):
     """
     Get the LLVM struct type for the given Structure class *struct*.
     """
     fields = [self.get_value_type(v) for _, v in struct._fields]
     return llvmir.LiteralStructType(fields)