Merge pull request #146 from hdevalence/refactor-avx2

Refactor AVX2 code and remove its "yolocrypto" designation
This commit is contained in:
Henry de Valence 2018-06-21 16:39:48 -07:00 committed by GitHub
commit 3d14343d61
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
11 changed files with 1032 additions and 752 deletions

View file

@ -10,7 +10,7 @@ env:
# Tests the u64 backend # Tests the u64 backend
- TEST_COMMAND=test EXTRA_FLAGS='--no-default-features' FEATURES='std u64_backend' - TEST_COMMAND=test EXTRA_FLAGS='--no-default-features' FEATURES='std u64_backend'
# Tests the avx2 backend # Tests the avx2 backend
- TEST_COMMAND=test EXTRA_FLAGS='--no-default-features' FEATURES='std avx2_backend yolocrypto' - TEST_COMMAND=test EXTRA_FLAGS='--no-default-features' FEATURES='std avx2_backend'
# Tests serde support and default feature selection # Tests serde support and default feature selection
- TEST_COMMAND=test EXTRA_FLAGS='' FEATURES='serde' - TEST_COMMAND=test EXTRA_FLAGS='' FEATURES='serde'
# Tests building without std. We have to select a backend, so we select the one # Tests building without std. We have to select a backend, so we select the one
@ -21,7 +21,7 @@ matrix:
exclude: exclude:
# Test the avx2 backend only on nightly # Test the avx2 backend only on nightly
- rust: stable - rust: stable
env: TEST_COMMAND=test EXTRA_FLAGS='--no-default-features' FEATURES='std avx2_backend yolocrypto' env: TEST_COMMAND=test EXTRA_FLAGS='--no-default-features' FEATURES='std avx2_backend'
# Test no_std only on nightly. # Test no_std only on nightly.
- rust: stable - rust: stable
env: TEST_COMMAND=build EXTRA_FLAGS=--no-default-features FEATURES='u32_backend' env: TEST_COMMAND=build EXTRA_FLAGS=--no-default-features FEATURES='u32_backend'

View file

@ -1,4 +1,4 @@
FEATURES := nightly yolocrypto FEATURES := nightly yolocrypto avx2_backend
doc: doc:
cargo rustdoc --features "$(FEATURES)" -- --html-in-header docs/assets/rustdoc-include-katex-header.html cargo rustdoc --features "$(FEATURES)" -- --html-in-header docs/assets/rustdoc-include-katex-header.html

View file

