本文整理汇总了Python中numba.cgutils.alloca_once函数的典型用法代码示例。如果您正苦于以下问题:Python alloca_once函数的具体用法?Python alloca_once怎么用?Python alloca_once使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了alloca_once函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: int_power_func_body
def int_power_func_body(context, builder, x, y):
pcounter = cgutils.alloca_once(builder, y.type)
presult = cgutils.alloca_once(builder, x.type)
result = Constant.int(x.type, 1)
counter = y
builder.store(counter, pcounter)
builder.store(result, presult)
bbcond = cgutils.append_basic_block(builder, ".cond")
bbbody = cgutils.append_basic_block(builder, ".body")
bbexit = cgutils.append_basic_block(builder, ".exit")
del counter
del result
builder.branch(bbcond)
with cgutils.goto_block(builder, bbcond):
counter = builder.load(pcounter)
ONE = Constant.int(counter.type, 1)
ZERO = Constant.null(counter.type)
builder.store(builder.sub(counter, ONE), pcounter)
pred = builder.icmp(lc.ICMP_SGT, counter, ZERO)
builder.cbranch(pred, bbbody, bbexit)
with cgutils.goto_block(builder, bbbody):
result = builder.load(presult)
builder.store(builder.mul(result, x), presult)
builder.branch(bbcond)
builder.position_at_end(bbexit)
return builder.load(presult)
示例2: string_as_string_and_size
def string_as_string_and_size(self, strobj):
"""
Returns a tuple of ``(ok, buffer, length)``.
The ``ok`` is i1 value that is set if ok.
The ``buffer`` is a i8* of the output buffer.
The ``length`` is a i32/i64 (py_ssize_t) of the length of the buffer.
"""
p_length = cgutils.alloca_once(self.builder, self.py_ssize_t)
if PYVERSION >= (3, 0):
fnty = Type.function(self.cstring, [self.pyobj,
self.py_ssize_t.as_pointer()])
fname = "PyUnicode_AsUTF8AndSize"
fn = self._get_function(fnty, name=fname)
buffer = self.builder.call(fn, [strobj, p_length])
ok = self.builder.icmp_unsigned('!=',
ir.Constant(buffer.type, None),
buffer)
else:
fnty = Type.function(lc.Type.int(), [self.pyobj,
self.cstring.as_pointer(),
self.py_ssize_t.as_pointer()])
fname = "PyString_AsStringAndSize"
fn = self._get_function(fnty, name=fname)
# Allocate space for the output parameters
p_buffer = cgutils.alloca_once(self.builder, self.cstring)
status = self.builder.call(fn, [strobj, p_buffer, p_length])
negone = ir.Constant(status.type, -1)
ok = self.builder.icmp_signed("!=", status, negone)
buffer = self.builder.load(p_buffer)
return (ok, buffer, self.builder.load(p_length))
示例3: call_function
def call_function(self, builder, callee, resty, argtys, args, env=None):
"""
Call the Numba-compiled *callee*.
"""
if env is None:
# This only works with functions that don't use the environment
# (nopython functions).
env = cgutils.get_null_value(PYOBJECT)
is_generator_function = isinstance(resty, types.Generator)
retty = self._get_return_argument(callee).type.pointee
retvaltmp = cgutils.alloca_once(builder, retty)
# initialize return value to zeros
builder.store(cgutils.get_null_value(retty), retvaltmp)
excinfoptr = cgutils.alloca_once(builder, ir.PointerType(excinfo_t),
name="excinfo")
arginfo = self.context.get_arg_packer(argtys)
args = list(arginfo.as_arguments(builder, args))
realargs = [retvaltmp, excinfoptr, env] + args
code = builder.call(callee, realargs)
status = self._get_return_status(builder, code,
builder.load(excinfoptr))
if is_generator_function:
retval = retvaltmp
else:
retval = builder.load(retvaltmp)
out = self.context.get_returned_value(builder, resty, retval)
return status, out
示例4: init_specific
def init_specific(self, context, builder, arrty, arr):
zero = context.get_constant(types.intp, 0)
data = arr.data
ndim = arrty.ndim
shapes = cgutils.unpack_tuple(builder, arr.shape, ndim)
indices = cgutils.alloca_once(builder, zero.type,
size=context.get_constant(types.intp,
arrty.ndim))
pointers = cgutils.alloca_once(builder, data.type,
size=context.get_constant(types.intp,
arrty.ndim))
strides = cgutils.unpack_tuple(builder, arr.strides, ndim)
exhausted = cgutils.alloca_once_value(builder, cgutils.false_byte)
# Initialize indices and pointers with their start values.
for dim in range(ndim):
idxptr = cgutils.gep(builder, indices, dim)
ptrptr = cgutils.gep(builder, pointers, dim)
builder.store(data, ptrptr)
builder.store(zero, idxptr)
# 0-sized dimensions really indicate an empty array,
# but we have to catch that condition early to avoid
# a bug inside the iteration logic (see issue #846).
dim_size = shapes[dim]
dim_is_empty = builder.icmp(lc.ICMP_EQ, dim_size, zero)
with cgutils.if_unlikely(builder, dim_is_empty):
builder.store(cgutils.true_byte, exhausted)
self.indices = indices
self.pointers = pointers
self.exhausted = exhausted
示例5: impl_iterator_iternext
def impl_iterator_iternext(context, builder, sig, args, result):
iter_type = sig.args[0]
it = context.make_helper(builder, iter_type, args[0])
p2p_bytes = ll_bytes.as_pointer()
iternext_fnty = ir.FunctionType(
ll_status,
[ll_bytes, p2p_bytes, p2p_bytes]
)
iternext = builder.module.get_or_insert_function(
iternext_fnty,
name='numba_dict_iter_next',
)
key_raw_ptr = cgutils.alloca_once(builder, ll_bytes)
val_raw_ptr = cgutils.alloca_once(builder, ll_bytes)
status = builder.call(iternext, (it.state, key_raw_ptr, val_raw_ptr))
# TODO: no handling of error state i.e. mutated dictionary
# all errors are treated as exhausted iterator
is_valid = builder.icmp_unsigned('==', status, status.type(0))
result.set_valid(is_valid)
with builder.if_then(is_valid):
yield_type = iter_type.yield_type
key_ty, val_ty = iter_type.parent.keyvalue_type
dm_key = context.data_model_manager[key_ty]
dm_val = context.data_model_manager[val_ty]
key_ptr = builder.bitcast(
builder.load(key_raw_ptr),
dm_key.get_data_type().as_pointer(),
)
val_ptr = builder.bitcast(
builder.load(val_raw_ptr),
dm_val.get_data_type().as_pointer(),
)
key = dm_key.load_from_data_pointer(builder, key_ptr)
val = dm_val.load_from_data_pointer(builder, val_ptr)
# All dict iterators use this common implementation.
# Their differences are resolved here.
if isinstance(iter_type.iterable, DictItemsIterableType):
# .items()
tup = context.make_tuple(builder, yield_type, [key, val])
result.yield_(tup)
elif isinstance(iter_type.iterable, DictKeysIterableType):
# .keys()
result.yield_(key)
elif isinstance(iter_type.iterable, DictValuesIterableType):
# .values()
result.yield_(val)
else:
# unreachable
raise AssertionError('unknown type: {}'.format(iter_type.iterable))
示例6: _gauss_impl
def _gauss_impl(context, builder, sig, args, state):
# The type for all computations (either float or double)
ty = sig.return_type
llty = context.get_data_type(ty)
state_ptr = get_state_ptr(context, builder, state)
_random = {"py": random.random,
"np": np.random.random}[state]
ret = cgutils.alloca_once(builder, llty, name="result")
gauss_ptr = get_gauss_ptr(builder, state_ptr)
has_gauss_ptr = get_has_gauss_ptr(builder, state_ptr)
has_gauss = cgutils.is_true(builder, builder.load(has_gauss_ptr))
with builder.if_else(has_gauss) as (then, otherwise):
with then:
# if has_gauss: return it
builder.store(builder.load(gauss_ptr), ret)
builder.store(const_int(0), has_gauss_ptr)
with otherwise:
# if not has_gauss: compute a pair of numbers using the Box-Muller
# transform; keep one and return the other
pair = context.compile_internal(builder,
_gauss_pair_impl(_random),
signature(types.UniTuple(ty, 2)),
())
first, second = cgutils.unpack_tuple(builder, pair, 2)
builder.store(first, gauss_ptr)
builder.store(second, ret)
builder.store(const_int(1), has_gauss_ptr)
mu, sigma = args
return builder.fadd(mu,
builder.fmul(sigma, builder.load(ret)))
示例7: iternext_zip
def iternext_zip(context, builder, sig, args, result):
[zip_type] = sig.args
[zipobj] = args
zipobj = context.make_helper(builder, zip_type, value=zipobj)
if len(zipobj) == 0:
# zip() is an empty iterator
result.set_exhausted()
return
p_ret_tup = cgutils.alloca_once(builder,
context.get_value_type(zip_type.yield_type))
p_is_valid = cgutils.alloca_once_value(builder, value=cgutils.true_bit)
for i, (iterobj, srcty) in enumerate(zip(zipobj, zip_type.source_types)):
is_valid = builder.load(p_is_valid)
# Avoid calling the remaining iternext if a iterator has been exhausted
with builder.if_then(is_valid):
srcres = call_iternext(context, builder, srcty, iterobj)
is_valid = builder.and_(is_valid, srcres.is_valid())
builder.store(is_valid, p_is_valid)
val = srcres.yielded_value()
ptr = cgutils.gep_inbounds(builder, p_ret_tup, 0, i)
builder.store(val, ptr)
is_valid = builder.load(p_is_valid)
result.set_valid(is_valid)
with builder.if_then(is_valid):
result.yield_(builder.load(p_ret_tup))
示例8: alloc_timedelta_result
def alloc_timedelta_result(builder, name='ret'):
"""
Allocate a NaT-initialized datetime64 (or timedelta64) result slot.
"""
ret = cgutils.alloca_once(builder, TIMEDELTA64, name=name)
builder.store(NAT, ret)
return ret
示例9: to_native_optional
def to_native_optional(self, obj, typ):
"""
Convert object *obj* to a native optional structure.
"""
noneval = self.context.make_optional_none(self.builder, typ.type)
is_not_none = self.builder.icmp(lc.ICMP_NE, obj, self.borrow_none())
retptr = cgutils.alloca_once(self.builder, noneval.type)
errptr = cgutils.alloca_once_value(self.builder, cgutils.false_bit)
with cgutils.ifelse(self.builder, is_not_none) as (then, orelse):
with then:
native = self.to_native_value(obj, typ.type)
just = self.context.make_optional_value(self.builder,
typ.type, native.value)
self.builder.store(just, retptr)
self.builder.store(native.is_error, errptr)
with orelse:
self.builder.store(ir.Constant(noneval.type, ir.Undefined),
retptr)
self.builder.store(noneval, retptr)
if native.cleanup is not None:
def cleanup():
with cgutils.ifthen(self.builder, is_not_none):
native.cleanup()
else:
cleanup = None
ret = self.builder.load(retptr)
return NativeValue(ret, is_error=self.builder.load(errptr),
cleanup=cleanup)
示例10: dot_2_vv
def dot_2_vv(context, builder, sig, args, conjugate=False):
"""
np.dot(vector, vector)
np.vdot(vector, vector)
"""
aty, bty = sig.args
dtype = sig.return_type
a = make_array(aty)(context, builder, args[0])
b = make_array(bty)(context, builder, args[1])
n, = cgutils.unpack_tuple(builder, a.shape)
def check_args(a, b):
m, = a.shape
n, = b.shape
if m != n:
raise ValueError("incompatible array sizes for np.dot(a, b) "
"(vector * vector)")
context.compile_internal(builder, check_args,
signature(types.none, *sig.args), args)
check_c_int(context, builder, n)
out = cgutils.alloca_once(builder, context.get_value_type(dtype))
call_xxdot(context, builder, conjugate, dtype, n, a.data, b.data, out)
return builder.load(out)
示例11: codegen
def codegen(context, builder, sig, args):
fnty = ir.FunctionType(
ll_status,
[ll_dict_type, ll_bytes, ll_hash, ll_bytes, ll_bytes],
)
[d, key, hashval, val] = args
[td, tkey, thashval, tval] = sig.args
fn = builder.module.get_or_insert_function(fnty, name='numba_dict_insert')
dm_key = context.data_model_manager[tkey]
dm_val = context.data_model_manager[tval]
data_key = dm_key.as_data(builder, key)
data_val = dm_val.as_data(builder, val)
ptr_key = cgutils.alloca_once_value(builder, data_key)
ptr_val = cgutils.alloca_once_value(builder, data_val)
# TODO: the ptr_oldval is not used. needed for refct
ptr_oldval = cgutils.alloca_once(builder, data_val.type)
dp = _dict_get_data(context, builder, td, d)
status = builder.call(
fn,
[
dp,
_as_bytes(builder, ptr_key),
hashval,
_as_bytes(builder, ptr_val),
_as_bytes(builder, ptr_oldval),
],
)
return status
示例12: to_native_arg
def to_native_arg(self, obj, typ):
if isinstance(typ, types.Record):
# Generate a dummy integer type that has the size of Py_buffer
dummy_py_buffer_type = Type.int(_helperlib.py_buffer_size * 8)
# Allocate the Py_buffer
py_buffer = cgutils.alloca_once(self.builder, dummy_py_buffer_type)
# Zero-fill the py_buffer. where the obj field in Py_buffer is NULL
# PyBuffer_Release has no effect.
zeroed_buffer = lc.Constant.null(dummy_py_buffer_type)
self.builder.store(zeroed_buffer, py_buffer)
buf_as_voidptr = self.builder.bitcast(py_buffer, self.voidptr)
ptr = self.extract_record_data(obj, buf_as_voidptr)
with cgutils.if_unlikely(self.builder,
cgutils.is_null(self.builder, ptr)):
self.builder.ret(ptr)
ltyp = self.context.get_value_type(typ)
val = cgutils.init_record_by_ptr(self.builder, ltyp, ptr)
def dtor():
self.release_record_buffer(buf_as_voidptr)
else:
val = self.to_native_value(obj, typ)
def dtor():
pass
return val, dtor
示例13: timedelta_floor_div_timedelta
def timedelta_floor_div_timedelta(context, builder, sig, args):
[va, vb] = args
[ta, tb] = sig.args
ll_ret_type = context.get_value_type(sig.return_type)
not_nan = are_not_nat(builder, [va, vb])
ret = cgutils.alloca_once(builder, ll_ret_type, name='ret')
zero = Constant.int(ll_ret_type, 0)
one = Constant.int(ll_ret_type, 1)
builder.store(zero, ret)
with cgutils.if_likely(builder, not_nan):
va, vb = normalize_timedeltas(context, builder, va, vb, ta, tb)
# is the denominator zero or NaT?
denom_ok = builder.not_(builder.icmp_signed('==', vb, zero))
with cgutils.if_likely(builder, denom_ok):
# is either arg negative?
vaneg = builder.icmp_signed('<', va, zero)
neg = builder.or_(vaneg, builder.icmp_signed('<', vb, zero))
with builder.if_else(neg) as (then, otherwise):
with then: # one or more value negative
with builder.if_else(vaneg) as (negthen, negotherwise):
with negthen:
top = builder.sub(va, one)
div = builder.sdiv(top, vb)
builder.store(div, ret)
with negotherwise:
top = builder.add(va, one)
div = builder.sdiv(top, vb)
builder.store(div, ret)
with otherwise:
div = builder.sdiv(va, vb)
builder.store(div, ret)
res = builder.load(ret)
return impl_ret_untracked(context, builder, sig.return_type, res)
示例14: get_constant_generic
def get_constant_generic(self, builder, ty, val):
"""
Return a LLVM constant representing value *val* of Numba type *ty*.
"""
if isinstance(ty, types.ExternalFunctionPointer):
ptrty = self.get_function_pointer_type(ty)
ptrval = ty.get_pointer(val)
return builder.inttoptr(self.get_constant(types.intp, ptrval),
ptrty)
elif isinstance(ty, types.Array):
return self.make_constant_array(builder, ty, val)
elif isinstance(ty, types.Dummy):
return self.get_dummy_value()
elif self.is_struct_type(ty):
struct = self.get_constant_struct(builder, ty, val)
if isinstance(ty, types.Record):
ptrty = self.data_model_manager[ty].get_data_type()
ptr = cgutils.alloca_once(builder, ptrty)
builder.store(struct, ptr)
return ptr
return struct
else:
return self.get_constant(ty, val)
示例15: impl_dict_getiter
def impl_dict_getiter(context, builder, sig, args):
"""Implement iter(Dict). Semantically equivalent to dict.keys()
"""
[td] = sig.args
[d] = args
iterablety = types.DictKeysIterableType(td)
it = context.make_helper(builder, iterablety.iterator_type)
fnty = ir.FunctionType(
ir.VoidType(),
[ll_dictiter_type, ll_dict_type],
)
fn = builder.module.get_or_insert_function(fnty, name='numba_dict_iter')
proto = ctypes.CFUNCTYPE(ctypes.c_size_t)
dictiter_sizeof = proto(_helperlib.c_helpers['dict_iter_sizeof'])
state_type = ir.ArrayType(ir.IntType(8), dictiter_sizeof())
pstate = cgutils.alloca_once(builder, state_type, zfill=True)
it.state = _as_bytes(builder, pstate)
it.parent = d
dp = _dict_get_data(context, builder, iterablety.parent, args[0])
builder.call(fn, [it.state, dp])
return impl_ret_borrowed(
context,
builder,
sig.return_type,
it._getvalue(),
)