示例#1
0
def bsort_expr(n, datatype):
    def assign(var, val):
        return ir.Stmt((ir.assignment, var, val))

    def item(name):
        return ir.Struct_item(ir.Primitive_type(datatype), (name))

    t = ir.Struct(ir.Scoped_id([("s")], ('Vector'), ''),
            [item('m%d'%i) for i in range(1, n+1)], '')
    a = ir.Arg([], ir.in_, t, 'a')
    b = ir.Arg([], ir.inout, t, 'b')
    copy = [ir.Stmt(ir.Set_struct_item(t, (ir.deref, "b"), item('m%d'%i),
                      ir.Get_struct_item(t, (ir.deref, "a"), item('m%d'%i))))
            for i in range(1, n+1)]
    sort = [(ir.var_decl, ir.pt_bool, ("swapped")),
            (ir.var_decl, ir.pt_int, ("tmp")),
            (ir.do_while, ("swapped"),
             # if A[i-1] > A[i]
             [assign(("swapped"), ir.Bool(ir.false))]+
             [[(ir.if_, 
                (ir.Infix_expr(ir.gt, 
                              ir.Get_struct_item(t, (ir.deref, "b"), item('m%d'%(i-1))),
                              ir.Get_struct_item(t, (ir.deref, "b"), item('m%d'%i)))),
                # swap( A[i-1], A[i] )
                # swapped = true
                [assign(("tmp"), 
                        ir.Get_struct_item(t, (ir.deref, "b"), item('m%d'%i))),
                 ir.Stmt(ir.Set_struct_item(t, (ir.deref, "b"), item('m%d'%i),
                           ir.Get_struct_item(t, (ir.deref, "b"), item('m%d'%(i-1))))),
                 ir.Stmt(ir.Set_struct_item(t, (ir.deref, "b"), item('m%d'%(i-1)),
                           ("tmp"))),
                 assign(("swapped"), ir.Bool(ir.true))])]
              for i in range(2, n+1)])]
    return copy+sort+[ir.Stmt(ir.Return(retval(n, datatype)))]
示例#2
0
def ir_object_type(package, name):
    """
    \return the IR node for the type of a Babel object 'name'
    \param name    the name of the object
    \param package the list of IDs making up the package
    """
    return ir.Pointer_type(
        ir.Struct(ir.Scoped_id(package, name, '__object'), [], ''))
示例#3
0
def reverse_expr(n, datatype):
    'b_i = a_{n-i}'
    def item(name):
        return ir.Struct_item(ir.Primitive_type(datatype), (name))

    t = ir.Struct(ir.Scoped_id([("s")], ('Vector'), ''), 
         [ir.Struct_item(ir.Primitive_type(datatype), ('m%d'%i)) for i in range(1, n+1)], '')
    revs = [ir.Stmt(ir.Set_struct_item(t, (ir.deref, "b"), item('m%d'%i),
                       ir.Get_struct_item(t, (ir.deref, "a"), item('m%d'%(n-i+1)))))
            for i in range(1, n+1)]
    return revs+[ir.Stmt(ir.Return(retval(n, datatype)))]
示例#4
0
    def get_ir(self):
        """
        return an s-expression of the EPV declaration
        """

        self.finalized = True
        name = ir.Scoped_id(self.symbol_table.prefix, self.name + '__epv', '')
        return ir.Struct(name, [
            ir.Struct_item(itype, iname)
            for itype, iname in map(get_type_name, self.methods)
        ], 'Entry Point Vector (EPV)')
示例#5
0
 def get_pre_epv_ir(self):
     """
     return an s-expression of the pre_EPV declaration
     """
     self.finalized = True
     name = ir.Scoped_id(self.symbol_table.prefix, self.name + '__pre_epv',
                         '')
     elems = [
         ir.Struct_item(itype, iname)
         for itype, iname in map(get_type_name, self.pre_methods)
     ]
     if elems == []: elems = [self.nonempty]
     return ir.Struct(name, elems, 'Pre Hooks Entry Point Vector (pre_EPV)')
