1""" This module provides the unsafe things for targets/numbers.py
2"""
3from numba.core import types, errors
4from numba.core.extending import intrinsic
5
6from llvmlite import ir
7
8
9@intrinsic
10def viewer(tyctx, val, viewty):
11 """ Bitcast a scalar 'val' to the given type 'viewty'. """
12 bits = val.bitwidth
13 if isinstance(viewty.dtype, types.Integer):
14 bitcastty = ir.IntType(bits)
15 elif isinstance(viewty.dtype, types.Float):
16 bitcastty = ir.FloatType() if bits == 32 else ir.DoubleType()
17 else:
18 assert 0, "unreachable"
19
20 def codegen(cgctx, builder, typ, args):
21 flt = args[0]
22 return builder.bitcast(flt, bitcastty)
23 retty = viewty.dtype
24 sig = retty(val, viewty)
25 return sig, codegen
26
27
28@intrinsic
29def trailing_zeros(typeingctx, src):
30 """Counts trailing zeros in the binary representation of an integer."""
31 if not isinstance(src, types.Integer):
32 msg = ("trailing_zeros is only defined for integers, but value passed "
33 f"was '{src}'.")
34 raise errors.NumbaTypeError(msg)
35
36 def codegen(context, builder, signature, args):
37 [src] = args
38 return builder.cttz(src, ir.Constant(ir.IntType(1), 0))
39 return src(src), codegen
40
41
42@intrinsic
43def leading_zeros(typeingctx, src):
44 """Counts leading zeros in the binary representation of an integer."""
45 if not isinstance(src, types.Integer):
46 msg = ("leading_zeros is only defined for integers, but value passed "
47 f"was '{src}'.")
48 raise errors.NumbaTypeError(msg)
49
50 def codegen(context, builder, signature, args):
51 [src] = args
52 return builder.ctlz(src, ir.Constant(ir.IntType(1), 0))
53 return src(src), codegen