Add an Implementation¶
At the end of Add a Function, absdiff works on every ISA but at L3: the registers are copied to arrays and processed lane by lane. This tutorial makes it fast:
- a native implementation on NEON, which has a dedicated instruction (
vabdq): L0; - a generic implementation for the other ISAs, written once with other MIPP functions: L2;
- a generic implementation of the masked variants: L2.
An ISA that has no single instruction but can build the operation from a few of its own intrinsics gets a dedicated emulation (L1), shown at the end of this page.
| Level | Code made of | Templates | Entries |
|---|---|---|---|
| L0 Native | one intrinsic (the constants and reinterpretations it uses do not count: broadcast of a literal, all-true predicate, reinterpret) |
simd_ext/<isa>/<isa>_native_templates.json |
simd_ext/<isa>/<isa>_native_implems.json |
| L1 Dedicated emulation | several intrinsics of the ISA, possibly MIPP calls | simd_ext/<isa>/<isa>_emu_templates.json |
simd_ext/<isa>/<isa>_emu_implems.json |
| L2 Generic emulation | MIPP calls only, for all ISAs | helpers_headers/generic_emu_templates*.json |
helpers_headers/generic_emu_implems*.json |
The file sets the level: the same template placed in another file gets another level. All paths are relative to generator/.
Step 1: Native Implementation on NEON L0¶
An implementation is made of a template, the code, and an entry, which applies the template to a function and a set of datatypes.
NEON already has a template for the instructions that take two registers and return one, in simd_ext/neon/neon_native_templates.json:
"arith_2args": {
"format": "short",
"code": "{{ isa.prefix }}{{ instr_name }}_{{ isa_dt_par.data_ext }}(vd0.vd, vd1.vd);"
}
add, sub, max and min use it. Add the absdiff entry to simd_ext/neon/neon_native_implems.json:
"absdiff": [
{
"instr_name": "abdq",
"datatypes": ["float64"],
"template": "arith_2args",
"if": "defined(__aarch64__)"
},
{
"instr_name": "abdq",
"datatypes": ["float32", "int32", "int16", "int8", "uint32", "uint16", "uint8"],
"template": "arith_2args"
}
]
vabdq_f64exists on AArch64 only, hence theifcondition. On ARMv7, the resolver looks for another candidate forfloat64.- NEON has no
vabdqfor 64-bit integers:int64anduint64are left out, the generic implementation of step 2 covers them.
After ./gen_mipp_headers.py, the NEON header contains:
#if defined(__aarch64__)
static inline vd_neon_float64_m1_t mipp_neon_absdiff_float64_m1(const vd_neon_float64_m1_t vd0, const vd_neon_float64_m1_t vd1) {
// Level 0 (Native Hardware)
vd_neon_float64_m1_t res;
res.vd = vabdq_f64(vd0.vd, vd1.vd);
return res;
}
#endif
Templates¶
A template has a format and a code:
short:codeis one expression. The generator declaresres, assigns the expression tores.vdand returnsres, as above.long:codeis the whole function body, as a list of lines.
The code is rendered by Jinja2 with these variables:
| Variable | Content |
|---|---|
isa |
The ISA descriptor (<isa>_isa.json): isa.prefix (v on NEON, _mm on SSE, _mm256 on AVX), isa.name, isa.size, ... |
instr_name |
The instr_name of the entry. |
isa_dt_par, isa_dt_ret |
The datatype entry of the ISA descriptor, for the parameter and the return types: data_ext (f32, s32, ps, epi32, ...), reg, msk, ... |
dt_par, dt_ret |
The generic description of the datatypes, from datatypes in tools.py: name, n_bits, category, cstd, log2_n_bytes (log2 of the size in bytes: a shift instead of a multiplication by sizeof), ... |
cstdint_ret |
The C type of the return datatype, the cstd of dt_ret (int32_t, float32_t, ...). |
func_name |
The MIPP function name (absdiff), useful in templates shared by several functions. |
lmul, mask_kind |
The LMUL and the mask variant being generated. |
compress_lut(lanes, units, fill) |
A function (helpers_headers/luts.py) that computes the constant table of a compress by permutation and returns its C initializer: static const uint8_t lut[16][16] = {{ compress_lut(lanes=4, units=4, fill=128) }}; (SSSE3 pshufb, 32-bit lanes). The tables of the templates are computed there at generation time, not written in the JSON files. The same file gives iota(n, start), iota_mod(n, m) and iota_block(n, m) (lane indices, lane in a block, first lane of the block). |
The separator between prefix and name belongs to the template: SSE templates write {{ isa.prefix }}_{{ instr_name }}, NEON ones {{ isa.prefix }}{{ instr_name }}. Inside the parameters, vd0.vd is the native register wrapped by the MIPP type vd_neon_float32_m1_t. The code may also call MIPP functions through the templating DSL (%max<tp>%(vd0, vd1)), as the L1 and L2 templates do.
An entry can also hold its template inline ("template": { "format": ..., "code": ... }) instead of a name.
The bodies used when an integer argument is a constant (immediate instructions: palignr, ext, pshufd...) are in <isa>_imm_templates.json and <isa>_imm_implems.json, in the same format, with the variable imm: see Immediate Versions.
A template shared by functions that differ by more than an intrinsic name can take several fields in instr_name, separated by | (a comma would cut the arguments of a call), and read them with Jinja set, on a line of its own: the %...% markers of the templating DSL must not share a line with a Jinja tag. For example, complex_cmla of NEON and SVE writes cmul, cmulconj and cfmadd as two cmla instructions, from "ZERO|90|vd0.vd|vd1.vd" (the accumulator, ZERO for a zero register; the rotation of the second instruction; the two operands):
{% set f = instr_name.split('|') -%}{%- set acc = f[0] if f[0] != 'ZERO' else (...) -%}{%- set rot, x, y = f[1], f[2], f[3] -%}
Step 2: Generic Implementation L2¶
\(|a - b| = \max(a, b) - \min(a, b)\) holds for every datatype, including unsigned ones, and uses three MIPP functions. Write it once in helpers_headers/generic_emu_templates.json:
"absdiff": {
"format": "long",
"code": [
"%vd<tp>% hi = %max<tp>%(vd0, vd1);",
"%vd<tp>% lo = %min<tp>%(vd0, vd1);",
"return %sub<tp>%(hi, lo);"
]
}
and the entry in helpers_headers/generic_emu_implems.json:
%vd<tp>% is the register type and %max<tp>% the max function of the ISA being generated, for the current datatype and LMUL. On AVX the template becomes:
static inline vd_avx_float32_m1_t mipp_avx_absdiff_float32_m1(const vd_avx_float32_m1_t vd0, const vd_avx_float32_m1_t vd1) {
// Level 2 (Generic Emulation)
vd_avx_float32_m1_t hi = mipp_avx_max_float32_m1(vd0, vd1);
vd_avx_float32_m1_t lo = mipp_avx_min_float32_m1(vd0, vd1);
return mipp_avx_sub_float32_m1(hi, lo);
}
On NEON, the L0 entries of step 1 have priority over the generic template: it only fills the gaps (int64 and uint64).
template_ref names a template of another file, with a prefix:
| Prefix | Templates | Entries |
|---|---|---|
tpl_generic_emu. |
generic_emu_templates.json |
generic_emu_implems.json |
tpl_mask_generic_emu. |
generic_emu_templates_mask.json |
generic_emu_implems_mask.json |
tpl_horiz_lmul_generic_emu. |
generic_emu_templates_lmulh.json |
generic_emu_implems_lmulh.json |
The lmulh files combine the registers of an LMUL > 1 group for the horizontal functions (reductions) and the lane-crossing functions (reverse, slide, ziplo...), whose result cannot be computed on each register of the group alone.
A generic template is only as fast as its dependencies
The resolver uses an L2 template only where the functions it calls exist. When one of them is itself an L3 fallback, the scalar fallback of absdiff is used instead, or the generic code is reported as L3 (see Invariants). Check the result with the methods of step 4.
Step 3: Masked Variants L2¶
At this point mipp_neon_absdiff_float32_maskz_m1 is still L3. The masked variants have their own candidates, selected with the variant field (m, z, s). generic_emu_templates_mask.json provides templates for any function with two register arguments, which compute the unmasked function then apply the mask:
"binary_maskz_all_datatypes": {
"format": "long",
"code": [
"%vd<tp>% op = %{{func_name}}<tp>%(vd0, vd1);",
"{% if isa.get('hw_mask', False) %}// hardware masks: a selection with zeros, which the compilers can fold into a zero-masked instruction",
"%vd<tp>% res = %select<tp>%(vm0, op, %set0<tp>%());",
"{%- else -%}",
"%vd<tp>% tmp = %tovd<tp>%(vm0);",
"%vd<tp>% res = %andb<tp>%(op, tmp);{% endif %}",
"return res;"
]
}
On the ISAs with hardware masks (hw_mask: AVX-512, SVE, RVV), the inactive lanes are zeroed by a selection: GCC and clang fold select(m, op, set0()) into the zero-masked instruction when the last operation of op has one (vaddps zmm0{k1}{z}), and it costs one instruction instead of two (tovd then andb) on SVE and RVV. Elsewhere a mask is a register of all-ones or zero lanes, and andb with it is the cheapest.
Reuse them in helpers_headers/generic_emu_implems_mask.json, as add, max or min do:
"absdiff": [
{
"instr_name": "absdiff",
"datatypes": "all_datatypes",
"variant": "m",
"template_ref": "tpl_mask_generic_emu.binary_mask_all_datatypes"
},
{
"instr_name": "absdiff",
"datatypes": "all_datatypes",
"variant": "z",
"template_ref": "tpl_mask_generic_emu.binary_maskz_all_datatypes"
},
{
"instr_name": "absdiff",
"datatypes": "all_datatypes",
"variant": "s",
"template_ref": "tpl_mask_generic_emu.binary_masks_all_datatypes"
}
]
The masked variants then follow the level of the unmasked one. An ISA with native masked instructions adds entries with a variant field in its own *_native_implems.json instead, as AVX-512, SVE (predicated instructions: svadd_f32_m, svadd_f32_z) and RVV do.
Step 4: Check the Levels¶
After ./gen_mipp_headers.py:
- every resolved function starts with a
// Level Ncomment, ininclude/mipp/internal/simd_ext/<isa>/c/functions/<category>/; the LMUL 1 aliases without suffix and the software LMUL wrappers (_m2,_m4,_m8, which call the function of half the LMUL) have none (Summary Table); - the summary table printed at the end of
gen_mipp_headers.pygives the distribution of the levels per ISA; - after
./gen_mipp_docs.py, the Function Support page ofabsdiffand the API Explorer show the level of each datatype, variant and ISA.
The absdiff of this tutorial (LMUL 1, unmasked) gives:
| ISA | L0 | L2 | L3 |
|---|---|---|---|
| NEON | float32, 8/16/32-bit integers; float64 on AArch64 |
int64, uint64 |
float64 on ARMv7 |
| AVX | all the datatypes | ||
| SSE | all the datatypes (from SSE2 on) | every datatype but float32 without SSE2 |
The masked variants are L2 wherever the unmasked function is L0 or L2, and L3 elsewhere. On x86 from SSE2 on, absdiff is L2 for every datatype: where the ISA has no max / min instruction (64-bit integers before AVX-512, some 8/16/32-bit integers before SSE4.1), max and min are themselves dedicated or generic emulations (compare and select), not scalar fallbacks.
Then run the tests on each target you changed (see Setup). On NEON the first run fails for int32 and int64: the test properties of absdiff must keep the signed differences in range.
Dedicated Emulation L1¶
When an ISA has no instruction for an operation but can build it from a few of its own intrinsics, faster than the generic code, the implementation goes to simd_ext/<isa>/<isa>_emu_templates.json and <isa>_emu_implems.json. The format is the same as for L0.
ARMv7 NEON has no floating-point division. neon_emu_templates.json computes a reciprocal estimate, refines it with two Newton-Raphson steps, then multiplies with the MIPP mul:
"arith_2args_recp": {
"format": "long",
"code": [
"%vd<tp>% recp;",
"recp.vd = {{ isa.prefix }}{{ instr_name }}_{{ isa_dt_par.data_ext }}(vd1.vd);",
"recp.vd = vmulq_{{ isa_dt_par.data_ext }}(recp.vd, vrecpsq_{{ isa_dt_par.data_ext }}(vd1.vd, recp.vd));",
"recp.vd = vmulq_{{ isa_dt_par.data_ext }}(recp.vd, vrecpsq_{{ isa_dt_par.data_ext }}(vd1.vd, recp.vd));",
"%vd<tp>% res = %mul<tp>%(vd0, recp);",
"return res;"
]
}
The entry in neon_emu_implems.json is restricted to 32-bit Arm, since AArch64 has a native vdivq_f32:
"div": [
{
"instr_name": "recpeq",
"datatypes": ["float32"],
"template": "arith_2args_recp",
"if": "!defined(__aarch64__)"
}
]
The levels audit checks that each entry is in the right file: a native entry must contain exactly one intrinsic and no MIPP call (the broadcasts of constants, the constant predicates and the reinterpretations do not count, see Audits), a dedicated emulation several intrinsics or intrinsics and MIPP calls. Code without any intrinsic belongs to the generic files. When an exception is justified, set "skip_audit_level": true and explain it in skip_audit_level_reason.
Fields of an Entry¶
The fields are the same in all the *_implems.json files. The complete reference is Implementations.
| Field | Use |
|---|---|
datatypes |
Required. Alias or list of datatypes (datatype pairs for conversions). |
template / template_ref |
Required, one of them. Template name of the ISA's templates file, inline template, or reference to a generic template with its prefix. |
instr_name |
String passed to the template as instr_name. |
if |
Preprocessor condition. The entry is emitted under #if <condition>; the rest of the condition space goes to the next candidate. |
variant |
m, z or s: the entry implements this mask variant (without it, the unmasked variant u). |
mode |
horiz_lmul: the entry implements an LMUL > 1 horizontal or lane-crossing function (generic_emu_implems_lmulh.json). It is not a mask variant. |
preferred_simd_ext |
ISA or list of ISAs. Among the candidates of the same level, the entry is tried first on these ISAs and last on the others. Used to choose between several generic entries. |
simd_size |
Register size or list of sizes (in bits, after LMUL) for which the entry applies, e.g. 128. |
skip_audit_level, skip_audit_level_reason |
Disable the levels audit for this entry, with a reason. |
Next Step¶
Add an ISA creates a new target from scratch. To understand how the resolver handles conditions and dependencies, see Code Generation.