@ -71,15 +71,17 @@ Curve arithmetic is implemented using one of the following backends:
* a `u32` backend using `u64` products; * a `u32` backend using `u64` products;
* a `u64` backend using `u128` products; * a `u64` backend using `u128` products;
* an experimental AVX2 backend, available using the `yolocrypto` feature when * an `avx2` backend using parallel formulas, available when compiling for a
compiling for a target with `target_feature=+avx2`. target with `target_feature=+avx2`.
By default the `u64` backend is selected. To select a specific backend, use: By default the `u64` backend is selected. To select a specific backend, use:
```sh ```sh
cargo build --no-default-features --features "std u32_backend" cargo build --no-default-features --features "std u32_backend"
cargo build --no-default-features --features "std u64_backend" cargo build --no-default-features --features "std u64_backend"
cargo build --no-default-features --features "std avx2_backend yolocrypto" cargo build --no-default-features --features "std avx2_backend"
``` ```
Crates using `curve25519-dalek` can either select a backend on behalf of their
users, or expose feature flags that control the `curve25519-dalek` backend.
Benchmarks are run using [`criterion.rs`][criterion]: Benchmarks are run using [`criterion.rs`][criterion]:
@ -88,7 +90,7 @@ Benchmarks are run using [`criterion.rs`][criterion]:
export RUSTFLAGS="-C target_cpu=native" export RUSTFLAGS="-C target_cpu=native"
cargo bench --no-default-features --features "std u32_backend" cargo bench --no-default-features --features "std u32_backend"
cargo bench --no-default-features --features "std u64_backend" cargo bench --no-default-features --features "std u64_backend"
cargo bench --no-default-features --features "std avx2_backend yolocrypto" cargo bench --no-default-features --features "std avx2_backend"
``` ```
# Contributing # Contributing
@ -117,7 +119,8 @@ to the Dalek race.*
Portions of this library were originally a port of [Adam Langley's Portions of this library were originally a port of [Adam Langley's
Golang ed25519 library](https://github.com/agl/ed25519), which was in Golang ed25519 library](https://github.com/agl/ed25519), which was in
turn a port of the reference `ref10` implementation. turn a port of the reference `ref10` implementation. Most of this code,
including the 32-bit field arithmetic, has since been rewritten.
The fast `u32` and `u64` scalar arithmetic was implemented by Andrew Moon, and The fast `u32` and `u64` scalar arithmetic was implemented by Andrew Moon, and
the addition chain for scalar inversion was provided by Brian Smith. the addition chain for scalar inversion was provided by Brian Smith.

View file

@ -1,5 +1,5 @@
#![cfg_attr(feature = "nightly", feature(cfg_target_feature))] #![cfg_attr(feature = "nightly", feature(cfg_target_feature))]
#![cfg_attr(all(feature = "nightly", feature = "yolocrypto"), feature(stdsimd))] #![cfg_attr(all(feature = "nightly", feature = "avx2_backend"), feature(stdsimd))]
#![allow(unused_variables)] #![allow(unused_variables)]
#![allow(non_snake_case)] #![allow(non_snake_case)]
#![allow(dead_code)] #![allow(dead_code)]

View file

@ -1,42 +1,48 @@
An implementation of group operations on the twisted Edwards form of A vectorized implementation of group operations on the twisted Edwards
Curve25519, using AVX2 to implement the 4-way parallel formulas of form of Curve25519, using a modification of the 4-way parallel
Hisil, Wong, Carter, and Dawson (HWCD). formulas of Hisil, Wong, Carter, and Dawson.
Their 2008 paper [_Twisted Edwards Curves Revisited_][hwcd08], which
introduced the extended coordinates used in other parts of `-dalek`,
also describes 4-way parallel formulas for point addition and
doubling:
* a unified addition algorithm taking an effective \\(2\mathbf M + # Overview
1\mathbf D\\);
* a doubling algorithm taking an effective \\(1\mathbf M + 1\mathbf The 2008 paper [_Twisted Edwards Curves Revisited_][hwcd08] by Hisil,
S\\); Wong, Carter, and Dawson (HWCD) introduced the “extended coordinates”
and mixed-model representations which are used by most Edwards curve
implementations.
* a dedicated (i.e., for distinct points) addition algorithm taking However, they also describe 4-way parallel formulas for point addition
an effective \\(2 \mathbf M \\). and doubling: a unified addition algorithm taking an effective
\\(2\mathbf M + 1\mathbf D\\), a doubling algorithm taking an
effective \\(1\mathbf M + 1\mathbf S\\), and a dedicated (i.e., for
distinct points) addition algorithm taking an effective \\(2 \mathbf M
\\). They compare these formulas with a 2-way parallel variant of the
Montgomery ladder.
Here \\(\mathbf M\\) and \\(\mathbf S\\) represent the cost of Unlike their serial formulas, which are used widely, their parallel
multiplication and squaring of generic field elements and \\(\mathbf formulas do not seem to have been implemented in software before. The
D\\) represents the cost of multiplication by a curve constant. 2-way parallel Montgomery ladder was used in 2015 by Tung Chou's
`sandy2x` implementation. Curiously, however, although the [`sandy2x`
paper][sandy2x] also implements Edwards arithmetic, and cites HWCD08,
it doesn't mention their parallel Edwards formulas.
A 2015 paper by Hernández and López describes an AVX2 implementation
of X25519. Neither the paper nor the code are publicly available, but
it apparently gives only a [slight speedup][avx2trac], suggesting that
it uses a 4-way parallel Montgomery ladder rather than parallel
Edwards formulas.
These formulas do not seem to have been implemented using SIMD before. The reason may be that HWCD08 describe their formulas as operating on
A 2015 paper by Hernández and López mentions using AVX2 for the X25519 four independent processors, which would make a software
Montgomery ladder, but neither the paper nor the code are publicly implementation impractical: all of the operations are too low-latency
available, and it apparently gives only a [slight speedup][avx2trac]. to effectively synchronize. But a closer inspection reveals that the
The 2008 HWCD paper also describes and analyzes a 2-wide variant of the (more expensive) multiplication and squaring steps are uniform, while
Montgomery ladder (for comparison with parallel Edwards formulas); this the instruction divergence occurs in the (much cheaper) addition and
strategy was used in 2015 by Tung Chou's `sandy2x` implementation, which subtraction steps. This means that a SIMD implementation can perform
used a 2-wide field implementation in 128-bit vector registers. the expensive steps uniformly, and handle divergence in the
Curiously, however, although the [`sandy2x` paper][sandy2x] also inexpensive steps using masking.
implements Edwards arithmetic, and cites the HWCD paper, it doesn't
mention the parallel formulas from HWCD, suggesting that they have been
overlooked for software implementations.
The notes below describe a tweak to the \\( 2\mathbf M + 1\mathbf D \\) These notes describe modifications to the original parallel formulas
unified addition formulas to give \\( 2\mathbf M \\) readdition with to allow a SIMD implementation, and this module contains an
\\(1\mathbf D\\) precomputation, and a tweak to the doubling formulas to implementation of the modified formulas using 256-bit AVX2 vector
avoid an extra reduction. These tweaked formulas are the ones used by operations.
the `avx2` backend of `curve25519-dalek`.
# Parallel formulas in HWCD'08 # Parallel formulas in HWCD'08
@ -60,218 +66,153 @@ and the unified addition algorithm is presented as follows:
| | \\( R\_1 \gets R\_6 - R\_5 \\) | \\( R\_2 \gets R\_8 - R\_7 \\) | \\( R\_3 \gets R\_8 + R\_7 \\) | \\( R\_4 \gets R\_6 + R\_5 \\) | | | \\( R\_1 \gets R\_6 - R\_5 \\) | \\( R\_2 \gets R\_8 - R\_7 \\) | \\( R\_3 \gets R\_8 + R\_7 \\) | \\( R\_4 \gets R\_6 + R\_5 \\) |
| \\(1\mathbf M\\) | \\( X\_3 \gets R\_1 R\_2 \\) | \\( Y\_3 \gets R\_3 R\_4 \\) | \\( T\_3 \gets R\_1 R\_4 \\) | \\( Z\_3 \gets R\_2 R\_3 \\) | | \\(1\mathbf M\\) | \\( X\_3 \gets R\_1 R\_2 \\) | \\( Y\_3 \gets R\_3 R\_4 \\) | \\( T\_3 \gets R\_1 R\_4 \\) | \\( Z\_3 \gets R\_2 R\_3 \\) |
Here \\( k = 2d \\) is a curve constant. Here \\(\mathbf M\\) and \\(\mathbf S\\) represent the cost of
multiplication and squaring of generic field elements, \\(\mathbf D\\)
represents the cost of multiplication by a curve constant (in this
case \\( k = 2d \\)).
For a software implementation, each processor's operations are too Notice that the \\(1\mathbf M\\) and \\(1\mathbf S\\) steps are
low-latency to parallelize across threads. However, the main cost uniform. The non-uniform steps are all inexpensive additions or
is in the multiplication and squaring steps, which are uniform, while subtractions, with the exception of the multiplication by the curve
the divergent steps involve inexpensive additions and subtractions. constant \\(k = 2d\\):
$$
R\_7 \gets 2 d R\_7.
$$
This means we can use SIMD to implement the expensive portions in HWCD suggest parallelising this step by breaking \\(k = 2d\\) into four
parallel, and handle the instruction divergence on the inexpensive parts
using masking.
The remaining obstacle to parallelism is the multiplication by the curve
constant \\(k = 2d\\). In the Curve25519 case, this is
$$ k \equiv 2 \frac{-121665}{121666} \\ \equiv 16295367250680780974490674513165176452449235426866156013048779062215315747161 \pmod p. $$
HWCD suggest parallelising this step by breaking \\(k\\) into four
parts as \\(k = k_0 + 2\^n k_1 + 2\^{2n} k_2 + 2\^{3n} k_3 \\) and parts as \\(k = k_0 + 2\^n k_1 + 2\^{2n} k_2 + 2\^{3n} k_3 \\) and
computing \\(k_i R_7 \\) in parallel. However, this would be computing \\(k_i R_7 \\) in parallel. This is quite awkward, but if
somewhat awkward in our case, since we would normally represent the curve constant is a ratio \\( d = d\_1/d\_2 \\), then projective
\\(k\\) as \\( 10 \\) 32-bit limbs, and \\(10 \\) is not divisible coordinates allow us to instead compute
by \\(4\\), so we would need a specialized routine to perform a $$
vectorized multiplication by 64-bit constants. (R\_5, R\_6, R\_7, R\_8) \gets (d\_2 R\_5, d\_2 R\_6, 2d\_1 R\_7, d\_2 R\_8).
$$
This can be performed as a uniform multiplication by a vector of
constants, and if \\(d\_1, d\_2\\) are small, it is relatively
inexpensive. (This trick was suggested by Mike Hamburg).
In the Curve25519 case, we have
$$
d = \frac{d\_1}{d\_2} = \frac{-121665}{121666};
$$
Since \\(2 \cdot 121666 < 2\^{18}\\), all the constants above fit (up
to sign) in 32 bits, so this can be done in parallel as four
multiplications by small constants \\( (121666, 121666, 2\cdot 121665,
2\cdot 121666) \\), followed by a negation to compute \\( - 2\cdot 121665\\).
Instead, since we are working projectively, we can multiply # Modified parallel formulas
\\(R_7\\) by \\( -2\cdot 121665 \\) and multiply the other three
variables by \\(121666\\). This trick was suggested by Mike
Hamburg. Ignoring the sign for the moment, since
\\(2 \cdot 121666 < 2\^{18}\\), all these constants fit in 32 bits,
so (up to sign) this can be done in parallel as four multiplications
by small constants \\( (121666, 121666, 2\cdot 121665, 2\cdot 121666) \\).
How do we handle the sign? Using the modifications sketched above, we can write SIMD-friendly
Since we're primarily interested in Ristretto performance, not versions of the parallel formulas as follows. To avoid confusion with
Curve25519 performance, we could alternately work on the the original formulas, temporary variables are named \\(S\\) instead
\\(4\\)-isogenous "IsoEd25519" curve, which has \\(d = 121665\\). of \\(R\\) and are in static single-assignment form.
However, this would only save the negation step, since multiplying
one field element by a 32-bit constant is not much easier than
multiplying four field elements by 32-bit constants, and it would
prevent accelerating Curve25519, so we don't make this choice.
Instead, we just negate one lane, and move the \\(1 \mathbf D\\)
into precomputation (see below).
# Tweaked formulas
After tweaking the formulas as described above, we obtain the
following. To avoid confusion with the original HWCD formulas,
temporary variables are named \\(S\\) instead of \\(R\\) and are in
static single-assignment form.
## Addition ## Addition
This implementation only implements readdition, but the tweaked addition To add points
formulas are described first. To add points \\(P_1 = (X_1 : Y_1 : Z_1 : \\(P_1 = (X_1 : Y_1 : Z_1 : T_1) \\)
T_1) \\) and \\(P_2 = (X_2 : Y_2 : Z_2 : T_2 ) \\), we compute and
\\(P_2 = (X_2 : Y_2 : Z_2 : T_2 ) \\),
we compute
$$ $$
\begin{aligned} \begin{aligned}
S\_0 &\gets Y\_1 - X\_1 \\\\ (S\_0 &&,&& S\_1 &&,&& S\_2 &&,&& S\_3 )
S\_1 &\gets Y\_1 + X\_1 \\\\ &\gets
S\_2 &\gets Y\_2 - X\_2 \\\\ (Y\_1 - X\_1&&,&& Y\_1 + X\_1&&,&& Y\_2 - X\_2&&,&& Y\_2 + X\_2)
S\_3 &\gets Y\_2 + X\_2 \\\\
(S\_4 &&,&& S\_5 &&,&& S\_6 &&,&& S\_7 )
&\gets
(S\_0 \cdot S\_2&&,&& S\_1 \cdot S\_3&&,&& Z\_1 \cdot Z\_2&&,&& T\_1 \cdot T\_2)
\\\\
(S\_8 &&,&& S\_9 &&,&& S\_{10} &&,&& S\_{11} )
&\gets
(d\_2 \cdot S\_4 &&,&& d\_2 \cdot S\_5 &&,&& 2 d\_2 \cdot S\_6 &&,&& 2 d\_1 \cdot S\_7 )
\\\\
(S\_{12} &&,&& S\_{13} &&,&& S\_{14} &&,&& S\_{15})
&\gets
(S\_9 - S\_8&&,&& S\_9 + S\_8&&,&& S\_{10} - S\_{11}&&,&& S\_{10} + S\_{11})
\\\\
(X\_3&&,&& Y\_3&&,&& Z\_3&&,&& T\_3)
&\gets
(S\_{12} \cdot S\_{14}&&,&& S\_{15} \cdot S\_{13}&&,&& S\_{15} \cdot S\_{14}&&,&& S\_{12} \cdot S\_{13})
\end{aligned} \end{aligned}
$$ $$
$$
\begin{aligned}
S\_4 &\gets S\_0 S\_2 \\\\
S\_5 &\gets S\_1 S\_3 \\\\
S\_6 &\gets Z\_1 Z\_2 \\\\
S\_7 &\gets T\_1 T\_2
\end{aligned}
$$
$$
\begin{aligned}
S\_8 &\gets S\_4 \cdot 121666 \\\\
S\_9 &\gets S\_5 \cdot 121666 \\\\
S\_{10} &\gets S\_6 \cdot 2 \cdot 121666 \\\\
S\_{11} &\gets S\_7 \cdot -2 \cdot 121665
\end{aligned}
$$
$$
\begin{aligned}
S\_{12} &\gets S\_9 - S\_8 \\\\
S\_{13} &\gets S\_9 + S\_8 \\\\
S\_{14} &\gets S\_{10} - S\_{11} \\\\
S\_{15} &\gets S\_{10} + S\_{11}
\end{aligned}
$$
$$
\begin{aligned}
X\_3 &\gets S\_{12} S\_{14} \\\\
Y\_3 &\gets S\_{15} S\_{13} \\\\
Z\_3 &\gets S\_{15} S\_{14} \\\\
T\_3 &\gets S\_{12} S\_{13}
\end{aligned}
$$
to obtain \\( P\_3 = (X\_3 : Y\_3 : Z\_3 : T\_3) = P\_1 + P\_2 \\). to obtain \\( P\_3 = (X\_3 : Y\_3 : Z\_3 : T\_3) = P\_1 + P\_2 \\).
This costs \\( 2\mathbf M + 1 \mathbf D\\).
## Readdition ## Readdition
If the point \\( P_2 = (X\_2 : Y\_2 : Z\_2 : T\_2) \\) is fixed, we can precompute If the point \\( P_2 = (X\_2 : Y\_2 : Z\_2 : T\_2) \\) is fixed, we
can cache the multiplication of the curve constants by computing
$$ $$
\begin{aligned} \begin{aligned}
S\_2 &\gets Y\_2 - X\_2 \\\\ (S\_2' &&,&& S\_3' &&,&& Z\_2' &&,&& T\_2' )
S\_3 &\gets Y\_2 + X\_2 &\gets
(d\_2 \cdot (Y\_2 - X\_2)&&,&& d\_2 \cdot (Y\_1 + X\_1)&&,&& 2d\_2 \cdot Z\_2 &&,&& 2d\_1 \cdot T\_2).
\end{aligned} \end{aligned}
$$ $$
This costs \\( 1\mathbf D\\); with \\( (S\_2', S\_3', Z\_2', T\_2')\\)
in hand, the addition formulas above become
$$ $$
\begin{aligned} \begin{aligned}
S\_2' &\gets S\_2 \cdot 121666 \\\\ (S\_0 &&,&& S\_1 &&,&& Z\_1 &&,&& T\_1 )
S\_3' &\gets S\_3 \cdot 121666 \\\\ &\gets
Z\_2' &\gets Z\_2 \cdot 2 \cdot 121666 \\\\ (Y\_1 - X\_1&&,&& Y\_1 + X\_1&&,&& Z\_1 &&,&& T\_1)
T\_2' &\gets T\_2 \cdot -2 \cdot 121665 \\\\ \\\\
(S\_8 &&,&& S\_9 &&,&& S\_{10} &&,&& S\_{11} )
&\gets
(S\_0 \cdot S\_2' &&,&& S\_1 \cdot S\_3'&&,&& Z\_1 \cdot Z\_2' &&,&& T\_1 \cdot T\_2')
\\\\
(S\_{12} &&,&& S\_{13} &&,&& S\_{14} &&,&& S\_{15})
&\gets
(S\_9 - S\_8&&,&& S\_9 + S\_8&&,&& S\_{10} - S\_{11}&&,&& S\_{10} + S\_{11})
\\\\
(X\_3&&,&& Y\_3&&,&& Z\_3&&,&& T\_3)
&\gets
(S\_{12} \cdot S\_{14}&&,&& S\_{15} \cdot S\_{13}&&,&& S\_{15} \cdot S\_{14}&&,&& S\_{12} \cdot S\_{13})
\end{aligned} \end{aligned}
$$ $$
which costs only \\( 2\mathbf M \\). This precomputation is
to obtain the `CachedPoint` \\( (S\_2', S\_3', Z\_2', T\_2') \\). essentially similar to the precomputation that HWCD suggest for their
This precomputation is essentially the same as that suggested in serial formulas. Because the cost of precomputation and then
§3.1 of HWCD, with the difference that the multiplication by the curve readdition is the same as addition, it's sufficient to only
constant \\( -121665 / 121666 \\) is spread over all four implement caching and readdition.
coordinates, to allow a vectorized computation of four
multiplications of small constants instead of a serial computation
of multiplication by a large constant.
To perform readdition of \\(P_1 = (X_1 : Y_1 : Z_1 : T_1) \\) and
\\(P_2 = (S\_2', S\_3', Z\_2', T\_2') \\), we compute
$$
\begin{aligned}
S\_0 &\gets Y\_1 - X\_1 \\\\
S\_1 &\gets Y\_1 + X\_1
\end{aligned}
$$
$$
\begin{aligned}
S\_8 &\gets S\_0 S\_2' \\\\
S\_9 &\gets S\_1 S\_3' \\\\
S\_{10} &\gets Z\_1 Z\_2' \\\\
S\_{11} &\gets T\_1 T\_2'
\end{aligned}
$$
$$
\begin{aligned}
S\_{12} &\gets S\_9 - S\_8 \\\\
S\_{13} &\gets S\_9 + S\_8 \\\\
S\_{14} &\gets S\_{10} - S\_{11} \\\\
S\_{15} &\gets S\_{10} + S\_{11}
\end{aligned}
$$
$$
\begin{aligned}
X\_3 &\gets S\_{12} S\_{14} \\\\
Y\_3 &\gets S\_{15} S\_{13} \\\\
Z\_3 &\gets S\_{15} S\_{14} \\\\
T\_3 &\gets S\_{12} S\_{13}
\end{aligned}
$$
to obtain \\( P\_3 = (X\_3 : Y\_3 : Z\_3 : T\_3) = P\_1 + P\_2 \\).
Compared to the addition formulas above, this saves \\( 1\mathbf D \\).
## Doubling ## Doubling
The non-uniform portions of the (re)addition formulas have a fairly
regular structure. Unfortunately, this is not the case for the
doubling formulas, which are much less nice.
To double a point \\( P = (X\_1 : Y\_1 : Z\_1 : T\_1) \\), we compute To double a point \\( P = (X\_1 : Y\_1 : Z\_1 : T\_1) \\), we compute
$$ S\_0 \gets X\_1 + Y\_1 $$
$$ $$
\begin{aligned} \begin{aligned}
S\_1 &\gets X\_1\^2 \\\\ (X\_1 &&,&& Y\_1 &&,&& Z\_1 &&,&& S\_0)
S\_2 &\gets Y\_1\^2 \\\\ &\gets
S\_3 &\gets Z\_1\^2 \\\\ (X\_1 &&,&& Y\_1 &&,&& Z\_1 &&,&& X\_1 + Y\_1)
S\_4 &\gets S\_0\^2 \\\\
(S\_1 &&,&& S\_2 &&,&& S\_3 &&,&& S\_4 )
&\gets
(X\_1\^2 &&,&& Y\_1\^2&&,&& Z\_1\^2 &&,&& S\_0\^2)
\\\\
(S\_5 &&,&& S\_6 &&,&& S\_8 &&,&& S\_9 )
&\gets
(S\_1 + S\_2 &&,&& S\_1 - S\_2 &&,&& S\_1 + 2S\_3 - S\_2 &&,&& S\_1 + S\_2 - S\_4)
\\\\
(X\_3 &&,&& Y\_3 &&,&& Z\_3 &&,&& T\_3 )
&\gets
(S\_8 \cdot S\_9 &&,&& S\_5 \cdot S\_6 &&,&& S\_8 \cdot S\_6 &&,&& S\_5 \cdot S\_9)
\end{aligned} \end{aligned}
$$ $$
$$
\begin{aligned}
S\_5 &\gets S\_1 + S\_2 \\\\
S\_6 &\gets S\_1 - S\_2 \\\\
S\_7 &\gets 2S\_3 \\\\
S\_8 &\gets S\_7 + S\_6 = S\_1 + 2S\_3 - S\_2 \\\\
S\_9 &\gets S\_5 - S\_4 = S\_1 + S\_2 - S\_4
\end{aligned}
$$
$$
\begin{aligned}
X\_3 &\gets S\_8 S\_9 \\\\
Y\_3 &\gets S\_5 S\_6 \\\\
Z\_3 &\gets S\_8 S\_6 \\\\
T\_3 &\gets S\_5 S\_9
\end{aligned}
$$
to obtain \\( P\_3 = (X\_3 : Y\_3 : Z\_3 : T\_3) = [2]P\_1 \\). to obtain \\( P\_3 = (X\_3 : Y\_3 : Z\_3 : T\_3) = [2]P\_1 \\).
Unlike the (re)addition formulas, the divergent parts of these formulas The intermediate step between the squaring and multiplication requires
are less nice. However, with some careful bounds-juggling, it is a long chain of additions, but with some care and finesse,
possible to implement them without inserting extra carry chains, as described below, it is possible (in our case) to arrange this
described below. computation without requiring an intermediate reduction.
However, it does mean that the doubling formulas have proportionately
more vectorization overhead than the (re)addition formulas. The
effects of this are discussed in the comparison section below.
# Field element representation # Field element representation
@ -329,39 +270,36 @@ much difficulty. Going the other direction, to extend this to AVX512,
we could either run two point operations in parallel in lower and upper we could either run two point operations in parallel in lower and upper
halves of the registers, or use 2-way parallelism within a field operation. halves of the registers, or use 2-way parallelism within a field operation.
# Handling the Doubling Formulas # Avoiding Overflow in Doubling
The non-parallel portion of the doubling formulas is To analyze the size of the field element coefficients during the
computations, we can parameterize the bounds on the limbs of each
field element by \\( b \in \mathbb R \\) representing the excess bits
above that limb's radix, so that each limb is bounded by either
\\(2\^{25+b} \\) or \\( 2\^{26+b} \\), as appropriate.
$$ The multiplication routine requires that its inputs are bounded with
\begin{aligned}
S\_5 &\gets S\_1 + S\_2 \\\\
S\_6 &\gets S\_1 - S\_2 \\\\
S\_7 &\gets 2S\_3 \\\\
S\_8 &\gets S\_7 + S\_6 = S\_1 + 2S\_3 - S\_2 \\\\
S\_9 &\gets S\_5 - S\_4 = S\_1 + S\_2 - S\_4
\end{aligned}
$$
Performing too many intermediate additions and subtractions grows
the bounds beyond what is allowed as input to multiplication,
forcing an extra carry pass. However, it is just possible to avoid
this by rearranging signs.
Assume that the bounds on the limbs of each field element are
parameterized by \\( b \in \mathbb R \\) representing the excess
bits, so that each limb is bounded by either
\\( 2\^{25+b} \\) or \\( 2\^{26+b} \\).
The multiplication routine requires that its inputs are bounded by
\\( b < 1.75 \\), in order to fit a multiplication by \\( 19 \\) \\( b < 1.75 \\), in order to fit a multiplication by \\( 19 \\)
into 32 bits. Since \\( \lg 19 < 4.25 \\), \\( 19x < 2\^{32} \\) into 32 bits. Since \\( \lg 19 < 4.25 \\), \\( 19x < 2\^{32} \\)
when \\( x < 2\^{27.75} = 2\^{26 + 1.75} \\). However, this is only when \\( x < 2\^{27.75} = 2\^{26 + 1.75} \\). However, this is only
required for one of the inputs; the other can grow up to \\( b < 2.5 required for one of the inputs; the other can grow up to \\( b < 2.5
\\). \\).
Computing \\( (S\_5, S\_6, S\_8, S\_9 ) \\) as In addition, the multiplication and squaring routines do not
canonically reduce their outputs, but can leave some small uncarried
excesses, so that their reduced outputs are bounded with
\\( b < 0.007 \\).
The non-parallel portion of the doubling formulas is
$$
\begin{aligned}
(S\_5 &&,&& S\_6 &&,&& S\_8 &&,&& S\_9 )
&\gets
(S\_1 + S\_2 &&,&& S\_1 - S\_2 &&,&& S\_1 + 2S\_3 - S\_2 &&,&& S\_1 + S\_2 - S\_4)
\end{aligned}
$$
Computing \\( (S\_5, S\_6, S\_8, S\_9 ) \\) as
$$ $$
\begin{matrix} \begin{matrix}
& S\_1 & S\_1 & S\_1 & S\_1 \\\\ & S\_1 & S\_1 & S\_1 & S\_1 \\\\
@ -374,24 +312,22 @@ $$
=& S\_5 & S\_6 & S\_8 & S\_9 =& S\_5 & S\_6 & S\_8 & S\_9
\end{matrix} \end{matrix}
$$ $$
results in bit-excesses \\( < (1.01, 1.60, 2.33, 2.01)\\) for
results in bit-excesses \\( (1.00, 1.59, 2.33, 2.00)\\) for
\\( (S\_5, S\_6, S\_8, S\_9 ) \\). The products we want to compute \\( (S\_5, S\_6, S\_8, S\_9 ) \\). The products we want to compute
are then are then
$$ $$
\begin{aligned} \begin{aligned}
X\_3 &\gets S\_8 S\_9 \leftrightarrow (2.33, 2.00) \\\\ X\_3 &\gets S\_8 S\_9 \leftrightarrow (2.33, 2.01) \\\\
Y\_3 &\gets S\_5 S\_6 \leftrightarrow (1.00, 1.59) \\\\ Y\_3 &\gets S\_5 S\_6 \leftrightarrow (1.01, 1.60) \\\\
Z\_3 &\gets S\_8 S\_6 \leftrightarrow (2.33, 1.59) \\\\ Z\_3 &\gets S\_8 S\_6 \leftrightarrow (2.33, 1.60) \\\\
T\_3 &\gets S\_5 S\_9 \leftrightarrow (1.00, 2.00) T\_3 &\gets S\_5 S\_9 \leftrightarrow (1.01, 2.01)
\end{aligned} \end{aligned}
$$ $$
which are too large: it's not possible to arrange the multiplicands so
which are too large. However, if we flip the sign of \\( S\_4 = that one vector has \\(b < 2.5\\) and the other has \\( b < 1.75 \\).
S\_0\^2 \\) during squaring, so that we output \\(S\_4' = -S\_4 However, if we flip the sign of \\( S\_4 = S\_0\^2 \\) during
\pmod p\\), then we can compute squaring, so that we output \\(S\_4' = -S\_4 \pmod p\\), then we can
compute
$$ $$
\begin{matrix} \begin{matrix}
& S\_1 & S\_1 & S\_1 & S\_1 \\\\ & S\_1 & S\_1 & S\_1 & S\_1 \\\\
@ -404,61 +340,120 @@ $$
=& S\_5 & S\_6 & S\_8 & S\_9 =& S\_5 & S\_6 & S\_8 & S\_9
\end{matrix} \end{matrix}
$$ $$
resulting in bit-excesses \\( < (1.01, 1.60, 2.33, 1.60)\\) for
resulting in bit-excesses \\( (1.00, 1.59, 2.33, 1.59)\\) for
\\( (S\_5, S\_6, S\_8, S\_9 ) \\). The products we want to compute \\( (S\_5, S\_6, S\_8, S\_9 ) \\). The products we want to compute
are then are then
$$ $$
\begin{aligned} \begin{aligned}
X\_3 &\gets S\_8 S\_9 \leftrightarrow (2.33, 1.59) \\\\ X\_3 &\gets S\_8 S\_9 \leftrightarrow (2.33, 1.60) \\\\
Y\_3 &\gets S\_5 S\_6 \leftrightarrow (1.00, 1.59) \\\\ Y\_3 &\gets S\_5 S\_6 \leftrightarrow (1.01, 1.60) \\\\
Z\_3 &\gets S\_8 S\_6 \leftrightarrow (2.33, 1.59) \\\\ Z\_3 &\gets S\_8 S\_6 \leftrightarrow (2.33, 1.60) \\\\
T\_3 &\gets S\_5 S\_9 \leftrightarrow (1.00, 1.59) T\_3 &\gets S\_5 S\_9 \leftrightarrow (1.01, 1.60)
\end{aligned} \end{aligned}
$$ $$
whose right-hand sides are all bounded with \\( b < 1.75 \\) and whose right-hand sides are all bounded with \\( b < 1.75 \\) and
whose left-hand sides are all bounded with \\( b < 2.5 \\). whose left-hand sides are all bounded with \\( b < 2.5 \\),
so that we can avoid any intermediate reductions.
# Comparison to non-vectorized formulas # Comparison to non-vectorized formulas
HWCD also suggest using a mixed representation, passing between \\( In theory, the parallel Edwards formulas seem to allow a \\(4\\)-way
\mathbb P\^3 \\) "extended" coordinates and \\( \mathbb P\^2 \\) speedup from parallelism. However, an actual vectorized
"projective" coordinates, where doubling is slightly cheaper (saving implementation has several slowdowns that cut into this speedup.
about \\(\mathbf 1M\\). This approach is used for the
non-vectorized `u32` and `u64` backends, and more
details on the different coordinate systems can be found in the
`curve_models` module documentation.
This optimization is not compatible with the parallel formulas, which are First, the parallel formulas can only use a \\( 32 \times 32
therefore slightly less efficient when counting the total number of
field multiplications and squarings. In particular, vectorized doublings
are less efficient than serial doublings.
In addition, the parallel formulas can only use a \\( 32 \times 32
\rightarrow 64 \\)-bit integer multiplier, so the speedup from \rightarrow 64 \\)-bit integer multiplier, so the speedup from
vectorization must overcome the disadvantage of losing the \\( 64 vectorization must overcome the disadvantage of losing the \\( 64
\times 64 \rightarrow 128\\)-bit (serial) integer multiplier. \times 64 \rightarrow 128\\)-bit (serial) integer multiplier. The
effect of this slowdown is microarchitecture-dependent, since it
requires accounting for the total number of multiplications and
additions and their relative costs. In the future, it will probably
be possible to avoid this slowdown by using the `IFMA52` instructions,
whose parallelism is perfectly suited to these formulas.
When compiling with AVX512VL, LLVM is able to use the extra Second, the parallel doubling formulas incur both a theoretical and
`ymm16..ymm31` registers to reduce register pressure, and avoid practical slowdown. The parallel formulas described above work on the
spills during field multiplication. This gives a small but \\( \mathbb P\^3 \\) “extended” coordinates. The \\( \mathbb P\^2 \\)
noticeable speedup. model introduced earlier by [Bernstein, Birkner, Joye, Lange, and
Peters][bbjlp08] allows slightly faster doublings, so HWCD suggest
mixing coordinate systems while performing scalar multiplication
(attributing the idea to [a 1998 paper][cmo98] by Cohen, Miyagi, and
Ono). The \\( T \\) coordinate is not required for doublings, so when
doublings are followed by doublings, its computation can be skipped.
More details on this approach and the different coordinate systems can
be found in the [`curve_models` module documentation][curve_models].
Another concern with AVX2 is that currently-available Intel processors Unfortunately, this optimization is not compatible with the parallel
(particularly Skylake and Skylake-X microarchitectures) perform thermal formulas, which cannot save time by skipping a single variable, so the
throttling when using wide vector instructions. For a mixed workload, parallel doubling formulas do slightly more work when counting the
total number of field multiplications and squarings.
In addition, the parallel doubling formulas have a less regular
pattern of additions and subtractions than the parallel addition
formulas, so the vectorization overhead is proportionately greater.
Both the parallel addition and parallel doubling formulas also require
some shuffling to rearrange data within the vectors, which places more
pressure on the shuffle unit than is desirable.
This means that the speedup from using a vectorized implementation of
parallel Edwards formulas is likely to be greatest in applications
that do fewer doublings and more additions (like a large multiscalar
multiplication) rather than applications that do fewer additions and
more doublings (like a double-base scalar multiplication).
Third, current Intel CPUs perform thermal throttling when using wide
vector instructions. A detailed description can be found in §15.26 of
[the Intel Optimization Manual][intel], but using wide vector
instructions prevents the core from operating at higher frequencies.
The core can return to the higher-frequency state after 2
milliseconds, but this timer is reset every time high-power
instructions are used.
Any speedup from vectorization therefore has to be weighed against a
slowdown for the next few million instructions. For a mixed workload,
where point operations are interspersed with other tasks, this can where point operations are interspersed with other tasks, this can
reduce overall performance. This probably means that this reduce overall performance. This implementation is therefore probably
implementation is not suitable for basic applications, like signatures, not suitable for basic applications, like signatures, but is
but could still be worthwhile for complex applications, like worthwhile for complex applications, like zero-knowledge proofs, which
zero-knowledge proofs, which do enough work to make it worthwhile. do sustained work.
For this reason, the AVX2 backend is not enabled by default, but can
be selected using the `avx2_backend` feature.
# Future work
There are several directions for future improvement:
* Using the vectorized field arithmetic code to parallelize across
point operations rather than within a single point operation. This
is less flexible, but would give a speedup both from allowing use of
the faster mixed-model arithmetic and from reducing shuffle
pressure. One approach in this direction would be to implement
batched scalar-point operations using vectors of points (AoSoA
layout). This less generally useful but would give a speedup for
Bulletproofs.
* Extending the implementation to use the full width of AVX512, either
handling the extra parallelism internally to a single point
operation (by using a 2-way parallel implementation of field
arithmetic instead of a wordsliced one), or externally,
parallelizing across point operations. Internal parallelism would
be preferable but might require too much shuffle pressure.
* Generalizing the implementation to non-AVX2 instructions,
particularly NEON. The current point arithmetic code is written in
terms of field element vectors, which are in turn implemented using
platform SIMD vectors. It should be possible to write an alternate
implementation of the `FieldElement32x4` using NEON without changing
the point arithmetic. NEON has 128-bit vectors rather than 256-bit
vectors, but this may still be worthwhile compared to a serial
implementation.
On AMD's Zen microarchitecture, thermal throttling is not a concern,
since AVX2 is implemented at half rate, so there is no penalty for mixed
workloads (but also no speedup).
[sandy2x]: https://eprint.iacr.org/2015/943.pdf [sandy2x]: https://eprint.iacr.org/2015/943.pdf
[avx2trac]: https://trac.torproject.org/projects/tor/ticket/8897#comment:28 [avx2trac]: https://trac.torproject.org/projects/tor/ticket/8897#comment:28
[hwcd08]: https://www.iacr.org/archive/asiacrypt2008/53500329/53500329.pdf [hwcd08]: https://www.iacr.org/archive/asiacrypt2008/53500329/53500329.pdf
[curve_models]: https://doc-internal.dalek.rs/curve25519_dalek/curve_models/index.html
[bbjlp08]: https://eprint.iacr.org/2008/013
[cmo98]: https://link.springer.com/content/pdf/10.1007%2F3-540-49649-1_6.pdf
[intel]: https://software.intel.com/sites/default/files/managed/9e/bc/64-ia-32-architectures-optimization-manual.pdf

View file

@ -16,6 +16,24 @@ use backend::avx2::edwards::{CachedPoint, ExtendedPoint};
use backend::avx2::field::FieldElement32x4; use backend::avx2::field::FieldElement32x4;
use scalar_mul::window::NafLookupTable8; use scalar_mul::window::NafLookupTable8;
/// The identity element as an `ExtendedPoint`.
pub(crate) static EXTENDEDPOINT_IDENTITY: ExtendedPoint = ExtendedPoint(FieldElement32x4([
u32x8::new(0, 1, 0, 0, 1, 0, 0, 0),
u32x8::splat(0),
u32x8::splat(0),
u32x8::splat(0),
u32x8::splat(0),
]));
/// The identity element as a `CachedPoint`.
pub(crate) static CACHEDPOINT_IDENTITY: CachedPoint = CachedPoint(FieldElement32x4([
u32x8::new(121647, 121666, 0, 0, 243332, 67108845, 0, 33554431),
u32x8::new(67108864, 0, 33554431, 0, 0, 67108863, 0, 33554431),
u32x8::new(67108863, 0, 33554431, 0, 0, 67108863, 0, 33554431),
u32x8::new(67108863, 0, 33554431, 0, 0, 67108863, 0, 33554431),
u32x8::new(67108863, 0, 33554431, 0, 0, 67108863, 0, 33554431),
]));
/// The low limbs of (2p, 2p, 2p, 2p), so that /// The low limbs of (2p, 2p, 2p, 2p), so that
/// ```no_run /// ```no_run
/// (2p, 2p, 2p, 2p) = [P_TIMES_2_LO, P_TIMES_2_HI, P_TIMES_2_HI, P_TIMES_2_HI, P_TIMES_2_HI] /// (2p, 2p, 2p, 2p) = [P_TIMES_2_LO, P_TIMES_2_HI, P_TIMES_2_HI, P_TIMES_2_HI, P_TIMES_2_HI]
@ -76,14 +94,6 @@ pub(crate) static P_TIMES_16_HI: u32x8 = u32x8::new(
33554431 << 4, 33554431 << 4,
); );
pub(crate) static P_TIMES_2_MASKED: FieldElement32x4 = FieldElement32x4([
u32x8::new(0, 134217690, 0, 67108862, 134217690, 0, 67108862, 0),
u32x8::new(0, 134217726, 0, 67108862, 134217726, 0, 67108862, 0),
u32x8::new(0, 134217726, 0, 67108862, 134217726, 0, 67108862, 0),
u32x8::new(0, 134217726, 0, 67108862, 134217726, 0, 67108862, 0),
u32x8::new(0, 134217726, 0, 67108862, 134217726, 0, 67108862, 0),
]);
/// Odd multiples of the Ed25519 basepoint: /// Odd multiples of the Ed25519 basepoint:
pub(crate) static BASEPOINT_ODD_LOOKUP_TABLE: NafLookupTable8<CachedPoint> = NafLookupTable8([ pub(crate) static BASEPOINT_ODD_LOOKUP_TABLE: NafLookupTable8<CachedPoint> = NafLookupTable8([
CachedPoint(FieldElement32x4([ CachedPoint(FieldElement32x4([

View file

@ -8,29 +8,53 @@
// - Isis Agora Lovecruft <isis@patternsinthevoid.net> // - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca> // - Henry de Valence <hdevalence@hdevalence.ca>
//! Extended Twisted Edwards for Curve25519, using AVX2. //! Parallel Edwards Arithmetic for Curve25519.
//!
//! This module currently has two point types:
//!
//! * `ExtendedPoint`: a point stored in vector-friendly format, with
//! vectorized doubling and addition;
//!
//! * `CachedPoint`: used for readdition.
//!
//! Details on the formulas can be found in the documentation for the
//! parent `avx2` module.
//!
//! This API is designed to be safe: vectorized points can only be
//! created from serial points (which do validation on decompression),
//! and operations on valid points return valid points, so invalid
//! point states should be unrepresentable.
//!
//! This design goal is met, with one exception: the `Neg`
//! implementation for the `CachedPoint` performs a lazy negation, so
//! that subtraction can be efficiently implemented as a negation and
//! an addition. Repeatedly negating a `CachedPoint` will cause its
//! coefficients to grow and eventually overflow. Repeatedly negating
//! a point should not be necessary anyways.
// just going to own it #![allow(non_snake_case)]
#![allow(bad_style)]
use core::convert::From; use core::convert::From;
use core::ops::{Add, Sub, Neg}; use core::ops::{Add, Neg, Sub};
use core::simd::{IntoBits, u32x8};
use subtle::ConditionallyAssignable;
use subtle::Choice; use subtle::Choice;
use subtle::ConditionallyAssignable;
use edwards; use edwards;
use scalar_mul::window::{LookupTable, NafLookupTable5, NafLookupTable8}; use scalar_mul::window::{LookupTable, NafLookupTable5, NafLookupTable8};
use traits::Identity; use traits::Identity;
use backend::avx2::field::{D_LANES, Lanes, FieldElement32x4}; use backend::avx2::field::{FieldElement32x4, Lanes, Shuffle};
use backend::avx2::constants;
use backend::avx2; /// A point on Curve25519, using parallel Edwards formulas for curve
/// operations.
/// A point on Curve25519, represented in an AVX2-friendly format. ///
/// # Invariant
///
/// The coefficients of an `ExtendedPoint` are bounded with
/// \\( b < 0.007 \\).
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
pub struct ExtendedPoint(pub(super) FieldElement32x4); pub struct ExtendedPoint(pub(super) FieldElement32x4);
@ -43,7 +67,12 @@ impl From<edwards::EdwardsPoint> for ExtendedPoint {
impl From<ExtendedPoint> for edwards::EdwardsPoint { impl From<ExtendedPoint> for edwards::EdwardsPoint {
fn from(P: ExtendedPoint) -> edwards::EdwardsPoint { fn from(P: ExtendedPoint) -> edwards::EdwardsPoint {
let tmp = P.0.split(); let tmp = P.0.split();
edwards::EdwardsPoint{X: tmp[0], Y: tmp[1], Z: tmp[2], T: tmp[3]} edwards::EdwardsPoint {
X: tmp[0],
Y: tmp[1],
Z: tmp[2],
T: tmp[3],
}
} }
} }
@ -61,111 +90,71 @@ impl Default for ExtendedPoint {
impl Identity for ExtendedPoint { impl Identity for ExtendedPoint {
fn identity() -> ExtendedPoint { fn identity() -> ExtendedPoint {
ExtendedPoint(FieldElement32x4([ constants::EXTENDEDPOINT_IDENTITY
u32x8::new(0,1,0,0,1,0,0,0),
u32x8::splat(0),
u32x8::splat(0),
u32x8::splat(0),
u32x8::splat(0),
]))
} }
} }
impl ExtendedPoint { impl ExtendedPoint {
/// Compute the double of this point.
pub fn double(&self) -> ExtendedPoint { pub fn double(&self) -> ExtendedPoint {
unsafe { // Want to compute (X1 Y1 Z1 X1+Y1).
use core::arch::x86_64::_mm256_permute2x128_si256; // Not sure how to do this less expensively than computing
use core::arch::x86_64::_mm256_permutevar8x32_epi32; // (X1 Y1 Z1 T1) --(256bit shuffle)--> (X1 Y1 X1 Y1)
use core::arch::x86_64::_mm256_blend_epi32; // (X1 Y1 X1 Y1) --(2x128b shuffle)--> (Y1 X1 Y1 X1)
use core::arch::x86_64::_mm256_shuffle_epi32; // and then adding.
let P = &self.0; // Set tmp0 = (X1 Y1 X1 Y1)
let mut tmp0 = self.0.shuffle(Shuffle::ABAB);
let mut t0 = FieldElement32x4::zero(); // Set tmp1 = (Y1 X1 Y1 X1)
let mut t1 = FieldElement32x4::zero(); let mut tmp1 = tmp0.shuffle(Shuffle::BADC);
// Want to compute (X1 Y1 Z1 X1+Y1). // Set tmp0 = (X1 Y1 Z1 X1+Y1)
// Not sure how to do this less expensively than computing tmp0 = self.0.blend(tmp0 + tmp1, Lanes::D);
// (X1 Y1 Z1 T1) --(256bit shuffle)--> (X1 Y1 X1 Y1)
// (X1 Y1 X1 Y1) --(2x128b shuffle)--> (Y1 X1 Y1 X1)
// and then adding.
// Set t0 = (X1 Y1 X1 Y1) // Set tmp1 = tmp0^2, negating the D values
t0.0[0] = _mm256_permute2x128_si256(P.0[0].into_bits(), P.0[0].into_bits(), 0b0000_0000).into_bits(); tmp1 = tmp0.square_and_negate_D();
t0.0[1] = _mm256_permute2x128_si256(P.0[1].into_bits(), P.0[1].into_bits(), 0b0000_0000).into_bits(); // Now tmp1 = (S1 S2 S3 -S4) with b < 0.007
t0.0[2] = _mm256_permute2x128_si256(P.0[2].into_bits(), P.0[2].into_bits(), 0b0000_0000).into_bits();
t0.0[3] = _mm256_permute2x128_si256(P.0[3].into_bits(), P.0[3].into_bits(), 0b0000_0000).into_bits();
t0.0[4] = _mm256_permute2x128_si256(P.0[4].into_bits(), P.0[4].into_bits(), 0b0000_0000).into_bits();
// Set t1 = (Y1 X1 Y1 X1) // See discussion of bounds in the module-level documentation.
t1.0[0] = _mm256_shuffle_epi32(t0.0[0].into_bits(), 0b10_11_00_01).into_bits(); // We want to compute
t1.0[1] = _mm256_shuffle_epi32(t0.0[1].into_bits(), 0b10_11_00_01).into_bits(); //
t1.0[2] = _mm256_shuffle_epi32(t0.0[2].into_bits(), 0b10_11_00_01).into_bits(); // + | S1 | S1 | S1 | S1 |
t1.0[3] = _mm256_shuffle_epi32(t0.0[3].into_bits(), 0b10_11_00_01).into_bits(); // + | S2 | | | S2 |
t1.0[4] = _mm256_shuffle_epi32(t0.0[4].into_bits(), 0b10_11_00_01).into_bits(); // + | | | S3 | |
// + | | | S3 | |
// + | | | |-S4 |
// + | | 2p | 2p | |
// - | | S2 | S2 | |
// =======================
// S5 S6 S8 S9
// Set t0 = (X1+Y1 X1+Y1 X1+Y1 X1+Y1) let zero = FieldElement32x4::zero();
t0.0[0] = t0.0[0] + t1.0[0]; let S_1 = tmp1.shuffle(Shuffle::AAAA);
t0.0[1] = t0.0[1] + t1.0[1]; let S_2 = tmp1.shuffle(Shuffle::BBBB);
t0.0[2] = t0.0[2] + t1.0[2];
t0.0[3] = t0.0[3] + t1.0[3];
t0.0[4] = t0.0[4] + t1.0[4];
// Set t0 = (X1 Y1 Z1 X1+Y1) tmp0 = zero.blend(tmp1 + tmp1, Lanes::C);
// why does this intrinsic take an i32 for the imm8 ??? // tmp0 = (0, 0, 2S_3, 0)
t0.0[0] = _mm256_blend_epi32(P.0[0].into_bits(), t0.0[0].into_bits(), D_LANES as i32).into_bits(); tmp0 = tmp0.blend(tmp1, Lanes::D);
t0.0[1] = _mm256_blend_epi32(P.0[1].into_bits(), t0.0[1].into_bits(), D_LANES as i32).into_bits(); // tmp0 = (0, 0, 2S_3, -S_4)
t0.0[2] = _mm256_blend_epi32(P.0[2].into_bits(), t0.0[2].into_bits(), D_LANES as i32).into_bits(); tmp0 = tmp0 + S_1;
t0.0[3] = _mm256_blend_epi32(P.0[3].into_bits(), t0.0[3].into_bits(), D_LANES as i32).into_bits(); // tmp0 = ( S_1, S_1, S_1 + 2S_3, S_1 - S_4)
t0.0[4] = _mm256_blend_epi32(P.0[4].into_bits(), t0.0[4].into_bits(), D_LANES as i32).into_bits(); tmp0 = tmp0 + zero.blend(S_2, Lanes::AD);
// tmp0 = (S_1 + S_2, S_1, S_1 + 2S_3, S_1 + S_2 - S_4)
tmp0 = tmp0 + zero.blend(S_2.negate_lazy(), Lanes::BC);
// tmp0 = (S_1 + S_2, S_1 - S_2, S_1 - S_2 + 2S_3, S_1 + S_2 - S_4)
// b < ( 1.01, 1.6, 2.33, 1.6)
// Now tmp0 = (S_5, S_6, S_8, S_9)
// Set t1 = t0^2, negating the D values // Set tmp1 = ( S_9, S_6, S_6, S_9)
t1 = t0.square_and_negate_D(); // b < ( 1.6, 1.6, 1.6, 1.6)
tmp1 = tmp0.shuffle(Shuffle::DBBD);
// Set tmp1 = ( S_8, S_5, S_8, S_5)
// b < (2.33, 1.01, 2.33, 1.01)
tmp0 = tmp0.shuffle(Shuffle::CACA);
// Now t1 = (S1 S2 S3 -S4) // Bounds on (tmp0, tmp1) are (2.33, 1.6) < (2.5, 1.75).
ExtendedPoint(&tmp0 * &tmp1)
let c0 = u32x8::new(0,0,2,2,0,0,2,2).into_bits(); // (ABCD) -> (AAAA)
let c1 = u32x8::new(1,1,3,3,1,1,3,3).into_bits(); // (ABCD) -> (BBBB)
// See discussion of bounds in the module-level documentation.
//
// We want to compute
//
// + | S1 | S1 | S1 | S1 |
// + | S2 | | | S2 |
// + | | | S3 | |
// + | | | S3 | |
// + | | | |-S4 |
// + | | 2p | 2p | |
// - | | S2 | S2 | |
// =======================
// S5 S6 S8 S9
//
for i in 0..5 {
let zero = u32x8::splat(0).into_bits();
let S1: u32x8 = _mm256_permutevar8x32_epi32(t1.0[i].into_bits(), c0).into_bits();
let S2: u32x8 = _mm256_permutevar8x32_epi32(t1.0[i].into_bits(), c1).into_bits();
let S3_2: u32x8 = _mm256_blend_epi32(zero, (t1.0[i] + t1.0[i]).into_bits(), 0b01010000).into_bits();
// tmp0 = (0 0 2*S3 -S4)
let tmp0: u32x8 = _mm256_blend_epi32(S3_2.into_bits(), t1.0[i].into_bits(), 0b10100000).into_bits();
t0.0[i] = (avx2::constants::P_TIMES_2_MASKED.0[i] + tmp0) + S1;
let S2_pos: u32x8 = _mm256_blend_epi32(zero, S2.into_bits(), 0b10100101).into_bits();
let S2_neg: u32x8 = _mm256_blend_epi32(S2.into_bits(), zero, 0b10100101).into_bits();
t0.0[i] = t0.0[i] + S2_pos;
t0.0[i] = t0.0[i] - S2_neg;
}
let c0 = u32x8::new(4,0,6,2,4,0,6,2).into_bits(); // (ABCD) -> (CACA)
let c1 = u32x8::new(5,1,7,3,1,5,3,7).into_bits(); // (ABCD) -> (DBBD)
for i in 0..5 {
let tmp = t0.0[i];
t0.0[i] = _mm256_permutevar8x32_epi32(tmp.into_bits(), c0).into_bits();
t1.0[i] = _mm256_permutevar8x32_epi32(tmp.into_bits(), c1).into_bits();
}
ExtendedPoint(&t0 * &t1)
}
} }
pub fn mul_by_pow_2(&self, k: u32) -> ExtendedPoint { pub fn mul_by_pow_2(&self, k: u32) -> ExtendedPoint {
@ -178,6 +167,15 @@ impl ExtendedPoint {
} }
/// A cached point with some precomputed variables used for readdition. /// A cached point with some precomputed variables used for readdition.
///
/// # Warning
///
/// It is not safe to negate this point more than once.
///
/// # Invariant
///
/// As long as the `CachedPoint` is not repeatedly negated, its
/// coefficients will be bounded with \\( b < 1.0 \\).
#[derive(Copy, Clone, Debug)] #[derive(Copy, Clone, Debug)]
pub struct CachedPoint(pub(super) FieldElement32x4); pub struct CachedPoint(pub(super) FieldElement32x4);
@ -185,15 +183,16 @@ impl From<ExtendedPoint> for CachedPoint {
fn from(P: ExtendedPoint) -> CachedPoint { fn from(P: ExtendedPoint) -> CachedPoint {
let mut x = P.0; let mut x = P.0;
// x = (S2 S3 Z2 T2) x = x.blend(x.diff_sum(), Lanes::AB);
x.diff_sum(Lanes::AB); // x = (X1 - Y1, X2 + Y2, Z2, T2) = (S2 S3 Z2 T2)
x = x * (121666, 121666, 2*121666, 2*121665);
// x = (121666*S2 121666*S3 2*121666*Z2 2*121665*T2) // x = (121666*S2 121666*S3 2*121666*Z2 2*121665*T2)
x.scale_by_curve_constants();
x = x.blend(-x, Lanes::D);
// x = (121666*S2 121666*S3 2*121666*Z2 -2*121665*T2) // x = (121666*S2 121666*S3 2*121666*Z2 -2*121665*T2)
x.negate_D();
// The coefficients of the output are bounded with b < 0.007.
CachedPoint(x) CachedPoint(x)
} }
} }
@ -206,13 +205,7 @@ impl Default for CachedPoint {
impl Identity for CachedPoint { impl Identity for CachedPoint {
fn identity() -> CachedPoint { fn identity() -> CachedPoint {
CachedPoint(FieldElement32x4([ constants::CACHEDPOINT_IDENTITY
u32x8::new(121647, 121666, 0, 0, 243332, 67108845, 0, 33554431),
u32x8::new(67108864, 0, 33554431, 0, 0, 67108863, 0, 33554431),
u32x8::new(67108863, 0, 33554431, 0, 0, 67108863, 0, 33554431),
u32x8::new(67108863, 0, 33554431, 0, 0, 67108863, 0, 33554431),
u32x8::new(67108863, 0, 33554431, 0, 0, 67108863, 0, 33554431),
]))
} }
} }
@ -224,52 +217,52 @@ impl ConditionallyAssignable for CachedPoint {
impl<'a> Neg for &'a CachedPoint { impl<'a> Neg for &'a CachedPoint {
type Output = CachedPoint; type Output = CachedPoint;
/// Lazily negate the point.
///
/// # Warning
///
/// Because this method does not perform a reduction, it is not
/// safe to repeatedly negate a point.
fn neg(self) -> CachedPoint { fn neg(self) -> CachedPoint {
let mut neg = *self; let swapped = self.0.shuffle(Shuffle::BACD);
neg.0.swap_AB(); CachedPoint(swapped.blend(swapped.negate_lazy(), Lanes::D))
neg.0.negate_D_lazy();
neg
} }
} }
impl<'a, 'b> Add<&'b CachedPoint> for &'a ExtendedPoint { impl<'a, 'b> Add<&'b CachedPoint> for &'a ExtendedPoint {
type Output = ExtendedPoint; type Output = ExtendedPoint;
/// Uses a slight tweak of the parallel unified formulas of HWCD'08 /// Add an `ExtendedPoint` and a `CachedPoint`.
fn add(self, other: &'b CachedPoint) -> ExtendedPoint { fn add(self, other: &'b CachedPoint) -> ExtendedPoint {
unsafe { // The coefficients of an `ExtendedPoint` are reduced after
use core::arch::x86_64::_mm256_permutevar8x32_epi32; // every operation. If the `CachedPoint` was negated, its
// coefficients grow by one bit. So on input, `self` is
// bounded with `b < 0.007` and `other` is bounded with
// `b < 1.0`.
let mut tmp = self.0;
let mut tmp = self.0; tmp = tmp.blend(tmp.diff_sum(), Lanes::AB);
// tmp = (Y1-X1 Y1+X1 Z1 T1) = (S0 S1 Z1 T1) with b < 1.6
// tmp = (Y1-X1 Y1+X1 Z1 T1) = (S0 S1 Z1 T1) // (tmp, other) bounded with b < (1.6, 1.0) < (2.5, 1.75).
tmp.diff_sum(Lanes::AB); tmp = &tmp * &other.0;
// tmp = (S0*S2' S1*S3' Z1*Z2' T1*T2') = (S8 S9 S10 S11)
// tmp = (S0*S2' S1*S3' Z1*Z2' T1*T2') = (S8 S9 S10 S11) tmp = tmp.shuffle(Shuffle::ABDC);
tmp = &tmp * &other.0; // tmp = (S8 S9 S11 S10)
// tmp = (S8 S9 S11 S10) tmp = tmp.diff_sum();
tmp.swap_CD(); // tmp = (S9-S8 S9+S8 S10-S11 S10+S11) = (S12 S13 S14 S15)
// tmp = (S9-S8 S9+S8 S10-S11 S10+S11) = (S12 S13 S14 S15) let t0 = tmp.shuffle(Shuffle::ADDA);
tmp.diff_sum(Lanes::ALL); // t0 = (S12 S15 S15 S12)
let t1 = tmp.shuffle(Shuffle::CBCB);
// t1 = (S14 S13 S14 S13)
let c0 = u32x8::new(0,5,2,7,5,0,7,2); // (ABCD) -> (ADDA) // All coefficients of t0, t1 are bounded with b < 1.6.
let c1 = u32x8::new(4,1,6,3,4,1,6,3); // (ABCD) -> (CBCB) // Return (S12*S14 S15*S13 S15*S14 S12*S13) = (X3 Y3 Z3 T3)
ExtendedPoint(&t0 * &t1)
// set t0 = (S12 S15 S15 S12)
// set t1 = (S14 S13 S14 S13)
let mut t0 = FieldElement32x4::zero();
let mut t1 = FieldElement32x4::zero();
for i in 0..5 {
t0.0[i] = _mm256_permutevar8x32_epi32(tmp.0[i].into_bits(), c0.into_bits()).into_bits();
t1.0[i] = _mm256_permutevar8x32_epi32(tmp.0[i].into_bits(), c1.into_bits()).into_bits();
}
// return (S12*S14 S15*S13 S15*S14 S12*S13) = (X3 Y3 Z3 T3)
ExtendedPoint(&t0 * &t1)
}
} }
} }
@ -278,8 +271,9 @@ impl<'a, 'b> Sub<&'b CachedPoint> for &'a ExtendedPoint {
/// Implement subtraction by negating the point and adding. /// Implement subtraction by negating the point and adding.
/// ///
/// Empirically, this seems about the same cost as a custom subtraction impl (maybe because the /// Empirically, this seems about the same cost as a custom
/// benefit is cancelled by increased code size?) /// subtraction impl (maybe because the benefit is cancelled by
/// increased code size?)
fn sub(self, other: &'b CachedPoint) -> ExtendedPoint { fn sub(self, other: &'b CachedPoint) -> ExtendedPoint {
self + &(-other) self + &(-other)
} }
@ -290,7 +284,7 @@ impl<'a> From<&'a edwards::EdwardsPoint> for LookupTable<CachedPoint> {
let P = ExtendedPoint::from(*point); let P = ExtendedPoint::from(*point);
let mut points = [CachedPoint::from(P); 8]; let mut points = [CachedPoint::from(P); 8];
for i in 0..7 { for i in 0..7 {
points[i+1] = (&P + &points[i]).into(); points[i + 1] = (&P + &points[i]).into();
} }
LookupTable(points) LookupTable(points)
} }
@ -335,23 +329,23 @@ mod test {
macro_rules! print_var { macro_rules! print_var {
($x:ident) => { ($x:ident) => {
println!("{} = {:?}", stringify!($x), $x.to_bytes()); println!("{} = {:?}", stringify!($x), $x.to_bytes());
} };
} }
let S0 = &Y1 - &X1; // R1 let S0 = &Y1 - &X1; // R1
let S1 = &Y1 + &X1; // R3 let S1 = &Y1 + &X1; // R3
let S2 = &Y2 - &X2; // R2 let S2 = &Y2 - &X2; // R2
let S3 = &Y2 + &X2; // R4 let S3 = &Y2 + &X2; // R4
print_var!(S0); print_var!(S0);
print_var!(S1); print_var!(S1);
print_var!(S2); print_var!(S2);
print_var!(S3); print_var!(S3);
println!(""); println!("");
let S4 = &S0 * &S2; // R5 = R1 * R2 let S4 = &S0 * &S2; // R5 = R1 * R2
let S5 = &S1 * &S3; // R6 = R3 * R4 let S5 = &S1 * &S3; // R6 = R3 * R4
let S6 = &Z1 * &Z2; // R8 let S6 = &Z1 * &Z2; // R8
let S7 = &T1 * &T2; // R7 let S7 = &T1 * &T2; // R7
print_var!(S4); print_var!(S4);
print_var!(S5); print_var!(S5);
print_var!(S6); print_var!(S6);
@ -362,8 +356,8 @@ mod test {
let S9 = &S5 * &FieldElement64([ 121666,0,0,0,0]); // R6 let S9 = &S5 * &FieldElement64([ 121666,0,0,0,0]); // R6
let S10 = &S6 * &FieldElement64([2*121666,0,0,0,0]); // R8 let S10 = &S6 * &FieldElement64([2*121666,0,0,0,0]); // R8
let S11 = &S7 * &(-&FieldElement64([2*121665,0,0,0,0])); // R7 let S11 = &S7 * &(-&FieldElement64([2*121665,0,0,0,0])); // R7
print_var!(S8 ); print_var!(S8);
print_var!(S9 ); print_var!(S9);
print_var!(S10); print_var!(S10);
print_var!(S11); print_var!(S11);
println!(""); println!("");
@ -378,12 +372,17 @@ mod test {
print_var!(S15); print_var!(S15);
println!(""); println!("");
let X3 = &S12 * &S14; // R1 * R2 let X3 = &S12 * &S14; // R1 * R2
let Y3 = &S15 * &S13; // R3 * R4 let Y3 = &S15 * &S13; // R3 * R4
let Z3 = &S15 * &S14; // R2 * R3 let Z3 = &S15 * &S14; // R2 * R3
let T3 = &S12 * &S13; // R1 * R4 let T3 = &S12 * &S13; // R1 * R4
edwards::EdwardsPoint{X: X3, Y: Y3, Z: Z3, T: T3} edwards::EdwardsPoint {
X: X3,
Y: Y3,
Z: Z3,
T: T3,
}
} }
fn addition_test_helper(P: edwards::EdwardsPoint, Q: edwards::EdwardsPoint) { fn addition_test_helper(P: edwards::EdwardsPoint, Q: edwards::EdwardsPoint) {
@ -437,15 +436,15 @@ mod test {
} }
fn serial_double(P: edwards::EdwardsPoint) -> edwards::EdwardsPoint { fn serial_double(P: edwards::EdwardsPoint) -> edwards::EdwardsPoint {
let (X1, Y1, Z1, T1) = (P.X, P.Y, P.Z, P.T); let (X1, Y1, Z1, _T1) = (P.X, P.Y, P.Z, P.T);
macro_rules! print_var { macro_rules! print_var {
($x:ident) => { ($x:ident) => {
println!("{} = {:?}", stringify!($x), $x.to_bytes()); println!("{} = {:?}", stringify!($x), $x.to_bytes());
} };
} }
let S0 = &X1 + &Y1; // R1 let S0 = &X1 + &Y1; // R1
print_var!(S0); print_var!(S0);
println!(""); println!("");
@ -476,7 +475,12 @@ mod test {
let Z3 = &S8 * &S6; let Z3 = &S8 * &S6;
let T3 = &S5 * &S9; let T3 = &S5 * &S9;
edwards::EdwardsPoint{X: X3, Y: Y3, Z: Z3, T: T3} edwards::EdwardsPoint {
X: X3,
Y: Y3,
Z: Z3,
T: T3,
}
} }
fn doubling_test_helper(P: edwards::EdwardsPoint) { fn doubling_test_helper(P: edwards::EdwardsPoint) {

File diff suppressed because it is too large Load diff

View file

@ -8,6 +8,8 @@
// - Isis Agora Lovecruft <isis@patternsinthevoid.net> // - Isis Agora Lovecruft <isis@patternsinthevoid.net>
// - Henry de Valence <hdevalence@hdevalence.ca> // - Henry de Valence <hdevalence@hdevalence.ca>
#![allow(non_snake_case)]
use core::borrow::Borrow; use core::borrow::Borrow;
use clear_on_drop::ClearOnDrop; use clear_on_drop::ClearOnDrop;

View file

@ -27,6 +27,6 @@ pub mod u32;
#[cfg(feature = "u64_backend")] #[cfg(feature = "u64_backend")]
pub mod u64; pub mod u64;
#[cfg(all(feature = "avx2_backend", feature = "yolocrypto", target_feature = "avx2"))] #[cfg(all(feature = "avx2_backend", target_feature = "avx2"))]
pub mod avx2; pub mod avx2;

View file

@ -14,7 +14,7 @@
#![cfg_attr(feature = "nightly", feature(cfg_target_feature))] #![cfg_attr(feature = "nightly", feature(cfg_target_feature))]
#![cfg_attr(feature = "nightly", feature(external_doc))] #![cfg_attr(feature = "nightly", feature(external_doc))]
#![cfg_attr(all(feature = "nightly", feature = "yolocrypto"), feature(stdsimd))] #![cfg_attr(all(feature = "nightly", feature = "avx2_backend"), feature(stdsimd))]
// Refuse to compile if documentation is missing, but only on nightly. // Refuse to compile if documentation is missing, but only on nightly.
// //