Debian Codegraph @

include/plink2_base.h

raw
1 #ifndef __PLINK2_BASE_H__
2 #define __PLINK2_BASE_H__
3
4 // This library is part of PLINK 2.0, copyright (C) 2005-2025 Shaun Purcell,
5 // Christopher Chang.
6 //
7 // This library is free software: you can redistribute it and/or modify it
8 // under the terms of the GNU Lesser General Public License as published by the
9 // Free Software Foundation; either version 3 of the License, or (at your
10 // option) any later version.
11 //
12 // This library is distributed in the hope that it will be useful, but WITHOUT
13 // ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
14 // FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
15 // for more details.
16 //
17 // You should have received a copy of the GNU Lesser General Public License
18 // along with this library. If not, see <http://www.gnu.org/licenses/>.
19
20
21 // Low-level C99/C++03/C++11 library covering basic I/O, SWAR/SIMD, and
22 // Windows/OS X/Linux portability. We try to benefit from as much C++ type
23 // safety as we can without either breaking compatibility with C-only codebases
24 // or making extension of pgenlib/plink2 code more difficult than the old
25 // type-unsafe style.
26 //
27 // Parameter conventions:
28 // - Input parameters, then in/out, then pure outputs, then temporary buffers.
29 // Reference-style input parameters tend to go in the very front, to make it
30 // more obvious that they aren't in/out.
31 // - "bitarr" indicates a word-aligned, packed array of bits, while "bitvec"
32 // indicates vector-alignment in 64-bit builds. ("vector" always means SIMD
33 // inputs/outputs here; C++ std::vector is not used in this codebase.)
34 // - Most pointers are stationary; moving pointers have an _iter suffix.
35 //
36 // Type-choice guidelines:
37 // - Integers are unsigned by default, signed only when necessary.
38 // It's necessary to choose one or the other to avoid drowning in a sea of
39 // casts and unexpected behavior. Each choice has its own surprising
40 // pitfalls that the developer had better be aware of; and I definitely do
41 // not take the position that unsigned is the better default *in all C and/or
42 // C++ code*. However, for this codebase, the extremely high frequency of
43 // bitwise operations makes unsigned-default the only sane choice.
44 // Some consequences of this choice:
45 // - All pointer differences that are part of a larger arithmetic or
46 // comparison expression are explicitly casted to uintptr_t.
47 // - Since uint64_t -> double conversion is frequently slower than int64_t ->
48 // double conversion, u63tod() should be used when the integer is known to
49 // be less than 2^63. If we also know it's less than 2^31, u31tod() can
50 // provide a performance improvement on Win32.
51 // - Integers that can be >= 2^32 in some of the largest existing datasets, but
52 // are usually smaller, should be defined as uintptr_t, to strike a good
53 // balance between 32-bit performance and 64-bit scaling. Exhaustive
54 // overflow checking in the 32-bit build is a non-goal; but I do aim for very
55 // high statistical reliability, by inserting checks whenever it occurs to me
56 // that overflow is especially likely (e.g. when multiplying two potentially
57 // large 32-bit numbers).
58 // - Bitarrays and 'nyparrays' (packed arrays of 2-bit elements, such as a row
59 // of a plink 1.x .bed file) are usually uintptr_t*, to encourage
60 // word-at-a-time iteration without requiring vector-alignment. Quite a few
61 // low-level library functions cast them to VecW*. As mentioned above, the
62 // affected function parameter names must end in 'vec' when this creates an
63 // alignment requirement.
64 // - A buffer/iterator expected to contain only UTF-8 text should be char*.
65 // unsigned char* should be reserved for byte-array buffers and iterators
66 // which are expected to interact with some non-text bytes, and generic
67 // memory-location pointers which will be subject to pointer arithmetic.
68 // (Note that this creates some clutter in low-level parsing code: since the
69 // signedness of char is platform-dependent, it becomes necessary to use e.g.
70 // ctou32() a fair bit.)
71 // - unsigned char is an acceptable argument type for functions intended to
72 // process a single text character, thanks to implicit char -> unsigned char
73 // conversion; it's just unsigned char* that should be avoided.
74 // - void* return values should be restricted to generic pointers which are
75 // *not* expected to be subject to pointer arithmetic. void* as input
76 // parameter type should only be used when there are at least two equally
77 // valid input types, NOT counting VecW*.
78
79
80 // gcc 8.3.0 has been miscompiling the ParseOnebitUnsafe() function in
81 // pgenlib_read.cc for the last several years. gcc 8.4 does not have this
82 // problem, and neither does any other gcc major version I've tested to date.
83 #ifndef __clang__
84 # if (__GNUC__ == 8) && (__GNUC_MINOR__ < 4)
85 # error "gcc 8.3 is known to have a miscompilation bug that was fixed in 8.4."
86 # endif
87 #endif
88
89 #if (__GNUC__ < 4)
90 // may eventually add MSVC support to gain access to MKL on Windows, but can't
91 // justify doing that before all major features are implemented.
92 # error "gcc 4.x+ or clang equivalent required."
93 #endif
94
95 // The -Wshorten-64-to-32 diagnostic forces the code to be cluttered with
96 // meaningless uintptr_t -> uint32_t static casts (number known to be < 2^32,
97 // just stored in a uintptr_t because there's no speed penalty and we generally
98 // want to think in terms of word-based operations). The code is more readable
99 // if S_CAST(uint32_t, <potentially wider value>) is reserved for situations
100 // where a higher bit may actually be set. This pragma can always be commented
101 // out on the few occasions where inappropriate silent truncation is suspected.
102 #ifdef __clang__
103 # pragma clang diagnostic ignored "-Wshorten-64-to-32"
104 #endif
105
106 // 10000 * major + 100 * minor + patch
107 // Exception to CONSTI32, since we want the preprocessor to have access
108 // to this value. Named with all caps as a consequence.
109 #define PLINK2_BASE_VERNUM 817
110
111
112 #define _FILE_OFFSET_BITS 64
113
114 #include <stdio.h>
115 #include <stdlib.h>
116 #include <string.h>
117 #include <stddef.h> // offsetof()
118 #include <stdint.h>
119 #ifndef __STDC_FORMAT_MACROS
120 # define __STDC_FORMAT_MACROS 1
121 #endif
122 #include <inttypes.h>
123 #include <limits.h> // CHAR_BIT, PATH_MAX
124
125 // #define NDEBUG
126 #include <assert.h>
127
128 #ifdef _WIN32
129 // needed for EnterCriticalSection, etc.
130 # ifndef _WIN64
131 # define WINVER 0x0501
132 # else
133 # define __LP64__
134 # endif
135 # ifndef WIN32_LEAN_AND_MEAN
136 # define WIN32_LEAN_AND_MEAN
137 # endif
138 # include <windows.h>
139 #endif
140
141 #if __cplusplus >= 201103L
142 # include <array>
143 #endif
144
145 #ifdef __LP64__
146 // Possible todo: working no-SSE2 fallback on 64-bit little-endian platforms
147 // unsupported by simde. Can perform early test by compiling on arm64 without
148 // simde.
149 // (But not yet aware of a use case that matters.)
150 # define USE_SSE2
151 # ifdef __x86_64__
152 # include <emmintrin.h>
153 # else
154 # define SIMDE_ENABLE_NATIVE_ALIASES
155 // Since e.g. an old zstd system header breaks the build, and plink2 is
156 // expected to remain under active development for the next few years, we
157 // currently default to using vendored copies of zstd/libdeflate/simde, which
158 // are manually updated as necessary.
159 // To use system headers, define IGNORE_BUNDLED_{ZSTD,LIBDEFLATE.SIMDE}.
160 # ifdef IGNORE_BUNDLED_SIMDE
161 # include <simde/x86/sse2.h>
162 # else
163 # include "../simde/x86/sse2.h"
164 # endif
165 # ifdef SIMDE_ARM_NEON_A32V8_NATIVE
166 // For Apple M1, we effectively use SSE2 + constrained _mm_shuffle_epi8().
167 // - We don't want to use simde's emulated _mm_shuffle_epi8 since it has an
168 // extra and-with-0x8f step that we never need.
169 // In the event the and-with-0x8f is actually needed, we'll define
170 // vec..._x86_shuffle8() helper functions.
171 // - M1 also doesn't have efficient word-popcount.
172 # define USE_SHUFFLE8
173 # endif
174 # endif
175 # ifdef __SSE4_2__
176 # define USE_SSE42
177 # define USE_SHUFFLE8
178 # include <smmintrin.h>
179 # ifdef __AVX2__
180 # if defined(__BMI__) && defined(__BMI2__) && defined(__LZCNT__)
181 # include <immintrin.h>
182 # define USE_AVX2
183 # else
184 // Graceful downgrade, in case -march=native misfires on a VM. See
185 // https://github.com/chrchang/plink-ng/issues/155 .
186 # warning "AVX2 builds require -mbmi, -mbmi2, and -mlzcnt as well. Downgrading to SSE4.2 build."
187 # undef USE_AVX2
188 # endif
189 # endif
190 # endif
191 # define ALIGNV16 __attribute__ ((aligned (16)))
192 #else
193 # define ALIGNV16
194 #endif
195
196 // done with #includes, can start C++ namespace...
197 #ifdef __cplusplus
198 namespace plink2 {
199 #endif
200
201 // ...though a bunch of symbols remain to be #defined; try to reduce the number
202 // over time.
203
204 #ifndef UINT32_MAX
205 // can theoretically be undefined in C++03
206 # define UINT32_MAX 0xffffffffU
207 #endif
208
209 #define UINT32_MAXM1 0xfffffffeU
210
211 #ifndef UINT64_MAX
212 # define UINT64_MAX 0xffffffffffffffffLLU
213 #endif
214
215 #ifdef __cplusplus
216 # define HEADER_INLINE inline
217 // Previously went on a wild constexpr spree, but now these are mostly unused.
218 // Reserve for cases where (i) there's a clear constant-initialization use case
219 // for an imaginable downstream program (I'm looking at you, DivUp() and
220 // RoundUpPow2()...), or (ii) it allows a useful static_assert to be inserted
221 // for a hardcoded constant.
222 # if __cplusplus >= 201103L
223 # define HEADER_CINLINE constexpr
224 # define CSINLINE static constexpr
225 # if __cplusplus > 201103L
226 # define HEADER_CINLINE2 constexpr
227 # define CSINLINE2 static constexpr
228 # else
229 # define HEADER_CINLINE2 inline
230 # define CSINLINE2 static inline
231 # endif
232 # else
233 # define HEADER_CINLINE inline
234 # define HEADER_CINLINE2 inline
235 # define CSINLINE static inline
236 # define CSINLINE2 static inline
237 # endif
238 # if __cplusplus <= 199711L
239 // this may be defined anyway, at least on OS X
240 # ifndef static_assert
241 // todo: check other cases
242 # define static_assert(cond, msg)
243 # endif
244 # endif
245 #else
246 # define HEADER_INLINE static inline
247 # define HEADER_CINLINE static inline
248 # define HEADER_CINLINE2 static inline
249 # define CSINLINE static inline
250 # define CSINLINE2 static inline
251 // _Static_assert() should work in gcc 4.6+
252 # if (__GNUC__ == 4) && (__GNUC_MINOR__ < 6)
253 # if defined(__clang__) && defined(__has_feature) && defined(__has_extension)
254 # if __has_feature(c_static_assert) || __has_extension(c_static_assert)
255 # define static_assert _Static_assert
256 # else
257 # define static_assert(cond, msg)
258 # endif
259 # else
260 # define static_assert(cond, msg)
261 # endif
262 # else
263 # define static_assert _Static_assert
264 # endif
265 #endif
266
267 #define __maybe_unused __attribute__((unused))
268
269 // Rule of thumb: Use these macros if, and only if, the condition would always
270 // trigger exit-from-program. As a side effect, this makes it more
271 // straightforward, if still tedious, to make global changes to error-handling
272 // strategy (always dump backtrace and exit immediately?), though provision
273 // must still be made for sometimes-error-sometimes-not return paths which
274 // don't get an unlikely annotation.
275 #ifndef likely
276 # define likely(expr) __builtin_expect(!!(expr), 1)
277 # define unlikely(expr) __builtin_expect(!!(expr), 0)
278 #endif
279
280 #ifdef __cplusplus
281 # define K_CAST(type, val) (const_cast<type>(val))
282 # define R_CAST(type, val) (reinterpret_cast<type>(val))
283 # define S_CAST(type, val) (static_cast<type>(val))
284 #else
285 # define K_CAST(type, val) ((type)(val))
286 # define R_CAST(type, val) ((type)(val))
287 # define S_CAST(type, val) ((type)(val))
288 #endif
289
290 // (from Linux kernel)
291 // container_of - cast a member of a structure out to the containing structure
292 // @ptr: the pointer to the member.
293 // @type: the type of the container struct this is embedded in.
294 // @member: the name of the member within the struct.
295 #define container_of(ptr, type, member) \
296 (R_CAST(type*, R_CAST(char*, ptr) - offsetof(type, member)))
297
298 // original macro doesn't work in C++ when e.g. ptr is a const char*, and the
299 // quick workaround of casting away the const is unsafe.
300 #define const_container_of(ptr, type, member) \
301 (R_CAST(const type*, R_CAST(const char*, ptr) - offsetof(type, member)))
302
303 HEADER_INLINE double u31tod(uint32_t uii) {
304 const int32_t ii = uii;
305 assert(ii >= 0);
306 return S_CAST(double, ii);
307 }
308
309 HEADER_INLINE double swtod(intptr_t lii) {
310 return S_CAST(double, lii);
311 }
312
313 HEADER_INLINE double u63tod(uint64_t ullii) {
314 const int64_t llii = ullii;
315 assert(llii >= 0);
316 return S_CAST(double, llii);
317 }
318
319 HEADER_INLINE float u31tof(uint32_t uii) {
320 const int32_t ii = uii;
321 assert(ii >= 0);
322 return S_CAST(float, ii);
323 }
324
325 HEADER_INLINE uint32_t ctou32(char cc) {
326 return S_CAST(unsigned char, cc);
327 }
328
329 HEADER_INLINE uintptr_t ctow(char cc) {
330 return S_CAST(unsigned char, cc);
331 }
332
333 HEADER_INLINE uint64_t ctou64(char cc) {
334 return S_CAST(unsigned char, cc);
335 }
336
337 HEADER_INLINE unsigned char* CToUc(char* pp) {
338 return R_CAST(unsigned char*, pp);
339 }
340
341 // Error return types. All of these evaluate to true on error and false on
342 // success, but otherwise they have slightly different semantics:
343 // * PglErr is the general-purpose enum. Unlike an enum, implicit conversion
344 // *to* int, not just from int, is prevented by the C++11 compiler (and the
345 // C++11-compiler-validated code still works under C99). (To achieve this
346 // additional safety, we engage in a bit of code duplication which would be
347 // unreasonable for flagsets.)
348 // (Previously, explicit cast to uint32_t, but not int32_t, was supported, to
349 // reflect the fact that all error codes are positive. This was deemed
350 // silly.)
351 // * BoolErr allows implicit conversion from int, but conversion back to
352 // uint32_t requires an explicit cast. (It should always be 0/1-valued, but
353 // this isn't enforced by the compiler.)
354 // * IntErr allows implicit conversion from int, but conversion back to
355 // int32_t requires an explicit cast. It mainly serves as a holding pen for
356 // C standard library error return values, which can be negative.
357 #if __cplusplus >= 201103L
358 struct PglErr {
359 enum class ec
360 #else
361 typedef enum
362 #endif
363 {
364 kPglRetSuccess,
365 kPglRetSkipped,
366 kPglRetNomem,
367 kPglRetOpenFail,
368 kPglRetReadFail,
369 kPglRetWriteFail,
370 // MalformedInput should be returned on low-level file format violations,
371 // while InconsistentInput should be returned for higher-level logical
372 // problems like mismatched files (generally solvable by fixing the command
373 // line), and DegenerateData for properly-formatted-and-matched files that
374 // yields degenerate computational results due to e.g. divide by zero or
375 // insufficient rank.
376 kPglRetMalformedInput,
377 kPglRetInconsistentInput,
378 kPglRetInvalidCmdline,
379 kPglRetThreadCreateFail,
380 kPglRetNetworkFail,
381 kPglRetVarRecordTooLarge,
382 kPglRetUnsupportedInstructions,
383 kPglRetDegenerateData,
384 kPglRetDecompressFail, // also distinguish this from MalformedInput
385 kPglRetRewindFail,
386 kPglRetGpuFail,
387 kPglRetInternalUse1,
388 kPglRetSampleMajorBed = 32,
389 kPglRetNomemCustomMsg = 59,
390 kPglRetInternalError = 60,
391 kPglRetWarningErrcode = 61,
392 kPglRetImproperFunctionCall = 62,
393 kPglRetNotYetSupported = 63,
394
395 // These are only for internal use. If any of these reach the top level
396 // instead of being handled or converted to another error code, that's a bug,
397 // and plink2 prints a message to that effect.
398 kPglRetRetry = 124,
399 kPglRetHelp = 125,
400 kPglRetLongLine = 126,
401 kPglRetEof = 127}
402 #if __cplusplus >= 201103L
403 ;
404
405 PglErr() {}
406
407 PglErr(const PglErr& source) : value_(source.value_) {}
408
409 PglErr(ec source) : value_(source) {}
410
411 // Allow explicit conversion from uint64_t, and NOT uint32_t, to this error
412 // type, to support reproducible multithreaded error reporting (where
413 // multiple threads may atomically attempt to modify a single uint64_t with
414 // the error code in the low 32 bits and a priority number in the high bits).
415 explicit PglErr(uint64_t source) : value_(static_cast<ec>(source)) {}
416
417 PglErr& operator=(const PglErr&) = default;
418
419 operator ec() const {
420 return value_;
421 }
422
423 explicit operator uint32_t() const {
424 return static_cast<uint32_t>(value_);
425 }
426
427 explicit operator int32_t() const {
428 return static_cast<int32_t>(value_);
429 }
430
431 explicit operator bool() const {
432 return (static_cast<uint32_t>(value_) != 0);
433 }
434
435 private:
436 ec value_;
437 };
438
439 const PglErr kPglRetSuccess = PglErr::ec::kPglRetSuccess;
440 const PglErr kPglRetSkipped = PglErr::ec::kPglRetSkipped;
441 const PglErr kPglRetNomem = PglErr::ec::kPglRetNomem;
442 const PglErr kPglRetOpenFail = PglErr::ec::kPglRetOpenFail;
443 const PglErr kPglRetReadFail = PglErr::ec::kPglRetReadFail;
444 const PglErr kPglRetWriteFail = PglErr::ec::kPglRetWriteFail;
445 const PglErr kPglRetMalformedInput = PglErr::ec::kPglRetMalformedInput;
446 const PglErr kPglRetInconsistentInput = PglErr::ec::kPglRetInconsistentInput;
447 const PglErr kPglRetInvalidCmdline = PglErr::ec::kPglRetInvalidCmdline;
448 const PglErr kPglRetRetry = PglErr::ec::kPglRetRetry;
449 const PglErr kPglRetHelp = PglErr::ec::kPglRetHelp;
450 const PglErr kPglRetThreadCreateFail = PglErr::ec::kPglRetThreadCreateFail;
451 const PglErr kPglRetNetworkFail = PglErr::ec::kPglRetNetworkFail;
452 const PglErr kPglRetVarRecordTooLarge = PglErr::ec::kPglRetVarRecordTooLarge;
453 const PglErr kPglRetUnsupportedInstructions = PglErr::ec::kPglRetUnsupportedInstructions;
454 const PglErr kPglRetDegenerateData = PglErr::ec::kPglRetDegenerateData;
455 const PglErr kPglRetDecompressFail = PglErr::ec::kPglRetDecompressFail;
456 const PglErr kPglRetRewindFail = PglErr::ec::kPglRetRewindFail;
457 const PglErr kPglRetGpuFail = PglErr::ec::kPglRetGpuFail;
458 const PglErr kPglRetInternalUse1 = PglErr::ec::kPglRetInternalUse1;
459 const PglErr kPglRetSampleMajorBed = PglErr::ec::kPglRetSampleMajorBed;
460 const PglErr kPglRetWarningErrcode = PglErr::ec::kPglRetWarningErrcode;
461 const PglErr kPglRetNomemCustomMsg = PglErr::ec::kPglRetNomemCustomMsg;
462 const PglErr kPglRetInternalError = PglErr::ec::kPglRetInternalError;
463 const PglErr kPglRetImproperFunctionCall = PglErr::ec::kPglRetImproperFunctionCall;
464 const PglErr kPglRetNotYetSupported = PglErr::ec::kPglRetNotYetSupported;
465 const PglErr kPglRetLongLine = PglErr::ec::kPglRetLongLine;
466 const PglErr kPglRetEof = PglErr::ec::kPglRetEof;
467 #else
468 PglErr;
469 #endif
470
471 #if __cplusplus >= 201103L
472 // allow efficient arithmetic on these, but force them to require explicit
473 // int32_t/uint32_t casts; only permit implicit assignment from
474 // int32_t/uint32_t by default.
475 // built-in bool type does too many things we don't want...
476
477 // expected to be integer-valued, but not necessarily 0/1 or positive
478 struct IntErr {
479 IntErr() {}
480
481 IntErr(int32_t source) : value_(source) {}
482
483 explicit operator int32_t() const {
484 return value_;
485 }
486
487 explicit operator bool() const {
488 return (value_ != 0);
489 }
490
491 private:
492 int32_t value_;
493 };
494
495 // expected to be 0/1-valued
496 struct BoolErr {
497 BoolErr() {}
498
499 BoolErr(uint32_t source) : value_(source) {}
500
501 explicit operator uint32_t() const {
502 return value_;
503 }
504
505 explicit operator bool() const {
506 return (value_ != 0);
507 }
508
509 private:
510 uint32_t value_;
511 };
512 #else
513 typedef int32_t IntErr;
514 typedef uint32_t BoolErr;
515 #endif
516
517 extern const char kErrprintfFopen[];
518 extern const char kErrprintfFread[];
519 extern const char kErrprintfRewind[];
520 extern const char kErrstrNomem[];
521 extern const char kErrstrWrite[];
522 extern const char kErrprintfDecompress[];
523
524 // make this work on 32-bit as well as 64-bit systems, across
525 // Windows/OS X/Linux
526 // (todo: clean this up a bit. it's inherently a baling-wire-and-duct-tape
527 // sort of thing, though...)
528 #ifdef _WIN32
529 // must compile with -std=gnu++11, not c++11, on 32-bit Windows since
530 // otherwise fseeko64 not defined...
531 # define fseeko fseeko64
532 # define ftello ftello64
533 # define FOPEN_RB "rb"
534 # define FOPEN_WB "wb"
535 # define FOPEN_AB "ab"
536 # define ferror_unlocked ferror
537 # define feof_unlocked feof
538 # ifdef __LP64__
539 # define getc_unlocked _fgetc_nolock
540 # define putc_unlocked _fputc_nolock
541 // todo: find mingw-w64 build which properly links _fread_nolock, and
542 // conditional-compile
543 # define fread_unlocked fread
544 # define fwrite_unlocked fwrite
545 # else
546 # define getc_unlocked getc
547 # define putc_unlocked putc
548 # define fread_unlocked fread
549 # define fwrite_unlocked fwrite
550 # endif
551 # if __cplusplus < 201103L
552 # define uint64_t unsigned long long
553 # define int64_t long long
554 # endif
555 #else // Linux or OS X
556 # define FOPEN_RB "r"
557 # define FOPEN_WB "w"
558 # define FOPEN_AB "a"
559 # if defined(__APPLE__) || defined(__FreeBSD__) || defined(__NetBSD__)
560 # define fread_unlocked fread
561 # define fwrite_unlocked fwrite
562 # endif
563 # if defined(__NetBSD__)
564 # define ferror_unlocked ferror
565 # define feof_unlocked feof
566 # endif
567 #endif
568
569 #ifdef _WIN32
570 # undef PRId64
571 # undef PRIu64
572 # define PRId64 "I64d"
573 # define PRIu64 "I64u"
574 #else
575 # ifdef __cplusplus
576 # ifndef PRId64
577 # define PRId64 "lld"
578 # endif
579 # endif
580 #endif
581
582 // These are useful for defending against base-pointer integer overflow on bad
583 // input.
584 HEADER_INLINE BoolErr PtrAddCk(const unsigned char* end, intptr_t incr, const unsigned char** basep) {
585 *basep += incr;
586 return unlikely((end - (*basep)) < 0);
587 }
588
589 // 'W' for writable
590 HEADER_INLINE BoolErr PtrWSubCk(unsigned char* base, intptr_t decr, unsigned char** endp) {
591 *endp -= decr;
592 return unlikely(((*endp) - base) < 0);
593 }
594
595 HEADER_INLINE BoolErr PtrCheck(const void* end, const void* base, intptr_t req) {
596 const unsigned char* end_uc = S_CAST(const unsigned char*, end);
597 const unsigned char* base_uc = S_CAST(const unsigned char*, base);
598 return unlikely((end_uc - base_uc) < req);
599 }
600
601 // We want this to return an uint32_t, not an int32_t.
602 HEADER_INLINE uint32_t ctzu32(uint32_t uii) {
603 return __builtin_ctz(uii);
604 }
605
606 // this should always compile down to bsr.
607 HEADER_INLINE uint32_t bsru32(uint32_t uii) {
608 return 31 - __builtin_clz(uii);
609 }
610
611 #ifdef _WIN64
612 HEADER_INLINE uint32_t ctzw(unsigned long long ullii) {
613 return __builtin_ctzll(ullii);
614 }
615
616 HEADER_INLINE uint32_t bsrw(unsigned long long ullii) {
617 // Note that this actually compiles to a single instruction on x86; it's
618 // naked __builtin_clzll which requires an additional subtraction.
619 return 63 - __builtin_clzll(ullii);
620 }
621 #else
622 HEADER_INLINE uint32_t ctzw(unsigned long ulii) {
623 return __builtin_ctzl(ulii);
624 }
625
626 HEADER_INLINE uint32_t bsrw(unsigned long ulii) {
627 return (8 * sizeof(intptr_t) - 1) - __builtin_clzl(ulii);
628 }
629 # ifndef __LP64__
630 // needed to prevent GCC 6 build failure
631 # if (__GNUC__ == 4) && (__GNUC_MINOR__ < 8)
632 # if (__cplusplus < 201103L) && !defined(__APPLE__)
633 # ifndef uintptr_t
634 # define uintptr_t unsigned long
635 # endif
636 # ifndef intptr_t
637 # define intptr_t long
638 # endif
639 # endif
640 # endif
641 # endif
642 #endif
643
644 #ifdef __LP64__
645 # ifdef _WIN32 // i.e. Win64
646
647 # undef PRIuPTR
648 # undef PRIdPTR
649 # define PRIuPTR PRIu64
650 # define PRIdPTR PRId64
651 # define PRIxPTR2 "016I64x"
652
653 # else // not _WIN32
654
655 # ifndef PRIuPTR
656 # define PRIuPTR "lu"
657 # endif
658 # ifndef PRIdPTR
659 # define PRIdPTR "ld"
660 # endif
661 # define PRIxPTR2 "016lx"
662
663 # endif // Win64
664
665 #else // not __LP64__
666
667 // without this, we get ridiculous warning spew...
668 // not 100% sure this is the right cutoff, but this has been tested on 4.7
669 // and 4.8 build machines, so it plausibly is.
670 # if (__GNUC__ == 4) && (__GNUC_MINOR__ < 8) && (__cplusplus < 201103L)
671 # undef PRIuPTR
672 # undef PRIdPTR
673 # define PRIuPTR "lu"
674 # define PRIdPTR "ld"
675 # endif
676
677 # define PRIxPTR2 "08lx"
678
679 #endif
680
681 #ifndef HAVE_NULLPTR
682 # ifndef __cplusplus
683 # define nullptr NULL
684 # else
685 # if __cplusplus <= 199711L
686 # ifndef nullptr
687 # define nullptr NULL
688 # endif
689 # endif
690 # endif
691 #endif
692
693 // Checked a bunch of alternatives to #define constants. For integer constants
694 // in [-2^31, 2^31), enum {} avoids macro expansion issues that actually
695 // matter, and that more than cancels out any tiny increase in binary size due
696 // to additional debugger information (which has value, anyway). However, we
697 // don't want to use this under C++ due to enumeral/non-enumeral conditional
698 // expression warnings, so this isn't one-size-fits-all; and plain old const
699 // int has all the functionality we want under C++ (including internal linkage,
700 // so it's fine to define them in header files). Thus we wrap the
701 // implementation in a macro.
702 //
703 // Otherwise, the macro expansion thing is still annoying but we suck it up due
704 // to the need for too much duplicate C vs. C++ code ("initializer element is
705 // not constant" when using const <type> in C99...)
706 //
707 // We start most plink2- and pgenlib-specific numeric constant names here with
708 // "kPgl", which should have a vanishingly small chance of colliding with
709 // anything in C99. Note that stuff like kBytesPerWord is not considered
710 // library-specific, so it's exempt from having "Pgl" in the name. Also, the
711 // few string literals here are of the FOPEN_WB sort, which have similar usage
712 // patterns to e.g. PRIuPTR which shouldn't be renamed, so those remain
713 // all-caps.
714 //
715 // (Update, May 2018: CONSTU31 was renamed to CONSTI32 and changed to type
716 // int32_t, to prevent C vs. C++ differences. This almost never makes a
717 // difference, since when int32_t and uint32_t are mixed in the same
718 // expression, the former gets converted to unsigned. However, unpleasant
719 // surprises are occasionally possible when mixing these constants with
720 // uint16_t or unsigned char values, since then the unsigned values are
721 // promoted to int32_t. Also, this essentially forces use of -Wno-sign-compare
722 // when using gcc 4.4.
723 //
724 // Biggest thing to watch out for is mixing of Halfword with these constants in
725 // 32-bit builds. Dosage and Vec8thUint are also relevant.)
726 #ifdef __cplusplus
727 # define CONSTI32(name, expr) const int32_t name = (expr)
728 #else
729 # define CONSTI32(name, expr) enum {name = (expr)}
730 #endif
731
732 // useful because of its bitwise complement: ~k0LU is a word with all 1 bits,
733 // while ~0 is always 32 1 bits.
734 // LLU is used over ULL for searchability (no conflict with NULL).
735 static const uintptr_t k0LU = S_CAST(uintptr_t, 0);
736
737 // mainly useful for bitshifts: (k1LU << 32) works in 64-bit builds, while
738 // (1 << 32) is undefined. also used as a quicker-to-type way of casting
739 // numbers/expressions to uintptr_t (via multiplication).
740 static const uintptr_t k1LU = S_CAST(uintptr_t, 1);
741
742 #ifdef __LP64__
743 CONSTI32(kBitsPerWord, 64);
744 CONSTI32(kBitsPerWordLog2, 6);
745
746 typedef uint32_t Halfword;
747 typedef uint16_t Quarterword;
748 #else
749 CONSTI32(kBitsPerWord, 32);
750 CONSTI32(kBitsPerWordLog2, 5);
751
752 typedef uint16_t Halfword;
753 typedef uint8_t Quarterword;
754 #endif
755
756 #ifdef USE_SSE2
757 # ifdef USE_AVX2
758 CONSTI32(kBytesPerVec, 32);
759
760 // 16 still seems to noticeably outperform 32 on my Mac test machine, and
761 // is about equal on my Linux test machine, probably due to reduced clock
762 // frequency when 32-byte floating point vector operations are used (as in, ALL
763 // operations, sometimes on ALL cores, become slower when a single core
764 // performs a 32-byte fp vector operation).
765 // However, processor power management, numeric libraries, and my AVX2 code
766 // should improve over time. There will probably come a time where switching
767 // to 32-byte fp is worthwhile.
768 # define FVEC_32
769
770 // bleah, have to define these here, vector_size doesn't see enum values
771 typedef uintptr_t VecW __attribute__ ((vector_size (32)));
772 typedef uint32_t VecU32 __attribute__ ((vector_size (32)));
773 typedef int32_t VecI32 __attribute__ ((vector_size (32)));
774 typedef unsigned short VecU16 __attribute__ ((vector_size (32)));
775 typedef short VecI16 __attribute__ ((vector_size (32)));
776 // documentation says 'char', but int8_t works fine under gcc 4.4 and conveys
777 // intent better (char not guaranteed to be signed)
778 typedef int8_t VecI8 __attribute__ ((vector_size (32)));
779 typedef unsigned char VecUc __attribute__ ((vector_size (32)));
780
781 HEADER_INLINE VecW VecToW(__m256i vv) {
782 return R_CAST(VecW, vv);
783 }
784
785 HEADER_INLINE VecU32 VecToU32(__m256i vv) {
786 return R_CAST(VecU32, vv);
787 }
788
789 HEADER_INLINE VecI32 VecToI32(__m256i vv) {
790 return R_CAST(VecI32, vv);
791 }
792
793 HEADER_INLINE VecU16 VecToU16(__m256i vv) {
794 return R_CAST(VecU16, vv);
795 }
796
797 HEADER_INLINE VecI16 VecToI16(__m256i vv) {
798 return R_CAST(VecI16, vv);
799 }
800
801 HEADER_INLINE VecUc VecToUc(__m256i vv) {
802 return R_CAST(VecUc, vv);
803 }
804
805 HEADER_INLINE VecI8 VecToI8(__m256i vv) {
806 return R_CAST(VecI8, vv);
807 }
808
809 HEADER_INLINE __m256i WToVec(VecW vv) {
810 return R_CAST(__m256i, vv);
811 }
812
813 HEADER_INLINE __m256i U32ToVec(VecU32 vv) {
814 return R_CAST(__m256i, vv);
815 }
816
817 HEADER_INLINE __m256i I32ToVec(VecI32 vv) {
818 return R_CAST(__m256i, vv);
819 }
820
821 HEADER_INLINE __m256i U16ToVec(VecU16 vv) {
822 return R_CAST(__m256i, vv);
823 }
824
825 HEADER_INLINE __m256i I16ToVec(VecI16 vv) {
826 return R_CAST(__m256i, vv);
827 }
828
829 HEADER_INLINE __m256i UcToVec(VecUc vv) {
830 return R_CAST(__m256i, vv);
831 }
832
833 HEADER_INLINE __m256i I8ToVec(VecI8 vv) {
834 return R_CAST(__m256i, vv);
835 }
836
837 // _mm256_set1_... seems to have the same performance; could use that instead.
838 # define VCONST_W(xx) {xx, xx, xx, xx}
839 # define VCONST_S(xx) {xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx}
840 # define VCONST_C(xx) {xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx}
841 # define VCONST_UC VCONST_C
842
843 // vv = VCONST_W(k0LU) doesn't work (only ok for initialization)
844 HEADER_INLINE VecW vecw_setzero() {
845 return VecToW(_mm256_setzero_si256());
846 }
847
848 HEADER_INLINE VecU32 vecu32_setzero() {
849 return VecToU32(_mm256_setzero_si256());
850 }
851
852 HEADER_INLINE VecU16 vecu16_setzero() {
853 return VecToU16(_mm256_setzero_si256());
854 }
855
856 HEADER_INLINE VecI16 veci16_setzero() {
857 return VecToI16(_mm256_setzero_si256());
858 }
859
860 HEADER_INLINE VecUc vecuc_setzero() {
861 return VecToUc(_mm256_setzero_si256());
862 }
863
864 HEADER_INLINE VecI8 veci8_setzero() {
865 return VecToI8(_mm256_setzero_si256());
866 }
867
868 // "vv >> ct" doesn't work, and Scientific Linux gcc 4.4 might not optimize
869 // VCONST_W shift properly (todo: test this)
870 HEADER_INLINE VecW vecw_srli(VecW vv, uint32_t ct) {
871 return VecToW(_mm256_srli_epi64(WToVec(vv), ct));
872 }
873
874 HEADER_INLINE VecW vecw_slli(VecW vv, uint32_t ct) {
875 return VecToW(_mm256_slli_epi64(WToVec(vv), ct));
876 }
877
878 HEADER_INLINE VecU32 vecu32_srli(VecU32 vv, uint32_t ct) {
879 return VecToU32(_mm256_srli_epi32(U32ToVec(vv), ct));
880 }
881
882 HEADER_INLINE VecU32 vecu32_slli(VecU32 vv, uint32_t ct) {
883 return VecToU32(_mm256_slli_epi32(U32ToVec(vv), ct));
884 }
885
886 HEADER_INLINE VecU16 vecu16_srli(VecU16 vv, uint32_t ct) {
887 return VecToU16(_mm256_srli_epi16(U16ToVec(vv), ct));
888 }
889
890 HEADER_INLINE VecU16 vecu16_slli(VecU16 vv, uint32_t ct) {
891 return VecToU16(_mm256_slli_epi16(U16ToVec(vv), ct));
892 }
893
894 // Compiler still doesn't seem to be smart enough to use andnot properly.
895 HEADER_INLINE VecW vecw_and_notfirst(VecW excl, VecW main) {
896 return VecToW(_mm256_andnot_si256(WToVec(excl), WToVec(main)));
897 }
898
899 HEADER_INLINE VecU32 vecu32_and_notfirst(VecU32 excl, VecU32 main) {
900 return VecToU32(_mm256_andnot_si256(U32ToVec(excl), U32ToVec(main)));
901 }
902
903 HEADER_INLINE VecI32 veci32_and_notfirst(VecI32 excl, VecI32 main) {
904 return VecToI32(_mm256_andnot_si256(I32ToVec(excl), I32ToVec(main)));
905 }
906
907 HEADER_INLINE VecU16 vecu16_and_notfirst(VecU16 excl, VecU16 main) {
908 return VecToU16(_mm256_andnot_si256(U16ToVec(excl), U16ToVec(main)));
909 }
910
911 HEADER_INLINE VecI16 veci16_and_notfirst(VecI16 excl, VecI16 main) {
912 return VecToI16(_mm256_andnot_si256(I16ToVec(excl), I16ToVec(main)));
913 }
914
915 HEADER_INLINE VecUc vecuc_and_notfirst(VecUc excl, VecUc main) {
916 return VecToUc(_mm256_andnot_si256(UcToVec(excl), UcToVec(main)));
917 }
918
919 HEADER_INLINE VecI8 veci8_and_notfirst(VecI8 excl, VecI8 main) {
920 return VecToI8(_mm256_andnot_si256(I8ToVec(excl), I8ToVec(main)));
921 }
922
923 HEADER_INLINE VecW vecw_set1(uintptr_t ulii) {
924 return VecToW(_mm256_set1_epi64x(ulii));
925 }
926
927 HEADER_INLINE VecU32 vecu32_set1(uint32_t uii) {
928 return VecToU32(_mm256_set1_epi32(uii));
929 }
930
931 HEADER_INLINE VecI32 veci32_set1(int32_t ii) {
932 return VecToI32(_mm256_set1_epi32(ii));
933 }
934
935 HEADER_INLINE VecU16 vecu16_set1(unsigned short usi) {
936 return VecToU16(_mm256_set1_epi16(usi));
937 }
938
939 HEADER_INLINE VecI16 veci16_set1(short si) {
940 return VecToI16(_mm256_set1_epi16(si));
941 }
942
943 HEADER_INLINE VecUc vecuc_set1_epi16(unsigned short usi) {
944 return VecToUc(_mm256_set1_epi16(usi));
945 }
946
947 HEADER_INLINE VecUc vecuc_set1(unsigned char ucc) {
948 return VecToUc(_mm256_set1_epi8(ucc));
949 }
950
951 HEADER_INLINE VecI8 veci8_set1(char cc) {
952 return VecToI8( _mm256_set1_epi8(cc));
953 }
954
955 HEADER_INLINE uint32_t vecw_movemask(VecW vv) {
956 return _mm256_movemask_epi8(WToVec(vv));
957 }
958
959 HEADER_INLINE uint32_t vecu32_movemask(VecU32 vv) {
960 return _mm256_movemask_epi8(U32ToVec(vv));
961 }
962
963 HEADER_INLINE uint32_t veci32_movemask(VecI32 vv) {
964 return _mm256_movemask_epi8(I32ToVec(vv));
965 }
966
967 HEADER_INLINE uint32_t vecu16_movemask(VecU16 vv) {
968 return _mm256_movemask_epi8(U16ToVec(vv));
969 }
970
971 HEADER_INLINE uint32_t veci16_movemask(VecI16 vv) {
972 return _mm256_movemask_epi8(I16ToVec(vv));
973 }
974
975 HEADER_INLINE uint32_t veci8_movemask(VecI8 vv) {
976 return _mm256_movemask_epi8(I8ToVec(vv));
977 }
978
979 HEADER_INLINE uint32_t vecuc_movemask(VecUc vv) {
980 return _mm256_movemask_epi8(UcToVec(vv));
981 }
982
983 // Repeats elements in second lane in AVX2 case.
984 HEADER_INLINE VecW vecw_setr8(char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) {
985 return VecToW(_mm256_setr_epi8(e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0, e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0));
986 }
987
988 HEADER_INLINE VecU16 vecu16_setr8(char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) {
989 return VecToU16(_mm256_setr_epi8(e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0, e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0));
990 }
991
992 HEADER_INLINE VecUc vecuc_setr8(char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) {
993 return VecToUc(_mm256_setr_epi8(e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0, e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0));
994 }
995
996 // Discards last 16 arguments in SSE2/SSE4.2 case.
997 HEADER_INLINE VecW vecw_setr8x(char e31, char e30, char e29, char e28, char e27, char e26, char e25, char e24, char e23, char e22, char e21, char e20, char e19, char e18, char e17, char e16, char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) {
998 return VecToW(_mm256_setr_epi8(e31, e30, e29, e28, e27, e26, e25, e24, e23, e22, e21, e20, e19, e18, e17, e16, e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0));
999 }
1000
1001 HEADER_INLINE VecUc vecuc_setr8x(char e31, char e30, char e29, char e28, char e27, char e26, char e25, char e24, char e23, char e22, char e21, char e20, char e19, char e18, char e17, char e16, char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) {
1002 return VecToUc(_mm256_setr_epi8(e31, e30, e29, e28, e27, e26, e25, e24, e23, e22, e21, e20, e19, e18, e17, e16, e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0));
1003 }
1004
1005 HEADER_INLINE VecW vecw_setr32(uint32_t e3, uint32_t e2, uint32_t e1, uint32_t e0) {
1006 return VecToW(_mm256_setr_epi32(e3, e2, e1, e0, e3, e2, e1, e0));
1007 }
1008
1009
1010 HEADER_INLINE VecW vecw_unpacklo8(VecW evens, VecW odds) {
1011 return VecToW(_mm256_unpacklo_epi8(WToVec(evens), WToVec(odds)));
1012 }
1013
1014 HEADER_INLINE VecW vecw_unpackhi8(VecW evens, VecW odds) {
1015 return VecToW(_mm256_unpackhi_epi8(WToVec(evens), WToVec(odds)));
1016 }
1017
1018 HEADER_INLINE VecI8 veci8_unpacklo8(VecI8 evens, VecI8 odds) {
1019 return VecToI8(_mm256_unpacklo_epi8(I8ToVec(evens), I8ToVec(odds)));
1020 }
1021
1022 HEADER_INLINE VecI8 veci8_unpackhi8(VecI8 evens, VecI8 odds) {
1023 return VecToI8(_mm256_unpackhi_epi8(I8ToVec(evens), I8ToVec(odds)));
1024 }
1025
1026 HEADER_INLINE VecUc vecuc_unpacklo8(VecUc evens, VecUc odds) {
1027 return VecToUc(_mm256_unpacklo_epi8(UcToVec(evens), UcToVec(odds)));
1028 }
1029
1030 HEADER_INLINE VecUc vecuc_unpackhi8(VecUc evens, VecUc odds) {
1031 return VecToUc(_mm256_unpackhi_epi8(UcToVec(evens), UcToVec(odds)));
1032 }
1033
1034 HEADER_INLINE VecW vecw_unpacklo16(VecW evens, VecW odds) {
1035 return VecToW(_mm256_unpacklo_epi16(WToVec(evens), WToVec(odds)));
1036 }
1037
1038 HEADER_INLINE VecW vecw_unpackhi16(VecW evens, VecW odds) {
1039 return VecToW(_mm256_unpackhi_epi16(WToVec(evens), WToVec(odds)));
1040 }
1041
1042 HEADER_INLINE VecW vecw_unpacklo32(VecW evens, VecW odds) {
1043 return VecToW(_mm256_unpacklo_epi32(WToVec(evens), WToVec(odds)));
1044 }
1045
1046 HEADER_INLINE VecW vecw_unpackhi32(VecW evens, VecW odds) {
1047 return VecToW(_mm256_unpackhi_epi32(WToVec(evens), WToVec(odds)));
1048 }
1049
1050 HEADER_INLINE VecW vecw_permute0xd8_if_avx2(VecW vv) {
1051 return VecToW(_mm256_permute4x64_epi64(WToVec(vv), 0xd8));
1052 }
1053
1054 HEADER_INLINE VecI8 veci8_permute0xd8_if_avx2(VecI8 vv) {
1055 return VecToI8(_mm256_permute4x64_epi64(I8ToVec(vv), 0xd8));
1056 }
1057
1058 HEADER_INLINE VecUc vecuc_permute0xd8_if_avx2(VecUc vv) {
1059 return VecToUc(_mm256_permute4x64_epi64(UcToVec(vv), 0xd8));
1060 }
1061
1062 // Could have a single-src gather_even function, but that should wait until
1063 // there is a clear SSE2 use case.
1064 HEADER_INLINE VecW vecw_gather_even(VecW src_lo, VecW src_hi, VecW m8) {
1065 const VecW gathered_laneswapped = VecToW(_mm256_packus_epi16(WToVec(src_lo & m8), WToVec(src_hi & m8)));
1066 return vecw_permute0xd8_if_avx2(gathered_laneswapped);
1067 }
1068
1069 HEADER_INLINE VecUc vecuc_gather_even(VecUc src_lo, VecUc src_hi, VecUc m8) {
1070 const VecUc gathered_laneswapped = VecToUc(_mm256_packus_epi16(UcToVec(src_lo & m8), UcToVec(src_hi & m8)));
1071 return vecuc_permute0xd8_if_avx2(gathered_laneswapped);
1072 }
1073
1074 HEADER_INLINE VecUc vecuc_gather_odd(VecUc src_lo, VecUc src_hi) {
1075 const VecUc gathered_laneswapped = VecToUc(_mm256_packus_epi16(_mm256_srli_epi16(UcToVec(src_lo), 8), _mm256_srli_epi16(UcToVec(src_hi), 8)));
1076 return vecuc_permute0xd8_if_avx2(gathered_laneswapped);
1077 }
1078
1079 HEADER_INLINE VecW vecw_shuffle8(VecW table, VecW indexes) {
1080 return VecToW(_mm256_shuffle_epi8(WToVec(table), WToVec(indexes)));
1081 }
1082
1083 HEADER_INLINE VecU16 vecu16_shuffle8(VecU16 table, VecU16 indexes) {
1084 return VecToU16(_mm256_shuffle_epi8(U16ToVec(table), U16ToVec(indexes)));
1085 }
1086
1087 HEADER_INLINE VecUc vecuc_shuffle8(VecUc table, VecUc indexes) {
1088 return VecToUc(_mm256_shuffle_epi8(UcToVec(table), UcToVec(indexes)));
1089 }
1090
1091 HEADER_INLINE uintptr_t vecw_extract64_0(VecW vv) {
1092 return _mm256_extract_epi64(WToVec(vv), 0);
1093 }
1094
1095 HEADER_INLINE uintptr_t vecw_extract64_1(VecW vv) {
1096 return _mm256_extract_epi64(WToVec(vv), 1);
1097 }
1098
1099 // *** AVX2-only section ***
1100 HEADER_INLINE uintptr_t vecw_extract64_2(VecW vv) {
1101 return _mm256_extract_epi64(WToVec(vv), 2);
1102 }
1103
1104 HEADER_INLINE uintptr_t vecw_extract64_3(VecW vv) {
1105 return _mm256_extract_epi64(WToVec(vv), 3);
1106 }
1107
1108 // todo: permute
1109
1110 // *** end AVX2-only section ***
1111
1112 # define kVec8thUintMax UINT32_MAX
1113
1114 typedef uint16_t Vec16thUint;
1115 typedef uint32_t Vec8thUint;
1116 typedef uint64_t Vec4thUint;
1117
1118 HEADER_INLINE VecW vecw_load(const void* mem_addr) {
1119 return VecToW(_mm256_load_si256(S_CAST(const __m256i*, mem_addr)));
1120 }
1121
1122 // There may be some value in adding a 4-consecutive-vector load function when
1123 // addresses are expected to be unaligned: see
1124 // https://www.agner.org/optimize/blog/read.php?i=627&v=t
1125
1126 HEADER_INLINE VecW vecw_loadu(const void* mem_addr) {
1127 return VecToW(_mm256_loadu_si256(S_CAST(const __m256i*, mem_addr)));
1128 }
1129
1130 HEADER_INLINE VecU32 vecu32_loadu(const void* mem_addr) {
1131 return VecToU32(_mm256_loadu_si256(S_CAST(const __m256i*, mem_addr)));
1132 }
1133
1134 HEADER_INLINE VecI32 veci32_loadu(const void* mem_addr) {
1135 return VecToI32(_mm256_loadu_si256(S_CAST(const __m256i*, mem_addr)));
1136 }
1137
1138 HEADER_INLINE VecU16 vecu16_loadu(const void* mem_addr) {
1139 return VecToU16(_mm256_loadu_si256(S_CAST(const __m256i*, mem_addr)));
1140 }
1141
1142 HEADER_INLINE VecI16 veci16_loadu(const void* mem_addr) {
1143 return VecToI16(_mm256_loadu_si256(S_CAST(const __m256i*, mem_addr)));
1144 }
1145
1146 HEADER_INLINE VecUc vecuc_loadu(const void* mem_addr) {
1147 return VecToUc(_mm256_loadu_si256(S_CAST(const __m256i*, mem_addr)));
1148 }
1149
1150 HEADER_INLINE VecI8 veci8_loadu(const void* mem_addr) {
1151 return VecToI8(_mm256_loadu_si256(S_CAST(const __m256i*, mem_addr)));
1152 }
1153
1154 HEADER_INLINE void vec_storeu(void* mem_addr, __m256i vv) {
1155 _mm256_storeu_si256(S_CAST(__m256i*, mem_addr), vv);
1156 }
1157
1158 HEADER_INLINE VecI32 veci32_max(VecI32 v1, VecI32 v2) {
1159 return VecToI32(_mm256_max_epi32(I32ToVec(v1), I32ToVec(v2)));
1160 }
1161
1162 HEADER_INLINE VecI16 veci16_max(VecI16 v1, VecI16 v2) {
1163 return VecToI16(_mm256_max_epi16(I16ToVec(v1), I16ToVec(v2)));
1164 }
1165
1166 HEADER_INLINE VecW vecw_sad(VecW v1, VecW v2) {
1167 return VecToW(_mm256_sad_epu8(WToVec(v1), WToVec(v2)));
1168 }
1169
1170 HEADER_INLINE VecUc vecuc_adds(VecUc v1, VecUc v2) {
1171 return VecToUc(_mm256_adds_epu8(UcToVec(v1), UcToVec(v2)));
1172 }
1173
1174 HEADER_INLINE VecU16 vecu16_min8(VecU16 v1, VecU16 v2) {
1175 return VecToU16(_mm256_min_epu8(U16ToVec(v1), U16ToVec(v2)));
1176 }
1177
1178 HEADER_INLINE VecUc vecuc_min(VecUc v1, VecUc v2) {
1179 return VecToUc(_mm256_min_epu8(UcToVec(v1), UcToVec(v2)));
1180 }
1181
1182 HEADER_INLINE VecW vecw_blendv(VecW aa, VecW bb, VecW mask) {
1183 return VecToW(_mm256_blendv_epi8(WToVec(aa), WToVec(bb), WToVec(mask)));
1184 }
1185
1186 HEADER_INLINE VecU32 vecu32_blendv(VecU32 aa, VecU32 bb, VecU32 mask) {
1187 return VecToU32(_mm256_blendv_epi8(U32ToVec(aa), U32ToVec(bb), U32ToVec(mask)));
1188 }
1189
1190 HEADER_INLINE VecU16 vecu16_blendv(VecU16 aa, VecU16 bb, VecU16 mask) {
1191 return VecToU16(_mm256_blendv_epi8(U16ToVec(aa), U16ToVec(bb), U16ToVec(mask)));
1192 }
1193
1194 HEADER_INLINE VecUc vecuc_blendv(VecUc aa, VecUc bb, VecUc mask) {
1195 return VecToUc(_mm256_blendv_epi8(UcToVec(aa), UcToVec(bb), UcToVec(mask)));
1196 }
1197
1198 # else // USE_SSE2, !USE_AVX2
1199
1200 CONSTI32(kBytesPerVec, 16);
1201 typedef uintptr_t VecW __attribute__ ((vector_size (16)));
1202 typedef uint32_t VecU32 __attribute ((vector_size (16)));
1203 typedef int32_t VecI32 __attribute ((vector_size (16)));
1204 typedef unsigned short VecU16 __attribute__ ((vector_size (16)));
1205 typedef short VecI16 __attribute__ ((vector_size (16)));
1206 typedef int8_t VecI8 __attribute__ ((vector_size (16)));
1207 typedef unsigned char VecUc __attribute__ ((vector_size (16)));
1208
1209 HEADER_INLINE VecW VecToW(__m128i vv) {
1210 return R_CAST(VecW, vv);
1211 }
1212
1213 HEADER_INLINE VecU32 VecToU32(__m128i vv) {
1214 return R_CAST(VecU32, vv);
1215 }
1216
1217 HEADER_INLINE VecI32 VecToI32(__m128i vv) {
1218 return R_CAST(VecI32, vv);
1219 }
1220
1221 HEADER_INLINE VecU16 VecToU16(__m128i vv) {
1222 return R_CAST(VecU16, vv);
1223 }
1224
1225 HEADER_INLINE VecI16 VecToI16(__m128i vv) {
1226 return R_CAST(VecI16, vv);
1227 }
1228
1229 HEADER_INLINE VecUc VecToUc(__m128i vv) {
1230 return R_CAST(VecUc, vv);
1231 }
1232
1233 HEADER_INLINE VecI8 VecToI8(__m128i vv) {
1234 return R_CAST(VecI8, vv);
1235 }
1236
1237 HEADER_INLINE __m128i WToVec(VecW vv) {
1238 return R_CAST(__m128i, vv);
1239 }
1240
1241 HEADER_INLINE __m128i U32ToVec(VecU32 vv) {
1242 return R_CAST(__m128i, vv);
1243 }
1244
1245 HEADER_INLINE __m128i I32ToVec(VecI32 vv) {
1246 return R_CAST(__m128i, vv);
1247 }
1248
1249 HEADER_INLINE __m128i U16ToVec(VecU16 vv) {
1250 return R_CAST(__m128i, vv);
1251 }
1252
1253 HEADER_INLINE __m128i I16ToVec(VecI16 vv) {
1254 return R_CAST(__m128i, vv);
1255 }
1256
1257 HEADER_INLINE __m128i UcToVec(VecUc vv) {
1258 return R_CAST(__m128i, vv);
1259 }
1260
1261 HEADER_INLINE __m128i I8ToVec(VecI8 vv) {
1262 return R_CAST(__m128i, vv);
1263 }
1264
1265 # define VCONST_W(xx) {xx, xx}
1266 # define VCONST_S(xx) {xx, xx, xx, xx, xx, xx, xx, xx}
1267 # define VCONST_C(xx) {xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx, xx}
1268 # define VCONST_UC VCONST_C
1269
1270 HEADER_INLINE VecW vecw_setzero() {
1271 return VecToW(_mm_setzero_si128());
1272 }
1273
1274 HEADER_INLINE VecU32 vecu32_setzero() {
1275 return VecToU32(_mm_setzero_si128());
1276 }
1277
1278 HEADER_INLINE VecU16 vecu16_setzero() {
1279 return VecToU16(_mm_setzero_si128());
1280 }
1281
1282 HEADER_INLINE VecI16 veci16_setzero() {
1283 return VecToI16(_mm_setzero_si128());
1284 }
1285
1286 HEADER_INLINE VecUc vecuc_setzero() {
1287 return VecToUc(_mm_setzero_si128());
1288 }
1289
1290 HEADER_INLINE VecI8 veci8_setzero() {
1291 return VecToI8(_mm_setzero_si128());
1292 }
1293
1294 // simde is incompatible with defining these as inline functions
1295 # define vecw_srli(vv, ct) VecToW(_mm_srli_epi64(WToVec(vv), ct))
1296
1297 # define vecw_slli(vv, ct) VecToW(_mm_slli_epi64(WToVec(vv), ct))
1298
1299 # define vecu32_srli(vv, ct) VecToU32(_mm_srli_epi32(U32ToVec(vv), ct))
1300
1301 # define vecu32_slli(vv, ct) VecToU32(_mm_slli_epi32(U32ToVec(vv), ct))
1302
1303 # define vecu16_srli(vv, ct) VecToU16(_mm_srli_epi16(U16ToVec(vv), ct))
1304
1305 # define vecu16_slli(vv, ct) VecToU16(_mm_slli_epi16(U16ToVec(vv), ct))
1306
1307 HEADER_INLINE VecW vecw_and_notfirst(VecW excl, VecW main) {
1308 return VecToW(_mm_andnot_si128(WToVec(excl), WToVec(main)));
1309 }
1310
1311 HEADER_INLINE VecU32 vecu32_and_notfirst(VecU32 excl, VecU32 main) {
1312 return VecToU32(_mm_andnot_si128(U32ToVec(excl), U32ToVec(main)));
1313 }
1314
1315 HEADER_INLINE VecI32 veci32_and_notfirst(VecI32 excl, VecI32 main) {
1316 return VecToI32(_mm_andnot_si128(I32ToVec(excl), I32ToVec(main)));
1317 }
1318
1319 HEADER_INLINE VecU16 vecu16_and_notfirst(VecU16 excl, VecU16 main) {
1320 return VecToU16(_mm_andnot_si128(U16ToVec(excl), U16ToVec(main)));
1321 }
1322
1323 HEADER_INLINE VecI16 veci16_and_notfirst(VecI16 excl, VecI16 main) {
1324 return VecToI16(_mm_andnot_si128(I16ToVec(excl), I16ToVec(main)));
1325 }
1326
1327 HEADER_INLINE VecUc vecuc_and_notfirst(VecUc excl, VecUc main) {
1328 return VecToUc(_mm_andnot_si128(UcToVec(excl), UcToVec(main)));
1329 }
1330
1331 HEADER_INLINE VecI8 veci8_and_notfirst(VecI8 excl, VecI8 main) {
1332 return VecToI8(_mm_andnot_si128(I8ToVec(excl), I8ToVec(main)));
1333 }
1334
1335 HEADER_INLINE VecW vecw_set1(uintptr_t ulii) {
1336 return VecToW(_mm_set1_epi64x(ulii));
1337 }
1338
1339 HEADER_INLINE VecU32 vecu32_set1(uint32_t uii) {
1340 return VecToU32(_mm_set1_epi32(uii));
1341 }
1342
1343 HEADER_INLINE VecI32 veci32_set1(int32_t ii) {
1344 return VecToI32(_mm_set1_epi32(ii));
1345 }
1346
1347 HEADER_INLINE VecU16 vecu16_set1(unsigned short usi) {
1348 return VecToU16(_mm_set1_epi16(usi));
1349 }
1350
1351 HEADER_INLINE VecI16 veci16_set1(short si) {
1352 return VecToI16(_mm_set1_epi16(si));
1353 }
1354
1355 HEADER_INLINE VecUc vecuc_set1_epi16(unsigned short usi) {
1356 return VecToUc(_mm_set1_epi16(usi));
1357 }
1358
1359 HEADER_INLINE VecUc vecuc_set1(unsigned char ucc) {
1360 return VecToUc(_mm_set1_epi8(ucc));
1361 }
1362
1363 HEADER_INLINE VecI8 veci8_set1(char cc) {
1364 return VecToI8(_mm_set1_epi8(cc));
1365 }
1366
1367 HEADER_INLINE uint32_t vecw_movemask(VecW vv) {
1368 return _mm_movemask_epi8(WToVec(vv));
1369 }
1370
1371 HEADER_INLINE uint32_t vecu32_movemask(VecU32 vv) {
1372 return _mm_movemask_epi8(U32ToVec(vv));
1373 }
1374
1375 HEADER_INLINE uint32_t veci32_movemask(VecI32 vv) {
1376 return _mm_movemask_epi8(I32ToVec(vv));
1377 }
1378
1379 HEADER_INLINE uint32_t vecu16_movemask(VecU16 vv) {
1380 return _mm_movemask_epi8(U16ToVec(vv));
1381 }
1382
1383 HEADER_INLINE uint32_t veci16_movemask(VecI16 vv) {
1384 return _mm_movemask_epi8(I16ToVec(vv));
1385 }
1386
1387 HEADER_INLINE uint32_t veci8_movemask(VecI8 vv) {
1388 return _mm_movemask_epi8(I8ToVec(vv));
1389 }
1390
1391 HEADER_INLINE uint32_t vecuc_movemask(VecUc vv) {
1392 return _mm_movemask_epi8(UcToVec(vv));
1393 }
1394
1395 CONSTI32(kVec8thUintMax, 65535);
1396
1397 // # define kVec8thUintMax 65535
1398
1399 typedef unsigned char Vec16thUint;
1400 typedef uint16_t Vec8thUint;
1401 typedef uint32_t Vec4thUint;
1402
1403 HEADER_INLINE VecW vecw_load(const void* mem_addr) {
1404 return VecToW(_mm_load_si128(S_CAST(const __m128i*, mem_addr)));
1405 }
1406
1407 HEADER_INLINE VecW vecw_loadu(const void* mem_addr) {
1408 return VecToW(_mm_loadu_si128(S_CAST(const __m128i*, mem_addr)));
1409 }
1410
1411 HEADER_INLINE VecU32 vecu32_loadu(const void* mem_addr) {
1412 return VecToU32(_mm_loadu_si128(S_CAST(const __m128i*, mem_addr)));
1413 }
1414
1415 HEADER_INLINE VecI32 veci32_loadu(const void* mem_addr) {
1416 return VecToI32(_mm_loadu_si128(S_CAST(const __m128i*, mem_addr)));
1417 }
1418
1419 HEADER_INLINE VecU16 vecu16_loadu(const void* mem_addr) {
1420 return VecToU16(_mm_loadu_si128(S_CAST(const __m128i*, mem_addr)));
1421 }
1422
1423 HEADER_INLINE VecI16 veci16_loadu(const void* mem_addr) {
1424 return VecToI16(_mm_loadu_si128(S_CAST(const __m128i*, mem_addr)));
1425 }
1426
1427 HEADER_INLINE VecUc vecuc_loadu(const void* mem_addr) {
1428 return VecToUc(_mm_loadu_si128(S_CAST(const __m128i*, mem_addr)));
1429 }
1430
1431 HEADER_INLINE VecI8 veci8_loadu(const void* mem_addr) {
1432 return VecToI8(_mm_loadu_si128(S_CAST(const __m128i*, mem_addr)));
1433 }
1434
1435 HEADER_INLINE void vec_storeu(void* mem_addr, __m128i vv) {
1436 _mm_storeu_si128(S_CAST(__m128i*, mem_addr), vv);
1437 }
1438
1439 // Repeats arguments in AVX2 case.
1440 HEADER_INLINE VecW vecw_setr8(char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) {
1441 return VecToW(_mm_setr_epi8(e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0));
1442 }
1443
1444 HEADER_INLINE VecU16 vecu16_setr8(char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) {
1445 return VecToU16(_mm_setr_epi8(e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0));
1446 }
1447
1448 HEADER_INLINE VecUc vecuc_setr8(char e15, char e14, char e13, char e12, char e11, char e10, char e9, char e8, char e7, char e6, char e5, char e4, char e3, char e2, char e1, char e0) {
1449 return VecToUc(_mm_setr_epi8(e15, e14, e13, e12, e11, e10, e9, e8, e7, e6, e5, e4, e3, e2, e1, e0));
1450 }
1451
1452 // Discards last 16 arguments in SSE2/SSE4.2 case.
1453 HEADER_INLINE VecW vecw_setr8x(
1454 char e31, char e30, char e29, char e28,
1455 char e27, char e26, char e25, char e24,
1456 char e23, char e22, char e21, char e20,
1457 char e19, char e18, char e17, char e16,
1458 __maybe_unused char e15, __maybe_unused char e14,
1459 __maybe_unused char e13, __maybe_unused char e12,
1460 __maybe_unused char e11, __maybe_unused char e10,
1461 __maybe_unused char e9, __maybe_unused char e8,
1462 __maybe_unused char e7, __maybe_unused char e6,
1463 __maybe_unused char e5, __maybe_unused char e4,
1464 __maybe_unused char e3, __maybe_unused char e2,
1465 __maybe_unused char e1, __maybe_unused char e0) {
1466 return VecToW(_mm_setr_epi8(e31, e30, e29, e28, e27, e26, e25, e24, e23, e22, e21, e20, e19, e18, e17, e16));
1467 }
1468
1469 HEADER_INLINE VecUc vecuc_setr8x(
1470 char e31, char e30, char e29, char e28,
1471 char e27, char e26, char e25, char e24,
1472 char e23, char e22, char e21, char e20,
1473 char e19, char e18, char e17, char e16,
1474 __maybe_unused char e15, __maybe_unused char e14,
1475 __maybe_unused char e13, __maybe_unused char e12,
1476 __maybe_unused char e11, __maybe_unused char e10,
1477 __maybe_unused char e9, __maybe_unused char e8,
1478 __maybe_unused char e7, __maybe_unused char e6,
1479 __maybe_unused char e5, __maybe_unused char e4,
1480 __maybe_unused char e3, __maybe_unused char e2,
1481 __maybe_unused char e1, __maybe_unused char e0) {
1482 return VecToUc(_mm_setr_epi8(e31, e30, e29, e28, e27, e26, e25, e24, e23, e22, e21, e20, e19, e18, e17, e16));
1483 }
1484
1485 HEADER_INLINE VecW vecw_setr32(uint32_t e3, uint32_t e2, uint32_t e1, uint32_t e0) {
1486 return VecToW(_mm_setr_epi32(e3, e2, e1, e0));
1487 }
1488
1489 HEADER_INLINE VecW vecw_unpacklo8(VecW evens, VecW odds) {
1490 return VecToW(_mm_unpacklo_epi8(WToVec(evens), WToVec(odds)));
1491 }
1492
1493 HEADER_INLINE VecW vecw_unpackhi8(VecW evens, VecW odds) {
1494 return VecToW(_mm_unpackhi_epi8(WToVec(evens), WToVec(odds)));
1495 }
1496
1497 HEADER_INLINE VecI8 veci8_unpacklo8(VecI8 evens, VecI8 odds) {
1498 return VecToI8(_mm_unpacklo_epi8(I8ToVec(evens), I8ToVec(odds)));
1499 }
1500
1501 HEADER_INLINE VecI8 veci8_unpackhi8(VecI8 evens, VecI8 odds) {
1502 return VecToI8(_mm_unpackhi_epi8(I8ToVec(evens), I8ToVec(odds)));
1503 }
1504
1505 HEADER_INLINE VecUc vecuc_unpacklo8(VecUc evens, VecUc odds) {
1506 return VecToUc(_mm_unpacklo_epi8(UcToVec(evens), UcToVec(odds)));
1507 }
1508
1509 HEADER_INLINE VecUc vecuc_unpackhi8(VecUc evens, VecUc odds) {
1510 return VecToUc(_mm_unpackhi_epi8(UcToVec(evens), UcToVec(odds)));
1511 }
1512
1513 HEADER_INLINE VecW vecw_unpacklo16(VecW evens, VecW odds) {
1514 return VecToW(_mm_unpacklo_epi16(WToVec(evens), WToVec(odds)));
1515 }
1516
1517 HEADER_INLINE VecW vecw_unpackhi16(VecW evens, VecW odds) {
1518 return VecToW(_mm_unpackhi_epi16(WToVec(evens), WToVec(odds)));
1519 }
1520
1521 HEADER_INLINE VecW vecw_unpacklo32(VecW evens, VecW odds) {
1522 return VecToW(_mm_unpacklo_epi32(WToVec(evens), WToVec(odds)));
1523 }
1524
1525 HEADER_INLINE VecW vecw_unpackhi32(VecW evens, VecW odds) {
1526 return VecToW(_mm_unpackhi_epi32(WToVec(evens), WToVec(odds)));
1527 }
1528
1529 HEADER_INLINE VecW vecw_unpacklo64(VecW evens, VecW odds) {
1530 return VecToW(_mm_unpacklo_epi64(WToVec(evens), WToVec(odds)));
1531 }
1532
1533 HEADER_INLINE VecW vecw_unpackhi64(VecW evens, VecW odds) {
1534 return VecToW(_mm_unpackhi_epi64(WToVec(evens), WToVec(odds)));
1535 }
1536
1537 HEADER_INLINE VecW vecw_permute0xd8_if_avx2(VecW vv) {
1538 return vv;
1539 }
1540
1541 HEADER_INLINE VecI8 veci8_permute0xd8_if_avx2(VecI8 vv) {
1542 return vv;
1543 }
1544
1545 HEADER_INLINE VecUc vecuc_permute0xd8_if_avx2(VecUc vv) {
1546 return vv;
1547 }
1548
1549 HEADER_INLINE VecW vecw_gather_even(VecW src_lo, VecW src_hi, VecW m8) {
1550 return VecToW(_mm_packus_epi16(WToVec(src_lo & m8), WToVec(src_hi & m8)));
1551 }
1552
1553 HEADER_INLINE VecUc vecuc_gather_even(VecUc src_lo, VecUc src_hi, VecUc m8) {
1554 return VecToUc(_mm_packus_epi16(UcToVec(src_lo & m8), UcToVec(src_hi & m8)));
1555 }
1556
1557 HEADER_INLINE VecUc vecuc_gather_odd(VecUc src_lo, VecUc src_hi) {
1558 return VecToUc(_mm_packus_epi16(_mm_srli_epi16(UcToVec(src_lo), 8), _mm_srli_epi16(UcToVec(src_hi), 8)));
1559 }
1560
1561 # ifdef USE_SHUFFLE8
1562 # ifdef SIMDE_ARM_NEON_A64V8_NATIVE
1563 // See simde_mm_shuffle_epi8().
1564 HEADER_INLINE __m128i _mm_shuffle_epi8(__m128i a, __m128i b) {
1565 SIMDE_ALIGN_TO_16 int8x16_t a_;
1566 SIMDE_ALIGN_TO_16 uint8x16_t b_;
1567 SIMDE_ALIGN_TO_16 int8x16_t r_;
1568 memcpy(&a_, &a, sizeof(a_));
1569 memcpy(&b_, &b, sizeof(b_));
1570 r_ = vqtbl1q_s8(a_, b_);
1571 __m128i r;
1572 memcpy(&r, &r_, sizeof(r));
1573 return r;
1574 }
1575 # endif
1576 HEADER_INLINE VecW vecw_shuffle8(VecW table, VecW indexes) {
1577 return VecToW(_mm_shuffle_epi8(WToVec(table), WToVec(indexes)));
1578 }
1579
1580 HEADER_INLINE VecU16 vecu16_shuffle8(VecU16 table, VecU16 indexes) {
1581 return VecToU16(_mm_shuffle_epi8(U16ToVec(table), U16ToVec(indexes)));
1582 }
1583
1584 HEADER_INLINE VecUc vecuc_shuffle8(VecUc table, VecUc indexes) {
1585 return VecToUc(_mm_shuffle_epi8(UcToVec(table), UcToVec(indexes)));
1586 }
1587 # endif
1588 # ifdef USE_SSE42
1589 HEADER_INLINE VecI32 veci32_max(VecI32 v1, VecI32 v2) {
1590 return VecToI32(_mm_max_epi32(I32ToVec(v1), I32ToVec(v2)));
1591 }
1592
1593 HEADER_INLINE uintptr_t vecw_extract64_0(VecW vv) {
1594 return _mm_extract_epi64(WToVec(vv), 0);
1595 }
1596
1597 HEADER_INLINE uintptr_t vecw_extract64_1(VecW vv) {
1598 return _mm_extract_epi64(WToVec(vv), 1);
1599 }
1600
1601 HEADER_INLINE VecW vecw_blendv(VecW aa, VecW bb, VecW mask) {
1602 return VecToW(_mm_blendv_epi8(WToVec(aa), WToVec(bb), WToVec(mask)));
1603 }
1604
1605 HEADER_INLINE VecU32 vecu32_blendv(VecU32 aa, VecU32 bb, VecU32 mask) {
1606 return VecToU32(_mm_blendv_epi8(U32ToVec(aa), U32ToVec(bb), U32ToVec(mask)));
1607 }
1608
1609 HEADER_INLINE VecU16 vecu16_blendv(VecU16 aa, VecU16 bb, VecU16 mask) {
1610 return VecToU16(_mm_blendv_epi8(U16ToVec(aa), U16ToVec(bb), U16ToVec(mask)));
1611 }
1612
1613 HEADER_INLINE VecUc vecuc_blendv(VecUc aa, VecUc bb, VecUc mask) {
1614 return VecToUc(_mm_blendv_epi8(UcToVec(aa), UcToVec(bb), UcToVec(mask)));
1615 }
1616 # else // USE_SSE2, !USE_SSE42
1617 HEADER_INLINE uintptr_t vecw_extract64_0(VecW vv) {
1618 return R_CAST(uintptr_t, _mm_movepi64_pi64(WToVec(vv)));
1619 }
1620
1621 // compiler recognizes this on ARMv8
1622 HEADER_INLINE uintptr_t vecw_extract64_1(VecW vv) {
1623 const __m128i v0 = _mm_srli_si128(WToVec(vv), 8);
1624 return R_CAST(uintptr_t, _mm_movepi64_pi64(v0));
1625 }
1626
1627 // N.B. we do *not* enforce the low bits of each mask byte matching the high
1628 // bit.
1629 HEADER_INLINE VecW vecw_blendv(VecW aa, VecW bb, VecW mask) {
1630 return vecw_and_notfirst(mask, aa) | (mask & bb);
1631 }
1632
1633 HEADER_INLINE VecU32 vecu32_blendv(VecU32 aa, VecU32 bb, VecU32 mask) {
1634 return vecu32_and_notfirst(mask, aa) | (mask & bb);
1635 }
1636
1637 HEADER_INLINE VecU16 vecu16_blendv(VecU16 aa, VecU16 bb, VecU16 mask) {
1638 return vecu16_and_notfirst(mask, aa) | (mask & bb);
1639 }
1640
1641 HEADER_INLINE VecUc vecuc_blendv(VecUc aa, VecUc bb, VecUc mask) {
1642 return vecuc_and_notfirst(mask, aa) | (mask & bb);
1643 }
1644 # endif
1645
1646 HEADER_INLINE VecI16 veci16_max(VecI16 v1, VecI16 v2) {
1647 return VecToI16(_mm_max_epi16(I16ToVec(v1), I16ToVec(v2)));
1648 }
1649
1650 HEADER_INLINE VecW vecw_sad(VecW v1, VecW v2) {
1651 return VecToW(_mm_sad_epu8(WToVec(v1), WToVec(v2)));
1652 }
1653
1654 HEADER_INLINE VecUc vecuc_adds(VecUc v1, VecUc v2) {
1655 return VecToUc(_mm_adds_epu8(UcToVec(v1), UcToVec(v2)));
1656 }
1657
1658 HEADER_INLINE VecU16 vecu16_min8(VecU16 v1, VecU16 v2) {
1659 return VecToU16(_mm_min_epu8(U16ToVec(v1), U16ToVec(v2)));
1660 }
1661
1662 HEADER_INLINE VecUc vecuc_min(VecUc v1, VecUc v2) {
1663 return VecToUc(_mm_min_epu8(UcToVec(v1), UcToVec(v2)));
1664 }
1665 # endif // USE_SSE2, !USE_AVX2
1666
1667 HEADER_INLINE void vecw_storeu(void* mem_addr, VecW vv) {
1668 vec_storeu(mem_addr, WToVec(vv));
1669 }
1670
1671 HEADER_INLINE void vecu32_storeu(void* mem_addr, VecU32 vv) {
1672 vec_storeu(mem_addr, U32ToVec(vv));
1673 }
1674
1675 HEADER_INLINE void veci32_storeu(void* mem_addr, VecI32 vv) {
1676 vec_storeu(mem_addr, I32ToVec(vv));
1677 }
1678
1679 HEADER_INLINE void vecu16_storeu(void* mem_addr, VecU16 vv) {
1680 vec_storeu(mem_addr, U16ToVec(vv));
1681 }
1682
1683 HEADER_INLINE void veci16_storeu(void* mem_addr, VecI16 vv) {
1684 vec_storeu(mem_addr, I16ToVec(vv));
1685 }
1686
1687 HEADER_INLINE void vecuc_storeu(void* mem_addr, VecUc vv) {
1688 vec_storeu(mem_addr, UcToVec(vv));
1689 }
1690
1691 HEADER_INLINE VecW vecw_bytesum(VecW src, VecW m0) {
1692 return vecw_sad(src, m0);
1693 }
1694
1695 CONSTI32(kVec8thUintPerWord, sizeof(intptr_t) / sizeof(Vec8thUint));
1696
1697 # ifdef FVEC_32
1698
1699 # ifndef __FMA__
1700 # error "32-byte-float-vector builds require FMA3 as well."
1701 # endif
1702
1703 CONSTI32(kBytesPerFVec, 32);
1704 CONSTI32(kBytesPerDVec, 32);
1705 typedef float VecF __attribute__ ((vector_size (32)));
1706 typedef double VecD __attribute__ ((vector_size (32)));
1707
1708 # define VCONST_F(xx) {xx, xx, xx, xx, xx, xx, xx, xx}
1709 # define VCONST_D(xx) {xx, xx, xx, xx}
1710
1711 HEADER_INLINE VecF VecToF(__m256 xxv) {
1712 return R_CAST(VecF, xxv);
1713 }
1714
1715 HEADER_INLINE VecD VecToD(__m256d xxv) {
1716 return R_CAST(VecD, xxv);
1717 }
1718
1719 HEADER_INLINE __m256 FToVec(VecF xxv) {
1720 return R_CAST(__m256, xxv);
1721 }
1722
1723 HEADER_INLINE __m256d DToVec(VecD xxv) {
1724 return R_CAST(__m256d, xxv);
1725 }
1726
1727 HEADER_INLINE VecF vecf_setzero() {
1728 return VecToF(_mm256_setzero_ps());
1729 }
1730
1731 HEADER_INLINE VecD vecd_setzero() {
1732 return VecToD(_mm256_setzero_pd());
1733 }
1734
1735 # else // !FVEC_32
1736
1737 CONSTI32(kBytesPerFVec, 16);
1738 CONSTI32(kBytesPerDVec, 16);
1739 typedef float VecF __attribute__ ((vector_size (16)));
1740 typedef double VecD __attribute__ ((vector_size (16)));
1741
1742 # define VCONST_F(xx) {xx, xx, xx, xx}
1743 # define VCONST_D(xx) {xx, xx}
1744
1745 HEADER_INLINE VecF VecToF(__m128 xxv) {
1746 return R_CAST(VecF, xxv);
1747 }
1748
1749 HEADER_INLINE VecD VecToD(__m128d xxv) {
1750 return R_CAST(VecD, xxv);
1751 }
1752
1753 HEADER_INLINE __m128 FToVec(VecF xxv) {
1754 return R_CAST(__m128, xxv);
1755 }
1756
1757 HEADER_INLINE __m128d DToVec(VecD xxv) {
1758 return R_CAST(__m128d, xxv);
1759 }
1760
1761 HEADER_INLINE VecF vecf_setzero() {
1762 return VecToF(_mm_setzero_ps());
1763 }
1764
1765 HEADER_INLINE VecD vecd_setzero() {
1766 return VecToD(_mm_setzero_pd());
1767 }
1768
1769 # endif // !FVEC_32
1770
1771 HEADER_INLINE VecUc VecWToUc(VecW vv) {
1772 return R_CAST(VecUc, vv);
1773 }
1774
1775 HEADER_INLINE VecW VecU16ToW(VecU16 vv) {
1776 return R_CAST(VecW, vv);
1777 }
1778
1779 HEADER_INLINE VecW VecUcToW(VecUc vv) {
1780 return R_CAST(VecW, vv);
1781 }
1782
1783 HEADER_INLINE void vecw_lo_and_hi_nybbles(VecW cur_vec, VecW m4, VecW* vec_lo_ptr, VecW* vec_hi_ptr) {
1784 // Assumes m4 is VCONST_W(kMask0F0F).
1785 // Returned vec_lo and vec_hi have top nybble of each byte zeroed out.
1786 cur_vec = vecw_permute0xd8_if_avx2(cur_vec);
1787 // AVX2:
1788 // vec_even contains {0, 2, 4, ..., 14, 32, 34, ..., 46,
1789 // 16, 18, ..., 30, 48, ... 62}
1790 // vec_odd contains {1, 3, 5, ..., 15, 33, 35, ..., 47,
1791 // 17, 19, ..., 31, 49, ..., 63}
1792 // SSE2:
1793 // vec_even contains {0, 2, 4, ..., 30}
1794 // vec_odd contains {1, 3, 5, ..., 31}
1795 const VecW vec_even = cur_vec & m4;
1796 const VecW vec_odd = vecw_srli(cur_vec, 4) & m4;
1797
1798 // AVX2:
1799 // vec_lo contains {0, 1, 2, ..., 31}
1800 // vec_hi contains {32, 33, 34, ..., 63}
1801 // SSE2:
1802 // vec_lo contains {0, 1, 2, ..., 15}
1803 // vec_hi contains {16, 17, 18, ..., 31}
1804 *vec_lo_ptr = vecw_unpacklo8(vec_even, vec_odd);
1805 *vec_hi_ptr = vecw_unpackhi8(vec_even, vec_odd);
1806 }
1807 #else // !USE_SSE2
1808 # ifdef __LP64__
1809 CONSTI32(kBytesPerVec, 8);
1810 # else
1811 CONSTI32(kBytesPerVec, 4);
1812 # endif
1813 CONSTI32(kBytesPerFVec, 4);
1814 CONSTI32(kBytesPerDVec, 8);
1815
1816 typedef uintptr_t VecW;
1817 typedef uint32_t VecU32;
1818 typedef float VecF;
1819 typedef double VecD;
1820 // VecI16 and VecI8 aren't worth the trouble of scaling down to 32-bit
1821
1822 # define VCONST_W(xx) (xx)
1823
1824 HEADER_INLINE VecW vecw_setzero() {
1825 return k0LU;
1826 }
1827
1828 HEADER_INLINE VecW vecw_srli(VecW vv, uint32_t ct) {
1829 return vv >> ct;
1830 }
1831
1832 HEADER_INLINE VecW vecw_slli(VecW vv, uint32_t ct) {
1833 return vv << ct;
1834 }
1835
1836 HEADER_INLINE VecW vecw_set1(uintptr_t ulii) {
1837 return ulii;
1838 }
1839
1840 HEADER_INLINE VecW vecw_loadu(const void* mem_addr) {
1841 return *S_CAST(const VecW*, mem_addr);
1842 }
1843
1844 # ifdef __LP64__
1845 HEADER_INLINE VecW vecw_bytesum(VecW src, __maybe_unused VecW m0) {
1846 src = (src & 0x00ff00ff00ff00ffLLU) + ((src >> 8) & 0x00ff00ff00ff00ffLLU);
1847 return (src * 0x1000100010001LLU) >> 48;
1848 }
1849 # else
1850 HEADER_INLINE VecW vecw_bytesum(VecW src, __maybe_unused VecW m0) {
1851 src = (src & 0x00ff00ff) + ((src >> 8) & 0x00ff00ff);
1852 return (src & 0xffff) + (src >> 16);
1853 }
1854 # endif
1855
1856 HEADER_INLINE VecW vecw_and_notfirst(VecW excl, VecW main) {
1857 return (~excl) & main;
1858 }
1859
1860 HEADER_INLINE VecU32 vecu32_and_notfirst(VecU32 excl, VecU32 main) {
1861 return (~excl) & main;
1862 }
1863 #endif // !USE_SSE2
1864
1865 HEADER_INLINE uint32_t* I32ToU32(int32_t* pp) {
1866 return R_CAST(uint32_t*, pp);
1867 }
1868
1869 // Unfortunately, we need to spell out S_CAST(uintptr_t, 0) instead of just
1870 // typing k0LU in C99.
1871 static const uintptr_t kMask5555 = (~S_CAST(uintptr_t, 0)) / 3;
1872 static const uintptr_t kMaskAAAA = ((~S_CAST(uintptr_t, 0)) / 3) * 2;
1873 static const uintptr_t kMask3333 = (~S_CAST(uintptr_t, 0)) / 5;
1874 static const uintptr_t kMask1111 = (~S_CAST(uintptr_t, 0)) / 15;
1875 static const uintptr_t kMask0F0F = (~S_CAST(uintptr_t, 0)) / 17;
1876 static const uintptr_t kMask0101 = (~S_CAST(uintptr_t, 0)) / 255;
1877 static const uintptr_t kMask00FF = (~S_CAST(uintptr_t, 0)) / 257;
1878 static const uintptr_t kMask0001 = (~S_CAST(uintptr_t, 0)) / 65535;
1879 static const uintptr_t kMask0000FFFF = (~S_CAST(uintptr_t, 0)) / 65537;
1880 static const uintptr_t kMask00000001 = (~S_CAST(uintptr_t, 0)) / 4294967295U;
1881
1882 static const uintptr_t kMask000000FF = (~S_CAST(uintptr_t, 0)) / 16843009;
1883 static const uintptr_t kMask000F = (~S_CAST(uintptr_t, 0)) / 4369;
1884 static const uintptr_t kMask0303 = (~S_CAST(uintptr_t, 0)) / 85;
1885
1886 CONSTI32(kBitsPerVec, kBytesPerVec * CHAR_BIT);
1887
1888 // We now use Knuth's Nyp/Nybble vocabulary for 2-bit and 4-bit elements,
1889 // respectively.
1890 CONSTI32(kNypsPerVec, kBytesPerVec * 4);
1891 CONSTI32(kNybblesPerVec, kBytesPerVec * 2);
1892
1893 CONSTI32(kBitsPerWordD2, kBitsPerWord / 2);
1894 CONSTI32(kBitsPerWordD4, kBitsPerWord / 4);
1895
1896 // number of bytes in a word
1897 CONSTI32(kBytesPerWord, kBitsPerWord / CHAR_BIT);
1898
1899 CONSTI32(kInt16PerWord, kBytesPerWord / 2);
1900
1901 static_assert(CHAR_BIT == 8, "plink2_base requires CHAR_BIT == 8.");
1902 static_assert(sizeof(int8_t) == 1, "plink2_base requires sizeof(int8_t) == 1.");
1903 static_assert(sizeof(int16_t) == 2, "plink2_base requires sizeof(int16_t) == 2.");
1904 static_assert(sizeof(int32_t) == 4, "plink2_base requires sizeof(int32_t) == 4.");
1905 static_assert(sizeof(int) >= 4, "plink2_base requires sizeof(int) >= 4.");
1906 static_assert(sizeof(intptr_t) == kBytesPerWord, "plink2_base requires sizeof(intptr_t) == kBytesPerWord.");
1907 static_assert(sizeof(int64_t) == 8, "plink2_base requires sizeof(int64_t) == 8.");
1908
1909 CONSTI32(kWordsPerVec, kBytesPerVec / kBytesPerWord);
1910 CONSTI32(kInt32PerVec, kBytesPerVec / 4);
1911 CONSTI32(kInt16PerVec, kBytesPerVec / 2);
1912
1913 CONSTI32(kFloatPerFVec, kBytesPerFVec / 4);
1914 CONSTI32(kDoublePerDVec, kBytesPerDVec / 8);
1915
1916 #if defined(__APPLE__) && defined(__LP64__) && !defined(__x86_64__)
1917 # define CACHELINE128
1918 CONSTI32(kCacheline, 128);
1919 #else
1920 # define CACHELINE64
1921 CONSTI32(kCacheline, 64);
1922 #endif
1923
1924 CONSTI32(kBitsPerCacheline, kCacheline * CHAR_BIT);
1925 CONSTI32(kNypsPerCacheline, kCacheline * 4);
1926 CONSTI32(kInt16PerCacheline, kCacheline / sizeof(int16_t));
1927 CONSTI32(kInt32PerCacheline, kCacheline / sizeof(int32_t));
1928 CONSTI32(kInt64PerCacheline, kCacheline / sizeof(int64_t));
1929 CONSTI32(kWordsPerCacheline, kCacheline / kBytesPerWord);
1930 CONSTI32(kDoublesPerCacheline, kCacheline / sizeof(double));
1931 CONSTI32(kVecsPerCacheline, kCacheline / kBytesPerVec);
1932
1933 // could use ioctl, etc. to dynamically determine this later, and pass it as a
1934 // parameter to e.g. PgfiMultiread()
1935 CONSTI32(kDiskBlockSize, 4096);
1936
1937 CONSTI32(kPglFwriteBlockSize, 131072);
1938
1939 // unsafe to fread or fwrite more bytes than this on e.g. OS X
1940 CONSTI32(kMaxBytesPerIO, 0x7ffff000);
1941
1942 // Maximum size of "dynamically" allocated line load buffer. (This is the
1943 // limit that applies to .vcf and similar files.) Inconvenient to go higher
1944 // since fgets() takes a int32_t size argument.
1945 #if defined(__APPLE__) && defined(__LP64__) && !defined(__x86_64__)
1946 CONSTI32(kMaxLongLine, 0x7fffff80);
1947 #else
1948 CONSTI32(kMaxLongLine, 0x7fffffc0);
1949 #endif
1950 static_assert(!(kMaxLongLine % kCacheline), "kMaxLongLine must be a multiple of kCacheline.");
1951
1952 #ifdef __APPLE__
1953 // OS X is limited to 256?
1954 CONSTI32(kMaxOpenFiles, 252);
1955 #else
1956 // Can't assume more than 512 are allowed on Windows, with current compilation
1957 // settings.
1958 CONSTI32(kMaxOpenFiles, 504);
1959 #endif
1960
1961 // note that this is NOT foolproof: see e.g.
1962 // http://insanecoding.blogspot.com/2007/11/pathmax-simply-isnt.html . (This
1963 // is why I haven't bothered with OS-based #ifdefs here.) But it should be
1964 // good enough in practice. And PATH_MAX itself is still relevant due to use
1965 // of realpath().
1966 CONSTI32(kPglFnamesize, 4096);
1967 #if defined(PATH_MAX) && !defined(_WIN32)
1968 static_assert(kPglFnamesize >= PATH_MAX, "plink2_base assumes PATH_MAX <= 4096. (Safe to increase kPglFnamesize to address this, up to 131072.)");
1969 #endif
1970
1971 // safe errstr_buf size for PgenInitPhase{1,2}(), PgrValidate(),
1972 // BitmapReaderInitPhase{1,2}()
1973 CONSTI32(kPglErrstrBufBlen, kPglFnamesize + 256);
1974
1975 // shared between .pgen and plink-bitmap formats
1976 // currently must be power of 2, and multiple of (kBitsPerWord / 2)
1977 CONSTI32(kPglDifflistGroupSize, 64);
1978
1979 // debug
1980 HEADER_INLINE void PrintVec(const void* vv) {
1981 const unsigned char* vv_alias = S_CAST(const unsigned char*, vv);
1982 for (uint32_t uii = 0; uii != kBytesPerVec; ++uii) {
1983 printf("%u ", vv_alias[uii]);
1984 }
1985 printf("\n");
1986 }
1987
1988 HEADER_INLINE void PrintVecD(const VecD* vv_ptr, const char* preprint) {
1989 fputs(preprint, stdout);
1990 const double* vv_alias = R_CAST(const double*, vv_ptr);
1991 for (uint32_t uii = 0; uii != kDoublePerDVec; ++uii) {
1992 printf(" %g", vv_alias[uii]);
1993 }
1994 fputs("\n", stdout);
1995 }
1996
1997 #if __cplusplus >= 201103L
1998 // Main application of std::array in this codebase is enforcing length when
1999 // passing references between functions. Conversely, if the array type has
2000 // different lengths in different functions (e.g. col_skips[]/col_types[]), we
2001 // actively want to avoid &arr[0] clutter.
2002 // When neither applies, it doesn't really matter whether we use this or not;
2003 // I normally won't use it unless it plausibly makes sense to pass
2004 // fixed-length-array-references in the future.
2005 # define STD_ARRAY_DECL(tt, nn, vv) std::array<tt, nn> vv
2006 # define STD_ARRAY_REF(tt, nn) std::array<tt, nn>&
2007
2008 // necessary if tt is a pointer type, otherwise optional
2009 # define STD_ARRAY_KREF(tt, nn) const std::array<tt, nn>&
2010
2011 # define STD_ARRAY_COPY(src, nn, dst) static_assert(sizeof(dst) == sizeof((dst)[0]) * nn, "Invalid STD_ARRAY_COPY() invocation."); (dst) = (src)
2012
2013 # define STD_ARRAY_PTR_TYPE(tt, nn) std::array<tt, nn>*
2014 # define STD_ARRAY_PTR_DECL(tt, nn, vv) std::array<tt, nn>* vv
2015
2016 // argh, need double-braces for C++11 std::array and single-braces for C
2017 # define STD_ARRAY_INIT_START() {
2018 # define STD_ARRAY_INIT_END() }
2019
2020 template <class T, std::size_t N> void STD_ARRAY_FILL0(std::array<T, N>& arr) {
2021 arr.fill(0);
2022 }
2023
2024 // plain STD_ARRAY_FILL0() can't be used on array-references due to fallback
2025 // code.
2026 // this macro ensures that we *only* use it with uint32_t array-references
2027 # define STD_ARRAY_REF_FILL0(ct, aref) static_assert(ct * sizeof(aref[0]) == sizeof(aref), "invalid STD_ARRAY_REF_FILL0() invocation"); aref.fill(0)
2028
2029 # define NONCOPYABLE(struct_name) \
2030 struct_name() = default; \
2031 struct_name(const struct_name&) = delete; \
2032 struct_name& operator=(const struct_name&) = delete
2033
2034 # define MOVABLE_BUT_NONCOPYABLE(struct_name) \
2035 struct_name() = default; \
2036 struct_name(const struct_name&) = delete; \
2037 struct_name& operator=(const struct_name&) = delete; \
2038 struct_name(struct_name&&) = default; \
2039 struct_name& operator=(struct_name&&) = default
2040
2041 #else
2042 # define STD_ARRAY_DECL(tt, nn, vv) tt vv[nn]
2043 # define STD_ARRAY_REF(tt, nn) tt* const
2044 # define STD_ARRAY_KREF(tt, nn) tt const* const
2045 # define STD_ARRAY_COPY(src, nn, dst) memcpy(dst, src, nn * sizeof(dst[0]));
2046 # define STD_ARRAY_PTR_TYPE(tt, nn) tt(*)[nn]
2047 # define STD_ARRAY_PTR_DECL(tt, nn, vv) tt(*vv)[nn]
2048 # define STD_ARRAY_INIT_START()
2049 # define STD_ARRAY_INIT_END()
2050 # define STD_ARRAY_FILL0(arr) memset(arr, 0, sizeof(arr))
2051 # define STD_ARRAY_REF_FILL0(ct, aref) memset(aref, 0, ct * sizeof(*aref))
2052
2053 # define NONCOPYABLE(struct_name)
2054 # define MOVABLE_BUT_NONCOPYABLE(struct_name)
2055 #endif
2056
2057 typedef union {
2058 VecW vw;
2059
2060 STD_ARRAY_DECL(uintptr_t, kWordsPerVec, w);
2061
2062 STD_ARRAY_DECL(uint32_t, kInt32PerVec, u32);
2063 } UniVec;
2064
2065 typedef union {
2066 VecF vf;
2067 STD_ARRAY_DECL(float, kFloatPerFVec, f4);
2068 } UniVecF;
2069
2070 typedef union {
2071 VecD vd;
2072 STD_ARRAY_DECL(double, kDoublePerDVec, d8);
2073 } UniVecD;
2074
2075 // sum must fit in 16 bits
2076 HEADER_INLINE uintptr_t UniVecHsum16(UniVec uv) {
2077 #ifdef __LP64__
2078 # ifdef USE_AVX2
2079 return ((uv.w[0] + uv.w[1] + uv.w[2] + uv.w[3]) * kMask0001) >> 48;
2080 # else
2081 return ((uv.w[0] + uv.w[1]) * kMask0001) >> 48;
2082 # endif
2083 #else
2084 return (uv.w[0] * kMask0001) >> 16;
2085 #endif
2086 }
2087
2088 // sum must fit in 32 bits
2089 HEADER_INLINE uintptr_t UniVecHsum32(UniVec uv) {
2090 #ifdef __LP64__
2091 # ifdef USE_AVX2
2092 return ((uv.w[0] + uv.w[1] + uv.w[2] + uv.w[3]) * kMask00000001) >> 32;
2093 # else
2094 return ((uv.w[0] + uv.w[1]) * kMask00000001) >> 32;
2095 # endif
2096 #else
2097 return uv.w[0];
2098 #endif
2099 }
2100
2101 HEADER_INLINE float VecFHsum(VecF vecf) {
2102 UniVecF uvf;
2103 uvf.vf = vecf;
2104 #ifdef __LP64__
2105 # ifdef FVEC_32
2106 // tested various uses of _mm256_hadd_ps, couldn't get them to be faster
2107 return uvf.f4[0] + uvf.f4[1] + uvf.f4[2] + uvf.f4[3] + uvf.f4[4] + uvf.f4[5] + uvf.f4[6] + uvf.f4[7];
2108 # else
2109 return uvf.f4[0] + uvf.f4[1] + uvf.f4[2] + uvf.f4[3];
2110 # endif
2111 #else
2112 return uvf.f4[0];
2113 #endif
2114 }
2115
2116 HEADER_INLINE double VecDHsum(VecD vecd) {
2117 UniVecD uvd;
2118 uvd.vd = vecd;
2119 #ifdef __LP64__
2120 # ifdef FVEC_32
2121 return uvd.d8[0] + uvd.d8[1] + uvd.d8[2] + uvd.d8[3];
2122 # else
2123 return uvd.d8[0] + uvd.d8[1];
2124 # endif
2125 #else
2126 return uvd.d8[0];
2127 #endif
2128 }
2129
2130 #ifdef USE_AVX2
2131 HEADER_INLINE uintptr_t UnpackHalfwordToWord(uintptr_t hw) {
2132 return _pdep_u64(hw, kMask5555);
2133 }
2134
2135 HEADER_INLINE uintptr_t UnpackHalfwordToWordShift1(uintptr_t hw) {
2136 return _pdep_u64(hw, kMaskAAAA);
2137 }
2138
2139 HEADER_INLINE Vec4thUint UnpackVec8thUintTo4th(Vec8thUint hw) {
2140 return _pdep_u64(hw, kMask5555);
2141 }
2142
2143 HEADER_INLINE Halfword PackWordToHalfword(uintptr_t ww) {
2144 return _pext_u64(ww, kMask5555);
2145 }
2146
2147 HEADER_INLINE Halfword PackWordToHalfwordMask5555(uintptr_t ww) {
2148 return _pext_u64(ww, kMask5555);
2149 }
2150
2151 HEADER_INLINE Halfword PackWordToHalfwordMaskAAAA(uintptr_t ww) {
2152 return _pext_u64(ww, kMaskAAAA);
2153 }
2154
2155 HEADER_INLINE uintptr_t PackTwo5555Mask(uintptr_t lo, uintptr_t hi) {
2156 const Halfword lo_packed = PackWordToHalfwordMask5555(lo);
2157 const uintptr_t hi_packed = _pext_u64(hi, kMask5555);
2158 return lo_packed | (hi_packed << kBitsPerWordD2);
2159 }
2160
2161 HEADER_INLINE Vec8thUint PackVec4thUintTo8th(Vec4thUint ww) {
2162 return _pext_u64(ww, kMask5555);
2163 }
2164
2165 HEADER_INLINE Vec16thUint PackVec8thUintTo16th(Vec8thUint ww) {
2166 return _pext_u64(ww, kMask5555);
2167 }
2168
2169 HEADER_INLINE Halfword Pack3333(uintptr_t ww) {
2170 return _pext_u64(ww, kMask3333);
2171 }
2172
2173 HEADER_INLINE Halfword Pack3333Mask(uintptr_t ww) {
2174 return _pext_u64(ww, kMask3333);
2175 }
2176
2177 HEADER_INLINE uintptr_t PackTwo3333Mask(uintptr_t lo, uintptr_t hi) {
2178 const Halfword lo_packed = Pack3333Mask(lo);
2179 const uintptr_t hi_packed = _pext_u64(hi, kMask3333);
2180 return lo_packed | (hi_packed << kBitsPerWordD2);
2181 }
2182
2183 HEADER_INLINE uintptr_t Unpack0F0F(uintptr_t hw) {
2184 return _pdep_u64(hw, kMask0F0F);
2185 }
2186
2187 HEADER_INLINE Halfword Pack0F0F(uintptr_t ww) {
2188 return _pext_u64(ww, kMask0F0F);
2189 }
2190
2191 HEADER_INLINE Halfword Pack0F0FMask(uintptr_t ww) {
2192 return _pext_u64(ww, kMask0F0F);
2193 }
2194
2195 HEADER_INLINE uintptr_t PackTwo0F0F(uintptr_t lo, uintptr_t hi) {
2196 const Halfword lo_packed = _pext_u64(lo, kMask0F0F);
2197 const uintptr_t hi_packed = _pext_u64(hi, kMask0F0F);
2198 return lo_packed | (hi_packed << kBitsPerWordD2);
2199 }
2200
2201 HEADER_INLINE uintptr_t PackTwo0F0FMask(uintptr_t lo, uintptr_t hi) {
2202 return PackTwo0F0F(lo, hi);
2203 }
2204
2205 HEADER_INLINE uintptr_t Unpack0303(uintptr_t qw) {
2206 return _pdep_u64(qw, kMask0303);
2207 }
2208
2209 HEADER_INLINE Quarterword Pack0303(uintptr_t ww) {
2210 return _pext_u64(ww, kMask0303);
2211 }
2212
2213 HEADER_INLINE Quarterword Pack0303Mask(uintptr_t ww) {
2214 return _pext_u64(ww, kMask0303);
2215 }
2216
2217 // See https://stackoverflow.com/questions/21622212/how-to-perform-the-inverse-of-mm256-movemask-epi8-vpmovmskb .
2218 HEADER_INLINE VecUc InverseMovemaskFF(Vec8thUint mask) {
2219 __m256i vmask = _mm256_set1_epi32(mask);
2220 const __m256i byte_gather = _mm256_setr_epi64x(0, kMask0101, 2 * kMask0101, 3 * kMask0101);
2221 vmask = _mm256_shuffle_epi8(vmask, byte_gather);
2222 const __m256i bit_mask = _mm256_set1_epi64x(0x7fbfdfeff7fbfdfeLL);
2223 vmask = _mm256_or_si256(vmask, bit_mask);
2224 return R_CAST(VecUc, _mm256_cmpeq_epi8(vmask, _mm256_set1_epi64x(-1)));
2225 }
2226
2227 // If we're only interested in the even bits of mask. No need to mask out odd
2228 // bits before calling.
2229 HEADER_INLINE VecUc InverseMovespreadmaskFF(Vec4thUint mask) {
2230 __m256i vmask = _mm256_set1_epi64x(mask);
2231 const __m256i byte_gather = _mm256_setr_epi32(0, 0x01010101, 0x02020202, 0x03030303, 0x04040404, 0x05050505, 0x06060606, 0x07070707);
2232 vmask = _mm256_shuffle_epi8(vmask, byte_gather);
2233 const __m256i bit_mask = _mm256_set1_epi32(0xbfeffbfeU);
2234 vmask = _mm256_or_si256(vmask, bit_mask);
2235 return R_CAST(VecUc, _mm256_cmpeq_epi8(vmask, _mm256_set1_epi64x(-1)));
2236 }
2237
2238 #else // !USE_AVX2
2239 HEADER_INLINE uintptr_t UnpackHalfwordToWord(uintptr_t hw) {
2240 # ifdef __LP64__
2241 hw = (hw | (hw << 16)) & kMask0000FFFF;
2242 # endif
2243 hw = (hw | (hw << 8)) & kMask00FF;
2244 hw = (hw | (hw << 4)) & kMask0F0F;
2245 hw = (hw | (hw << 2)) & kMask3333;
2246 return ((hw | (hw << 1)) & kMask5555);
2247 }
2248
2249 HEADER_INLINE uintptr_t UnpackHalfwordToWordShift1(uintptr_t hw) {
2250 return UnpackHalfwordToWord(hw) << 1;
2251 }
2252
2253 HEADER_INLINE Halfword PackWordToHalfword(uintptr_t ww) {
2254 // assumes only even bits of ww can be set
2255 ww = (ww | (ww >> 1)) & kMask3333;
2256 ww = (ww | (ww >> 2)) & kMask0F0F;
2257 ww = (ww | (ww >> 4)) & kMask00FF;
2258 # ifdef __LP64__
2259 ww = (ww | (ww >> 8)) & kMask0000FFFF;
2260 # endif
2261 return S_CAST(Halfword, ww | (ww >> kBitsPerWordD4));
2262 }
2263
2264 HEADER_INLINE Halfword PackWordToHalfwordMask5555(uintptr_t ww) {
2265 return PackWordToHalfword(ww & kMask5555);
2266 }
2267
2268 HEADER_INLINE Halfword PackWordToHalfwordMaskAAAA(uintptr_t ww) {
2269 return PackWordToHalfword((ww >> 1) & kMask5555);
2270 }
2271
2272 HEADER_INLINE uintptr_t PackTwo5555Mask(uintptr_t lo, uintptr_t hi) {
2273 const Halfword lo_packed = PackWordToHalfwordMask5555(lo);
2274
2275 // Avoid Halfword cast here.
2276 hi = hi & kMask5555;
2277 hi = (hi | (hi >> 1)) & kMask3333;
2278 hi = (hi | (hi >> 2)) & kMask0F0F;
2279 hi = (hi | (hi >> 4)) & kMask00FF;
2280 # ifdef __LP64__
2281 hi = (hi | (hi >> 8)) & kMask0000FFFF;
2282 # endif
2283 const uintptr_t hi_packed = hi | (hi >> kBitsPerWordD4);
2284 return lo_packed | (hi_packed << kBitsPerWordD2);
2285 }
2286
2287 HEADER_INLINE Halfword Pack3333(uintptr_t ww) {
2288 ww = (ww | (ww >> 2)) & kMask0F0F;
2289 ww = (ww | (ww >> 4)) & kMask00FF;
2290 # ifdef __LP64__
2291 ww = (ww | (ww >> 8)) & kMask0000FFFF;
2292 # endif
2293 return S_CAST(Halfword, ww | (ww >> kBitsPerWordD4));
2294 }
2295
2296 HEADER_INLINE Halfword Pack3333Mask(uintptr_t ww) {
2297 return Pack3333(ww & kMask3333);
2298 }
2299
2300 HEADER_INLINE uintptr_t PackTwo3333Mask(uintptr_t lo, uintptr_t hi) {
2301 const Halfword lo_packed = Pack3333Mask(lo);
2302
2303 // Avoid Halfword cast here.
2304 hi = hi & kMask3333;
2305 hi = (hi | (hi >> 2)) & kMask0F0F;
2306 hi = (hi | (hi >> 4)) & kMask00FF;
2307 # ifdef __LP64__
2308 hi = (hi | (hi >> 8)) & kMask0000FFFF;
2309 # endif
2310 const uintptr_t hi_packed = hi | (hi >> kBitsPerWordD4);
2311 return lo_packed | (hi_packed << kBitsPerWordD2);
2312 }
2313
2314 HEADER_INLINE uintptr_t Unpack0F0F(uintptr_t hw) {
2315 # ifdef __LP64__
2316 hw = (hw | (hw << 16)) & kMask0000FFFF;
2317 # endif
2318 hw = (hw | (hw << 8)) & kMask00FF;
2319 return ((hw | (hw << 4)) & kMask0F0F);
2320 }
2321
2322 HEADER_INLINE Halfword Pack0F0F(uintptr_t ww) {
2323 ww = (ww | (ww >> 4)) & kMask00FF;
2324 # ifdef __LP64__
2325 ww = (ww | (ww >> 8)) & kMask0000FFFF;
2326 # endif
2327 return S_CAST(Halfword, ww | (ww >> kBitsPerWordD4));
2328 }
2329
2330 HEADER_INLINE Halfword Pack0F0FMask(uintptr_t ww) {
2331 return Pack0F0F(ww & kMask0F0F);
2332 }
2333
2334 HEADER_INLINE uintptr_t PackTwo0F0F(uintptr_t lo, uintptr_t hi) {
2335 const Halfword lo_packed = Pack0F0F(lo);
2336
2337 // Avoid Halfword cast here.
2338 hi = (hi | (hi >> 4)) & kMask00FF;
2339 # ifdef __LP64__
2340 hi = (hi | (hi >> 8)) & kMask0000FFFF;
2341 # endif
2342 const uintptr_t hi_packed = hi | (hi >> kBitsPerWordD4);
2343 return lo_packed | (hi_packed << kBitsPerWordD2);
2344 }
2345
2346 HEADER_INLINE uintptr_t PackTwo0F0FMask(uintptr_t lo, uintptr_t hi) {
2347 const Halfword lo_packed = Pack0F0FMask(lo);
2348
2349 // Avoid Halfword cast here.
2350 hi = hi & kMask0F0F;
2351 hi = (hi | (hi >> 4)) & kMask00FF;
2352 # ifdef __LP64__
2353 hi = (hi | (hi >> 8)) & kMask0000FFFF;
2354 # endif
2355 const uintptr_t hi_packed = hi | (hi >> kBitsPerWordD4);
2356 return lo_packed | (hi_packed << kBitsPerWordD2);
2357 }
2358
2359
2360 HEADER_INLINE uintptr_t Unpack0303(uintptr_t qw) {
2361 // ................................................fedcba9876543210
2362 # ifdef __LP64__
2363 qw = (qw | (qw << 24)) & kMask000000FF;
2364 // ........................fedcba98........................76543210
2365 # endif
2366 qw = qw | (qw << 12);
2367 // ............fedcba98....fedcba98............76543210....76543210
2368
2369 qw = qw | (qw << 6);
2370 // ......fedcbaXXdcbaXXdcbaXXdcba98......765432XX5432XX5432XX543210
2371
2372 return (qw & kMask0303);
2373 // ......fe......dc......ba......98......76......54......32......10
2374 }
2375
2376 HEADER_INLINE Quarterword Pack0303(uintptr_t ww) {
2377 // ......fe......dc......ba......98......76......54......32......10
2378
2379 ww = ww | (ww >> 6);
2380 // ......fe....fedc....dcba....ba98....9876....7654....5432....3210
2381
2382 ww = ww | (ww >> 12);
2383 // ......fe....fedc..fedcbafedcba98dcba9876ba9876549876543276543210
2384
2385 # ifdef __LP64__
2386 ww = ww & kMask000000FF;
2387 // ........................fedcba98........................76543210
2388
2389 return S_CAST(Quarterword, ww | (ww >> 24));
2390 # else
2391 return S_CAST(Quarterword, ww);
2392 # endif
2393 }
2394
2395 HEADER_INLINE uintptr_t Pack0303Mask(uintptr_t ww) {
2396 return Pack0303(ww & kMask0303);
2397 }
2398
2399 # ifdef USE_SSE2
2400 HEADER_INLINE Vec4thUint UnpackVec8thUintTo4th(Vec8thUint hw) {
2401 hw = (hw | (hw << 8)) & 0x00ff00ffU;
2402 hw = (hw | (hw << 4)) & 0x0f0f0f0fU;
2403 hw = (hw | (hw << 2)) & 0x33333333U;
2404 return (hw | (hw << 1)) & 0x55555555U;
2405 }
2406
2407 HEADER_INLINE Vec8thUint PackVec4thUintTo8th(Vec4thUint ww) {
2408 ww = (ww | (ww >> 1)) & kMask3333;
2409 ww = (ww | (ww >> 2)) & kMask0F0F;
2410 ww = (ww | (ww >> 4)) & kMask00FF;
2411 return S_CAST(Vec8thUint, ww | (ww >> 8));
2412 }
2413
2414 HEADER_INLINE Vec16thUint PackVec8thUintTo16th(Vec8thUint ww) {
2415 ww = (ww | (ww >> 1)) & 0x3333;
2416 ww = (ww | (ww >> 2)) & 0x0f0f;
2417 return S_CAST(Vec16thUint, ww | (ww >> 4));
2418 }
2419
2420 # ifdef USE_SSE42
2421 HEADER_INLINE VecUc InverseMovemaskFF(Vec8thUint mask) {
2422 __m128i vmask = _mm_set1_epi16(mask);
2423 const __m128i byte_gather = _mm_setr_epi32(0, 0, 0x01010101, 0x01010101);
2424 vmask = _mm_shuffle_epi8(vmask, byte_gather);
2425 const __m128i bit_mask = _mm_set1_epi64x(0x7fbfdfeff7fbfdfeLL);
2426 vmask = _mm_or_si128(vmask, bit_mask);
2427 return R_CAST(VecUc, _mm_cmpeq_epi8(vmask, _mm_set1_epi64x(-1)));
2428 }
2429
2430 HEADER_INLINE VecUc InverseMovespreadmaskFF(Vec4thUint mask) {
2431 __m128i vmask = _mm_set1_epi32(mask);
2432 const __m128i byte_gather = _mm_setr_epi32(0, 0x01010101, 0x02020202, 0x03030303);
2433 vmask = _mm_shuffle_epi8(vmask, byte_gather);
2434 const __m128i bit_mask = _mm_set1_epi32(0xbfeffbfeU);
2435 vmask = _mm_or_si128(vmask, bit_mask);
2436 return R_CAST(VecUc, _mm_cmpeq_epi8(vmask, _mm_set1_epi64x(-1)));
2437 }
2438 # endif
2439
2440 # endif // !USE_SSE2
2441 #endif // !USE_AVX2
2442
2443 // alignment must be a power of 2
2444 // tried splitting out RoundDownPow2U32() and RoundUpPow2U32() functions, no
2445 // practical difference
2446 HEADER_CINLINE uintptr_t RoundDownPow2(uintptr_t val, uintptr_t alignment) {
2447 return val & (~(alignment - 1));
2448 }
2449
2450 HEADER_CINLINE uint64_t RoundDownPow2U64(uint64_t val, uint64_t alignment) {
2451 return val & (~(alignment - 1));
2452 }
2453
2454 HEADER_CINLINE uintptr_t RoundUpPow2(uintptr_t val, uintptr_t alignment) {
2455 return (val + alignment - 1) & (~(alignment - 1));
2456 }
2457
2458 HEADER_CINLINE uint64_t RoundUpPow2U64(uint64_t val, uint64_t alignment) {
2459 return (val + alignment - 1) & (~(alignment - 1));
2460 }
2461
2462
2463 // This is best when the divisor is constant (so (divisor - 1) can be
2464 // collapsed), and handles val == 0 properly. If the divisor isn't constant
2465 // and val is guaranteed to be nonzero, go with explicit
2466 // "1 + (val - 1) / divisor".
2467 //
2468 // Note that this fails if (val + divisor - 1) overflows the widest integer
2469 // type on the left.
2470 //
2471 // Since forced-uint32_t RoundDownPow2 was pointless, it stands to reason that
2472 // the same applies to DivUp. With that said, we may as well make divisor a
2473 // uint32_t just in case this ever gets used on a not-known-at-compile-time
2474 // divisor, since 64/64 can be slower than 64/32.
2475 HEADER_CINLINE uintptr_t DivUp(uintptr_t val, uint32_t divisor) {
2476 return (val + divisor - 1) / divisor;
2477 }
2478
2479 HEADER_CINLINE uint64_t DivUpU64(uint64_t val, uint32_t divisor) {
2480 return (val + divisor - 1) / divisor;
2481 }
2482
2483 // "Nz" means nonzero in two ways:
2484 // * result is in [1, modulus], not [0, modulus - 1]
2485 // * val should not be zero (though this expression still works if val is zero
2486 // and modulus is a hardcoded power of 2)
2487 HEADER_INLINE uint32_t ModNz(uintptr_t val, uint32_t modulus) {
2488 return (1 + ((val - 1) % modulus));
2489 }
2490
2491 // No need for ModNzU64 in practice, since high bits don't affect result when
2492 // modulus is a power of 2.
2493
2494 // Equivalent to (static_cast<int32_t>(uii) < 0). Most frequently used on
2495 // possibly-error chromosome indexes.
2496 HEADER_INLINE uint32_t IsI32Neg(uint32_t uii) {
2497 return uii >> 31;
2498 }
2499
2500 HEADER_INLINE uint32_t abs_i32(int32_t ii) {
2501 // Arithmetic right shift. 0xffffffffU when ii is negative, 0 otherwise.
2502 const uint32_t neg_sign_bit = S_CAST(uint32_t, ii >> 31);
2503
2504 return (S_CAST(uint32_t, ii) ^ neg_sign_bit) - neg_sign_bit;
2505 }
2506
2507 extern uint64_t g_failed_alloc_attempt_size;
2508 // with NDEBUG undefined, may want to define a bunch of macros so that line
2509 // number is printed as well; see e.g.
2510 // https://stackoverflow.com/questions/15884793/how-to-get-the-name-or-file-and-line-of-caller-method
2511
2512 #if (((__GNUC__ == 4) && (__GNUC_MINOR__ < 7)) || (__GNUC__ >= 11)) && !defined(__APPLE__)
2513 // putting this in the header file caused a bunch of gcc 4.4 strict-aliasing
2514 // warnings, while not doing so seems to inhibit some malloc-related compiler
2515 // optimizations, bleah
2516 // compromise: header-inline iff gcc version >= 4.7 (might not be the right
2517 // cutoff?)
2518 // update (18 Feb 2022): looks like inlined pgl_malloc is not compiled as
2519 // intended by gcc 11, due to new ipa-modref pass? Open to suggestions on how
2520 // to fix this; maybe it's now necessary to define type-specific malloc
2521 // wrappers, ugh...
2522 BoolErr pgl_malloc(uintptr_t size, void* pp);
2523 #else
2524 // Unfortunately, defining the second parameter to be of type void** doesn't do
2525 // the right thing.
2526 HEADER_INLINE BoolErr pgl_malloc(uintptr_t size, void* pp) {
2527 *S_CAST(unsigned char**, pp) = S_CAST(unsigned char*, malloc(size));
2528 if (likely(*S_CAST(unsigned char**, pp))) {
2529 return 0;
2530 }
2531 g_failed_alloc_attempt_size = size;
2532 return 1;
2533 }
2534 #endif
2535
2536 // This must be used for all fwrite() calls where len could be >= 2^31, since
2537 // OS X raw fwrite() doesn't work in that case.
2538 static_assert(sizeof(size_t) == sizeof(intptr_t), "plink2_base assumes size_t and intptr_t are synonymous.");
2539 BoolErr fwrite_checked(const void* buf, uintptr_t len, FILE* outfile);
2540
2541 HEADER_INLINE IntErr putc_checked(int32_t ii, FILE* outfile) {
2542 putc_unlocked(ii, outfile);
2543 return ferror_unlocked(outfile);
2544 }
2545
2546 // Only use this if loading < len bytes is not an error.
2547 // IntErr fread_checked2(void* buf, uintptr_t len, FILE* infile, uintptr_t* bytes_read_ptr);
2548
2549 BoolErr fread_checked(void* buf, uintptr_t len, FILE* infile);
2550
2551 HEADER_INLINE BoolErr fclose_null(FILE** fptr_ptr) {
2552 int32_t ii = ferror_unlocked(*fptr_ptr);
2553 int32_t jj = fclose(*fptr_ptr);
2554 *fptr_ptr = nullptr;
2555 return ii || jj;
2556 }
2557
2558
2559 #ifdef __LP64__
2560 // Reads an integer in [1, cap].
2561 // * Errors out unless first character is a digit, or is '+' followed by a
2562 // digit. Initial whitespace is not permitted.
2563 // * Like atoi(), this considereds the number to be terminated by *any*
2564 // nondigit character. E.g. "1000genomes" is treated as a valid instance of
2565 // 1000 rather than a nonnumeric token, and "98.6" is treated as 98. (See
2566 // ScanmovPosintCapped(), ScanmovUintCapped(), etc. in plink2_string if
2567 // you want strtol-like semantics, where the pointer is moved.)
2568 // * Errors out on overflow. This may be the biggest advantage over atoi().
2569 BoolErr ScanPosintCapped(const char* str_iter, uint64_t cap, uint32_t* valp);
2570
2571 // [0, cap]
2572 BoolErr ScanUintCapped(const char* str_iter, uint64_t cap, uint32_t* valp);
2573
2574 // [-bound, bound]
2575 BoolErr ScanIntAbsBounded(const char* str_iter, uint64_t bound, int32_t* valp);
2576 #else // not __LP64__
2577 // Need to be more careful in 32-bit case due to overflow.
2578 // A funny-looking div_10/mod_10 interface is used since the cap will usually
2579 // be a constant, and we want the integer division/modulus to occur at compile
2580 // time.
2581 BoolErr ScanPosintCapped32(const char* str_iter, uint32_t cap_div_10, uint32_t cap_mod_10, uint32_t* valp);
2582
2583 BoolErr ScanUintCapped32(const char* str_iter, uint32_t cap_div_10, uint32_t cap_mod_10, uint32_t* valp);
2584
2585 BoolErr ScanIntAbsBounded32(const char* str_iter, uint32_t bound_div_10, uint32_t bound_mod_10, int32_t* valp);
2586
2587 HEADER_INLINE BoolErr ScanPosintCapped(const char* str, uint32_t cap, uint32_t* valp) {
2588 return ScanPosintCapped32(str, cap / 10, cap % 10, valp);
2589 }
2590
2591 HEADER_INLINE BoolErr ScanUintCapped(const char* str, uint32_t cap, uint32_t* valp) {
2592 return ScanUintCapped32(str, cap / 10, cap % 10, valp);
2593 }
2594
2595 HEADER_INLINE BoolErr ScanIntAbsBounded(const char* str, uint32_t bound, int32_t* valp) {
2596 return ScanIntAbsBounded32(str, bound / 10, bound % 10, valp);
2597 }
2598 #endif
2599
2600
2601 // intentionally rejects -2^31 for now
2602 // (that's a reason why this doesn't have the shorter name 'ScanI32')
2603 HEADER_INLINE BoolErr ScanInt32(const char* str, int32_t* valp) {
2604 return ScanIntAbsBounded(str, 0x7fffffff, valp);
2605 }
2606
2607 // default cap = 0x7ffffffe
2608 HEADER_INLINE BoolErr ScanPosintDefcap(const char* str, uint32_t* valp) {
2609 return ScanPosintCapped(str, 0x7ffffffe, valp);
2610 }
2611
2612 HEADER_INLINE BoolErr ScanUintDefcap(const char* str, uint32_t* valp) {
2613 return ScanUintCapped(str, 0x7ffffffe, valp);
2614 }
2615
2616 HEADER_INLINE BoolErr ScanIntAbsDefcap(const char* str, int32_t* valp) {
2617 return ScanIntAbsBounded(str, 0x7ffffffe, valp);
2618 }
2619
2620 HEADER_INLINE BoolErr ScanUintIcap(const char* str, uint32_t* valp) {
2621 return ScanUintCapped(str, 0x7fffffff, valp);
2622 }
2623
2624
2625 // memcpya() tends to be used to copy known-length text strings, while
2626 // memseta() has more mixed usage but char* type is also at least as common as
2627 // unsigned char*; append comes up less when working with raw byte arrays. So
2628 // give the shortest-name forms char* return types.
2629 HEADER_INLINE char* memseta(void* target, unsigned char val, uintptr_t ct) {
2630 memset(target, val, ct);
2631 return &(S_CAST(char*, target)[ct]);
2632 }
2633
2634 HEADER_INLINE unsigned char* memsetua(void* target, unsigned char val, uintptr_t ct) {
2635 memset(target, val, ct);
2636 return &(S_CAST(unsigned char*, target)[ct]);
2637 }
2638
2639 HEADER_CINLINE uintptr_t BitCtToVecCt(uintptr_t val) {
2640 return DivUp(val, kBitsPerVec);
2641 }
2642
2643 HEADER_CINLINE uintptr_t BitCtToWordCt(uintptr_t val) {
2644 return DivUp(val, kBitsPerWord);
2645 }
2646
2647 HEADER_CINLINE uintptr_t BitCtToAlignedWordCt(uintptr_t val) {
2648 return kWordsPerVec * BitCtToVecCt(val);
2649 }
2650
2651 HEADER_CINLINE uintptr_t BitCtToCachelineCt(uintptr_t val) {
2652 return DivUp(val, kBitsPerCacheline);
2653 }
2654
2655 HEADER_CINLINE uintptr_t Int32CtToVecCt(uintptr_t val) {
2656 return DivUp(val, kInt32PerVec);
2657 }
2658
2659 HEADER_CINLINE uintptr_t Int32CtToCachelineCt(uintptr_t val) {
2660 return DivUp(val, kInt32PerCacheline);
2661 }
2662
2663 HEADER_CINLINE uintptr_t WordCtToVecCt(uintptr_t val) {
2664 return DivUp(val, kWordsPerVec);
2665 }
2666
2667 HEADER_CINLINE uintptr_t WordCtToCachelineCt(uintptr_t val) {
2668 return DivUp(val, kWordsPerCacheline);
2669 }
2670
2671 HEADER_CINLINE uint64_t WordCtToCachelineCtU64(uint64_t val) {
2672 return DivUpU64(val, kWordsPerCacheline);
2673 }
2674
2675 #ifdef __LP64__
2676 HEADER_CINLINE uintptr_t Int64CtToVecCt(uintptr_t val) {
2677 return DivUp(val, kBytesPerVec / 8);
2678 }
2679 #else
2680 HEADER_CINLINE uintptr_t Int64CtToVecCt(uintptr_t val) {
2681 return val * 2;
2682 }
2683 #endif
2684
2685 HEADER_CINLINE uintptr_t Int64CtToCachelineCt(uintptr_t val) {
2686 return DivUp(val, kInt64PerCacheline);
2687 }
2688
2689 HEADER_CINLINE uintptr_t DblCtToVecCt(uintptr_t val) {
2690 return Int64CtToVecCt(val);
2691 }
2692
2693 HEADER_CINLINE uintptr_t VecCtToCachelineCt(uintptr_t val) {
2694 return DivUp(val, kVecsPerCacheline);
2695 }
2696
2697 HEADER_CINLINE uint64_t VecCtToCachelineCtU64(uint64_t val) {
2698 return DivUpU64(val, kVecsPerCacheline);
2699 }
2700
2701 // C++11 standard guarantees std::min and std::max return leftmost minimum in
2702 // case of equality; best to adhere to that
2703 // We don't actually use std::min/max since casting one argument when comparing
2704 // e.g. a uint32_t with a uintptr_t is pointlessly verbose. Compiler will
2705 // still warn against comparison of signed with unsigned.
2706 #define MAXV(aa, bb) (((bb) > (aa))? (bb) : (aa))
2707 #define MINV(aa, bb) (((bb) < (aa))? (bb) : (aa))
2708
2709
2710 // don't use PglErr here since there's only one failure mode, it's
2711 // obvious what it is, and stacking multiple aligned_mallocs in a single
2712 // if-statement is useful.
2713 BoolErr aligned_malloc(uintptr_t size, uintptr_t alignment, void* aligned_pp);
2714
2715 #ifdef USE_SSE42
2716 HEADER_CINLINE uint32_t NypsumWord(uintptr_t val) {
2717 return __builtin_popcountll(val) + __builtin_popcountll(val & kMaskAAAA);
2718 }
2719 #else
2720 HEADER_CINLINE2 uint32_t NypsumWord(uintptr_t val) {
2721 val = (val & kMask3333) + ((val >> 2) & kMask3333);
2722 return (((val + (val >> 4)) & kMask0F0F) * kMask0101) >> (kBitsPerWord - 8);
2723 }
2724 #endif
2725
2726 // the simple version, good enough for all non-time-critical stuff
2727 // (without SSE4.2, PopcountWords() tends to be >3x as fast on arrays. with
2728 // SSE4.2 but no AVX2, there's no noticeable difference. with AVX2,
2729 // PopcountWords() gains another factor of 1.5-2x.)
2730 #ifdef USE_SSE42
2731 HEADER_CINLINE uint32_t PopcountWord(uintptr_t val) {
2732 return __builtin_popcountll(val);
2733 }
2734 #else
2735 HEADER_CINLINE2 uint32_t PopcountWord(uintptr_t val) {
2736 // Sadly, this was still faster than the LLVM implementation of the intrinsic
2737 // as of 2016.
2738 return NypsumWord(val - ((val >> 1) & kMask5555));
2739 }
2740 #endif
2741
2742 #ifdef USE_SSE42
2743 HEADER_INLINE uint32_t Popcount2Words(uintptr_t val0, uintptr_t val1) {
2744 return __builtin_popcountll(val0) + __builtin_popcountll(val1);
2745 }
2746 #else
2747 HEADER_INLINE uint32_t Popcount2Words(uintptr_t val0, uintptr_t val1) {
2748 val0 -= (val0 >> 1) & kMask5555;
2749 val1 -= (val1 >> 1) & kMask5555;
2750 const uintptr_t four_bit = (val0 & kMask3333) + ((val0 >> 2) & kMask3333) + (val1 & kMask3333) + ((val1 >> 2) & kMask3333);
2751 // up to 16 values in 0..12; sum fits in 8 bits
2752 return (((four_bit & kMask0F0F) + ((four_bit >> 4) & kMask0F0F)) * kMask0101) >> (kBitsPerWord - 8);
2753 }
2754 #endif
2755
2756 #ifndef __LP64__
2757 HEADER_INLINE uint32_t Popcount4Words(uintptr_t val0, uintptr_t val1, uintptr_t val2, uintptr_t val3) {
2758 val0 -= (val0 >> 1) & kMask5555;
2759 val1 -= (val1 >> 1) & kMask5555;
2760 val2 -= (val2 >> 1) & kMask5555;
2761 val3 -= (val3 >> 1) & kMask5555;
2762 const uintptr_t four_bit_0 = (val0 & kMask3333) + ((val0 >> 2) & kMask3333) + (val1 & kMask3333) + ((val1 >> 2) & kMask3333);
2763 const uintptr_t four_bit_1 = (val2 & kMask3333) + ((val2 >> 2) & kMask3333) + (val3 & kMask3333) + ((val3 >> 2) & kMask3333);
2764 return (((four_bit_0 & kMask0F0F) + ((four_bit_0 >> 4) & kMask0F0F) + (four_bit_1 & kMask0F0F) + ((four_bit_1 >> 4) & kMask0F0F)) * kMask0101) >> (kBitsPerWord - 8);
2765 }
2766 #endif
2767
2768 #ifdef USE_SSE42
2769 HEADER_INLINE uint32_t PopcountHW(uint32_t val) {
2770 return __builtin_popcount(val);
2771 }
2772
2773 HEADER_INLINE uint32_t PopcountByte(uint32_t val) {
2774 return __builtin_popcount(val);
2775 }
2776 #else
2777 # ifdef __LP64__
2778 HEADER_INLINE uint32_t PopcountHW(uint32_t val) {
2779 val = val - ((val >> 1) & 0x55555555);
2780 val = (val & 0x33333333) + ((val >> 2) & 0x33333333);
2781 val = (val + (val >> 4)) & 0x0f0f0f0f;
2782 return (val * 0x1010101) >> 24;
2783 }
2784 # else
2785 HEADER_INLINE uint32_t PopcountHW(uint32_t val) {
2786 val = val - ((val >> 1) & 0x5555);
2787 val = (val & 0x3333) + ((val >> 2) & 0x3333);
2788 val = (val + (val >> 4)) & 0x0f0f;
2789 return (val + (val >> 8)) & 0xff;
2790 }
2791 # endif
2792
2793 HEADER_INLINE uint32_t PopcountByte(uint32_t val) {
2794 val = val - ((val >> 1) & 0x55);
2795 val = (val & 0x33) + ((val >> 2) & 0x33);
2796 return (val + (val >> 4)) & 0xf;
2797 }
2798 #endif
2799
2800 #ifdef USE_SSE2
2801 # ifdef USE_SSE42
2802 HEADER_INLINE uint32_t PopcountVec8thUint(uint32_t val) {
2803 return __builtin_popcount(val);
2804 }
2805 # else
2806 HEADER_INLINE uint32_t PopcountVec8thUint(uint32_t val) {
2807 // May as well exploit the fact that only the low 16 bits may be set.
2808 val = val - ((val >> 1) & 0x5555);
2809 val = (val & 0x3333) + ((val >> 2) & 0x3333);
2810 val = (val + (val >> 4)) & 0x0f0f;
2811 return (val + (val >> 8)) & 0xff;
2812 }
2813 # endif
2814 #endif
2815
2816 #ifdef USE_SSE2
2817 // On ARM, emulated movemask isn't great. But there are alternative
2818 // instructions that efficiently perform what you usually want to do with
2819 // movemasks:
2820 // https://community.arm.com/arm-community-blogs/b/infrastructure-solutions-blog/posts/porting-x86-vector-bitmask-optimizations-to-arm-neon
2821
2822 # ifndef SIMDE_ARM_NEON_A32V8_NATIVE
2823 // vec0255 refers to a VecUc where all bytes are equal to 0 or 255.
2824 // (possible todo: define this as its own type, with automatic downcast to
2825 // VecUc but not the other way around.)
2826 //
2827 // Return value in nonzero case is architecture-dependent (though always
2828 // nonzero). So, best to only use this in other architecture-specific code;
2829 // hence the leading underscore in the function name.
2830 HEADER_INLINE uint64_t _vec0255_is_nonzero(VecUc vv) {
2831 return vecuc_movemask(vv);
2832 }
2833
2834 HEADER_INLINE uint32_t vec0255_set_ct(VecUc vv) {
2835 return PopcountVec8thUint(vecuc_movemask(vv));
2836 }
2837
2838 HEADER_INLINE uint32_t vec0255_is_all_set(VecUc vv) {
2839 return (vecuc_movemask(vv) == kVec8thUintMax);
2840 }
2841
2842 HEADER_INLINE uint32_t vec0255u16_is_all_set(VecU16 vv) {
2843 return (vecu16_movemask(vv) == kVec8thUintMax);
2844 }
2845
2846 HEADER_INLINE uint32_t m128is_are_equal(__m128i v1, __m128i v2) {
2847 return (_mm_movemask_epi8(_mm_cmpeq_epi8(v1, v2)) == 65535);
2848 }
2849 # else
2850 HEADER_INLINE uint64_t arm_shrn4_uc(VecUc vv) {
2851 uint16x8_t vv_;
2852 memcpy(&vv_, &vv, sizeof(vv_));
2853 return vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(vv_, 4)), 0);
2854 }
2855
2856 HEADER_INLINE uint64_t arm_shrn4_i8(VecI8 vv) {
2857 uint16x8_t vv_;
2858 memcpy(&vv_, &vv, sizeof(vv_));
2859 return vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(vv_, 4)), 0);
2860 }
2861
2862 HEADER_INLINE uint64_t arm_shrn4_u16(VecU16 vv) {
2863 uint16x8_t vv_;
2864 memcpy(&vv_, &vv, sizeof(vv_));
2865 return vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(vv_, 4)), 0);
2866 }
2867
2868 HEADER_INLINE uint64_t arm_shrn4_m128i(__m128i vv) {
2869 uint16x8_t vv_;
2870 memcpy(&vv_, &vv, sizeof(vv_));
2871 return vget_lane_u64(vreinterpret_u64_u8(vshrn_n_u16(vv_, 4)), 0);
2872 }
2873
2874 HEADER_INLINE uint64_t _vec0255_is_nonzero(VecUc vv) {
2875 return arm_shrn4_uc(vv);
2876 }
2877
2878 // set_bits4 must only have bits in 0, 4, ..., 60 set.
2879 // move this out of ARM-only ifdef if we ever want this elsewhere.
2880 HEADER_INLINE uint32_t popcount_bits4(uint64_t set_bits4) {
2881 // Branchlessly count the number of set bits, taking advantage of the limited
2882 // set of positions they can be in.
2883 // Multiplication by the magic constant kMask1111 usually puts the sum of
2884 // all 16 bits of interest in the high nybble of the result... except that
2885 // the nybble overflows when all 16 bits are set. We work around this by
2886 // (i) multiplying by (kMask1111 >> 4) instead, which excludes the lowest bit
2887 // from the high-nybble sum, and
2888 // (ii) then adding the lowest bit afterward.
2889 const uint32_t set_ct_excluding_lowest = (set_bits4 * (kMask1111 >> 4)) >> 60;
2890 return set_ct_excluding_lowest + (set_bits4 & 1);
2891 }
2892
2893 // xx must have all nybbles equal to 0 or 15.
2894 HEADER_INLINE uint32_t count_set_nybbles(uint64_t xx) {
2895 return popcount_bits4(xx & kMask1111);
2896 }
2897
2898 HEADER_INLINE uint32_t vec0255_set_ct(VecUc vv) {
2899 return count_set_nybbles(arm_shrn4_uc(vv));
2900 }
2901
2902 HEADER_INLINE uint32_t vec0255_is_all_set(VecUc vv) {
2903 return (arm_shrn4_uc(vv) == UINT64_MAX);
2904 }
2905
2906 HEADER_INLINE uint32_t vec0255u16_is_all_set(VecU16 vv) {
2907 return (arm_shrn4_u16(vv) == UINT64_MAX);
2908 }
2909
2910 HEADER_INLINE uint32_t m128is_are_equal(__m128i v1, __m128i v2) {
2911 const uint64_t set_nybbles = arm_shrn4_m128i(_mm_cmpeq_epi8(v1, v2));
2912 return (set_nybbles == UINT64_MAX);
2913 }
2914 # endif
2915
2916 HEADER_INLINE uint32_t vecucs_are_equal(VecUc v1, VecUc v2) {
2917 return vec0255_is_all_set(v1 == v2);
2918 }
2919
2920 HEADER_INLINE uint32_t vecu16s_are_equal(VecU16 v1, VecU16 v2) {
2921 return vec0255u16_is_all_set(v1 == v2);
2922 }
2923 #endif
2924
2925 // Downcasts don't risk alignment issues.
2926 HEADER_INLINE unsigned char* DowncastToUc(void* pp) {
2927 return S_CAST(unsigned char*, pp);
2928 }
2929
2930 HEADER_INLINE char* DowncastToC(void* pp) {
2931 return S_CAST(char*, pp);
2932 }
2933
2934 HEADER_INLINE const unsigned char* DowncastKToUc(const void* pp) {
2935 return S_CAST(const unsigned char*, pp);
2936 }
2937
2938 HEADER_INLINE const char* DowncastKToC(const void* pp) {
2939 return S_CAST(const char*, pp);
2940 }
2941
2942 HEADER_INLINE uintptr_t* DowncastVecWToW(VecW* pp) {
2943 return R_CAST(uintptr_t*, pp);
2944 }
2945
2946 HEADER_INLINE uint32_t* DowncastVecWToU32(VecW* pp) {
2947 return R_CAST(uint32_t*, pp);
2948 }
2949
2950 HEADER_INLINE Halfword* DowncastWToHW(uintptr_t* pp) {
2951 return R_CAST(Halfword*, pp);
2952 }
2953
2954 HEADER_INLINE uint32_t* DowncastWToU32(uintptr_t* pp) {
2955 return R_CAST(uint32_t*, pp);
2956 }
2957
2958 HEADER_INLINE uint16_t* DowncastWToU16(uintptr_t* pp) {
2959 return R_CAST(uint16_t*, pp);
2960 }
2961
2962 HEADER_INLINE int16_t* DowncastWToI16(uintptr_t* pp) {
2963 return R_CAST(int16_t*, pp);
2964 }
2965
2966 #ifdef USE_SSE2
2967 HEADER_INLINE Vec8thUint* DowncastWToV8(uintptr_t* pp) {
2968 return R_CAST(Vec8thUint*, pp);
2969 }
2970 #endif
2971
2972 HEADER_INLINE uint16_t* DowncastU32ToU16(uint32_t* pp) {
2973 return R_CAST(uint16_t*, pp);
2974 }
2975
2976 HEADER_INLINE const uintptr_t* DowncastKVecWToW(const VecW* pp) {
2977 return R_CAST(const uintptr_t*, pp);
2978 }
2979
2980 HEADER_INLINE const uint16_t* DowncastKVecWToU16(const VecW* pp) {
2981 return R_CAST(const uint16_t*, pp);
2982 }
2983
2984 HEADER_INLINE const Halfword* DowncastKWToHW(const uintptr_t* pp) {
2985 return R_CAST(const Halfword*, pp);
2986 }
2987
2988 HEADER_INLINE const uint32_t* DowncastKWToU32(const uintptr_t* pp) {
2989 return R_CAST(const uint32_t*, pp);
2990 }
2991
2992 HEADER_INLINE const uint16_t* DowncastKWToU16(const uintptr_t* pp) {
2993 return R_CAST(const uint16_t*, pp);
2994 }
2995
2996 HEADER_INLINE const uint16_t* DowncastKU64ToU16(const uint64_t* pp) {
2997 return R_CAST(const uint16_t*, pp);
2998 }
2999
3000
3001 HEADER_INLINE uint32_t IsVecAligned(const void* ptr) {
3002 return !(R_CAST(uintptr_t, ptr) % kBytesPerVec);
3003 }
3004
3005 #ifdef USE_SSE2
3006 HEADER_INLINE void AlignWToVec(uintptr_t** pp) {
3007 const uintptr_t addr = R_CAST(uintptr_t, *pp);
3008 *pp = R_CAST(uintptr_t*, RoundUpPow2(addr, kBytesPerVec));
3009 }
3010 #else
3011 HEADER_INLINE void AlignWToVec(__maybe_unused uintptr_t** pp) {
3012 }
3013 #endif
3014
3015 HEADER_INLINE void AlignKUcToVec(const unsigned char** pp) {
3016 const uintptr_t addr = R_CAST(uintptr_t, *pp);
3017 *pp = R_CAST(const unsigned char*, RoundUpPow2(addr, kBytesPerVec));
3018 }
3019
3020 /*
3021 HEADER_INLINE uint32_t AlignToVecW(void* prestart, VecW** result_ptr) {
3022 unsigned char* prestart_uc = S_CAST(unsigned char*, prestart);
3023 const uint32_t lead_byte_ct = (-R_CAST(uintptr_t, prestart_uc)) % kBytesPerVec;
3024 *result_ptr = R_CAST(VecW*, &(prestart_uc[lead_byte_ct]));
3025 return lead_byte_ct;
3026 }
3027 */
3028
3029 HEADER_INLINE uint32_t AlignKToAW(const void* prestart, const uintptr_t** result_ptr) {
3030 const unsigned char* prestart_uc = S_CAST(const unsigned char*, prestart);
3031 const uint32_t lead_byte_ct = (-R_CAST(uintptr_t, prestart_uc)) % kBytesPerVec;
3032 *result_ptr = R_CAST(const uintptr_t*, &(prestart_uc[lead_byte_ct]));
3033 return lead_byte_ct;
3034 }
3035
3036 HEADER_INLINE uint32_t AlignKToW(const void* prestart, const uintptr_t** result_ptr) {
3037 const unsigned char* prestart_uc = S_CAST(const unsigned char*, prestart);
3038 const uint32_t lead_byte_ct = (-R_CAST(uintptr_t, prestart_uc)) % kBytesPerWord;
3039 *result_ptr = R_CAST(const uintptr_t*, &(prestart_uc[lead_byte_ct]));
3040 return lead_byte_ct;
3041 }
3042
3043
3044 // Turns out memcpy(&cur_word, bytearr, ct) can't be trusted to be fast when ct
3045 // isn't known at compile time.
3046 //
3047 // ct must be less than sizeof(intptr_t). ct == 0 handled correctly, albeit
3048 // inefficiently.
3049 #ifndef NO_UNALIGNED
3050 HEADER_INLINE uintptr_t ProperSubwordLoad(const void* bytearr, uint32_t ct) {
3051 const unsigned char* bytearr_uc = S_CAST(const unsigned char*, bytearr);
3052 # ifdef __LP64__
3053 if (ct >= 4) {
3054 const uint32_t remainder = ct - 4;
3055 bytearr_uc = &(bytearr_uc[remainder]);
3056 uintptr_t cur_word = *R_CAST(const uint32_t*, bytearr_uc);
3057 if (remainder) {
3058 cur_word <<= remainder * CHAR_BIT;
3059 cur_word |= *S_CAST(const uint32_t*, bytearr);
3060 }
3061 return cur_word;
3062 }
3063 # endif
3064 if (ct >= 2) {
3065 const uint32_t remainder = ct & 1;
3066 uintptr_t cur_word = *R_CAST(const uint16_t*, &(bytearr_uc[remainder]));
3067 if (remainder) {
3068 cur_word <<= 8;
3069 cur_word |= bytearr_uc[0];
3070 }
3071 return cur_word;
3072 }
3073 return ct? bytearr_uc[0] : 0;
3074 }
3075
3076 HEADER_INLINE uintptr_t SubwordLoad(const void* bytearr, uint32_t ct) {
3077 if (ct == S_CAST(uint32_t, kBytesPerWord)) {
3078 return *S_CAST(const uintptr_t*, bytearr);
3079 }
3080 return ProperSubwordLoad(bytearr, ct);
3081 }
3082
3083 // ct must be in 1..4.
3084 HEADER_INLINE uint32_t SubU32Load(const void* bytearr, uint32_t ct) {
3085 if (ct & 1) {
3086 const unsigned char* bytearr_iter = S_CAST(const unsigned char*, bytearr);
3087 uint32_t cur_uint = *bytearr_iter;
3088 if (ct == 3) {
3089 ++bytearr_iter;
3090 cur_uint |= S_CAST(uint32_t, *R_CAST(const uint16_t*, bytearr_iter)) << 8;
3091 }
3092 return cur_uint;
3093 }
3094 if (ct == 2) {
3095 return *S_CAST(const uint16_t*, bytearr);
3096 }
3097 return *S_CAST(const uint32_t*, bytearr);
3098 }
3099
3100 // ct must be 1 or 2.
3101 HEADER_INLINE uint16_t SubU16Load(const void* bytearr, uint32_t ct) {
3102 if (ct == 1) {
3103 const unsigned char* bytearr_uc = S_CAST(const unsigned char*, bytearr);
3104 return bytearr_uc[0];
3105 }
3106 return *S_CAST(const uint16_t*, bytearr);
3107 }
3108
3109 // ct must be in 1..sizeof(Halfword).
3110 #ifdef __LP64__
3111 HEADER_INLINE Halfword SubHWLoad(const void* bytearr, uint32_t ct) {
3112 return SubU32Load(bytearr, ct);
3113 }
3114 #else
3115 HEADER_INLINE Halfword SubHWLoad(const void* bytearr, uint32_t ct) {
3116 return SubU16Load(bytearr, ct);
3117 }
3118 #endif
3119
3120 // tried making this non-inline, loop took more than 50% longer
3121 HEADER_INLINE void ProperSubwordStore(uintptr_t cur_word, uint32_t byte_ct, void* target) {
3122 unsigned char* target_iter = S_CAST(unsigned char*, target);
3123 # ifdef __LP64__
3124 if (byte_ct >= 4) {
3125 *R_CAST(uint32_t*, target_iter) = cur_word;
3126 if (byte_ct == 4) {
3127 return;
3128 }
3129 const uint32_t remainder = byte_ct - 4;
3130 target_iter = &(target_iter[remainder]);
3131 cur_word >>= remainder * CHAR_BIT;
3132 *R_CAST(uint32_t*, target_iter) = cur_word;
3133 return;
3134 }
3135 # endif
3136 if (byte_ct & 1) {
3137 *target_iter++ = cur_word;
3138 cur_word >>= 8;
3139 }
3140 if (byte_ct & 2) {
3141 *R_CAST(uint16_t*, target_iter) = cur_word;
3142 }
3143 }
3144
3145 HEADER_INLINE void SubwordStore(uintptr_t cur_word, uint32_t byte_ct, void* target) {
3146 if (byte_ct == kBytesPerWord) {
3147 *S_CAST(uintptr_t*, target) = cur_word;
3148 return;
3149 }
3150 ProperSubwordStore(cur_word, byte_ct, target);
3151 }
3152
3153 // byte_ct must be in 1..4.
3154 HEADER_INLINE void SubU32Store(uint32_t cur_uint, uint32_t byte_ct, void* target) {
3155 if (byte_ct & 1) {
3156 unsigned char* target_iter = S_CAST(unsigned char*, target);
3157 *target_iter = cur_uint;
3158 if (byte_ct == 3) {
3159 ++target_iter;
3160 *R_CAST(uint16_t*, target_iter) = cur_uint >> 8;
3161 }
3162 return;
3163 }
3164 if (byte_ct == 2) {
3165 *S_CAST(uint16_t*, target) = cur_uint;
3166 return;
3167 }
3168 *S_CAST(uint32_t*, target) = cur_uint;
3169 return;
3170 }
3171 #else // NO_UNALIGNED
3172 HEADER_INLINE uintptr_t ProperSubwordLoad(const void* bytearr, uint32_t ct) {
3173 uintptr_t cur_word = 0;
3174 memcpy(&cur_word, bytearr, ct);
3175 return cur_word;
3176 }
3177
3178 HEADER_INLINE uintptr_t SubwordLoad(const void* bytearr, uint32_t ct) {
3179 uintptr_t cur_word = 0;
3180 memcpy(&cur_word, bytearr, ct);
3181 return cur_word;
3182 }
3183
3184 HEADER_INLINE uint32_t SubU32Load(const void* bytearr, uint32_t ct) {
3185 uint32_t cur_uint = 0;
3186 memcpy(&cur_uint, bytearr, ct);
3187 return cur_uint;
3188 }
3189
3190 HEADER_INLINE Halfword SubHWLoad(const void* bytearr, uint32_t ct) {
3191 Halfword cur_uint = 0;
3192 memcpy(&cur_uint, bytearr, ct);
3193 return cur_uint;
3194 }
3195
3196 HEADER_INLINE void ProperSubwordStore(uintptr_t cur_word, uint32_t byte_ct, void* target) {
3197 memcpy(target, &cur_word, byte_ct);
3198 }
3199
3200 HEADER_INLINE void SubwordStore(uintptr_t cur_word, uint32_t byte_ct, void* target) {
3201 memcpy(target, &cur_word, byte_ct);
3202 }
3203
3204 HEADER_INLINE void SubU32Store(uint32_t cur_uint, uint32_t byte_ct, void* target) {
3205 memcpy(target, &cur_uint, byte_ct);
3206 }
3207 #endif // NO_UNALIGNED
3208
3209 HEADER_INLINE uint64_t SubU64Load(const void* bytearr, uint32_t ct) {
3210 #ifdef __LP64__
3211 return SubwordLoad(bytearr, ct);
3212 #else
3213 uint64_t cur_u64 = 0;
3214 memcpy(&cur_u64, bytearr, ct);
3215 return cur_u64;
3216 #endif
3217 }
3218
3219 HEADER_INLINE void ProperSubwordStoreMov(uintptr_t cur_word, uint32_t byte_ct, unsigned char** targetp) {
3220 ProperSubwordStore(cur_word, byte_ct, *targetp);
3221 *targetp += byte_ct;
3222 }
3223
3224 HEADER_INLINE void SubwordStoreMov(uintptr_t cur_word, uint32_t byte_ct, unsigned char** targetp) {
3225 SubwordStore(cur_word, byte_ct, *targetp);
3226 *targetp += byte_ct;
3227 }
3228
3229 HEADER_INLINE void SubU32StoreMov(uint32_t cur_uint, uint32_t byte_ct, unsigned char** targetp) {
3230 SubU32Store(cur_uint, byte_ct, *targetp);
3231 *targetp += byte_ct;
3232 }
3233
3234 #ifndef NO_UNALIGNED
3235 # ifdef __LP64__
3236 HEADER_INLINE void SubU64StoreMov(uint64_t cur_u64, uint32_t byte_ct, unsigned char** targetp) {
3237 return SubwordStoreMov(cur_u64, byte_ct, targetp);
3238 }
3239 # else
3240 HEADER_INLINE void SubU64StoreMov(uint64_t cur_u64, uint32_t byte_ct, unsigned char** targetp) {
3241 if (byte_ct > 4) {
3242 *R_CAST(uint32_t*, *targetp) = cur_u64;
3243 *targetp += 4;
3244 byte_ct -= 4;
3245 cur_u64 >>= 32;
3246 }
3247 return SubU32StoreMov(cur_u64, byte_ct, targetp);
3248 }
3249 # endif
3250 #else
3251 HEADER_INLINE void SubU64StoreMov(uint64_t cur_u64, uint32_t byte_ct, unsigned char** targetp) {
3252 memcpy(*targetp, &cur_u64, byte_ct);
3253 *targetp += byte_ct;
3254 }
3255 #endif
3256
3257
3258 HEADER_INLINE BoolErr vecaligned_malloc(uintptr_t size, void* aligned_pp) {
3259 #ifdef USE_AVX2
3260 return aligned_malloc(size, kBytesPerVec, aligned_pp);
3261 #else
3262 # if defined(__APPLE__) || !defined(__LP64__)
3263 const BoolErr ret_boolerr = pgl_malloc(size, aligned_pp);
3264 assert(IsVecAligned(*S_CAST(uintptr_t**, aligned_pp)));
3265 return ret_boolerr;
3266 # else
3267 return aligned_malloc(size, kBytesPerVec, aligned_pp);
3268 # endif
3269 #endif
3270 }
3271
3272 HEADER_INLINE BoolErr cachealigned_malloc(uintptr_t size, void* aligned_pp) {
3273 return aligned_malloc(size, kCacheline, aligned_pp);
3274 }
3275
3276 HEADER_INLINE void aligned_free(void* aligned_ptr) {
3277 free(R_CAST(void*, S_CAST(uintptr_t*, aligned_ptr)[-1]));
3278 }
3279
3280 HEADER_INLINE void aligned_free_cond(void* aligned_ptr) {
3281 if (aligned_ptr) {
3282 free(R_CAST(void*, S_CAST(uintptr_t*, aligned_ptr)[-1]));
3283 }
3284 }
3285
3286 // Common pattern is to initialize a data structure, then use it without
3287 // mutating it, then free it.
3288 // Yes, in principle you should have a non-const pointer to the data structure
3289 // to free it. But my experience is that that makes too many beneficial uses
3290 // of const less ergonomic, without offering enough in return. So we cheat a
3291 // bit, in a way that can be systematically cleaned up later if necessary.
3292 HEADER_INLINE void free_const(const void* memptr) {
3293 free(K_CAST(void*, memptr));
3294 }
3295
3296 HEADER_INLINE void free_cond(const void* memptr) {
3297 if (memptr) {
3298 free_const(memptr);
3299 }
3300 }
3301
3302 #ifdef USE_AVX2
3303 HEADER_INLINE void vecaligned_free(void* aligned_ptr) {
3304 aligned_free(aligned_ptr);
3305 }
3306
3307 HEADER_INLINE void vecaligned_free_cond(void* aligned_ptr) {
3308 aligned_free_cond(aligned_ptr);
3309 }
3310 #else
3311 # if defined(__APPLE__) || !defined(__LP64__)
3312 HEADER_INLINE void vecaligned_free(void* aligned_ptr) {
3313 free(aligned_ptr);
3314 }
3315
3316 HEADER_INLINE void vecaligned_free_cond(void* aligned_ptr) {
3317 free_cond(aligned_ptr);
3318 }
3319 # else
3320 HEADER_INLINE void vecaligned_free(void* aligned_ptr) {
3321 aligned_free(aligned_ptr);
3322 }
3323
3324 HEADER_INLINE void vecaligned_free_cond(void* aligned_ptr) {
3325 aligned_free_cond(aligned_ptr);
3326 }
3327 # endif
3328 #endif
3329
3330
3331 #if defined(USE_SSE2) && !defined(NO_UNALIGNED)
3332 int32_t memequal(const void* m1, const void* m2, uintptr_t byte_ct);
3333
3334 // This is also better than the June 2018 OS X/LLVM stock implementation,
3335 // especially for small values of ct.
3336 // (gcc 7.1 and clang 6.0.0 should have better stock implementations;
3337 // re-benchmark this once Linux build machine is upgraded to Ubuntu 18.04.)
3338 int32_t Memcmp(const void* m1, const void* m2, uintptr_t ct);
3339 #else
3340 HEADER_INLINE int32_t memequal(const void* m1, const void* m2, uintptr_t byte_ct) {
3341 return !memcmp(m1, m2, byte_ct);
3342 }
3343
3344 HEADER_INLINE int32_t Memcmp(const void* m1, const void* m2, uintptr_t ct) {
3345 return memcmp(m1, m2, ct);
3346 }
3347 #endif
3348
3349
3350 HEADER_INLINE char* memcpya(void* __restrict target, const void* __restrict source, uintptr_t ct) {
3351 memcpy(target, source, ct);
3352 return &(S_CAST(char*, target)[ct]);
3353 }
3354
3355 HEADER_INLINE unsigned char* memcpyua(void* __restrict target, const void* __restrict source, uintptr_t ct) {
3356 memcpy(target, source, ct);
3357 return &(S_CAST(unsigned char*, target)[ct]);
3358 }
3359
3360 // Tried beating memcpy for usually-small strings not known to have length <=
3361 // 8, gave up.
3362
3363 #if defined(USE_SSE2) && defined(__cplusplus) && !defined(NO_UNALIGNED)
3364 // See https://stackoverflow.com/questions/9510514/integer-range-based-template-specialisation .
3365
3366 template <bool> struct TRange;
3367
3368 // This makes MemequalKImpl<byte_ct> expand to
3369 // MemequalKImpl<byte_ct, TRange<true> >.
3370 // If a later single-parameter template defines the same thing, that takes
3371 // precedence.
3372 template <uint32_t N, typename = TRange<true> > struct MemequalKImpl {
3373 static int32_t MemequalK(const void* m1, const void* m2) {
3374 return memequal(m1, m2, N);
3375 }
3376 };
3377
3378 template <> struct MemequalKImpl<1> {
3379 static int32_t MemequalK(const void* m1, const void* m2) {
3380 const unsigned char* m1_uc = S_CAST(const unsigned char*, m1);
3381 const unsigned char* m2_uc = S_CAST(const unsigned char*, m2);
3382 return (m1_uc[0] == m2_uc[0]);
3383 }
3384 };
3385
3386 template <> struct MemequalKImpl<2> {
3387 static int32_t MemequalK(const void* m1, const void* m2) {
3388 return ((*R_CAST(const uint16_t*, m1)) == (*R_CAST(const uint16_t*, m2)));
3389 }
3390 };
3391
3392 template <> struct MemequalKImpl<3> {
3393 static int32_t MemequalK(const void* m1, const void* m2) {
3394 const unsigned char* m1_uc = S_CAST(const unsigned char*, m1);
3395 const unsigned char* m2_uc = S_CAST(const unsigned char*, m2);
3396 return
3397 ((*R_CAST(const uint16_t*, m1)) == (*R_CAST(const uint16_t*, m2))) &&
3398 (m1_uc[2] == m2_uc[2]);
3399 }
3400 };
3401
3402 template <> struct MemequalKImpl<4> {
3403 static int32_t MemequalK(const void* m1, const void* m2) {
3404 return ((*R_CAST(const uint32_t*, m1)) == (*R_CAST(const uint32_t*, m2)));
3405 }
3406 };
3407
3408 template <uint32_t N> struct MemequalKImpl<N, TRange<(5 <= N) && (N <= 7)> > {
3409 static int32_t MemequalK(const void* m1, const void* m2) {
3410 const unsigned char* m1_uc = S_CAST(const unsigned char*, m1);
3411 const unsigned char* m2_uc = S_CAST(const unsigned char*, m2);
3412 return
3413 ((*R_CAST(const uint32_t*, m1)) == (*R_CAST(const uint32_t*, m2))) &&
3414 ((*R_CAST(const uint32_t*, &(m1_uc[N - 4]))) == (*R_CAST(const uint32_t*, &(m2_uc[N - 4]))));
3415 }
3416 };
3417
3418 template <> struct MemequalKImpl<8> {
3419 static int32_t MemequalK(const void* m1, const void* m2) {
3420 return ((*R_CAST(const uint64_t*, m1)) == (*R_CAST(const uint64_t*, m2)));
3421 }
3422 };
3423
3424 template <uint32_t N> struct MemequalKImpl<N, TRange<(9 <= N) && (N <= 15)> > {
3425 static int32_t MemequalK(const void* m1, const void* m2) {
3426 const unsigned char* m1_uc = S_CAST(const unsigned char*, m1);
3427 const unsigned char* m2_uc = S_CAST(const unsigned char*, m2);
3428 return
3429 ((*R_CAST(const uint64_t*, m1)) == (*R_CAST(const uint64_t*, m2))) &&
3430 ((*R_CAST(const uint64_t*, &(m1_uc[N - 8]))) == (*R_CAST(const uint64_t*, &(m2_uc[N - 8]))));
3431 }
3432 };
3433
3434 template <> struct MemequalKImpl<16> {
3435 static int32_t MemequalK(const void* m1, const void* m2) {
3436 const __m128i v1 = _mm_loadu_si128(S_CAST(const __m128i*, m1));
3437 const __m128i v2 = _mm_loadu_si128(S_CAST(const __m128i*, m2));
3438 return m128is_are_equal(v1, v2);
3439 }
3440 };
3441
3442 template <uint32_t N> struct MemequalKImpl<N, TRange<(17 <= N) && (N <= 24)> > {
3443 static int32_t MemequalK(const void* m1, const void* m2) {
3444 const unsigned char* m1_uc = S_CAST(const unsigned char*, m1);
3445 const unsigned char* m2_uc = S_CAST(const unsigned char*, m2);
3446 const __m128i v1 = _mm_loadu_si128(S_CAST(const __m128i*, m1));
3447 const __m128i v2 = _mm_loadu_si128(S_CAST(const __m128i*, m2));
3448 return
3449 m128is_are_equal(v1, v2) &&
3450 ((*R_CAST(const uint64_t*, &(m1_uc[N - 8]))) == (*R_CAST(const uint64_t*, &(m2_uc[N - 8]))));
3451 }
3452 };
3453
3454 template <uint32_t N> struct MemequalKImpl<N, TRange<(25 <= N) && (N <= 31)> > {
3455 static int32_t MemequalK(const void* m1, const void* m2) {
3456 __m128i v1 = _mm_loadu_si128(S_CAST(const __m128i*, m1));
3457 __m128i v2 = _mm_loadu_si128(S_CAST(const __m128i*, m2));
3458 if (!m128is_are_equal(v1, v2)) {
3459 return 0;
3460 }
3461 const unsigned char* m1_uc = S_CAST(const unsigned char*, m1);
3462 const unsigned char* m2_uc = S_CAST(const unsigned char*, m2);
3463 v1 = _mm_loadu_si128(R_CAST(const __m128i*, &(m1_uc[N - 16])));
3464 v2 = _mm_loadu_si128(R_CAST(const __m128i*, &(m2_uc[N - 16])));
3465 return m128is_are_equal(v1, v2);
3466 }
3467 };
3468
3469 # define memequal_k(m1, m2, byte_ct) plink2::MemequalKImpl<byte_ct>::MemequalK(m1, m2)
3470
3471 template <uint32_t N, typename = TRange<true> > struct MemcpyKImpl {
3472 static void MemcpyK(void* __restrict dst, const void* __restrict src) {
3473 memcpy(dst, src, N);
3474 }
3475 };
3476
3477 // Patch a bunch of cases where some commonly-used gcc and clang versions
3478 // generate suboptimal code. (Since this code is shamelessly x86-specific, we
3479 // don't worry about the formal undefinedness of unaligned pointer dereferences
3480 // here.)
3481 // (todo: check if/when this has been fixed, and remove this bloat once all
3482 // production build machines have sufficiently new compilers.)
3483 template <> struct MemcpyKImpl<2> {
3484 static void MemcpyK(void* __restrict dst, const void* __restrict src) {
3485 *S_CAST(uint16_t*, dst) = *S_CAST(const uint16_t*, src);
3486 }
3487 };
3488
3489 template <> struct MemcpyKImpl<3> {
3490 static void MemcpyK(void* __restrict dst, const void* __restrict src) {
3491 unsigned char* dst_uc = S_CAST(unsigned char*, dst);
3492 const unsigned char* src_uc = S_CAST(const unsigned char*, src);
3493 *S_CAST(uint16_t*, dst) = *S_CAST(const uint16_t*, src);
3494 dst_uc[2] = src_uc[2];
3495 }
3496 };
3497
3498 template <> struct MemcpyKImpl<5> {
3499 static void MemcpyK(void* __restrict dst, const void* __restrict src) {
3500 unsigned char* dst_uc = S_CAST(unsigned char*, dst);
3501 const unsigned char* src_uc = S_CAST(const unsigned char*, src);
3502 *S_CAST(uint32_t*, dst) = *S_CAST(const uint32_t*, src);
3503 dst_uc[4] = src_uc[4];
3504 }
3505 };
3506
3507 template <> struct MemcpyKImpl<6> {
3508 static void MemcpyK(void* __restrict dst, const void* __restrict src) {
3509 uint16_t* dst_u16 = S_CAST(uint16_t*, dst);
3510 const uint16_t* src_u16 = S_CAST(const uint16_t*, src);
3511 *S_CAST(uint32_t*, dst) = *S_CAST(const uint32_t*, src);
3512 dst_u16[2] = src_u16[2];
3513 }
3514 };
3515
3516 template <> struct MemcpyKImpl<7> {
3517 static void MemcpyK(void* __restrict dst, const void* __restrict src) {
3518 unsigned char* dst_uc = S_CAST(unsigned char*, dst);
3519 const unsigned char* src_uc = S_CAST(const unsigned char*, src);
3520 *S_CAST(uint32_t*, dst) = *S_CAST(const uint32_t*, src);
3521 *R_CAST(uint32_t*, &(dst_uc[3])) = *R_CAST(const uint32_t*, &(src_uc[3]));
3522 }
3523 };
3524
3525 template <> struct MemcpyKImpl<9> {
3526 static void MemcpyK(void* __restrict dst, const void* __restrict src) {
3527 unsigned char* dst_uc = S_CAST(unsigned char*, dst);
3528 const unsigned char* src_uc = S_CAST(const unsigned char*, src);
3529 *S_CAST(uint64_t*, dst) = *S_CAST(const uint64_t*, src);
3530 dst_uc[8] = src_uc[8];
3531 }
3532 };
3533
3534 template <> struct MemcpyKImpl<10> {
3535 static void MemcpyK(void* __restrict dst, const void* __restrict src) {
3536 uint16_t* dst_u16 = S_CAST(uint16_t*, dst);
3537 const uint16_t* src_u16 = S_CAST(const uint16_t*, src);
3538 *S_CAST(uint64_t*, dst) = *S_CAST(const uint64_t*, src);
3539 dst_u16[4] = src_u16[4];
3540 }
3541 };
3542
3543 template <uint32_t N> struct MemcpyKImpl<N, TRange<(11 <= N) && (N <= 12)> > {
3544 static void MemcpyK(void* __restrict dst, const void* __restrict src) {
3545 unsigned char* dst_uc = S_CAST(unsigned char*, dst);
3546 const unsigned char* src_uc = S_CAST(const unsigned char*, src);
3547 *S_CAST(uint64_t*, dst) = *S_CAST(const uint64_t*, src);
3548 *R_CAST(uint32_t*, &(dst_uc[N - 4])) = *R_CAST(const uint32_t*, &(src_uc[N - 4]));
3549 }
3550 };
3551
3552 template <uint32_t N> struct MemcpyKImpl<N, TRange<(13 <= N) && (N <= 15)> > {
3553 static void MemcpyK(void* __restrict dst, const void* __restrict src) {
3554 unsigned char* dst_uc = S_CAST(unsigned char*, dst);
3555 const unsigned char* src_uc = S_CAST(const unsigned char*, src);
3556 *S_CAST(uint64_t*, dst) = *S_CAST(const uint64_t*, src);
3557 *R_CAST(uint64_t*, &(dst_uc[N - 8])) = *R_CAST(const uint64_t*, &(src_uc[N - 8]));
3558 }
3559 };
3560
3561 template <> struct MemcpyKImpl<17> {
3562 static void MemcpyK(void* __restrict dst, const void* __restrict src) {
3563 unsigned char* dst_uc = S_CAST(unsigned char*, dst);
3564 const unsigned char* src_uc = S_CAST(const unsigned char*, src);
3565 const __m128i vv = _mm_loadu_si128(S_CAST(const __m128i*, src));
3566 _mm_storeu_si128(S_CAST(__m128i*, dst), vv);
3567 dst_uc[16] = src_uc[16];
3568 }
3569 };
3570
3571 template <> struct MemcpyKImpl<18> {
3572 static void MemcpyK(void* __restrict dst, const void* __restrict src) {
3573 uint16_t* dst_u16 = S_CAST(uint16_t*, dst);
3574 const uint16_t* src_u16 = S_CAST(const uint16_t*, src);
3575 const __m128i vv = _mm_loadu_si128(S_CAST(const __m128i*, src));
3576 _mm_storeu_si128(S_CAST(__m128i*, dst), vv);
3577 dst_u16[8] = src_u16[8];
3578 }
3579 };
3580
3581 template <uint32_t N> struct MemcpyKImpl<N, TRange<(19 <= N) && (N <= 20)> > {
3582 static void MemcpyK(void* __restrict dst, const void* __restrict src) {
3583 unsigned char* dst_uc = S_CAST(unsigned char*, dst);
3584 const unsigned char* src_uc = S_CAST(const unsigned char*, src);
3585 const __m128i vv = _mm_loadu_si128(S_CAST(const __m128i*, src));
3586 _mm_storeu_si128(S_CAST(__m128i*, dst), vv);
3587 *R_CAST(uint32_t*, &(dst_uc[N - 4])) = *R_CAST(const uint32_t*, &(src_uc[N - 4]));
3588 }
3589 };
3590
3591 template <uint32_t N> struct MemcpyKImpl<N, TRange<(21 <= N) && (N <= 24)> > {
3592 static void MemcpyK(void* __restrict dst, const void* __restrict src) {
3593 unsigned char* dst_uc = S_CAST(unsigned char*, dst);
3594 const unsigned char* src_uc = S_CAST(const unsigned char*, src);
3595 const __m128i vv = _mm_loadu_si128(S_CAST(const __m128i*, src));
3596 _mm_storeu_si128(S_CAST(__m128i*, dst), vv);
3597 *R_CAST(uint64_t*, &(dst_uc[N - 8])) = *R_CAST(const uint64_t*, &(src_uc[N - 8]));
3598 }
3599 };
3600
3601 template <uint32_t N> struct MemcpyKImpl<N, TRange<(25 <= N) && (N <= 31)> > {
3602 static void MemcpyK(void* __restrict dst, const void* __restrict src) {
3603 unsigned char* dst_uc = S_CAST(unsigned char*, dst);
3604 const unsigned char* src_uc = S_CAST(const unsigned char*, src);
3605 const __m128i v1 = _mm_loadu_si128(S_CAST(const __m128i*, src));
3606 const __m128i v2 = _mm_loadu_si128(R_CAST(const __m128i*, &(src_uc[N - 16])));
3607 _mm_storeu_si128(S_CAST(__m128i*, dst), v1);
3608 _mm_storeu_si128(R_CAST(__m128i*, &(dst_uc[N - 16])), v2);
3609 }
3610 };
3611
3612 // Note that there's no difference between memcpy() and memcpy_k() for common
3613 // 'well-behaved' sizes like 1, 4, 8, and 16. It's the funny numbers in
3614 // between, which often arise with constant strings, which this template is
3615 // targeting.
3616 # define memcpy_k(dst, src, ct) plink2::MemcpyKImpl<ct>::MemcpyK(dst, src)
3617
3618 template <uint32_t N> char* MemcpyaK(void* __restrict dst, const void* __restrict src) {
3619 MemcpyKImpl<N>::MemcpyK(dst, src);
3620 char* dst_c = S_CAST(char*, dst);
3621 return &(dst_c[N]);
3622 }
3623
3624 # define memcpya_k(dst, src, ct) plink2::MemcpyaK<ct>(dst, src)
3625 # define memcpyua_k(dst, src, ct) CToUc(plink2::MemcpyaK<ct>(dst, src))
3626
3627 template <uint32_t N> struct MemcpyoKImpl {
3628 static void MemcpyoK(void* __restrict dst, const void* __restrict src) {
3629 MemcpyKImpl<N>::MemcpyK(dst, src);
3630 }
3631 };
3632
3633 template <> struct MemcpyoKImpl<3> {
3634 static void MemcpyoK(void* __restrict dst, const void* __restrict src) {
3635 *S_CAST(uint32_t*, dst) = *S_CAST(const uint32_t*, src);
3636 }
3637 };
3638
3639 template <> struct MemcpyoKImpl<7> {
3640 static void MemcpyoK(void* __restrict dst, const void* __restrict src) {
3641 *S_CAST(uint64_t*, dst) = *S_CAST(const uint64_t*, src);
3642 }
3643 };
3644
3645 template <> struct MemcpyoKImpl<15> {
3646 static void MemcpyoK(void* __restrict dst, const void* __restrict src) {
3647 const __m128i vv = _mm_loadu_si128(S_CAST(const __m128i*, src));
3648 _mm_storeu_si128(S_CAST(__m128i*, dst), vv);
3649 }
3650 };
3651
3652 // interestingly, __m256i copy does not seem to be better in 31 byte case
3653
3654 # define memcpyo_k(dst, src, ct) plink2::MemcpyoKImpl<ct>::MemcpyoK(dst, src)
3655
3656 template <uint32_t N> char* MemcpyaoK(void* __restrict dst, const void* __restrict src) {
3657 MemcpyoKImpl<N>::MemcpyoK(dst, src);
3658 char* dst_c = S_CAST(char*, dst);
3659 return &(dst_c[N]);
3660 }
3661
3662 # define memcpyao_k(dst, src, ct) plink2::MemcpyaoK<ct>(dst, src)
3663 # define memcpyuao_k(dst, src, ct) DowncastToUc(plink2::MemcpyaoK<ct>(dst, src))
3664
3665 # else // !(defined(__LP64__) && defined(__cplusplus) && !defined(NO_UNALIGNED))
3666
3667 HEADER_INLINE int32_t memequal_k(const void* m1, const void* m2, uintptr_t ct) {
3668 return !memcmp(m1, m2, ct);
3669 }
3670
3671 HEADER_INLINE void memcpy_k(void* __restrict dst, const void* __restrict src, uintptr_t ct) {
3672 memcpy(dst, src, ct);
3673 }
3674
3675 HEADER_INLINE char* memcpya_k(void* __restrict dst, const void* __restrict src, uintptr_t ct) {
3676 return memcpya(dst, src, ct);
3677 }
3678
3679 HEADER_INLINE unsigned char* memcpyua_k(void* __restrict dst, const void* __restrict src, uintptr_t ct) {
3680 return memcpyua(dst, src, ct);
3681 }
3682
3683 HEADER_INLINE void memcpyo_k(void* __restrict dst, const void* __restrict src, uintptr_t ct) {
3684 memcpy(dst, src, ct);
3685 }
3686
3687 HEADER_INLINE char* memcpyao_k(void* __restrict dst, const void* __restrict src, uintptr_t ct) {
3688 return memcpya(dst, src, ct);
3689 }
3690
3691 HEADER_INLINE unsigned char* memcpyuao_k(void* __restrict dst, const void* __restrict src, uintptr_t ct) {
3692 return memcpyua(dst, src, ct);
3693 }
3694
3695 #endif
3696
3697 HEADER_INLINE char* strcpya(char* __restrict dst, const void* __restrict src) {
3698 const uintptr_t slen = strlen(S_CAST(const char*, src));
3699 return memcpya(dst, src, slen);
3700 }
3701
3702 #if defined(__LP64__) && (__cplusplus >= 201103L)
3703 constexpr uint32_t CompileTimeSlen(const char* k_str) {
3704 return k_str[0]? (1 + CompileTimeSlen(&(k_str[1]))) : 0;
3705 }
3706 #endif
3707
3708 #if defined(USE_SSE2) && (__cplusplus >= 201103L) && !defined(NO_UNALIGNED)
3709
3710 # define strcpy_k(dst, src) plink2::MemcpyKImpl<plink2::CompileTimeSlen(src) + 1>::MemcpyK(dst, src);
3711
3712 # define strcpya_k(dst, src) plink2::MemcpyaoK<plink2::CompileTimeSlen(src)>(dst, src);
3713
3714 #else
3715
3716 HEADER_INLINE void strcpy_k(char* __restrict dst, const void* __restrict src) {
3717 strcpy(dst, S_CAST(const char*, src));
3718 }
3719
3720 HEADER_INLINE char* strcpya_k(char* __restrict dst, const void* __restrict src) {
3721 return strcpya(dst, src);
3722 }
3723
3724 #endif
3725
3726 // A few more string-rendering functions that would normally live in
3727 // plink2_string, to work around PRI{d,u}PTR and PRI{d,u}64 warning on CRAN
3728 // Windows builds.
3729
3730 extern const uint16_t kDigitPair[];
3731
3732 char* u32toa(uint32_t uii, char* start);
3733
3734 HEADER_INLINE char* uitoa_z4(uint32_t uii, char* start) {
3735 uint32_t quotient = uii / 100;
3736 assert(quotient < 100);
3737 uii -= 100 * quotient;
3738 start = memcpya_k(start, &(kDigitPair[quotient]), 2);
3739 return memcpya_k(start, &(kDigitPair[uii]), 2);
3740 }
3741
3742 HEADER_INLINE char* u32toa_z6(uint32_t uii, char* start) {
3743 uint32_t quotient = uii / 10000;
3744 start = memcpya_k(start, &(kDigitPair[quotient]), 2);
3745 return uitoa_z4(uii - 10000 * quotient, start);
3746 }
3747
3748 HEADER_INLINE char* uitoa_z8(uint32_t uii, char* start) {
3749 uint32_t quotient = uii / 1000000;
3750 start = memcpya_k(start, &(kDigitPair[quotient]), 2);
3751 return u32toa_z6(uii - 1000000 * quotient, start);
3752 }
3753
3754 char* i64toa(int64_t llii, char* start);
3755
3756 #ifdef __LP64__
3757 // really just for printing line numbers
3758 // must be less than 2^63
3759 HEADER_INLINE char* wtoa(uintptr_t ulii, char* start) {
3760 return i64toa(ulii, start);
3761 }
3762 #else
3763 HEADER_INLINE char* wtoa(uintptr_t ulii, char* start) {
3764 return u32toa(ulii, start);
3765 }
3766 #endif
3767
3768 HEADER_INLINE void CopyFromUnalignedW(uintptr_t* dst, const unsigned char* src) {
3769 memcpy_k(dst, src, kBytesPerWord);
3770 }
3771
3772 HEADER_INLINE void CopyFromUnalignedU32(uint32_t* dst, const unsigned char* src) {
3773 memcpy_k(dst, src, sizeof(int32_t));
3774 }
3775
3776 HEADER_INLINE void CopyFromUnalignedU16(uint16_t* dst, const unsigned char* src) {
3777 memcpy_k(dst, src, sizeof(int16_t));
3778 }
3779
3780 HEADER_INLINE void CopyFromUnalignedI16(int16_t* dst, const unsigned char* src) {
3781 memcpy_k(dst, src, sizeof(int16_t));
3782 }
3783
3784 HEADER_INLINE void CopyFromUnalignedF(float* dst, const unsigned char* src) {
3785 memcpy_k(dst, src, sizeof(float));
3786 }
3787
3788 // [u]int16_t (and unsigned char) arithmetic is slower than uint32_t/uint64_t
3789 // arithmetic on some CPUs.
3790 // todo: check whether uint32_t vs. uintptr_t return value matters
3791 HEADER_INLINE uint32_t CopyFromUnalignedU16ZX(const unsigned char* src) {
3792 #ifndef NO_UNALIGNED
3793 return *R_CAST(const uint16_t*, src);
3794 #else
3795 uint16_t cur_u16;
3796 memcpy_k(&cur_u16, src, sizeof(int16_t));
3797 return cur_u16;
3798 #endif
3799 }
3800
3801 HEADER_INLINE int32_t CopyFromUnalignedI16ZX(const unsigned char* src) {
3802 #ifndef NO_UNALIGNED
3803 return *R_CAST(const int16_t*, src);
3804 #else
3805 int16_t cur_i16;
3806 memcpy_k(&cur_i16, src, sizeof(int16_t));
3807 return cur_i16;
3808 #endif
3809 }
3810
3811 HEADER_INLINE void CopyToUnalignedW(unsigned char* dst, const uintptr_t* src) {
3812 memcpy_k(dst, src, kBytesPerWord);
3813 }
3814
3815 HEADER_INLINE void CopyToUnalignedU64(unsigned char* dst, const uint64_t* src) {
3816 memcpy_k(dst, src, sizeof(int64_t));
3817 }
3818
3819 HEADER_INLINE void CopyToUnalignedU32(unsigned char* dst, const uint32_t* src) {
3820 memcpy_k(dst, src, sizeof(int32_t));
3821 }
3822
3823 HEADER_INLINE void CopyToUnalignedF(unsigned char* dst, const float* src) {
3824 memcpy_k(dst, src, sizeof(float));
3825 }
3826
3827 HEADER_INLINE void CopyFromUnalignedOffsetW(uintptr_t* dst, const unsigned char* src, uintptr_t offset) {
3828 memcpy_k(dst, &(src[offset * kBytesPerWord]), kBytesPerWord);
3829 }
3830
3831 HEADER_INLINE void CopyFromUnalignedOffsetHW(Halfword* dst, const unsigned char* src, uintptr_t offset) {
3832 memcpy_k(dst, &(src[offset * sizeof(Halfword)]), sizeof(Halfword));
3833 }
3834
3835 HEADER_INLINE void CopyFromUnalignedOffsetQW(Quarterword* dst, const unsigned char* src, uintptr_t offset) {
3836 memcpy_k(dst, &(src[offset * sizeof(Quarterword)]), sizeof(Quarterword));
3837 }
3838
3839 HEADER_INLINE void CopyFromUnalignedOffsetU64(uint64_t* dst, const unsigned char* src, uintptr_t offset) {
3840 memcpy_k(dst, &(src[offset * sizeof(int64_t)]), sizeof(int64_t));
3841 }
3842
3843 HEADER_INLINE void CopyFromUnalignedOffsetU32(uint32_t* dst, const unsigned char* src, uintptr_t offset) {
3844 memcpy_k(dst, &(src[offset * sizeof(int32_t)]), sizeof(int32_t));
3845 }
3846
3847 HEADER_INLINE void CopyFromUnalignedOffsetI32(int32_t* dst, const unsigned char* src, uintptr_t offset) {
3848 memcpy_k(dst, &(src[offset * sizeof(int32_t)]), sizeof(int32_t));
3849 }
3850
3851 HEADER_INLINE void CopyFromUnalignedOffsetU16(uint16_t* dst, const unsigned char* src, uintptr_t offset) {
3852 memcpy_k(dst, &(src[offset * sizeof(int16_t)]), sizeof(int16_t));
3853 }
3854
3855 HEADER_INLINE void CopyFromUnalignedOffsetI16(int16_t* dst, const unsigned char* src, uintptr_t offset) {
3856 memcpy_k(dst, &(src[offset * sizeof(int16_t)]), sizeof(int16_t));
3857 }
3858
3859 HEADER_INLINE void CopyFromUnalignedOffsetF(float* dst, const unsigned char* src, uintptr_t offset) {
3860 memcpy_k(dst, &(src[offset * sizeof(float)]), sizeof(float));
3861 }
3862
3863 HEADER_INLINE uint32_t CopyFromUnalignedOffsetU16ZX(const unsigned char* src, uintptr_t offset) {
3864 #ifndef NO_UNALIGNED
3865 return R_CAST(const uint16_t*, src)[offset];
3866 #else
3867 uint16_t cur_u16;
3868 memcpy_k(&cur_u16, &(src[offset * sizeof(int16_t)]), sizeof(int16_t));
3869 return cur_u16;
3870 #endif
3871 }
3872
3873 HEADER_INLINE int32_t CopyFromUnalignedOffsetI16ZX(const unsigned char* src, uintptr_t offset) {
3874 #ifndef NO_UNALIGNED
3875 return R_CAST(const int16_t*, src)[offset];
3876 #else
3877 int16_t cur_i16;
3878 memcpy_k(&cur_i16, &(src[offset * sizeof(int16_t)]), sizeof(int16_t));
3879 return cur_i16;
3880 #endif
3881 }
3882
3883 HEADER_INLINE void CopyToUnalignedOffsetW(unsigned char* dst, const uintptr_t* src, uintptr_t offset) {
3884 memcpy_k(&(dst[offset * sizeof(intptr_t)]), src, sizeof(intptr_t));
3885 }
3886
3887 HEADER_INLINE void CopyToUnalignedOffsetHW(unsigned char* dst, const Halfword* src, uintptr_t offset) {
3888 memcpy_k(&(dst[offset * sizeof(Halfword)]), src, sizeof(Halfword));
3889 }
3890
3891 HEADER_INLINE void CopyToUnalignedOffsetU64(unsigned char* dst, const uint64_t* src, uintptr_t offset) {
3892 memcpy_k(&(dst[offset * sizeof(int64_t)]), src, sizeof(int64_t));
3893 }
3894
3895 HEADER_INLINE void CopyToUnalignedOffsetU32(unsigned char* dst, const uint32_t* src, uintptr_t offset) {
3896 memcpy_k(&(dst[offset * sizeof(int32_t)]), src, sizeof(int32_t));
3897 }
3898
3899 HEADER_INLINE void CopyToUnalignedOffsetU16(unsigned char* dst, const uint16_t* src, uintptr_t offset) {
3900 memcpy_k(&(dst[offset * sizeof(int16_t)]), src, sizeof(int16_t));
3901 }
3902
3903 HEADER_INLINE void CopyToUnalignedOffsetI16(unsigned char* dst, const int16_t* src, uintptr_t offset) {
3904 memcpy_k(&(dst[offset * sizeof(int16_t)]), src, sizeof(int16_t));
3905 }
3906
3907 HEADER_INLINE void CopyToUnalignedOffsetF(unsigned char* dst, const float* src, uintptr_t offset) {
3908 memcpy_k(&(dst[offset * sizeof(float)]), src, sizeof(float));
3909 }
3910
3911 #ifdef USE_SSE2
3912 HEADER_INLINE void CopyToUnalignedOffsetV8(unsigned char* dst, const Vec8thUint* src, uintptr_t offset) {
3913 memcpy_k(&(dst[offset * sizeof(Vec8thUint)]), src, sizeof(Vec8thUint));
3914 }
3915
3916 HEADER_INLINE void CopyToUnalignedOffsetV16(unsigned char* dst, const Vec16thUint* src, uintptr_t offset) {
3917 memcpy_k(&(dst[offset * sizeof(Vec16thUint)]), src, sizeof(Vec16thUint));
3918 }
3919 #endif
3920
3921 HEADER_INLINE void CopyFromUnalignedIncrW(uintptr_t* dst, const unsigned char** srcp) {
3922 memcpy_k(dst, *srcp, kBytesPerWord);
3923 *srcp += kBytesPerWord;
3924 }
3925
3926 HEADER_INLINE void CopyFromUnalignedIncrU32(uint32_t* dst, const unsigned char** srcp) {
3927 memcpy_k(dst, *srcp, sizeof(int32_t));
3928 *srcp += sizeof(int32_t);
3929 }
3930
3931 HEADER_INLINE void CopyFromUnalignedIncrU16(uint16_t* dst, const unsigned char** srcp) {
3932 memcpy_k(dst, *srcp, sizeof(int16_t));
3933 *srcp += sizeof(int16_t);
3934 }
3935
3936 HEADER_INLINE void CopyFromUnalignedIncrI16(int16_t* dst, const unsigned char** srcp) {
3937 memcpy_k(dst, *srcp, sizeof(int16_t));
3938 *srcp += sizeof(int16_t);
3939 }
3940
3941 HEADER_INLINE uint32_t CopyFromUnalignedIncrU16ZX(const unsigned char** srcp) {
3942 #ifndef NO_UNALIGNED
3943 const uint32_t result = *R_CAST(const uint16_t*, *srcp);
3944 #else
3945 uint16_t result;
3946 memcpy_k(&result, *srcp, sizeof(int16_t));
3947 #endif
3948 *srcp += sizeof(int16_t);
3949 return result;
3950 }
3951
3952 HEADER_INLINE int32_t CopyFromUnalignedIncrI16ZX(const unsigned char** srcp) {
3953 #ifndef NO_UNALIGNED
3954 const int32_t result = *R_CAST(const int16_t*, *srcp);
3955 #else
3956 int16_t result;
3957 memcpy_k(&result, *srcp, sizeof(int16_t));
3958 #endif
3959 *srcp += sizeof(int16_t);
3960 return result;
3961 }
3962
3963 // no need to spell out 'CopyToUnalignedIncr' here; and we append constants
3964 // often enough to justify no src pointer
3965
3966 HEADER_INLINE void AppendW(uintptr_t ulii, unsigned char** targetp) {
3967 memcpy_k(*targetp, &ulii, kBytesPerWord);
3968 *targetp += kBytesPerWord;
3969 }
3970
3971 HEADER_INLINE void AppendU64(uint64_t ullii, unsigned char** targetp) {
3972 memcpy_k(*targetp, &ullii, sizeof(int64_t));
3973 *targetp += sizeof(int64_t);
3974 }
3975
3976 HEADER_INLINE void AppendU32(uint32_t uii, unsigned char** targetp) {
3977 memcpy_k(*targetp, &uii, sizeof(int32_t));
3978 *targetp += sizeof(int32_t);
3979 }
3980
3981 HEADER_INLINE void AppendU16(uint16_t usii, unsigned char** targetp) {
3982 memcpy_k(*targetp, &usii, sizeof(int16_t));
3983 *targetp += sizeof(int16_t);
3984 }
3985
3986 HEADER_INLINE void CAppendW(uintptr_t ulii, char** targetp) {
3987 memcpy_k(*targetp, &ulii, kBytesPerWord);
3988 *targetp += kBytesPerWord;
3989 }
3990
3991 HEADER_INLINE void CAppendU32(uint32_t uii, char** targetp) {
3992 memcpy_k(*targetp, &uii, sizeof(int32_t));
3993 *targetp += sizeof(int32_t);
3994 }
3995
3996 HEADER_INLINE void CAppendU16(uint16_t usii, char** targetp) {
3997 memcpy_k(*targetp, &usii, sizeof(int16_t));
3998 *targetp += sizeof(int16_t);
3999 }
4000
4001
4002 // now compiling with gcc >= 4.4 (or clang equivalent) on all platforms, so
4003 // safe to use memset everywhere
4004 HEADER_INLINE void ZeroU32Arr(uintptr_t entry_ct, uint32_t* u32arr) {
4005 memset(u32arr, 0, entry_ct * sizeof(int32_t));
4006 }
4007
4008 HEADER_INLINE void ZeroWArr(uintptr_t entry_ct, uintptr_t* warr) {
4009 memset(warr, 0, entry_ct * sizeof(intptr_t));
4010 }
4011
4012 HEADER_INLINE void ZeroU64Arr(uintptr_t entry_ct, uint64_t* u64arr) {
4013 memset(u64arr, 0, entry_ct * sizeof(int64_t));
4014 }
4015
4016 HEADER_INLINE void ZeroPtrArr(uintptr_t entry_ct, void* pp) {
4017 memset(pp, 0, entry_ct * sizeof(intptr_t));
4018 }
4019
4020 HEADER_INLINE void ZeroHwArr(uintptr_t entry_ct, Halfword* hwarr) {
4021 memset(hwarr, 0, entry_ct * sizeof(Halfword));
4022 }
4023
4024 HEADER_INLINE void ZeroFArr(uintptr_t entry_ct, float* farr) {
4025 for (uintptr_t ulii = 0; ulii != entry_ct; ulii++) {
4026 *farr++ = 0.0;
4027 }
4028 }
4029
4030 HEADER_INLINE void ZeroDArr(uintptr_t entry_ct, double* darr) {
4031 for (uintptr_t ulii = 0; ulii != entry_ct; ulii++) {
4032 *darr++ = 0.0;
4033 }
4034 }
4035
4036 HEADER_INLINE void SetAllWArr(uintptr_t entry_ct, uintptr_t* warr) {
4037 // todo: test this against vecset()
4038 for (uintptr_t idx = 0; idx != entry_ct; ++idx) {
4039 warr[idx] = ~k0LU;
4040 }
4041 }
4042
4043 HEADER_INLINE void SetAllU32Arr(uintptr_t entry_ct, uint32_t* u32arr) {
4044 for (uintptr_t ulii = 0; ulii != entry_ct; ulii++) {
4045 *u32arr++ = ~0U;
4046 }
4047 }
4048
4049
4050 // tried _bzhi_u64() in AVX2 case, it was actually worse on my Mac (more
4051 // opaque to compiler?)
4052 // todo: check gcc behavior since it may be different: see
4053 // https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82298 .
4054 //
4055 // This is undefined if idx == kBitsPerWord.
4056 HEADER_INLINE uintptr_t bzhi(uintptr_t ww, uint32_t idx) {
4057 return ww & ((k1LU << idx) - k1LU);
4058 }
4059
4060 // This is undefined if idx == 0.
4061 HEADER_INLINE uintptr_t bzhi_max(uintptr_t ww, uint32_t idx) {
4062 return ww & ((~k0LU) >> (kBitsPerWord - idx));
4063 }
4064
4065 // Don't bother defining blsr(), compiler should automatically use the
4066 // instruction under -mbmi and regular code is more readable? (again, should
4067 // verify this is true for gcc)
4068
4069 HEADER_INLINE uint32_t BytesToRepresentNzU32(uint32_t uii) {
4070 return 1 + (bsru32(uii) / CHAR_BIT);
4071 }
4072
4073 // analogous to memset()
4074 // this can be slightly slower if e.g. system supports AVX2 but non-AVX2 plink2
4075 // build is in use; fine to pay that price given the small-array advantage for
4076 // now. Should revisit this after next build-machine Ubuntu upgrade, though.
4077 HEADER_INLINE void vecset(void* target_vec, uintptr_t ww, uintptr_t vec_ct) {
4078 VecW* target_vec_iter = S_CAST(VecW*, target_vec);
4079 #ifdef USE_SSE2
4080 const VecW payload = VCONST_W(ww);
4081 for (uintptr_t vec_idx = 0; vec_idx != vec_ct; ++vec_idx) {
4082 *target_vec_iter++ = payload;
4083 }
4084 #else
4085 for (uintptr_t vec_idx = 0; vec_idx != vec_ct; ++vec_idx) {
4086 *target_vec_iter++ = ww;
4087 }
4088 #endif
4089 }
4090
4091 // todo: make sure these are efficient for small ct
4092 HEADER_INLINE void u16set(void* dst, uint16_t usii, uintptr_t ct) {
4093 uint16_t* dst_u16 = S_CAST(uint16_t*, dst);
4094 for (uintptr_t ulii = 0; ulii != ct; ++ulii) {
4095 dst_u16[ulii] = usii;
4096 }
4097 }
4098
4099 HEADER_INLINE char* u16setsa(char* dst, uint16_t usii, uintptr_t ct) {
4100 u16set(dst, usii, ct);
4101 return &(dst[ct * 2]);
4102 }
4103
4104 HEADER_INLINE uintptr_t ClearBottomSetBits(uint32_t ct, uintptr_t ulii) {
4105 #ifdef USE_AVX2
4106 return _pdep_u64((~k0LU) << ct, ulii);
4107 #else
4108 for (uint32_t uii = 0; uii != ct; ++uii) {
4109 ulii &= ulii - 1;
4110 }
4111 return ulii;
4112 #endif
4113 }
4114
4115 HEADER_INLINE uint32_t WordBitIdxToUidx(uintptr_t ulii, uint32_t bit_idx) {
4116 return ctzw(ClearBottomSetBits(bit_idx, ulii));
4117 }
4118
4119 CONSTI32(kNybblesPerWord, 2 * kBytesPerWord);
4120 CONSTI32(kNybblesPerCacheline, 2 * kCacheline);
4121
4122 HEADER_CINLINE uintptr_t NybbleCtToByteCt(uintptr_t val) {
4123 return DivUp(val, 2);
4124 }
4125
4126 HEADER_CINLINE uintptr_t NybbleCtToWordCt(uintptr_t val) {
4127 return DivUp(val, kNybblesPerWord);
4128 }
4129
4130 HEADER_INLINE uintptr_t GetNybbleArrEntry(const uintptr_t* nybblearr, uint32_t idx) {
4131 return (nybblearr[idx / kBitsPerWordD4] >> (4 * (idx % kBitsPerWordD4))) & 15;
4132 }
4133
4134 // Returns zero when ww has no zero bytes, and a word where the lowest set bit
4135 // is at position 8x + 7 when the first zero byte is [8x .. 8x+7].
4136 HEADER_INLINE uintptr_t DetectFirstZeroByte(uintptr_t ww) {
4137 return (ww - kMask0101) & (~ww) & (kMask0101 * 0x80);
4138 }
4139
4140 // From TAOCP 4a, 7.1.3, (91).
4141 // Position 8x + 7 is always set iff byte x is zero. All other bits are always
4142 // zero.
4143 HEADER_INLINE uintptr_t DetectAllZeroBytes(uintptr_t ww) {
4144 return (kMask0101 * 0x80) & (~(ww | ((ww | (kMask0101 * 0x80)) - kMask0101)));
4145 }
4146
4147 HEADER_INLINE uintptr_t DetectAllZeroNybbles(uintptr_t ww) {
4148 return (kMask1111 * 8) & (~(ww | ((ww | (kMask1111 * 8)) - kMask1111)));
4149 }
4150
4151 #if defined(USE_SSE2) && !defined(NO_UNALIGNED)
4152 // This requires nbytes >= 4.
4153 uintptr_t FirstUnequal4(const void* arr1, const void* arr2, uintptr_t nbytes);
4154
4155 HEADER_INLINE uintptr_t FirstUnequal(const void* arr1, const void* arr2, uintptr_t nbytes) {
4156 // Returns position of first byte mismatch, or nbytes if none was found.
4157 if (nbytes >= 4) {
4158 return FirstUnequal4(arr1, arr2, nbytes);
4159 }
4160 const char* s1 = S_CAST(const char*, arr1);
4161 const char* s2 = S_CAST(const char*, arr2);
4162 for (uintptr_t pos = 0; pos != nbytes; ++pos) {
4163 if (s1[pos] != s2[pos]) {
4164 return pos;
4165 }
4166 }
4167 return nbytes;
4168 }
4169 #else // !(defined(USE_SSE2) && !defined(NO_UNALIGNED))
4170 // This requires nbytes >= kBytesPerWord.
4171 uintptr_t FirstUnequalW(const void* arr1, const void* arr2, uintptr_t nbytes);
4172
4173 HEADER_INLINE uintptr_t FirstUnequal(const void* arr1, const void* arr2, uintptr_t nbytes) {
4174 // Returns position of first byte mismatch, or nbytes if none was found.
4175 if (nbytes >= kBytesPerWord) {
4176 return FirstUnequalW(arr1, arr2, nbytes);
4177 }
4178 const char* s1 = S_CAST(const char*, arr1);
4179 const char* s2 = S_CAST(const char*, arr2);
4180 for (uintptr_t pos = 0; pos != nbytes; ++pos) {
4181 if (s1[pos] != s2[pos]) {
4182 return pos;
4183 }
4184 }
4185 return nbytes;
4186 }
4187 #endif
4188
4189
4190 HEADER_INLINE uintptr_t FirstUnequalFrom(const void* arr1, const void* arr2, uintptr_t start, uintptr_t nbytes) {
4191 const char* s1 = S_CAST(const char*, arr1);
4192 const char* s2 = S_CAST(const char*, arr2);
4193 return start + FirstUnequal(&(s1[start]), &(s2[start]), nbytes - start);
4194 }
4195
4196
4197 HEADER_INLINE void* arena_alloc_raw(uintptr_t size, unsigned char** arena_bottom_ptr) {
4198 assert(!(size % kCacheline));
4199 unsigned char* alloc_ptr = *arena_bottom_ptr;
4200 *arena_bottom_ptr = &(alloc_ptr[size]);
4201 return alloc_ptr;
4202 }
4203
4204 HEADER_INLINE void* arena_alloc_raw_rd(uintptr_t size, unsigned char** arena_bottom_ptr) {
4205 unsigned char* alloc_ptr = *arena_bottom_ptr;
4206 *arena_bottom_ptr = &(alloc_ptr[RoundUpPow2(size, kCacheline)]);
4207 return alloc_ptr;
4208 }
4209
4210 // A VINT is a sequence of bytes where each byte stores just 7 bits of an
4211 // an integer, and the high bit is set when the integer has more nonzero bits.
4212 // See e.g.
4213 // https://developers.google.com/protocol-buffers/docs/encoding#varints
4214 // (Note that protocol buffers used "group varints" at one point, but then
4215 // abandoned them. I suspect they'd be simultaneously slower and less
4216 // compact here.)
4217
4218 HEADER_INLINE unsigned char* Vint32Append(uint32_t uii, unsigned char* buf) {
4219 while (uii > 127) {
4220 *buf++ = (uii & 127) + 128;
4221 uii >>= 7;
4222 }
4223 *buf++ = uii;
4224 return buf;
4225 }
4226
4227 // Returns 0x80000000U on read-past-end instead of UINT32_MAX so overflow check
4228 // works properly in 32-bit build. Named "GetVint31" to make it more obvious
4229 // that a 2^31 return value can't be legitimate.
4230 HEADER_INLINE uint32_t GetVint31(const unsigned char* buf_end, const unsigned char** buf_iterp) {
4231 if (likely(buf_end > (*buf_iterp))) {
4232 uint32_t vint32 = *((*buf_iterp)++);
4233 if (vint32 <= 127) {
4234 return vint32;
4235 }
4236 vint32 &= 127;
4237 uint32_t shift = 7;
4238 while (likely(buf_end > (*buf_iterp))) {
4239 uint32_t uii = *((*buf_iterp)++);
4240 vint32 |= (uii & 127) << shift;
4241 if (uii <= 127) {
4242 return vint32;
4243 }
4244 shift += 7;
4245 // currently don't check for shift >= 32 (that's what ValidateVint31()
4246 // is for).
4247 }
4248 }
4249 return 0x80000000U;
4250 }
4251
4252 #ifdef __LP64__
4253 uintptr_t CountVintsNonempty(const unsigned char* buf, const unsigned char* buf_end);
4254
4255 HEADER_INLINE uintptr_t CountVints(const unsigned char* buf, const unsigned char* buf_end) {
4256 if (buf == buf_end) {
4257 return 0;
4258 }
4259 return CountVintsNonempty(buf, buf_end);
4260 }
4261 #else
4262 uintptr_t CountVints(const unsigned char* buf, const unsigned char* buf_end);
4263
4264 HEADER_INLINE uintptr_t CountVintsNonempty(const unsigned char* buf, const unsigned char* buf_end) {
4265 return CountVints(buf, buf_end);
4266 }
4267 #endif
4268
4269 // Number of bytes required to encode ulii as a varint.
4270 HEADER_INLINE uint32_t VintBytect(uintptr_t ulii) {
4271 if (ulii < 128) {
4272 // bsrw(0) is undefined.
4273 return 1;
4274 }
4275 return 1 + (bsrw(ulii) / 7);
4276 }
4277
4278 // Flagset conventions:
4279 // * Each 32-bit and 64-bit flagset has its own type, which is guaranteed to be
4280 // the appropriate width. (Todo: verify that bit 31 works properly in 32-bit
4281 // case.)
4282 // * Constant flag names start with "kf[CamelCase description]", followed by a
4283 // description that shouldn't suck too badly. The zero flagset is always
4284 // named kf[CamelCase description]0.
4285 // * The type name is always of the form [snake_case description]_flags_t.
4286 // * To gain the desired level of type-checking under C++11 without pointless
4287 // verbosity, &, |, ^, ~, &=, |=, and ^= operations are defined; [my_flags_t
4288 // variable] |= [another my_flags_t variable] & [a my_flags_t constant] works
4289 // without an explicit cast. (Defining "struct my_flags_t" separately from
4290 // the enum global-scope-constants container is necessary to make |= work
4291 // without a cast. inline is needed due to duplicate operator definitions
4292 // across multiple files.)
4293 // * To slightly reduce the chance of breakage under C99/C++03, the enum is
4294 // nameless; the flagset type is just a uint32_t/uint64_t alias. This is
4295 // because the C99 and C++03 specs do not provide enough control over the
4296 // enum base type to make it safe for the enum to serve as the flagset type.
4297 // * Implicit conversion to int is not prevented for now, since I'm trying to
4298 // keep PglErr-style code duplication to a minimum.
4299 #if __cplusplus >= 201103L
4300
4301 // could avoid the typedef here, but that leads to a bit more verbosity.
4302 # define FLAGSET_DEF_START() typedef enum : uint32_t {
4303 # define FLAGSET_DEF_END(tname) } tname ## _PLINK2_BASE_DO_NOT_USE__ ; \
4304 \
4305 inline tname ## _PLINK2_BASE_DO_NOT_USE__ operator|(tname ## _PLINK2_BASE_DO_NOT_USE__ aa, tname ## _PLINK2_BASE_DO_NOT_USE__ bb) { \
4306 return static_cast<tname ## _PLINK2_BASE_DO_NOT_USE__>(static_cast<uint32_t>(aa) | static_cast<uint32_t>(bb)); \
4307 } \
4308 \
4309 inline tname ## _PLINK2_BASE_DO_NOT_USE__ operator&(tname ## _PLINK2_BASE_DO_NOT_USE__ aa, tname ## _PLINK2_BASE_DO_NOT_USE__ bb) { \
4310 return static_cast<tname ## _PLINK2_BASE_DO_NOT_USE__>(static_cast<uint32_t>(aa) & static_cast<uint32_t>(bb)); \
4311 } \
4312 \
4313 inline tname ## _PLINK2_BASE_DO_NOT_USE__ operator^(tname ## _PLINK2_BASE_DO_NOT_USE__ aa, tname ## _PLINK2_BASE_DO_NOT_USE__ bb) { \
4314 return static_cast<tname ## _PLINK2_BASE_DO_NOT_USE__>(static_cast<uint32_t>(aa) ^ static_cast<uint32_t>(bb)); \
4315 } \
4316 \
4317 inline tname ## _PLINK2_BASE_DO_NOT_USE__ operator~(tname ## _PLINK2_BASE_DO_NOT_USE__ aa) { \
4318 return static_cast<tname ## _PLINK2_BASE_DO_NOT_USE__>(~static_cast<uint32_t>(aa)); \
4319 } \
4320 \
4321 struct tname { \
4322 tname() {} \
4323 \
4324 tname(const tname& source) : value_(source.value_) {} \
4325 \
4326 tname(const tname ## _PLINK2_BASE_DO_NOT_USE__ source) : value_(static_cast<uint32_t>(source)) {} \
4327 \
4328 explicit tname(uint32_t source) : value_(source) {} \
4329 \
4330 operator tname ## _PLINK2_BASE_DO_NOT_USE__() const { \
4331 return static_cast<tname ## _PLINK2_BASE_DO_NOT_USE__>(value_); \
4332 } \
4333 \
4334 tname& operator|=(const tname ## _PLINK2_BASE_DO_NOT_USE__ rhs) { \
4335 value_ |= rhs; \
4336 return *this; \
4337 } \
4338 \
4339 tname& operator&=(const tname ## _PLINK2_BASE_DO_NOT_USE__ rhs) { \
4340 value_ &= rhs; \
4341 return *this; \
4342 } \
4343 \
4344 tname& operator^=(const tname ## _PLINK2_BASE_DO_NOT_USE__ rhs) { \
4345 value_ ^= rhs; \
4346 return *this; \
4347 } \
4348 \
4349 tname& operator=(const tname& rhs) = default; \
4350 \
4351 private: \
4352 uint32_t value_; \
4353 }
4354
4355 # define FLAGSET64_DEF_START() typedef enum : uint64_t {
4356 # define FLAGSET64_DEF_END(tname) } tname ## _PLINK2_BASE_DO_NOT_USE__ ; \
4357 \
4358 inline tname ## _PLINK2_BASE_DO_NOT_USE__ operator|(tname ## _PLINK2_BASE_DO_NOT_USE__ aa, tname ## _PLINK2_BASE_DO_NOT_USE__ bb) { \
4359 return static_cast<tname ## _PLINK2_BASE_DO_NOT_USE__>(static_cast<uint64_t>(aa) | static_cast<uint64_t>(bb)); \
4360 } \
4361 \
4362 inline tname ## _PLINK2_BASE_DO_NOT_USE__ operator&(tname ## _PLINK2_BASE_DO_NOT_USE__ aa, tname ## _PLINK2_BASE_DO_NOT_USE__ bb) { \
4363 return static_cast<tname ## _PLINK2_BASE_DO_NOT_USE__>(static_cast<uint64_t>(aa) & static_cast<uint64_t>(bb)); \
4364 } \
4365 \
4366 inline tname ## _PLINK2_BASE_DO_NOT_USE__ operator^(tname ## _PLINK2_BASE_DO_NOT_USE__ aa, tname ## _PLINK2_BASE_DO_NOT_USE__ bb) { \
4367 return static_cast<tname ## _PLINK2_BASE_DO_NOT_USE__>(static_cast<uint64_t>(aa) ^ static_cast<uint64_t>(bb)); \
4368 } \
4369 \
4370 inline tname ## _PLINK2_BASE_DO_NOT_USE__ operator~(tname ## _PLINK2_BASE_DO_NOT_USE__ aa) { \
4371 return static_cast<tname ## _PLINK2_BASE_DO_NOT_USE__>(~static_cast<uint64_t>(aa)); \
4372 } \
4373 \
4374 struct tname { \
4375 tname() {} \
4376 \
4377 tname(const tname& source) : value_(source.value_) {} \
4378 \
4379 tname(const tname ## _PLINK2_BASE_DO_NOT_USE__ source) : value_(static_cast<uint64_t>(source)) {} \
4380 \
4381 explicit tname(uint64_t source) : value_(source) {} \
4382 \
4383 operator tname ## _PLINK2_BASE_DO_NOT_USE__() const { \
4384 return static_cast<tname ## _PLINK2_BASE_DO_NOT_USE__>(value_); \
4385 } \
4386 \
4387 tname& operator|=(const tname ## _PLINK2_BASE_DO_NOT_USE__ rhs) { \
4388 value_ |= rhs; \
4389 return *this; \
4390 } \
4391 \
4392 tname& operator&=(const tname ## _PLINK2_BASE_DO_NOT_USE__ rhs) { \
4393 value_ &= rhs; \
4394 return *this; \
4395 } \
4396 \
4397 tname& operator^=(const tname ## _PLINK2_BASE_DO_NOT_USE__ rhs) { \
4398 value_ ^= rhs; \
4399 return *this; \
4400 } \
4401 \
4402 tname& operator=(const tname& rhs) = default; \
4403 \
4404 private: \
4405 uint64_t value_; \
4406 }
4407
4408 # define ENUM_U31_DEF_START() typedef enum : uint32_t {
4409 # define ENUM_U31_DEF_END(tname) } tname
4410
4411 #else // !__cplusplus >= 201103L
4412
4413 # define FLAGSET_DEF_START() enum {
4414 # define FLAGSET_DEF_END(tname) } ; \
4415 typedef uint32_t tname
4416
4417 // don't use a nameless enum here, since we want to be able to static_assert
4418 // the enum size.
4419 // best to artificially add an element to the end for now to force width to
4420 // 64-bit, otherwise gcc actually shrinks it even when the constants are
4421 // defined with LLU.
4422 # define FLAGSET64_DEF_START() typedef enum {
4423 # define FLAGSET64_DEF_END(tname) , \
4424 tname ## PLINK2_BASE_DO_NOT_USE__ALL_64_SET__ = ~(0LLU) } tname ## _PLINK2_BASE_DO_NOT_USE__ ; \
4425 static_assert(sizeof(tname ## _PLINK2_BASE_DO_NOT_USE__) == 8, "64-bit flagset constants are not actually uint64_ts."); \
4426 typedef uint64_t tname
4427
4428 # define ENUM_U31_DEF_START() typedef enum {
4429 # define ENUM_U31_DEF_END(tname) } tname ## _PLINK2_BASE_DO_NOT_USE__ ; \
4430 typedef uint32_t tname
4431
4432 #endif
4433
4434 // This supports private struct members in code that still compiles as C.
4435 //
4436 // Internal code should access these members with GET_PRIVATE(), and define a
4437 // pair of public C++-only GET_PRIVATE_...() member functions (one const and
4438 // one non-const) that each return a reference to the member; see plink2_thread
4439 // for examples. In addition, .cc API code should define a small number of
4440 // standard GET_PRIVATE() accessors at the top of the file, and practically all
4441 // private-member access should occur through those file-scope accessors; this
4442 // keeps the surface area under control.
4443 //
4444 // (Tried to define a DECLARE_PRIVATE(typ, member) macro as well, but didn't
4445 // get that to work. This is already pretty painless if it's restricted to key
4446 // APIs, though.)
4447 //
4448 // probable todo: see if the intended effect can be achieved in a simpler
4449 // manner with well-chosen explicit and implicit type conversions.
4450 #ifdef __cplusplus
4451 # define GET_PRIVATE(par, member) (par).GET_PRIVATE_ ## member()
4452 #else
4453 # define GET_PRIVATE(par, member) (par).member
4454 #endif
4455
4456 static const double kLn2 = 0.6931471805599453;
4457
4458 #ifdef __cplusplus
4459 } // namespace plink2
4460 #endif
4461
4462 #endif // __PLINK2_BASE_H__