示例#6
0
    def get_sepv_ir(self):
        """
        return an s-expression of the SEPV declaration
        """

        if not self.has_static_methods:
            return ''

        self.finalized = True
        name = ir.Scoped_id(self.symbol_table.prefix, self.name + '__sepv', '')
        return ir.Struct(name, [
            ir.Struct_item(itype, iname)
            for itype, iname in map(get_type_name, self.static_methods)
        ], 'Static Entry Point Vector (SEPV)')
示例#7
0
def const_access_expr(n, datatype):
    def add(a, b):
        return ir.Plus(a, b)

    def item(name):
        return ir.Struct_item(ir.Primitive_type(datatype), (name))

    t = ir.Struct(ir.Scoped_id([("s")], ('Vector'), ''), 
         [ir.Struct_item(ir.Primitive_type(datatype), ('m%d'%i)) for i in range(1, n+1)], '')
    e = reduce(add, map(lambda i:
                            ("*",
                             ir.Get_struct_item(t, (ir.deref, "a"), item('m%d'%(i%n+1))),
			     ir.Get_struct_item(t, (ir.deref, "b"), item('m%d'%(i%n+1)))),
                        range(1, 129)))
    return ir.Stmt(ir.Return(e))
示例#8
0
def dotproduct_expr(n, datatype):
    def add(a, b):
        return ir.Plus(a, b)

    def item(name):
        return ir.Struct_item(ir.Primitive_type(datatype), (name))

    a = ir.Struct(ir.Scoped_id([("s")], ('Vector'), ''),
         [ir.Struct_item(ir.Primitive_type(datatype), ('m%d'%i)) for i in range(1, n+1)], '')
    b = a
    e = reduce(add, map(lambda i:
                            ("*",
                             ir.Get_struct_item(a, (ir.deref, "a"), 'm%d'%i),
                             ir.Get_struct_item(b, (ir.deref, "b"), 'm%d'%i)),
                        range(1, n+1)))
    return ir.Stmt(ir.Return(e))
示例#9
0
    def get_post_sepv_ir(self):
        """
        return an s-expression of the post_SEPV declaration
        """
        if not self.has_static_methods:
            return ''

        self.finalized = True
        name = ir.Scoped_id(self.symbol_table.prefix,
                            self.name + '__post_sepv', '')

        if self.static_post_methods:
            entries = [
                ir.Struct_item(itype, iname) for itype, iname in map(
                    get_type_name, self.static_post_methods)
            ]
        else:
            entries = [self.nonempty]
        return ir.Struct(name, entries,
                         'Post Hooks Entry Point Vector (post_EPV)')
示例#10
0
 def get_sepv_type(self):
     """
     return an s-expression of the SEPV's (incomplete) type
     """
     name = ir.Scoped_id(self.symbol_table.prefix, self.name + '__sepv', '')
     return ir.Struct(name, [], 'Static Entry Point Vector (SEPV)')
