forked from ocxtal/dozeu
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdozeu.h
2523 lines (2275 loc) · 97 KB
/
dozeu.h
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// $(CC) -O3 -march=native -DMAIN -o dozeu dozeu.c
//#ifdef DZ_QUAL_ADJ
//#define DEBUG
//#endif
//#define DZ_PRINT_VECTOR
/**
* @file dozeu.h
* @brief SIMD X-drop DP for read-to-graph alignment
*
* @author Hajime Suzuki
* @date 18/03/20 at Kyoto
* @license MIT
*
* @datail
* minimum requirements:
* SSE4.1 (Core 2 / Bobcat or later)
* { gcc, clang, icc } x { Linux, Mac OS }
* input sequence encoding to be either of the three (not required to be terminated with '\0'):
* 1. {'A','C','G','T','U','a','c','g','t','u'} (ASCII nucleotide)
* 2. { 0, 1, 2, 3 } (2-bit nucleotide)
* 3. { 0, 1, 2, 3, ..., 19 } (integer protein)
*
* References:
* 1. BLAST X-drop DP
* https://github.com/elucify/blast-docs/wiki/The-Developer's-Guide-to-BLAST (the most datailed document that describes the original X-drop DP algorithm)
* 2. Myers bit vector (describes vertical (horizontal) tiling)
* Gene Myers, A fast bit-vector algorithm for approximate string matching based on dynamic programming, JACM (1999)
*/
/* make sure POSIX APIs are properly activated */
#if defined(__linux__) && !defined(_POSIX_C_SOURCE)
# define _POSIX_C_SOURCE 200112L
#endif
#if defined(__darwin__) && !defined(_BSD_SOURCE)
# define _BSD_SOURCE
#endif
#define SIMDE_ENABLE_NATIVE_ALIASES
#include "simde/x86/sse4.1.h"
// Only turn on extern "C" after including code that can use C++ features.
#ifdef __cplusplus
extern "C" {
#endif
#include <assert.h>
#include <stdlib.h>
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#ifndef DZ_INCLUDE_ONCE
#define DZ_NUM_QUAL_SCORES 64
#define DZ_QUAL_MATRIX_SIZE (16 * DZ_NUM_QUAL_SCORES)
#ifndef DZ_CIGAR_OP
# define DZ_CIGAR_OP 0x04030201
#endif
#ifndef dz_cmp_max
# define dz_cmp_max(x, y) ( (x) > (y) )
#endif
/* default encoding: ascii */
#ifndef DZ_PROTEIN
# if !defined(DZ_NUCL_ASCII) && !defined(DZ_NUCL_2BIT)
# define DZ_NUCL_ASCII
# endif
#if defined(DZ_NUCL_2BIT) && defined(DZ_QUAL_ADJ)
#error "Base quality adjustment is only supported in ASCII configuration"
#endif
/* define DZ_N_AS_UNMATCHING_BASE to penalize Ns, otherwise scores for (x, N) and (N, x) are always set zero */
// #define DZ_N_AS_UNMATCHING_BASE
enum dz_alphabet {
rA = 0x00, rC = 0x01, rG = 0x02, rT = 0x03, rU = 0x03,
qA = 0x00, qC = 0x04, qG = 0x08, qT = 0x0c, qU = 0x0c,
#ifdef DZ_N_AS_UNMATCHING_BASE
rN = 0x04, qN = 0x02, qS = 0x02
#else
rN = 0x90, qN = 0x90, qS = 0x02 /* pshufb instruction clears the column when the 7-th bit of the index is set */
#endif
};
#ifdef DZ_FULL_LENGTH_BONUS
#define dz_end_bonus(_self, _query, _i) ((_i) / 8 == (_query)->blen - 1 ? (_query)->bonus[8 + ((_i) & 7)] : 0)
#else
#define dz_end_bonus(_self, _query, _i) 0;
#endif
/* get the first index of the quals from a packed query (only valid if DZ_QUAL_ADJ is defined) */
#define dz_quals(_query) ( (uint8_t const *) &(_query)->arr[(_query)->arr_end] )
/* get the base quality adjusted matrix (only valid if DZ_QUAL_ADJ is defined) */
#define dz_qual_matrix(_self) ( (int8_t const *)((_self) + 1) )
#define dz_pair_score(_self, _q, _r, _i) ( (_self)->matrix[((_r) | (_q)->arr[(_i)]) & 0x1f] + dz_end_bonus(_self, _q, _i))
#define dz_qual_adj_pair_score(_self, _q, _r, _i) ( dz_qual_matrix(_self)[(((uint32_t) dz_quals(_q)[(_i)]) << 5) | ((uint32_t)(_r)) | ((uint32_t)((_q)->arr[(_i)] & 0x1f))] + dz_end_bonus(_self, _q, _i) )
#define dz_pair_eq(_self, _q, _r, _i) ( (uint32_t)((_q)->arr[(_i)]) == ((uint32_t)(_r)<<2) )
#else // ! DZ_PROTEIN
/* protein */
# ifndef DZ_MAT_SIZE
# define DZ_MAT_SIZE ( 32 )
# endif
#ifdef DZ_FULL_LENGTH_BONUS
#define dz_end_bonus(_self, _query, _i) ((_i) / 8 == (_query)->blen - 1 ? (_query)->bonus[8 + ((_i) & 7)] : 0)
#else
#define dz_end_bonus(_self, _query, _i) 0;
#endif
#define dz_pair_score(_self, _q, _r, _i) ( (int8_t)((_q)->arr[(_r) * (_q)->blen * L + (_i)]) + dz_end_bonus(_self, _q, _i))
#define dz_pair_eq(_self, _q, _r, _i) ( (uint32_t)((_q)->q[(_i) - 1] & 0x1f) == (uint32_t)(_r) )
#endif
/* utils */
#define dz_pp_cat_intl(x, y) x##y
#define dz_pp_cat(x, y) dz_pp_cat_intl(x, y)
#define dz_static_assert(expr) typedef char dz_pp_cat(_st_, __LINE__)[(expr) ? 1 : -1]
#define dz_trap() { *((volatile uint8_t *)NULL); }
#ifdef DZ_PROTEIN
dz_static_assert(DZ_MAT_SIZE <= 32);
#endif // DZ_PROTEIN
#if (defined(DEBUG) || defined(UNITTEST))
# include "log.h"
#else
# define debug(...) ;
#endif
#ifdef UNITTEST
# define UNITTEST_ALIAS_MAIN 0
# define UNITTEST_UNIQUE_ID 3213
# include "unittest.h"
unittest_config( "dozeu" );
unittest() { debug("hello"); }
#else
# define unittest(...) static void dz_pp_cat(dz_unused_, __LINE__)(void)
# define ut_assert(...) ;
# define trap() ;
#endif
#define dz_die(...) { \
dz_die_impl(__VA_ARGS__, ""); \
}
#define dz_die_impl(fmt, ...) { \
fprintf(stderr, "[%s: %s(%d)] " fmt "%s\n", __FILE__, __func__, __LINE__, __VA_ARGS__); \
exit(1); \
}
#define dz_error dz_die
#if defined(DZ_NUCL_ASCII)
# define DZ_UNITTEST_INDEX 0
#elif defined(DZ_NUCL_2BIT)
# define DZ_UNITTEST_INDEX 1
#elif defined(DZ_PROTEIN)
# define DZ_UNITTEST_INDEX 2
#endif
#define dz_ut_sel(a, b, c) ( (DZ_UNITTEST_INDEX == 0) ? (a) : ((DZ_UNITTEST_INDEX == 1) ? (b) : (c)) )
/* vectorize */
#define __dz_vectorize /* follow the compiler options */
/* inlining (FIXME: add appropriate __force_inline flag) */
#define __dz_force_inline inline
#ifdef __cplusplus
# define dz_unused(x)
#else
# define dz_unused(x) (void)(x)
#endif
#define dz_likely(x) __builtin_expect(!!(x), 1)
#define dz_unlikely(x) __builtin_expect(!!(x), 0)
#define dz_roundup(x, base) ( ((x) + (base) - 1) & ~((base) - 1) )
#define dz_rounddown(x, base) ( (x) & ~((base) - 1) )
#define dz_max2(x, y) ( (x) < (y) ? (y) : (x) )
#define dz_min2(x, y) ( (x) < (y) ? (x) : (y) )
#define dz_inside(x, y, z) ( ((uint64_t)(y) - (uint64_t)(x)) < ((uint64_t)(z) - (uint64_t)(x)) )
#define dz_loadu_u64(p) ({ uint8_t const *_p = (uint8_t const *)(p); *((uint64_t const *)_p); })
#define dz_storeu_u64(p, e) { uint8_t *_p = (uint8_t *)(p); *((uint64_t *)(_p)) = (e); }
#define dz_is_all_zero(x) ( _mm_test_all_zeros((x), (x)) == 1 )
#define DZ_MEM_MARGIN_SIZE ( 256 )
#define DZ_MEM_ALIGN_SIZE ( 16 )
#define DZ_MEM_INIT_SIZE ( 16 * 1024 * 1024 )
#define DZ_CELL_MIN ( INT16_MIN )
#define DZ_CELL_MAX ( INT16_MAX )
#define DZ_CELL_MARGIN ( 32 )
#define DZ_CELL_MARGINED_MIN ( DZ_CELL_MIN + DZ_CELL_MARGIN )
#define DZ_CELL_MARGINED_MAX ( DZ_CELL_MAX - DZ_CELL_MARGIN )
/* query; preconverted query sequence; blen = roundup(qlen, L) / L; array must have 16-byte-length margin at the tail */
struct dz_query_s {
uint32_t blen;
uint32_t arr_end;
char const *q;
int16_t bonus[16];
uint8_t arr[];
};
dz_static_assert(sizeof(struct dz_query_s) % sizeof(__m128i) == 0);
/* node (reference) */
struct dz_node_s { int32_t id, len; uint8_t const *ptr; };
dz_static_assert(sizeof(struct dz_node_s) % sizeof(__m128i) == 0);
/* DP matrix structures */
/*
* The Dozeu DP matrix for a node looks like:
* - A head column, containing
* - An array of pointers to forefronts for preceeding nodes
* - A head cap (same size as a normal cap)
* - 0 or more internal columns, which are:
* - An array slice of score vector items
* - A cap, containing:
* - The range of the array slice
* - Other data
* - A final column, which is:
* - An array slice of score vector items
* - A forefront (a special final cap), containing
* - The range of the array slice
* - Other data
*
* So, each slice has the cap for the preceeding slice before it, and its own
* range stored immediately after it. This is because we dynamically stop
* slices early, and we put the final range actually used once we know it.
*
* We are able to break this structure in memory! If the next column's slice
* and cap could be too big to fit right after the previous column in the
* contiguous memory available, we start a new head column with the previous
* column's cap as a forefront, and all the forefront data except the cap left
* uninitialized. We call this an "internal bridge".
*/
/* Score vector item. Array of these will be followed by a dz_cap_s, which leads with a range. */
struct dz_swgv_s { __m128i e, f, s; };
/* placed just after every score vector (as part of a cap) to indicate the length */
struct dz_range_s { uint32_t spos, epos; };
/* A special kind of initial cap. Identical in size to a cap. */
struct dz_head_s {
struct dz_range_s r;
uint32_t rch, n_forefronts;
};
/* followed by dz_forefront_s; range spos and epos are "shared to" (???) forefront_s */
struct dz_cap_s {
struct dz_range_s r;
uint32_t rch; int32_t rrem;
};
/*
* A forefront. Appears at the end of a matrix.
*
* Is also a special kind of cap.
*/
struct dz_forefront_s {
struct dz_range_s r; // the range that applies to the preceding column
uint32_t rid;
int32_t rlen;
struct dz_range_s fr; // the range that should continue forward
uint32_t rsum, rcnt; int32_t max, inc;
uint8_t _pad[8];
struct dz_query_s const *query;
struct dz_cap_s const *mcap;
};
/*
* When initializing forefronts, we want to be able to fill in the pad without saying 0s everywhere.
*/
#define DZ_FOREFRONT_PAD {0, 0, 0, 0, 0, 0, 0, 0}
/*
* This holds the forefront for the alignment root, and the x-drop threshold,
* computed from the max gap length.
*/
struct dz_alignment_init_s {
struct dz_forefront_s const *root;
uint16_t xt;
};
dz_static_assert(sizeof(struct dz_swgv_s) % sizeof(__m128i) == 0);
dz_static_assert(sizeof(struct dz_cap_s) % sizeof(__m128i) == 0);
dz_static_assert(sizeof(struct dz_forefront_s) % sizeof(__m128i) == 0);
#define dz_swgv(_p) ( (struct dz_swgv_s *)(_p) )
#define dz_cswgv(_p) ( (struct dz_swgv_s const *)(_p) )
#define dz_range(_p) ( (struct dz_range_s *)(_p) )
#define dz_crange(_p) ( (struct dz_range_s const *)(_p) )
#define dz_head(_p) ( (struct dz_head_s *)(_p) )
#define dz_chead(_p) ( (struct dz_head_s const *)(_p) )
#define dz_cap(_p) ( (struct dz_cap_s *)(_p) )
#define dz_ccap(_p) ( (struct dz_cap_s const *)(_p) )
#define dz_forefront(_p) ( (struct dz_forefront_s *)(_p) )
#define dz_cff(_p) ( (struct dz_forefront_s const *)(_p) )
/* alignment path */
struct dz_path_span_s {
uint32_t id;
uint32_t offset;
};
struct dz_alignment_s {
struct dz_path_span_s const *span;
uint8_t const *path;
uint32_t span_length, path_length, ref_length, query_length;
int32_t rrem, score;
uint32_t mismatch_count, match_count, ins_count, del_count;
};
/* context (constants and working buffers) */
/*
* Header for a block of memory used in an arena.
*
* Exists at the beginning of the block.
*/
struct dz_mem_block_s { struct dz_mem_block_s *next; size_t size; };
/*
* Bookkeeping information for the arena allocator.
*
* Exists at the beginning of the first block, just after its block header.
*/
struct dz_stack_s { struct dz_mem_block_s *curr; uint8_t *top, *end; uint64_t being_allocated; uint64_t reservation_remaining; uint8_t *dz_flush_top; };
/*
* Represents a Dozeu memory allocation arena.
*
* Exists at the beginning of the arena's first block, and contains its block
* header and also its stack bookkeeping information.
*/
struct dz_mem_s { struct dz_mem_block_s blk; struct dz_stack_s stack; };
/* Compute the number of bytes available to allocate in the current active block of an arena. */
#define dz_mem_stack_rem(_mem) ( (size_t)((_mem)->stack.end - (_mem)->stack.top) )
struct dz_s {
int8_t matrix[32];
uint16_t giv[8], gev[8], riv[8], rev[8]; // padding ensures memory alignment
int8_t protein_matrix[];
};
dz_static_assert(sizeof(struct dz_s) % sizeof(__m128i) == 0);
#define dz_mem(_self) ( (struct dz_mem_s *)(_self) - 1 )
/* get the base quality adjusted matrix (only valid if DZ_QUAL_ADJ is defined) */
#define dz_qual_matrix(_self) ( (int8_t const *)((_self) + 1) )
//#define dz_root(_self) ( (struct dz_forefront_s const **)(&_self->root) )
#define dz_is_terminated(_ff) ( dz_cff(_ff)->r.spos >= dz_cff(_ff)->r.epos )
#define dz_gt(_ff) ( dz_cff(_ff)->inc > 0 )
#define dz_geq(_ff) ( dz_cff(_ff)->mcap != NULL )
#ifdef DZ_PRINT_VECTOR
#define print_vector(v) { \
debug("%s (%d, %d, %d, %d, %d, %d, %d, %d)", #v, \
(int16_t)_mm_extract_epi16(v, 7), \
(int16_t)_mm_extract_epi16(v, 6), \
(int16_t)_mm_extract_epi16(v, 5), \
(int16_t)_mm_extract_epi16(v, 4), \
(int16_t)_mm_extract_epi16(v, 3), \
(int16_t)_mm_extract_epi16(v, 2), \
(int16_t)_mm_extract_epi16(v, 1), \
(int16_t)_mm_extract_epi16(v, 0)); \
}
#define print_vector8(v) { \
debug("%s (%d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d, %d)", #v, \
(int)(int8_t)_mm_extract_epi8(v, 15), \
(int)(int8_t)_mm_extract_epi8(v, 14), \
(int)(int8_t)_mm_extract_epi8(v, 13), \
(int)(int8_t)_mm_extract_epi8(v, 12), \
(int)(int8_t)_mm_extract_epi8(v, 11), \
(int)(int8_t)_mm_extract_epi8(v, 10), \
(int)(int8_t)_mm_extract_epi8(v, 9), \
(int)(int8_t)_mm_extract_epi8(v, 8), \
(int)(int8_t)_mm_extract_epi8(v, 7), \
(int)(int8_t)_mm_extract_epi8(v, 6), \
(int)(int8_t)_mm_extract_epi8(v, 5), \
(int)(int8_t)_mm_extract_epi8(v, 4), \
(int)(int8_t)_mm_extract_epi8(v, 3), \
(int)(int8_t)_mm_extract_epi8(v, 2), \
(int)(int8_t)_mm_extract_epi8(v, 1), \
(int)(int8_t)_mm_extract_epi8(v, 0)); \
}
#else
#define print_vector(v) ;
#define print_vector8(v) ;
#endif
/**
* @fn dz_malloc, dz_free
* @brief aligned and margined malloc and free
*/
static __dz_force_inline
void *dz_malloc(
size_t size)
{
void *ptr = NULL;
/* roundup to align boundary, add margin at the head and forefront */
size = dz_roundup(size, DZ_MEM_ALIGN_SIZE);
if(posix_memalign(&ptr, DZ_MEM_ALIGN_SIZE, size + 2 * DZ_MEM_MARGIN_SIZE) != 0) {
debug("posix_memalign failed");
dz_trap(); return(NULL);
}
debug("posix_memalign(%p), size(%lu)", ptr, size);
return((void *)((uint8_t *)ptr + DZ_MEM_MARGIN_SIZE));
}
static __dz_force_inline
void dz_free(
void *ptr)
{
debug("free(%p)", (uint8_t const *)ptr - DZ_MEM_MARGIN_SIZE);
free((void *)((uint8_t *)ptr - DZ_MEM_MARGIN_SIZE));
return;
}
#endif // DZ_INCLUDE_ONCE
#if !defined(DZ_UNITTESTS_INCLUDED) && !defined(DZ_QUAL_ADJ)
unittest() {
size_t size[] = { 10, 100, 1000, 10000, 100000, 1000000, 10000000 };
for(size_t i = 0; i < sizeof(size) / sizeof(size_t); i++) {
uint8_t *p = (uint8_t *)dz_malloc(size[i]);
ut_assert(p != NULL);
volatile uint8_t a = p[-32], b = p[0], c = p[size[i]], d = p[size[i] + 32];
dz_unused(a); dz_unused(b); dz_unused(c); dz_unused(d);
memset(p, 0, size[i]);
dz_free(p);
}
}
#endif
#ifndef DZ_INCLUDE_ONCE
/**
* @fn dz_mem_init, dz_mem_destroy, dz_mem_add_stack, dz_mem_malloc, dz_mem_flush
* @brief stack chain
*/
/*
* "Flush" a memory arena.
*
* Retain all blocks allocated from the system allcoator, but internally mark
* all the space as free.
*/
static __dz_force_inline
void dz_mem_flush(
struct dz_mem_s *mem)
{
mem->stack.curr = &mem->blk;
mem->stack.top = (uint8_t *)dz_roundup((uintptr_t)(mem + 1), DZ_MEM_ALIGN_SIZE);
// TODO: i think this margin is redundant, since dz_malloc adds the margin past the end
// of the requested size
mem->stack.end = (uint8_t *)mem + mem->blk.size;// - DZ_MEM_MARGIN_SIZE;
mem->stack.being_allocated = 0;
mem->stack.reservation_remaining = 0;
return;
}
/*
* Create a new memory arena.
*
* The arena will initially have space for internal allocation structures, and
* at least the given number of bytes of user data.
*
* If allocation fails, NULL is returned.
*/
static __dz_force_inline
struct dz_mem_s *dz_mem_init(
size_t size)
{
size = dz_max2(DZ_MEM_INIT_SIZE, sizeof(struct dz_mem_s) + dz_roundup(size, DZ_MEM_ALIGN_SIZE));
struct dz_mem_s *mem = (struct dz_mem_s *)dz_malloc(size);
if(mem == NULL) {
debug("failed to malloc memory");
return(NULL);
}
/* init mem object then stack pointers */
mem->blk = (struct dz_mem_block_s){ .next = NULL, .size = size };
dz_mem_flush(mem);
return(mem);
}
/*
* Free a memory arena created with dz_mem_init().
*
* The arena must not be NULL.
*/
static __dz_force_inline
void dz_mem_destroy(
struct dz_mem_s *mem)
{
struct dz_mem_block_s *blk = mem->blk.next;
debug("cleanup memory chain, blk(%p)", blk);
while(blk != NULL) {
struct dz_mem_block_s *next = blk->next;
debug("free blk(%p), next(%p)", blk, next);
dz_free(blk); blk = next;
}
dz_free(mem);
return;
}
/*
* Advance a memory arena to a next block that can allocate the given number of bytes.
*
* Always advances to a new block; assumes sufficient space is definitely not
* available in the current block.
*
* Handles creating new blocks for the arena, or replacing old blocks that are
* not large enough.
*
* Returns 0 on success, and 1 if memory could not be allocated.
*/
static __dz_force_inline
uint64_t dz_mem_add_stack(
struct dz_mem_s *mem,
size_t size)
{
debug("add_stack, ptr(%p)", mem->stack.curr->next);
if(mem->stack.curr->next == NULL
|| dz_unlikely(mem->stack.curr->next->size < size + dz_roundup(sizeof(struct dz_mem_block_s), DZ_MEM_ALIGN_SIZE))) {
if (mem->stack.curr->next != NULL) {
/* didn't allocate enough memory earlier, throw out all subsequent blocks so we can start again bigger */
struct dz_mem_block_s *blk = mem->stack.curr->next;
while (blk != NULL) {
struct dz_mem_block_s *next = blk->next;
dz_free(blk);
blk = next;
}
mem->stack.curr->next = NULL;
}
/* current stack is the forefront of the memory block chain, add new block */
size = dz_max2(
size + dz_roundup(sizeof(struct dz_mem_block_s), DZ_MEM_ALIGN_SIZE),
2 * mem->stack.curr->size
);
struct dz_mem_block_s *blk = (struct dz_mem_block_s *)dz_malloc(size);
debug("malloc called, blk(%p)", blk);
if(blk == NULL) { return(1); }
/* link new node to the forefront of the current chain */
mem->stack.curr->next = blk;
/* initialize the new memory block */
blk->next = NULL;
blk->size = size;
}
/* follow a forward link and init stack pointers */
mem->stack.curr = mem->stack.curr->next;
mem->stack.top = (uint8_t *)dz_roundup((uintptr_t)(mem->stack.curr + 1), DZ_MEM_ALIGN_SIZE);
mem->stack.end = (uint8_t *)mem->stack.curr + mem->stack.curr->size - DZ_MEM_MARGIN_SIZE;
return(0);
}
/*
* Dump stack information to standard error.
*/
static __dz_force_inline
void dz_mem_log_stack(
struct dz_mem_s *mem)
{
fprintf(stderr, "Dozeu stack blocks:\n");
struct dz_mem_block_s *blk = &(mem->blk);
while (blk != NULL) {
fprintf(stderr, "\t%p\t%lu\n", blk, blk->size);
blk = blk->next;
}
}
/*
* Allocate memory from an arena.
*
* Returns NULL if memory could not be allocated.
*/
static __dz_force_inline
void *dz_mem_malloc(
struct dz_mem_s *mem,
size_t size)
{
/* Make sure to maintain memory alignment.
*
* We need to precompute the aligned size instead of just bumping top by
* the aligned size, because we need to make sure the alignment padding
* memory is actually available in the space between top and end.
* Otherwise, top could pass end, and dz_mem_stack_rem() could overflow.
*/
size = dz_roundup(size, sizeof(__m128i));
if(dz_mem_stack_rem(mem) < size) {
if(dz_mem_add_stack(mem, size)) {
/* Report a failed allocation. */
dz_die("Allocation of %lu bytes failed", size);
return NULL;
}
}
void *ptr = (void *)mem->stack.top;
mem->stack.top += size;
return(ptr);
}
/*
* Prepare a contiguous run of memory from an arena.
*
* Returns 0 if successful, and 1 on failure.
*/
static __dz_force_inline
uint64_t dz_mem_stream_reserve(
struct dz_mem_s *mem,
size_t size)
{
debug("Reserve %lu bytes for stream", size);
mem->stack.reservation_remaining = size;
/* We cheat and just use a whole block as a run. */
if(dz_likely(dz_mem_stack_rem(mem) < size)) {
if (dz_mem_add_stack(mem, size)) {
dz_error("Could not reserve %lu bytes", size);
return 1;
}
return 0;
}
return 0;
}
/*
* Get the amount of stream reservation remaining.
*/
static __dz_force_inline
uint64_t dz_mem_stream_remaining(
struct dz_mem_s *mem)
{
return mem->stack.reservation_remaining;
}
/*
* Begin an allocation of up to the given number of bytes from the current
* stream reservation.
*
* Returns a pointer to them, or NULL if they do not fit.
*/
static __dz_force_inline
void *dz_mem_stream_alloc_begin(
struct dz_mem_s *mem,
size_t size)
{
if(dz_mem_stack_rem(mem) < size || mem->stack.being_allocated != 0) {
if (dz_mem_stack_rem(mem) < size) {
dz_error("Asked to allocate %lu bytes, but only %lu bytes remain on stack", size, dz_mem_stack_rem(mem));
} else if (mem->stack.being_allocated != 0) {
dz_error("Asked to allocate %lu bytes, but another allocaton of %lu bytes is already in progress", size, mem->stack.being_allocated);
}
return NULL;
}
if (mem->stack.reservation_remaining < size) {
dz_error("Asked to allocate %lu bytes, but only %lu bytes remain in reservation", size, mem->stack.reservation_remaining);
return NULL;
}
void *ptr = (void *)mem->stack.top;
debug("Begin allocating %lu bytes (%p) from %lu in reservation", size, ptr, mem->stack.reservation_remaining);
/* Reserve this area above the stack */
mem->stack.being_allocated = size;
return(ptr);
}
/*
* Get the start address of the active allocation.
*
* Returns NULL if no allocation is active.
*/
static __dz_force_inline
void *dz_mem_stream_alloc_current(
struct dz_mem_s *mem)
{
if(mem->stack.being_allocated == 0) {
dz_error("Nothing currently being allocated");
return NULL;
}
return (void *)mem->stack.top;
}
/*
* End an active allocation, having used the given number of bytes.
*
* Returns 0 on success, or 1 if too many bytes were used.
*/
static __dz_force_inline
uint64_t dz_mem_stream_alloc_end(
struct dz_mem_s *mem,
size_t size)
{
debug("Finish allocating %lu bytes (%p)", size, mem->stack.top);
if(size > mem->stack.being_allocated) {
/* Too much memory was used vs. what we set aside for the stream. */
debug("That was too many");
return 1;
}
mem->stack.top += size;
mem->stack.being_allocated = 0;
mem->stack.reservation_remaining -= size;
return 0;
}
/*
* Allocate the given number of bytes from the current stream reservation.
*
* Returns a pointer to them, or NULL if they do not fit.
*/
static __dz_force_inline
void *dz_mem_stream_alloc(
struct dz_mem_s *mem,
size_t size)
{
/* TODO: Optimize instead of using the async primitives. */
void *ptr = dz_mem_stream_alloc_begin(mem, size);
if(dz_mem_stream_alloc_end(mem, size)) {
debug("Stream alloc failed");
ptr = NULL;
}
return ptr;
}
/*
* Allocate the given number of items of the given size from the current
* reservation, right-justified, in a block aligned to the given alignemnt.
*
* Returns a pointer to them, or NULL if they do not fit.
*/
static __dz_force_inline
void *dz_mem_stream_right_alloc(
struct dz_mem_s *mem,
size_t items,
size_t size,
size_t alignment)
{
size_t data_size = size * items;
size_t alloc_size = dz_roundup(data_size, alignment);
void *ptr = dz_mem_stream_alloc(mem, alloc_size);
if(ptr == NULL) {
debug("Stream right alloc failed");
return ptr;
}
void* right_aligned_ptr = (void*)((uint8_t*)ptr + (alloc_size - data_size));
debug("Allocated %lu items of %lu bytes each padded to %lu: block %p and right-aligned array %p", items, size, alignment, ptr, right_aligned_ptr);
return right_aligned_ptr;
}
#endif // DZ_INCLUDE_ONCE
#if !defined(DZ_UNITTESTS_INCLUDED) && !defined(DZ_QUAL_ADJ)
unittest() {
size_t size[] = { 10, 100, 1000, 10000, 100000, 1000000, 10000000 };
for(size_t i = 0; i < sizeof(size) / sizeof(size_t); i++) {
struct dz_mem_s *mem = dz_mem_init(size[i]);
uint8_t *p = (uint8_t *)dz_mem_malloc(mem, size[i]);
ut_assert(p != NULL);
memset(p, 0, size[i]);
dz_mem_destroy(mem);
}
}
#endif
/**
* vector update macros
*/
#define _calc_max_slice_size(_sp, _ep) ({ \
size_t max_slice_size = (2 * ((_ep) - (_sp)) * sizeof(struct dz_swgv_s)); \
debug("sp(%lu), ep(%lu), max_slice_size(%lu)", (size_t) (_sp), (size_t) (_ep), max_slice_size); \
max_slice_size; \
})
/*
* Determine how many bytes are needed to store forefront pointers, the head
* cap, the column vector, and the cap at the end from _end_column, which may
* need to be a (larger) forefront if this ends up being the last column.
* _sp: start position in the column
* _ep: end position in the column
* _nt: number of forefronts that need pointers
*/
#define _calc_next_size(_sp, _ep, _nt) ({ \
size_t forefront_arr_size = dz_roundup(sizeof(struct dz_forefront_s *) * (_nt), sizeof(__m128i)); \
size_t est_column_size = _calc_max_slice_size(_sp, _ep); \
size_t head_cap_size = sizeof(struct dz_head_s); \
size_t end_cap_size = sizeof(struct dz_forefront_s); \
size_t next_req = forefront_arr_size + head_cap_size + est_column_size + end_cap_size; \
debug("sp(%lu), ep(%lu), nt(%lu), forefront_arr_size(%lu), head_cap_size(%lu), est_column_size(%lu), end_cap_size(%lu), next_req(%lu)", (size_t) (_sp), (size_t) (_ep), (size_t) (_nt), forefront_arr_size, head_cap_size, est_column_size, end_cap_size, next_req); \
next_req; \
})
/*
* Save an array of forefront pointers to the stack, followed by a head cap
* that indicates the number of forefronts before it.
*
* Space must have been reserved in the arena.
*/
#define _init_cap(_adj, _rch, _forefronts, _n_forefronts) ({ \
/* push forefront pointers */ \
size_t forefront_arr_size = dz_roundup(sizeof(struct dz_forefront_s *) * (_n_forefronts), sizeof(__m128i)); \
struct dz_forefront_s const **dst = (struct dz_forefront_s const **)(dz_mem_stream_right_alloc(dz_mem(self), (int64_t)(_n_forefronts), sizeof(struct dz_forefront_s *), sizeof(__m128i))); \
struct dz_forefront_s const **src = (struct dz_forefront_s const **)(_forefronts); \
for(size_t i = 0; i < (_n_forefronts); i++) { dst[i] = src[i]; } \
/* push head-cap info */ \
struct dz_head_s *_head = (struct dz_head_s *)(dz_mem_stream_alloc(dz_mem(self), sizeof(struct dz_head_s))); \
(_head)->r.spos = (_adj); /* save merging adjustment */ \
(_head)->r.epos = 0; /* head marked as zero */ \
(_head)->rch = (_rch); /* rch for the first column */ \
(_head)->n_forefronts = (_n_forefronts); /* record n_forefronts */ \
debug("create head cap(%p), n_forefronts(%lu)", _head, (uint64_t)(_n_forefronts)); \
dz_cap(_head); \
})
/*
* Reserve space for the forefront pointers, head cap, and column vector, in
* that order.
*
* Return the slice array address, for which the _spos to _epos range
* corresponds to the column vector.
*
* The returned pointer must be passed to _end_column() before _begin_column()
* can be called. The final column's slice array address must be passed to
* _end_matrix() before the arena can be used again for something else.
*/
#define _begin_column_head(_spos, _epos, _adj, _forefronts, _n_forefronts) ({ \
debug("Beginning column head"); \
/* calculate sizes */ \
size_t next_req = _calc_next_size(_spos, _epos, _n_forefronts); \
/* reserve stream of memory to push onto */ \
dz_mem_stream_reserve(dz_mem(self), next_req); \
/* push head-cap */ \
struct dz_cap_s *cap = _init_cap(_adj, 0xff, _forefronts, _n_forefronts); \
/* start array slice allocation */ \
struct dz_swgv_s *slice_data = dz_swgv(dz_mem_stream_alloc_begin(dz_mem(self), _calc_max_slice_size(_spos, _epos))); \
/* return array pointer */ \
slice_data - (_spos); \
})
/*
* Fill in a terminating cap for the most recent column passed to _end_column,
* using the range information in the current active allocation.
* Either immediately after it or in a new contiguous run of memory, reserve
* space for a new column. If the new column is not immediately after the old
* column, copy a (fake?) version of the old column's cap to be before it.
*
* Return the slice array address, for which the _spos to _epos range
* corresponds to the column vector.
*
* The returned pointer must be passed to _end_column() before another column
* can be begun, and the last column must be passed to _end_matrix() before the
* arena can be used again.
*/
#define _begin_column(_w, _rch, _rlen) ({ \
debug("Beginning column"); \
/* push cap info */ \
struct dz_cap_s *cap = dz_cap(dz_mem_stream_alloc_current(dz_mem(self))); \
dz_mem_stream_alloc_end(dz_mem(self), sizeof(struct dz_cap_s)); \
cap->rch = (_rch); /* record rch for the next column */ \
cap->rrem = (_rlen); /* record rlen for use in traceback */ \
/* calculate size of next column if it is here */ \
size_t next_req_here = _calc_next_size((_w).fr.spos, (_w).fr.epos, 0); \
if(dz_likely(dz_mem_stream_remaining(dz_mem(self)) < next_req_here)) { \
/* Next column will not fit here. */ \
debug("create internal bridge"); \
size_t next_req_split = _calc_next_size((_w).fr.spos, (_w).fr.epos, 1); \
/* We start a new head column with the previous column's cap pointed to as if it were a forefront. */ \
dz_mem_stream_reserve(dz_mem(self), next_req_split); \
cap = _init_cap(0, _rch, &cap, 1); \
} \
debug("create column(%p), [%u, %u), span(%u), rrem(%ld), max(%d), inc(%d)", cap, (_w).fr.spos, (_w).fr.epos, (_w).r.epos - (_w).r.spos, (_rlen), (_w).max, (_w).inc); \
/* start array slice allocation */ \
struct dz_swgv_s *slice_data = dz_swgv(dz_mem_stream_alloc_begin(dz_mem(self), _calc_max_slice_size((_w).fr.spos, (_w).fr.epos))); \
/* return array pointer */ \
slice_data - (_w).fr.spos; \
})
/*
* Given the slice array address for a column begun with _begin_column() or
* _begin_column_head(), finish the column.
*
* Note that we have actually used the _spos to _epos part of the column's
* vector, and save range data after that vector recording the range its slice
* covers.
*
* Returns the address of the filled-in range, which it stores in a current
* allocation, to be made into a cap by _begin_column() or into a forefront by
* _end_matrix().
*/
#define _end_column(_p, _spos, _epos) ({ \
debug("Ending column"); \
/* finish the slice data allocation with what was actually used */ \
dz_mem_stream_alloc_end(dz_mem(self), ((_epos) - (_spos)) * sizeof(struct dz_swgv_s)); \
/* immediately next in memory, allocate up to a forefront, as a range */ \
struct dz_range_s *r = dz_range(dz_mem_stream_alloc_begin(dz_mem(self), sizeof(struct dz_forefront_s))); \
debug("create range(%p), [%u, %u)", r, (_spos), (_epos)); \
r->spos = (_spos); r->epos = (_epos); \
/* Return it as a cap */ \
(struct dz_cap_s *)r; \
})
/*
* Given the slice array address of the final column, which has been ended (so
* its filled-in range is in an active forefront-sized allocation), turn that
* filled-in range into a full forefront.
*
* After calling this, no allocation will be active and no memory adjacency
* relationships will need to be maintained.
*/
#define _end_matrix(_p, _wp, _rrem) ({ \
debug("Ending matrix"); \
/* create forefront object */ \
struct dz_forefront_s *forefront = dz_forefront(dz_mem_stream_alloc_current(dz_mem(self))); \
dz_mem_stream_alloc_end(dz_mem(self), sizeof(struct dz_forefront_s)); \
forefront->rid = (_wp)->rid; \
forefront->rlen = (_wp)->rlen; \
forefront->fr = (_wp)->fr; \
forefront->rsum = (_wp)->rsum + ((_wp)->rlen < 0 ? -1 : 1) * ((_wp)->rlen - (_rrem)); \
forefront->rcnt = (_wp)->rcnt + 1; \
forefront->max = (_wp)->max + (_wp)->inc; \
forefront->inc = (_wp)->inc; \
forefront->query = (_wp)->query; \
forefront->mcap = (_wp)->mcap; \
debug("create forefront(%p), [%u, %u), [%u, %u), max(%d), inc(%d), rlen(%d), query(%p), rrem(%d)", forefront, (_wp)->r.spos, (_wp)->r.epos, (_wp)->fr.spos, (_wp)->fr.epos, (_wp)->max, (_wp)->inc, (int32_t)(_wp)->rlen, (_wp)->query, (int32_t)(_rrem)); \
/* return the forefront pointer */ \
(struct dz_forefront_s const *)forefront; \
})
/**
* @macro _calc_bonus
* @brief add bonus to cells on the tail row; bonus constant vectors are always placed just before parr
*/
#ifdef DZ_FULL_LENGTH_BONUS
#define _init_bonus(_query) \
uint32_t blim = (_query)->blen - 1; \
uint8_t const *pbonus = (_query)->arr;
#define _add_bonus(_i, _v) ( _mm_add_epi16((_v), _mm_load_si128(&((__m128i const *)pbonus)[-2 + ((_i) == blim)])) )
#else
#define _init_bonus(_query) ;
#define _add_bonus(_i, _v) ( (_v) )
#endif
#if defined(DZ_NUCL_ASCII)
#ifdef DZ_QUAL_ADJ
#define _init_rch(_query, _rt, _rrem) \
_init_bonus(_query); \
uint32_t rch = conv[_rt[-_rrem] & 0x0f]; \
/* debug("rch(%c, %u, %x)", _rt[-_rrem], rch, rch); */ \
uint8_t const *parr = (_query)->arr; \
uint8_t const *qarr = dz_quals(_query); \
__m128i const rv = _mm_set1_epi8(rch);
#define _calc_score_profile(_i) ({ \
/* load qual and query index values */ \
__m128i qxv = _mm_cvtepi8_epi16(_mm_loadl_epi64((__m128i const *)&qarr[(_i) * L])); \
__m128i sxv = _mm_or_si128(rv, _mm_loadl_epi64((__m128i const *)&parr[(_i) * L])); /* note: left in 8-bit */\
__m128i sc; \
if (_mm_movemask_epi8(_mm_cmpeq_epi8(qxv, _mm_alignr_epi8(qxv, qxv, 2))) == 0xffff) { \
/* we have uniform quality values, so we can pull from just one matrix */ \
int8_t const *qual_mat = dz_qual_matrix(self) + 32 * (*((int16_t*)&qxv)); \
sc = _mm_cvtepi8_epi16(_mm_shuffle_epi8(_mm_load_si128((__m128i const *)qual_mat), sxv)); \
}\
else { \
/* combine the qual and sequence indexes */\
__m128i xv = _mm_or_si128(_mm_slli_epi16(qxv, 5), \
_mm_and_si128(_mm_cvtepi8_epi16(sxv), _mm_set1_epi16(0x1f)));\
print_vector(xv);\
/* get the scores from the quality matrices (unvectorized, unfortunately) */ \
int8_t const *qual_mat = dz_qual_matrix(self); \
sc = _mm_setr_epi16(qual_mat[_mm_extract_epi16(xv, 0)], \
qual_mat[_mm_extract_epi16(xv, 1)], \
qual_mat[_mm_extract_epi16(xv, 2)], \
qual_mat[_mm_extract_epi16(xv, 3)], \
qual_mat[_mm_extract_epi16(xv, 4)], \
qual_mat[_mm_extract_epi16(xv, 5)], \
qual_mat[_mm_extract_epi16(xv, 6)], \
qual_mat[_mm_extract_epi16(xv, 7)]);\
} \
print_vector(sc)\
sc; \
})
#else
#define _init_rch(_query, _rt, _rrem) \
_init_bonus(_query); \
uint32_t rch = conv[_rt[-_rrem] & 0x0f]; \
/* debug("rch(%c, %u, %x)", _rt[-_rrem], rch, rch); */ \
uint8_t const *parr = (_query)->arr; \
__m128i const rv = _mm_set1_epi8(rch);
#define _calc_score_profile(_i) ({ \
__m128i qv = _mm_loadl_epi64((__m128i const *)&parr[(_i) * L]); \
__m128i sc = _mm_cvtepi8_epi16(_mm_shuffle_epi8(_mm_load_si128((__m128i const *)self->matrix), _mm_or_si128(rv, qv))); \
print_vector(sc); \
/* print_vector(_mm_cvtepi8_epi16(rv)); print_vector(_mm_cvtepi8_epi16(qv)); */ \
sc; \
})
#endif
#elif defined(DZ_NUCL_2BIT)
#define _init_rch(_query, _rt, _rrem) \
_init_bonus(_query); \
uint32_t rch = dir < 0 ? _rt[-_rrem] : (_rt[-_rrem] ^ 0x03); \
/* debug("rch(%c, %u, %x)", _rt[-_rrem], rch, rch); */ \