67965b3312e5109c5f2a06f675370c649f5d011a
[openssl.git] / crypto / ec / curve448 / arch_x86_64 / f_impl.h
1 /*
2  * Copyright 2017 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright 2014-2016 Cryptography Research, Inc.
4  *
5  * Licensed under the OpenSSL license (the "License").  You may not use
6  * this file except in compliance with the License.  You can obtain a copy
7  * in the file LICENSE in the source distribution or at
8  * https://www.openssl.org/source/license.html
9  *
10  * Originally written by Mike Hamburg
11  */
12
13 #define GF_HEADROOM 60
14 #define FIELD_LITERAL(a,b,c,d,e,f,g,h) {{a,b,c,d,e,f,g,h}}
15 #define LIMB_PLACE_VALUE(i) 56
16
17 void gf_add_RAW(gf out, const gf a, const gf b)
18 {
19     for (unsigned int i = 0; i < sizeof(*out) / sizeof(uint64xn_t); i++) {
20         ((uint64xn_t *) out)[i] =
21             ((const uint64xn_t *)a)[i] + ((const uint64xn_t *)b)[i];
22     }
23 }
24
25 void gf_sub_RAW(gf out, const gf a, const gf b)
26 {
27     for (unsigned int i = 0; i < sizeof(*out) / sizeof(uint64xn_t); i++) {
28         ((uint64xn_t *) out)[i] =
29             ((const uint64xn_t *)a)[i] - ((const uint64xn_t *)b)[i];
30     }
31 }
32
33 void gf_bias(gf a, int amt)
34 {
35     uint64_t co1 = ((1ull << 56) - 1) * amt, co2 = co1 - amt;
36
37 #if __AVX2__
38     uint64x4_t lo = { co1, co1, co1, co1 }, hi = {
39     co2, co1, co1, co1};
40     uint64x4_t *aa = (uint64x4_t *) a;
41     aa[0] += lo;
42     aa[1] += hi;
43 #elif __SSE2__
44     uint64x2_t lo = { co1, co1 }, hi = {
45     co2, co1};
46     uint64x2_t *aa = (uint64x2_t *) a;
47     aa[0] += lo;
48     aa[1] += lo;
49     aa[2] += hi;
50     aa[3] += lo;
51 #else
52     for (unsigned int i = 0; i < sizeof(*a) / sizeof(uint64_t); i++) {
53         a->limb[i] += (i == 4) ? co2 : co1;
54     }
55 #endif
56 }
57
58 void gf_weak_reduce(gf a)
59 {
60     /* PERF: use pshufb/palignr if anyone cares about speed of this */
61     uint64_t mask = (1ull << 56) - 1;
62     uint64_t tmp = a->limb[7] >> 56;
63
64     a->limb[4] += tmp;
65     for (unsigned int i = 7; i > 0; i--) {
66         a->limb[i] = (a->limb[i] & mask) + (a->limb[i - 1] >> 56);
67     }
68     a->limb[0] = (a->limb[0] & mask) + tmp;
69 }