示例#11
0
def lower_ir(symbol_table,
             sidl_term,
             header=None,
             struct_suffix='__data',
             enum_suffix='__enum',
             lower_scoped_ids=True,
             qualify_names=True,
             qualify_enums=True,
             raw_ior_arrays=False,
             wrap_rarrays=False):
    """
    FIXME!! can we merge this with convert_arg??
    lower SIDL types into IR

    The idea is that no Chapel-specific code is in this function. It
    should provide a generic translation from SIDL -> IR.

    @param lower_scoped_ids  This is a broken design, but right now the
                             Chapel code generator accepts some sidl
                             node types such as array, rarray, and
                             class.  If False, then these types will
                             not be lowered.

    @param qualify_names     If \c True, enum values will get prefixed
                             with the full qualified name of the enum.
    """
    def low(sidl_term):
        return lower_ir(symbol_table, sidl_term, header, struct_suffix,
                        enum_suffix, lower_scoped_ids, qualify_names,
                        qualify_enums, raw_ior_arrays, wrap_rarrays)

    # print 'low(',sidl_term, ')'
    array_prefix = '/* IOR */ ' if raw_ior_arrays else ''

    with match(sidl_term):
        if (sidlir.arg, Attrs, Mode, (sidlir.scoped_id, _, _, _), Name):
            lowtype = low(sidl_term[3])
            if lowtype[0] == ir.struct and Mode == ir.in_:
                # struct arguments are passed as pointer, regardless of mode
                # unless they are a return value
                lowtype = ir.Pointer_type(lowtype)
            return (ir.arg, Attrs, Mode, lowtype, Name)

        elif (sidlir.arg, Attrs, Mode, Typ, Name):
            return (ir.arg, Attrs, Mode, low(Typ), Name)

        elif (sidlir.scoped_id, Prefix, Name, Ext):
            return low(symbol_table[sidl_term][1])

        elif (sidlir.void):
            return ir.pt_void
        elif (ir.void_ptr):
            return ir.void_ptr
        elif (sidlir.primitive_type, sidlir.opaque):
            return ir.Pointer_type(ir.pt_void)
        elif (sidlir.primitive_type, sidlir.string):
            return sidl_term  #ir.const_str
        elif (sidlir.primitive_type, Type):
            return ir.Primitive_type(Type)

        elif (sidlir.enum, Name, Enumerators, DocComment):
            # in the IOR enums are represented as int64
            if qualify_enums:
                es = lower_ir(
                    SymbolTable(symbol_table,
                                symbol_table.prefix + [Name]), Enumerators,
                    header, struct_suffix, enum_suffix, lower_scoped_ids,
                    qualify_names, qualify_enums, raw_ior_arrays, wrap_rarrays)
                return ir.Enum(
                    qual_name(symbol_table, sidl_term[1]) + enum_suffix, es,
                    DocComment)
            else:
                return ir.Enum(sidl_term[1], low(Enumerators), DocComment)

        elif (sidlir.enumerator, Name):
            if qualify_enums:
                return ir.Enumerator(qual_name(symbol_table, Name))
            else:
                return sidl_term

        elif (sidlir.enumerator_value, Name, Val):
            if qualify_enums:
                return ir.Enumerator_value(qual_name(symbol_table, Name), Val)
            else:
                return sidl_term

        elif (sidlir.struct, (sidlir.scoped_id, Prefix, Name, Ext), Items,
              DocComment):
            # a nested Struct
            return ir.Struct(
                qual_id(sidl_term[1]) + struct_suffix, low(Items), '')

        elif (sidlir.struct, Name, Items, DocComment):
            return ir.Struct(
                qual_name(symbol_table, Name) + struct_suffix, low(Items), '')

        elif (sidlir.struct_item, Type, Name):
            if Type[0] == sidlir.scoped_id:
                t = symbol_table[Type][1]
                if t[0] == sidlir.class_ or t[0] == sidlir.interface:
                    if header: header.genh(ir.Import(qual_id(t[1]) + '_IOR'))
                    t = ir_object_type(t[1][1], t[1][2])
                elif t[0] == sidlir.struct or t[0] == sidlir.enum:
                    return (ir.struct_item, low(t), Name)
                return (ir.struct_item, t, Name)
            return (ir.struct_item, low(Type), Name)

        # elif (sidlir.rarray, Scalar_type, Dimension, Extents):
        #     # Future optimization:
        #     # Direct-call version (r-array IOR)
        #     # return ir.Pointer_type(lower_type_ir(symbol_table, Scalar_type)) # FIXME
        #     # SIDL IOR version
        #     return ir.Typedef_type('sidl_%s__array'%Scalar_type[1])

        elif (sidlir.rarray, Scalar_type, Dimension, Extents):
            if wrap_rarrays:
                return ir.Pointer_type(
                    ir.Struct(
                        '%ssidl_%s__array' % (array_prefix, Scalar_type[1]),
                        [], ''))
            else:
                return ir.Rarray(low(Scalar_type), Dimension, Extents)

        elif (sidlir.array, [], [], []):
            #if not lower_scoped_ids: return sidl_term
            #return ir.Pointer_type(ir.pt_void)
            return ir.Pointer_type(ir.Struct('sidl__array', [], ''))

        elif (sidlir.array, Scalar_type, Dimension, Orientation):
            #if not lower_scoped_ids: return sidl_term
            if Scalar_type[0] == ir.scoped_id:
                # All object arrays are called sidl_interface__array
                t = 'interface'
                if header: header.genh(ir.Import('sidl_BaseInterface_IOR'))
            else:
                t = Scalar_type[1]
            if header: header.genh(ir.Import('sidl_' + t + '_IOR'))
            return ir.Pointer_type(
                ir.Struct('%ssidl_%s__array' % (array_prefix, t), [], ''))

        elif (sidlir.class_, ScopedId, _, _, _, _, _):
            if not lower_scoped_ids: return ScopedId
            else: return ir_object_type(ScopedId[1], ScopedId[2])

        elif (sidlir.interface, ScopedId, _, _, _, _):
            if not lower_scoped_ids: return ScopedId
            return ir_object_type(ScopedId[1], ScopedId[2])

        elif (Terms):
            if (isinstance(Terms, list)):
                return map(low, Terms)
            else:
                raise Exception("lower_ir: Not implemented: " + str(sidl_term))
        else:
            raise Exception("match error")
