c739b70d51e18811299b7917548cf3ad8858b025
[openssl.git] / crypto / ec / curve448 / word.h
1 /*
2  * Copyright 2017-2018 The OpenSSL Project Authors. All Rights Reserved.
3  * Copyright 2014 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 #ifndef HEADER_WORD_H
14 # define HEADER_WORD_H
15
16 # include <string.h>
17 # include <assert.h>
18 # include <stdlib.h>
19 # include <openssl/e_os2.h>
20 # include "arch_intrinsics.h"
21 # include "curve448utils.h"
22
23 # if defined(__ARM_NEON__)
24 #  include <arm_neon.h>
25 # elif defined(__SSE2__)
26 #  if !defined(__GNUC__) || defined(__clang__) || __GNUC__ >= 5 \
27       || (__GNUC__==4 && __GNUC_MINOR__ >= 4)
28 #   include <immintrin.h>
29 #  else
30 #   include <emmintrin.h>
31 #  endif
32 # endif
33
34 # if (ARCH_WORD_BITS == 64)
35 typedef uint64_t word_t, mask_t;
36 typedef __uint128_t dword_t;
37 typedef int32_t hsword_t;
38 typedef int64_t sword_t;
39 typedef __int128_t dsword_t;
40 # elif (ARCH_WORD_BITS == 32)
41 typedef uint32_t word_t, mask_t;
42 typedef uint64_t dword_t;
43 typedef int16_t hsword_t;
44 typedef int32_t sword_t;
45 typedef int64_t dsword_t;
46 # else
47 #  error "For now, we only support 32- and 64-bit architectures."
48 # endif
49
50 /*
51  * Scalar limbs are keyed off of the API word size instead of the arch word
52  * size.
53  */
54 # if C448_WORD_BITS == 64
55 #  define SC_LIMB(x) (x)
56 # elif C448_WORD_BITS == 32
57 #  define SC_LIMB(x) ((uint32_t)(x)),((x) >> 32)
58 # else
59 #  error "For now we only support 32- and 64-bit architectures."
60 # endif
61
62 /*
63  * The plan on booleans: The external interface uses c448_bool_t, but this
64  * might be a different size than our particular arch's word_t (and thus
65  * mask_t).  Also, the caller isn't guaranteed to pass it as nonzero.  So
66  * bool_to_mask converts word sizes and checks nonzero. On the flip side,
67  * mask_t is always -1 or 0, but it might be a different size than
68  * c448_bool_t. On the third hand, we have success vs boolean types, but
69  * that's handled in common.h: it converts between c448_bool_t and
70  * c448_error_t.
71  */
72 static ossl_inline c448_bool_t mask_to_bool(mask_t m)
73 {
74     return (c448_sword_t)(sword_t)m;
75 }
76
77 static ossl_inline mask_t bool_to_mask(c448_bool_t m)
78 {
79     /* On most arches this will be optimized to a simple cast. */
80     mask_t ret = 0;
81     unsigned int i;
82     unsigned int limit = sizeof(c448_bool_t) / sizeof(mask_t);
83
84     if (limit < 1)
85         limit = 1;
86     for (i = 0; i < limit; i++)
87         ret |= ~word_is_zero(m >> (i * 8 * sizeof(word_t)));
88
89     return ret;
90 }
91
92 #endif                          /* HEADER_WORD_H */