本文整理汇总了Python中numba.cgutils.ifthen函数的典型用法代码示例。如果您正苦于以下问题:Python ifthen函数的具体用法?Python ifthen怎么用?Python ifthen使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了ifthen函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: build_wrapper
def build_wrapper(self, api, builder, closure, args, kws):
nargs = len(self.fndesc.args)
keywords = self.make_keywords(self.fndesc.args)
fmt = self.make_const_string("O" * nargs)
objs = [api.alloca_obj() for _ in range(nargs)]
parseok = api.parse_tuple_and_keywords(args, kws, fmt, keywords, *objs)
pred = builder.icmp(lc.ICMP_EQ, parseok, Constant.null(parseok.type))
with cgutils.if_unlikely(builder, pred):
builder.ret(api.get_null_object())
# Block that returns after erroneous argument unboxing/cleanup
endblk = cgutils.append_basic_block(builder, "arg.end")
with cgutils.goto_block(builder, endblk):
builder.ret(api.get_null_object())
cleanup_manager = _ArgManager(builder, api, endblk, nargs)
innerargs = []
for obj, ty in zip(objs, self.fndesc.argtypes):
val = cleanup_manager.add_arg(obj, ty)
innerargs.append(val)
if self.release_gil:
cleanup_manager = _GilManager(builder, api, cleanup_manager)
# The wrapped function doesn't take a full closure, only
# the Environment object.
env = self.context.get_env_from_closure(builder, closure)
status, res = self.context.call_function(builder, self.func,
self.fndesc.restype,
self.fndesc.argtypes,
innerargs, env)
# Do clean up
cleanup_manager.emit_cleanup()
# Determine return status
with cgutils.if_likely(builder, status.ok):
with cgutils.ifthen(builder, status.none):
api.return_none()
retval = api.from_native_return(res, self.fndesc.restype)
builder.ret(retval)
with cgutils.ifthen(builder, builder.not_(status.exc)):
# !ok && !exc
# User exception raised
self.make_exception_switch(api, builder, status.code)
# !ok && exc
builder.ret(api.get_null_object())
示例2: build_wrapper
def build_wrapper(self, api, builder, closure, args, kws):
nargs = len(self.fndesc.args)
objs = [api.alloca_obj() for _ in range(nargs)]
parseok = api.unpack_tuple(args, self.fndesc.qualname, nargs, nargs, *objs)
pred = builder.icmp(lc.ICMP_EQ, parseok, Constant.null(parseok.type))
with cgutils.if_unlikely(builder, pred):
builder.ret(api.get_null_object())
# Block that returns after erroneous argument unboxing/cleanup
endblk = cgutils.append_basic_block(builder, "arg.end")
with cgutils.goto_block(builder, endblk):
builder.ret(api.get_null_object())
cleanup_manager = _ArgManager(self.context, builder, api, endblk, nargs)
innerargs = []
for obj, ty in zip(objs, self.fndesc.argtypes):
val = cleanup_manager.add_arg(obj, ty)
innerargs.append(val)
if self.release_gil:
cleanup_manager = _GilManager(builder, api, cleanup_manager)
# Extract the Environment object from the Closure
envptr = self.context.get_env_from_closure(builder, closure)
env_body = self.context.get_env_body(builder, envptr)
env_manager = api.get_env_manager(self.env, env_body)
status, res = self.context.call_conv.call_function(
builder, self.func, self.fndesc.restype, self.fndesc.argtypes,
innerargs, envptr)
# Do clean up
cleanup_manager.emit_cleanup()
# Determine return status
with cgutils.if_likely(builder, status.is_ok):
# Ok => return boxed Python value
with cgutils.ifthen(builder, status.is_none):
api.return_none()
retval = api.from_native_return(res, self._simplified_return_type(),
env_manager)
builder.ret(retval)
with cgutils.ifthen(builder, builder.not_(status.is_python_exc)):
# User exception raised
self.make_exception_switch(api, builder, status)
# Error out
builder.ret(api.get_null_object())
示例3: build_wrapper
def build_wrapper(self, api, builder, closure, args, kws):
nargs = len(self.fndesc.args)
keywords = self.make_keywords(self.fndesc.args)
fmt = self.make_const_string("O" * nargs)
objs = [api.alloca_obj() for _ in range(nargs)]
parseok = api.parse_tuple_and_keywords(args, kws, fmt, keywords, *objs)
pred = builder.icmp(lc.ICMP_EQ, parseok, Constant.null(parseok.type))
with cgutils.if_unlikely(builder, pred):
builder.ret(api.get_null_object())
innerargs = []
cleanups = []
for obj, ty in zip(objs, self.fndesc.argtypes):
#api.context.debug_print(builder, "%s -> %s" % (obj, ty))
#api.print_object(builder.load(obj))
val, dtor = api.to_native_arg(builder.load(obj), ty)
innerargs.append(val)
cleanups.append(dtor)
# The wrapped function doesn't take a full closure, only
# the Environment object.
env = self.context.get_env_from_closure(builder, closure)
status, res = self.context.call_function(builder, self.func,
self.fndesc.restype,
self.fndesc.argtypes,
innerargs, env)
# Do clean up
for dtor in cleanups:
dtor()
# Determine return status
with cgutils.if_likely(builder, status.ok):
with cgutils.ifthen(builder, status.none):
api.return_none()
retval = api.from_native_return(res, self.fndesc.restype)
builder.ret(retval)
with cgutils.ifthen(builder, builder.not_(status.exc)):
# !ok && !exc
# User exception raised
self.make_exception_switch(api, builder, status.code)
# !ok && exc
builder.ret(api.get_null_object())
示例4: lower_global
def lower_global(self, name, value):
"""
1) Check global scope dictionary.
2) Check __builtins__.
2a) is it a dictionary (for non __main__ module)
2b) is it a module (for __main__ module)
"""
moddict = self.pyapi.get_module_dict()
obj = self.pyapi.dict_getitem_string(moddict, name)
self.incref(obj) # obj is borrowed
if hasattr(builtins, name):
obj_is_null = self.is_null(obj)
bbelse = self.builder.basic_block
with cgutils.ifthen(self.builder, obj_is_null):
mod = self.pyapi.dict_getitem_string(moddict, "__builtins__")
builtin = self.builtin_lookup(mod, name)
bbif = self.builder.basic_block
retval = self.builder.phi(self.pyapi.pyobj)
retval.add_incoming(obj, bbelse)
retval.add_incoming(builtin, bbif)
else:
retval = obj
with cgutils.if_unlikely(self.builder, self.is_null(retval)):
self.pyapi.raise_missing_global_error(name)
self.return_exception_raised()
self.incref(retval)
return retval
示例5: poisson_impl
def poisson_impl(context, builder, sig, args):
state_ptr = get_np_state_ptr(context, builder)
retptr = cgutils.alloca_once(builder, int64_t, name="ret")
bbcont = cgutils.append_basic_block(builder, "bbcont")
bbend = cgutils.append_basic_block(builder, "bbend")
if len(args) == 1:
lam, = args
big_lam = builder.fcmp_ordered('>=', lam, ir.Constant(double, 10.0))
with cgutils.ifthen(builder, big_lam):
# For lambda >= 10.0, we switch to a more accurate
# algorithm (see _helperlib.c).
fnty = ir.FunctionType(int64_t, (rnd_state_ptr_t, double))
fn = builder.function.module.get_or_insert_function(fnty,
"numba_poisson_ptrs")
ret = builder.call(fn, (state_ptr, lam))
builder.store(ret, retptr)
builder.branch(bbend)
builder.branch(bbcont)
builder.position_at_end(bbcont)
_random = np.random.random
_exp = math.exp
def poisson_impl(lam):
"""Numpy's algorithm for poisson() on small *lam*.
This method is invoked only if the parameter lambda of the
distribution is small ( < 10 ). The algorithm used is described
in "Knuth, D. 1969. 'Seminumerical Algorithms. The Art of
Computer Programming' vol 2.
"""
if lam < 0.0:
raise ValueError("poisson(): lambda < 0")
if lam == 0.0:
return 0
enlam = _exp(-lam)
X = 0
prod = 1.0
while 1:
U = _random()
prod *= U
if prod <= enlam:
return X
X += 1
if len(args) == 0:
sig = signature(sig.return_type, types.float64)
args = (ir.Constant(double, 1.0),)
ret = context.compile_internal(builder, poisson_impl, sig, args)
builder.store(ret, retptr)
builder.branch(bbend)
builder.position_at_end(bbend)
return builder.load(retptr)
示例6: _emit_python_wrapper
def _emit_python_wrapper(self, llvm_module):
# Figure out the Python C API module creation function, and
# get a LLVM function for it.
create_module_fn = llvm_module.add_function(*self.module_create_definition)
create_module_fn.linkage = lc.LINKAGE_EXTERNAL
# Define a constant string for the module name.
mod_name_init = lc.Constant.stringz(self.module_name)
mod_name_const = llvm_module.add_global_variable(mod_name_init.type, '.module_name')
mod_name_const.initializer = mod_name_init
mod_name_const.linkage = lc.LINKAGE_INTERNAL
mod_def_base_init = lc.Constant.struct(
(lt._pyobject_head_init, # PyObject_HEAD
lc.Constant.null(self.m_init_ty), # m_init
lc.Constant.null(lt._llvm_py_ssize_t), # m_index
lc.Constant.null(lt._pyobject_head_p), # m_copy
)
)
mod_def_base = llvm_module.add_global_variable(mod_def_base_init.type, '.module_def_base')
mod_def_base.initializer = mod_def_base_init
mod_def_base.linkage = lc.LINKAGE_INTERNAL
mod_def_init = lc.Constant.struct(
(mod_def_base_init, # m_base
lc.Constant.gep(mod_name_const, [ZERO, ZERO]), # m_name
lc.Constant.null(self._char_star), # m_doc
lc.Constant.int(lt._llvm_py_ssize_t, -1), # m_size
self._emit_method_array(llvm_module), # m_methods
lc.Constant.null(self.inquiry_ty), # m_reload
lc.Constant.null(self.traverseproc_ty), # m_traverse
lc.Constant.null(self.inquiry_ty), # m_clear
lc.Constant.null(self.freefunc_ty) # m_free
)
)
# Define a constant string for the module name.
mod_def = llvm_module.add_global_variable(mod_def_init.type, '.module_def')
mod_def.initializer = mod_def_init
mod_def.linkage = lc.LINKAGE_INTERNAL
# Define the module initialization function.
mod_init_fn = llvm_module.add_function(*self.module_init_definition)
entry = mod_init_fn.append_basic_block('Entry')
builder = lc.Builder.new(entry)
mod = builder.call(create_module_fn,
(mod_def,
lc.Constant.int(lt._int32, sys.api_version)))
# Test if module has been created correctly.
# (XXX for some reason comparing with the NULL constant fails llvm
# with an assertion in pydebug mode)
with cgutils.ifthen(builder, cgutils.is_null(builder, mod)):
builder.ret(NULL.bitcast(mod_init_fn.type.pointee.return_type))
builder.ret(mod)
示例7: _randrange_impl
def _randrange_impl(context, builder, start, stop, step, state):
state_ptr = get_state_ptr(context, builder, state)
ty = stop.type
zero = ir.Constant(ty, 0)
one = ir.Constant(ty, 1)
nptr = cgutils.alloca_once(builder, ty, name="n")
# n = stop - start
builder.store(builder.sub(stop, start), nptr)
with cgutils.ifthen(builder, builder.icmp_signed('<', step, zero)):
# n = (n + step + 1) // step
w = builder.add(builder.add(builder.load(nptr), step), one)
n = builder.sdiv(w, step)
builder.store(n, nptr)
with cgutils.ifthen(builder, builder.icmp_signed('>', step, one)):
# n = (n + step - 1) // step
w = builder.sub(builder.add(builder.load(nptr), step), one)
n = builder.sdiv(w, step)
builder.store(n, nptr)
n = builder.load(nptr)
with cgutils.if_unlikely(builder, builder.icmp_signed('<=', n, zero)):
# n <= 0
msg = "empty range for randrange()"
context.call_conv.return_user_exc(builder, ValueError, (msg,))
fnty = ir.FunctionType(ty, [ty, cgutils.true_bit.type])
fn = builder.function.module.get_or_insert_function(fnty, "llvm.ctlz.%s" % ty)
nbits = builder.trunc(builder.call(fn, [n, cgutils.true_bit]), int32_t)
nbits = builder.sub(ir.Constant(int32_t, ty.width), nbits)
bbwhile = cgutils.append_basic_block(builder, "while")
bbend = cgutils.append_basic_block(builder, "while.end")
builder.branch(bbwhile)
builder.position_at_end(bbwhile)
r = get_next_int(context, builder, state_ptr, nbits)
r = builder.trunc(r, ty)
too_large = builder.icmp_signed('>=', r, n)
builder.cbranch(too_large, bbwhile, bbend)
builder.position_at_end(bbend)
return builder.add(start, builder.mul(r, step))
示例8: make_exception_switch
def make_exception_switch(self, api, builder, status):
"""
Handle user exceptions. Unserialize the exception info and raise it.
"""
code = status.code
# Handle user exceptions
with cgutils.ifthen(builder, status.is_user_exc):
exc = api.unserialize(status.excinfoptr)
with cgutils.if_likely(builder,
cgutils.is_not_null(builder, exc)):
api.raise_object(exc) # steals ref
builder.ret(api.get_null_object())
with cgutils.ifthen(builder, status.is_stop_iteration):
api.err_set_none("PyExc_StopIteration")
builder.ret(api.get_null_object())
msg = "unknown error in native function: %s" % self.fndesc.mangled_name
api.err_set_string("PyExc_SystemError", msg)
示例9: imp
def imp(context, builder, typ, value):
api = context.get_python_api(builder)
aval = api.object_getattr_string(value, attr)
with cgutils.ifthen(builder, cgutils.is_null(builder, aval)):
context.return_exc(builder)
if isinstance(atyp, types.Method):
return aval
else:
nativevalue = api.to_native_value(aval, atyp)
api.decref(aval)
return nativevalue
示例10: build_wrapper
def build_wrapper(self, api, builder, args, kws):
nargs = len(self.fndesc.args)
keywords = self.make_keywords(self.fndesc.args)
fmt = self.make_const_string("O" * nargs)
objs = [api.alloca_obj() for _ in range(nargs)]
parseok = api.parse_tuple_and_keywords(args, kws, fmt, keywords, *objs)
pred = builder.icmp(lc.ICMP_EQ, parseok, Constant.null(parseok.type))
with cgutils.if_unlikely(builder, pred):
builder.ret(api.get_null_object())
innerargs = []
for obj, ty in zip(objs, self.fndesc.argtypes):
#api.context.debug_print(builder, "%s -> %s" % (obj, ty))
#api.print_object(builder.load(obj))
val = api.to_native_arg(builder.load(obj), ty)
innerargs.append(val)
status, res = self.context.call_function(builder, self.func,
self.fndesc.restype,
self.fndesc.argtypes,
innerargs)
with cgutils.if_likely(builder, status.ok):
with cgutils.ifthen(builder, status.none):
api.return_none()
retval = api.from_native_return(res, self.fndesc.restype)
builder.ret(retval)
with cgutils.ifthen(builder, builder.not_(status.exc)):
# User exception raised
# TODO we will just raise a RuntimeError for now.
api.raise_native_error("error in native function: %s" %
self.fndesc.mangled_name)
builder.ret(api.get_null_object())
示例11: iternext
def iternext(self, context, builder, result):
zero = context.get_constant(int_type, 0)
countptr = self.count
count = builder.load(countptr)
is_valid = builder.icmp(lc.ICMP_SGT, count, zero)
result.set_valid(is_valid)
with cgutils.ifthen(builder, is_valid):
value = builder.load(self.iter)
result.yield_(value)
one = context.get_constant(int_type, 1)
builder.store(builder.sub(count, one), countptr)
builder.store(builder.add(value, self.step), self.iter)
示例12: iternext_enumerate
def iternext_enumerate(context, builder, sig, args, result):
[enumty] = sig.args
[enum] = args
enumcls = make_enumerate_cls(enumty)
enum = enumcls(context, builder, value=enum)
count = builder.load(enum.count)
ncount = builder.add(count, context.get_constant(types.intp, 1))
builder.store(ncount, enum.count)
srcres = call_iternext(context, builder, enumty.source_type, enum.iter)
is_valid = srcres.is_valid()
result.set_valid(is_valid)
with cgutils.ifthen(builder, is_valid):
srcval = srcres.yielded_value()
result.yield_(cgutils.make_anonymous_struct(builder, [count, srcval]))
示例13: int_divmod
def int_divmod(context, builder, x, y):
"""
Reference Objects/intobject.c
xdivy = x / y;
xmody = (long)(x - (unsigned long)xdivy * y);
/* If the signs of x and y differ, and the remainder is non-0,
* C89 doesn't define whether xdivy is now the floor or the
* ceiling of the infinitely precise quotient. We want the floor,
* and we have it iff the remainder's sign matches y's.
*/
if (xmody && ((y ^ xmody) < 0) /* i.e. and signs differ */) {
xmody += y;
--xdivy;
assert(xmody && ((y ^ xmody) >= 0));
}
*p_xdivy = xdivy;
*p_xmody = xmody;
"""
assert x.type == y.type
xdivy = builder.sdiv(x, y)
xmody = builder.srem(x, y) # Intel has divmod instruction
ZERO = Constant.null(y.type)
ONE = Constant.int(y.type, 1)
y_xor_xmody_ltz = builder.icmp(lc.ICMP_SLT, builder.xor(y, xmody), ZERO)
xmody_istrue = builder.icmp(lc.ICMP_NE, xmody, ZERO)
cond = builder.and_(xmody_istrue, y_xor_xmody_ltz)
bb1 = builder.basic_block
with cgutils.ifthen(builder, cond):
xmody_plus_y = builder.add(xmody, y)
xdivy_minus_1 = builder.sub(xdivy, ONE)
bb2 = builder.basic_block
resdiv = builder.phi(y.type)
resdiv.add_incoming(xdivy, bb1)
resdiv.add_incoming(xdivy_minus_1, bb2)
resmod = builder.phi(x.type)
resmod.add_incoming(xmody, bb1)
resmod.add_incoming(xmody_plus_y, bb2)
return resdiv, resmod
示例14: iternext_unituple
def iternext_unituple(context, builder, sig, args, result):
[tupiterty] = sig.args
[tupiter] = args
tupitercls = make_unituple_iter(tupiterty)
iterval = tupitercls(context, builder, value=tupiter)
tup = iterval.tuple
idxptr = iterval.index
idx = builder.load(idxptr)
count = context.get_constant(types.intp, tupiterty.unituple.count)
is_valid = builder.icmp(lc.ICMP_SLT, idx, count)
result.set_valid(is_valid)
with cgutils.ifthen(builder, is_valid):
getitem_sig = typing.signature(sig.return_type, tupiterty.unituple,
types.intp)
result.yield_(getitem_unituple(context, builder, getitem_sig, [tup, idx]))
nidx = builder.add(idx, context.get_constant(types.intp, 1))
builder.store(nidx, iterval.index)
示例15: return_optional_value
def return_optional_value(self, builder, retty, valty, value):
if valty == types.none:
self.return_native_none(builder)
elif retty == valty:
optcls = self.make_optional(retty)
optval = optcls(self, builder, value=value)
validbit = builder.trunc(optval.valid, lc.Type.int(1))
with cgutils.ifthen(builder, validbit):
self.return_value(builder, optval.data)
self.return_native_none(builder)
elif not isinstance(valty, types.Optional):
if valty != retty.type:
value = self.cast(builder, value, fromty=valty, toty=retty.type)
self.return_value(builder, value)
else:
raise NotImplementedError("returning {0} for {1}".format(valty, retty))