示例#12
0
    def gen_default_methods(self, cls, has_contracts, ci):
        """
        Generate default Babel object methods such as _cast() Also
        generates other IOR data structures such as the _object and
        the controls and statistics struct.
        """

        def unscope((struct, scoped_id, items, doc)):
            return struct, c_gen(scoped_id), items, doc

        def builtin(t, name, args):
            ci.epv.add_method(
                sidlir.Method(t, sidlir.Method_name(name, ''), [],
                            args, [], [], [], [], 
                            'Implicit built-in method: '+name))

        def static_builtin(t, name, args):
            ci.epv.add_method(
                sidlir.Method(t, sidlir.Method_name(name, ''), [sidlir.static],
                            args, [], [], [], [], 
                            'Implicit built-in method: '+name))

        def inarg(t, name):
            return sidlir.Arg([], sidlir.in_, t, name)

        # Implicit Built-in methods
        builtin(sidlir.pt_opaque, '_cast',
                [inarg(sidlir.pt_string, 'name')])

        builtin(sidlir.void, '_delete', [])

        builtin(sidlir.void, '_exec', [
                inarg(sidlir.pt_string, 'methodName'),
                inarg(babel.object_type(['sidl', 'rmi'], 'Call'), 'inArgs'),
                inarg(babel.object_type(['sidl', 'rmi'], 'Return'), 'outArgs')])

        builtin(sidlir.pt_string, '_getURL', [])
        builtin(sidlir.void, '_raddRef', [])
        builtin(sidlir.pt_bool, '_isRemote', [])
        builtin(sidlir.void, '_set_hooks', 
                [inarg(sidlir.pt_bool, 'enable')])
        builtin(sidlir.void, '_set_contracts', [
                inarg(sidlir.pt_bool, 'enable'),
                inarg(sidlir.pt_string, 'enfFilename'),
                inarg(sidlir.pt_bool, 'resetCounters')],
                )
        builtin(sidlir.void, '_dump_stats', 
                [inarg(sidlir.pt_string, 'filename'),
                 inarg(sidlir.pt_string, 'prefix')])
        if not cls.is_interface():
            builtin(sidlir.void, '_ctor', [])
            builtin(sidlir.void, '_ctor2',
                    [(sidlir.arg, [], sidlir.in_, ir.void_ptr, 'private_data')])
            builtin(sidlir.void, '_dtor', [])
            builtin(sidlir.void, '_load', [])

        static_builtin(sidlir.void, '_set_hooks_static', 
                [inarg(sidlir.pt_bool, 'enable')])
        static_builtin(sidlir.void, '_set_contracts_static', [
                inarg(sidlir.pt_bool, 'enable'),
                inarg(sidlir.pt_string, 'enfFilename'),
                inarg(sidlir.pt_bool, 'resetCounters')],
                )
        static_builtin(sidlir.void, '_dump_stats_static', 
                [inarg(sidlir.pt_string, 'filename'),
                 inarg(sidlir.pt_string, 'prefix')])


        prefix = ci.epv.symbol_table.prefix
        # cstats
        cstats = []
        contract_cstats = []
        ci.methodcstats = []
        num_methods = cls.number_of_methods()
        
        if has_contracts:
            ci.methodcstats = ir.Struct(
                ir.Scoped_id(prefix, ci.epv.name+'__method_cstats', ''),
                [ir.Struct_item(ir.Typedef_type('int32_t'), 'tries'),
                 ir.Struct_item(ir.Typedef_type('int32_t'), 'successes'),
                 ir.Struct_item(ir.Typedef_type('int32_t'), 'failures'),
                 ir.Struct_item(ir.Typedef_type('int32_t'), 'nonvio_exceptions')],
                '')
            contract_cstats.append(ir.Struct_item(ir.Typedef_type('sidl_bool'), 'enabled'))
            contract_cstats.append(ir.Struct_item(
                    ci.methodcstats, 'method_cstats[%d]'%num_methods))

        ci.cstats = ir.Struct(
            ir.Scoped_id(prefix, ci.epv.name+'__cstats', ''),
            [ir.Struct_item(ir.Typedef_type('sidl_bool'), 'use_hooks')]+contract_cstats,
            'The controls and statistics structure')

        # @class@__object
        inherits = []
        def gen_inherits(baseclass):
            inherits.append(ir.Struct_item(
                babel.ir_object_type(baseclass[1], baseclass[2])
                [1], # not a pointer, it is an embedded struct
                'd_'+str.lower(babel.qual_id(baseclass))))

        with_sidl_baseclass = not cls.is_interface() and cls.qualified_name <> ['sidl', 'BaseClass']
        
        # pointers to the base class' EPV
        par = cls.get_parent()
        if par and par.is_class():
            gen_inherits(par.get_scoped_id())
            with_sidl_baseclass = False

        # pointers to the implemented interface's EPV
        if not cls.is_interface():
            for impl in cls.get_unique_interfaces():
                if impl <> (sidlir.scoped_id, ('sidl',), 'BaseInterface', ''):
                    gen_inherits(impl)

        baseclass = []
        if with_sidl_baseclass:
            baseclass.append(
                ir.Struct_item(ir.Struct('sidl_BaseClass__object', [],''),
                               'd_sidl_baseclass'))

        if ior_template.generateContractEPVs(ci.co):
            cstats = [ir.Struct_item(unscope(ci.cstats), 'd_cstats')]

        ior_template.braid_config = self.config
        epv  = [ir.Struct_item(ir.Pointer_type(unscope(ci.epv.get_type())), 'd_epv')]
        bepv = [ir.Struct_item(ir.Pointer_type(unscope(ci.epv.get_type())), 'd_bepv')] \
               if ior_template.generateBaseEPVAttr(ci.co) else []

        ci.obj = \
            ir.Struct(ir.Scoped_id(prefix, ci.epv.name+'__object', ''),
                      baseclass+
                      inherits+
                      epv+
                      bepv+
                      cstats+
                       [ir.Struct_item(ir.Pointer_type(ir.pt_void),
                                       'd_object' if cls.is_interface() else
                                       'd_data')],
                       'The class object structure')
        ci.external = \
            ir.Struct(ir.Scoped_id(prefix, ci.epv.name+'__external', ''),
                      ([ir.Struct_item(ir.Pointer_type(ir.Fn_decl([],
                                                       ir.Pointer_type(ci.obj),
                                                       'createObject', [
                                                           ir.Arg([], ir.inout, ir.void_ptr, 'ddata'),
                                                           ir.Arg([], sidlir.out, babel.ir_exception_type(), '_ex')],
                                                       '')),
                                                       'createObject')] 
                      if not cls.is_abstract else []) +
                      ([ir.Struct_item(ir.Pointer_type(ir.Fn_decl([],
                                                       ir.Pointer_type(unscope(ci.epv.get_sepv_type())),
                                                       'getStaticEPV', [], '')),
                                                       'getStaticEPV')] 
                      if cls.has_static_methods else []) +
                      [ir.Struct_item(
                        ir.Pointer_type(
                            ir.Fn_decl([], ir.Pointer_type(ir.Struct('sidl_BaseClass__epv', [],'')),
                                       'getSuperEPV', [], '')),
                        'getSuperEPV'),
                       ir.Struct_item(ir.pt_int, 'd_ior_major_version'),
                       ir.Struct_item(ir.pt_int, 'd_ior_minor_version')
                       ],
                       'The static class object structure')