forked from RcppCore/RcppParallel
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtest_atomic.cpp
More file actions
1603 lines (1457 loc) · 63.4 KB
/
test_atomic.cpp
File metadata and controls
1603 lines (1457 loc) · 63.4 KB
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
/*
Copyright 2005-2014 Intel Corporation. All Rights Reserved.
This file is part of Threading Building Blocks. Threading Building Blocks is free software;
you can redistribute it and/or modify it under the terms of the GNU General Public License
version 2 as published by the Free Software Foundation. Threading Building Blocks is
distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the
implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
See the GNU General Public License for more details. You should have received a copy of
the GNU General Public License along with Threading Building Blocks; if not, write to the
Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
As a special exception, you may use this file as part of a free software library without
restriction. Specifically, if other files instantiate templates or use macros or inline
functions from this file, or you compile this file and link it with other files to produce
an executable, this file does not by itself cause the resulting executable to be covered
by the GNU General Public License. This exception does not however invalidate any other
reasons why the executable file might be covered by the GNU General Public License.
*/
#include "harness_defs.h"
#if __TBB_TEST_SKIP_PIC_MODE || (__TBB_TEST_SKIP_GCC_BUILTINS_MODE && __TBB_TEST_SKIP_ICC_BUILTINS_MODE)
#include "harness.h"
int TestMain() {
REPORT("Known issue: %s\n",
__TBB_TEST_SKIP_PIC_MODE? "PIC mode is not supported" : "Compiler builtins for atomic operations aren't available");
return Harness::Skipped;
}
#else
// Put tbb/atomic.h first, so if it is missing a prerequisite header, we find out about it.
// The tests here do *not* test for atomicity, just serial correctness. */
#include "tbb/atomic.h"
#include "harness_assert.h"
#include <cstring> // memcmp
#include "tbb/aligned_space.h"
#include <new> //for placement new
using std::memcmp;
#if _MSC_VER && !defined(__INTEL_COMPILER)
// Unary minus operator applied to unsigned type, result still unsigned
// Constant conditional expression
#pragma warning( disable: 4127 4310 )
#endif
#if __TBB_GCC_STRICT_ALIASING_BROKEN
#pragma GCC diagnostic ignored "-Wstrict-aliasing"
#endif
// Intel(R) Compiler have an issue when a scoped enum with a specified underlying type has negative values.
#define __TBB_ICC_SCOPED_ENUM_WITH_UNDERLYING_TYPE_NEGATIVE_VALUE_BROKEN ( _MSC_VER && !__TBB_DEBUG && __INTEL_COMPILER && __INTEL_COMPILER <= 1500 )
// Intel(R) Compiler have an issue with __atomic_load_explicit from a scoped enum with a specified underlying type.
#define __TBB_ICC_SCOPED_ENUM_WITH_UNDERLYING_TYPE_ATOMIC_LOAD_BROKEN ( TBB_USE_ICC_BUILTINS && !__TBB_DEBUG && __INTEL_COMPILER && __INTEL_COMPILER <= 1500 )
enum LoadStoreExpression {
UseOperators,
UseImplicitAcqRel,
UseExplicitFullyFenced,
UseExplicitAcqRel,
UseExplicitRelaxed,
UseGlobalHelperFullyFenced,
UseGlobalHelperAcqRel,
UseGlobalHelperRelaxed
};
//! Structure that holds an atomic<T> and some guard bytes around it.
template<typename T, LoadStoreExpression E = UseOperators>
struct TestStruct {
typedef unsigned char byte_type;
T prefix;
tbb::atomic<T> counter;
T suffix;
TestStruct( T i ) {
ASSERT( sizeof(*this)==3*sizeof(T), NULL );
for (size_t j = 0; j < sizeof(T); ++j) {
reinterpret_cast<byte_type*>(&prefix)[j] = byte_type(0x11*(j+1));
reinterpret_cast<byte_type*>(&suffix)[sizeof(T)-j-1] = byte_type(0x11*(j+1));
}
if ( E == UseOperators )
counter = i;
else if ( E == UseExplicitRelaxed )
counter.template store<tbb::relaxed>(i);
else
tbb::store<tbb::full_fence>( counter, i );
}
~TestStruct() {
// Check for writes outside the counter.
for (size_t j = 0; j < sizeof(T); ++j) {
ASSERT( reinterpret_cast<byte_type*>(&prefix)[j] == byte_type(0x11*(j+1)), NULL );
ASSERT( reinterpret_cast<byte_type*>(&suffix)[sizeof(T)-j-1] == byte_type(0x11*(j+1)), NULL );
}
}
static tbb::atomic<T> gCounter;
};
// A global variable of type tbb::atomic<>
template<typename T, LoadStoreExpression E> tbb::atomic<T> TestStruct<T, E>::gCounter;
//! Test compare_and_swap template members of class atomic<T> for memory_semantics=M
template<typename T,tbb::memory_semantics M>
void TestCompareAndSwapWithExplicitOrdering( T i, T j, T k ) {
ASSERT( i!=k, "values must be distinct" );
// Test compare_and_swap that should fail
TestStruct<T> x(i);
T old = x.counter.template compare_and_swap<M>( j, k );
ASSERT( old==i, NULL );
ASSERT( x.counter==i, "old value not retained" );
// Test compare and swap that should succeed
old = x.counter.template compare_and_swap<M>( j, i );
ASSERT( old==i, NULL );
ASSERT( x.counter==j, "value not updated?" );
}
//! i, j, k must be different values
template<typename T>
void TestCompareAndSwap( T i, T j, T k ) {
ASSERT( i!=k, "values must be distinct" );
// Test compare_and_swap that should fail
TestStruct<T> x(i);
T old = x.counter.compare_and_swap( j, k );
ASSERT( old==i, NULL );
ASSERT( x.counter==i, "old value not retained" );
// Test compare and swap that should succeed
old = x.counter.compare_and_swap( j, i );
ASSERT( old==i, NULL );
if( x.counter==i ) {
ASSERT( x.counter==j, "value not updated?" );
} else {
ASSERT( x.counter==j, "value trashed" );
}
// Check that atomic global variables work
TestStruct<T>::gCounter = i;
old = TestStruct<T>::gCounter.compare_and_swap( j, i );
ASSERT( old==i, NULL );
ASSERT( TestStruct<T>::gCounter==j, "value not updated?" );
TestCompareAndSwapWithExplicitOrdering<T,tbb::full_fence>(i,j,k);
TestCompareAndSwapWithExplicitOrdering<T,tbb::acquire>(i,j,k);
TestCompareAndSwapWithExplicitOrdering<T,tbb::release>(i,j,k);
TestCompareAndSwapWithExplicitOrdering<T,tbb::relaxed>(i,j,k);
}
//! memory_semantics variation on TestFetchAndStore
template<typename T, tbb::memory_semantics M>
void TestFetchAndStoreWithExplicitOrdering( T i, T j ) {
ASSERT( i!=j, "values must be distinct" );
TestStruct<T> x(i);
T old = x.counter.template fetch_and_store<M>( j );
ASSERT( old==i, NULL );
ASSERT( x.counter==j, NULL );
}
//! i and j must be different values
template<typename T>
void TestFetchAndStore( T i, T j ) {
ASSERT( i!=j, "values must be distinct" );
TestStruct<T> x(i);
T old = x.counter.fetch_and_store( j );
ASSERT( old==i, NULL );
ASSERT( x.counter==j, NULL );
// Check that atomic global variables work
TestStruct<T>::gCounter = i;
old = TestStruct<T>::gCounter.fetch_and_store( j );
ASSERT( old==i, NULL );
ASSERT( TestStruct<T>::gCounter==j, "value not updated?" );
TestFetchAndStoreWithExplicitOrdering<T,tbb::full_fence>(i,j);
TestFetchAndStoreWithExplicitOrdering<T,tbb::acquire>(i,j);
TestFetchAndStoreWithExplicitOrdering<T,tbb::release>(i,j);
TestFetchAndStoreWithExplicitOrdering<T,tbb::relaxed>(i,j);
}
#if _MSC_VER && !defined(__INTEL_COMPILER)
// conversion from <bigger integer> to <smaller integer>, possible loss of data
// the warning seems a complete nonsense when issued for e.g. short+=short
#pragma warning( disable: 4244 )
#endif
//! Test fetch_and_add members of class atomic<T> for memory_semantics=M
template<typename T,tbb::memory_semantics M>
void TestFetchAndAddWithExplicitOrdering( T i ) {
TestStruct<T> x(i);
T actual;
T expected = i;
// Test fetch_and_add member template
for( int j=0; j<10; ++j ) {
actual = x.counter.fetch_and_add(j);
ASSERT( actual==expected, NULL );
expected += j;
}
for( int j=0; j<10; ++j ) {
actual = x.counter.fetch_and_add(-j);
ASSERT( actual==expected, NULL );
expected -= j;
}
// Test fetch_and_increment member template
ASSERT( x.counter==i, NULL );
actual = x.counter.template fetch_and_increment<M>();
ASSERT( actual==i, NULL );
ASSERT( x.counter==T(i+1), NULL );
// Test fetch_and_decrement member template
actual = x.counter.template fetch_and_decrement<M>();
ASSERT( actual==T(i+1), NULL );
ASSERT( x.counter==i, NULL );
}
//! Test fetch_and_add and related operators
template<typename T>
void TestFetchAndAdd( T i ) {
TestStruct<T> x(i);
T value;
value = ++x.counter;
ASSERT( value==T(i+1), NULL );
value = x.counter++;
ASSERT( value==T(i+1), NULL );
value = x.counter--;
ASSERT( value==T(i+2), NULL );
value = --x.counter;
ASSERT( value==i, NULL );
T actual;
T expected = i;
for( int j=-100; j<=100; ++j ) {
expected += j;
actual = x.counter += j;
ASSERT( actual==expected, NULL );
}
for( int j=-100; j<=100; ++j ) {
expected -= j;
actual = x.counter -= j;
ASSERT( actual==expected, NULL );
}
// Test fetch_and_increment
ASSERT( x.counter==i, NULL );
actual = x.counter.fetch_and_increment();
ASSERT( actual==i, NULL );
ASSERT( x.counter==T(i+1), NULL );
// Test fetch_and_decrement
actual = x.counter.fetch_and_decrement();
ASSERT( actual==T(i+1), NULL );
ASSERT( x.counter==i, NULL );
x.counter = i;
ASSERT( x.counter==i, NULL );
// Check that atomic global variables work
TestStruct<T>::gCounter = i;
value = TestStruct<T>::gCounter.fetch_and_add( 42 );
expected = i+42;
ASSERT( value==i, NULL );
ASSERT( TestStruct<T>::gCounter==expected, "value not updated?" );
TestFetchAndAddWithExplicitOrdering<T,tbb::full_fence>(i);
TestFetchAndAddWithExplicitOrdering<T,tbb::acquire>(i);
TestFetchAndAddWithExplicitOrdering<T,tbb::release>(i);
TestFetchAndAddWithExplicitOrdering<T,tbb::relaxed>(i);
}
//! A type with unknown size.
class IncompleteType;
void TestFetchAndAdd( IncompleteType* ) {
// There are no fetch-and-add operations on a IncompleteType*.
}
void TestFetchAndAdd( void* ) {
// There are no fetch-and-add operations on a void*.
}
void TestFetchAndAdd( bool ) {
// There are no fetch-and-add operations on a bool.
}
template<typename T>
void TestConst( T i ) {
// Try const
const TestStruct<T> x(i);
ASSERT( memcmp( &i, &x.counter, sizeof(T) )==0, "write to atomic<T> broken?" );
ASSERT( x.counter==i, "read of atomic<T> broken?" );
const TestStruct<T, UseExplicitRelaxed> y(i);
ASSERT( memcmp( &i, &y.counter, sizeof(T) )==0, "relaxed write to atomic<T> broken?" );
ASSERT( tbb::load<tbb::relaxed>(y.counter) == i, "relaxed read of atomic<T> broken?" );
const TestStruct<T, UseGlobalHelperFullyFenced> z(i);
ASSERT( memcmp( &i, &z.counter, sizeof(T) )==0, "sequentially consistent write to atomic<T> broken?" );
ASSERT( z.counter.template load<tbb::full_fence>() == i, "sequentially consistent read of atomic<T> broken?" );
}
#include "harness.h"
#include <sstream>
//TODO: consider moving it to separate file, and unify with one in examples command line interface
template<typename T>
std::string to_string(const T& a){
std::stringstream str; str <<a;
return str.str();
}
namespace initialization_tests {
template<typename T>
struct test_initialization_fixture{
typedef tbb::atomic<T> atomic_t;
tbb::aligned_space<atomic_t> non_zeroed_storage;
enum {fill_value = 0xFF };
test_initialization_fixture(){
memset(non_zeroed_storage.begin(),fill_value,sizeof(non_zeroed_storage));
ASSERT( char(fill_value)==*(reinterpret_cast<char*>(non_zeroed_storage.begin()))
,"failed to fill the storage; memset error?");
}
//TODO: consider move it to destructor, even in a price of UB
void tear_down(){
non_zeroed_storage.begin()->~atomic_t();
}
};
template<typename T>
struct TestValueInitialization : test_initialization_fixture<T>{
void operator()(){
typedef typename test_initialization_fixture<T>::atomic_t atomic_type;
//please note that explicit braces below are needed to get zero initialization.
//in C++11, 8.5 Initializers [dcl.init], see paragraphs 10,7,5
new (this->non_zeroed_storage.begin()) atomic_type();
//TODO: add use of KNOWN_ISSUE macro on SunCC 5.11
#if !__SUNPRO_CC || __SUNPRO_CC > 0x5110
//TODO: add printing of typename to the assertion
ASSERT(char(0)==*(reinterpret_cast<char*>(this->non_zeroed_storage.begin()))
,("value initialization for tbb::atomic should do zero initialization; "
"actual value:"+to_string(this->non_zeroed_storage.begin()->load())).c_str());
#endif
this->tear_down();
};
};
template<typename T>
struct TestDefaultInitialization : test_initialization_fixture<T>{
void operator ()(){
typedef typename test_initialization_fixture<T>::atomic_t atomic_type;
new (this->non_zeroed_storage.begin()) atomic_type;
ASSERT( char(this->fill_value)==*(reinterpret_cast<char*>(this->non_zeroed_storage.begin()))
,"default initialization for atomic should do no initialization");
this->tear_down();
}
};
# if __TBB_ATOMIC_CTORS
template<typename T>
struct TestDirectInitialization : test_initialization_fixture<T> {
void operator()(T i){
typedef typename test_initialization_fixture<T>::atomic_t atomic_type;
new (this->non_zeroed_storage.begin()) atomic_type(i);
ASSERT(i == this->non_zeroed_storage.begin()->load()
,("tbb::atomic initialization failed; "
"value:"+to_string(this->non_zeroed_storage.begin()->load())+
"; expected:"+to_string(i)).c_str());
this->tear_down();
}
};
# endif
}
template<typename T>
void TestValueInitialization(){
initialization_tests::TestValueInitialization<T>()();
}
template<typename T>
void TestDefaultInitialization(){
initialization_tests::TestDefaultInitialization<T>()();
}
#if __TBB_ATOMIC_CTORS
template<typename T>
void TestDirectInitialization(T i){
initialization_tests::TestDirectInitialization<T>()(i);
}
//TODO: it would be great to have constructor doing dynamic initialization of local atomic objects implicitly (with zero?),
// but do no dynamic initializations by default for static objects
namespace test_constexpr_initialization_helper {
struct white_box_ad_hoc_type {
int _int;
constexpr white_box_ad_hoc_type(int a =0) : _int(a) {};
constexpr operator int() const { return _int;}
};
}
//some white boxing
namespace tbb { namespace internal {
template<>
struct atomic_impl<test_constexpr_initialization_helper::white_box_ad_hoc_type>: atomic_impl<int> {
atomic_impl() = default;
constexpr atomic_impl(test_constexpr_initialization_helper::white_box_ad_hoc_type value):atomic_impl<int>(value){}
constexpr operator int(){ return this->my_storage.my_value;}
};
}}
//TODO: make this a parameterized macro
void TestConstExprInitializationIsTranslationTime(){
const char* ct_init_failed_msg = "translation time init failed?";
typedef tbb::atomic<int> atomic_t;
constexpr atomic_t a(8);
ASSERT(a == 8,ct_init_failed_msg);
constexpr tbb::atomic<test_constexpr_initialization_helper::white_box_ad_hoc_type> ct_atomic(10);
//for some unknown reason clang does not managed to enum syntax
#if __clang__
constexpr int ct_atomic_value_ten = (int)ct_atomic;
#else
enum {ct_atomic_value_ten = (int)ct_atomic};
#endif
__TBB_STATIC_ASSERT(ct_atomic_value_ten == 10, "translation time init failed?");
ASSERT(ct_atomic_value_ten == 10,ct_init_failed_msg);
int array[ct_atomic_value_ten];
ASSERT(Harness::array_length(array) == 10,ct_init_failed_msg);
}
#include <string>
#include <vector>
namespace TestConstExprInitializationOfGlobalObjectsHelper{
struct static_objects_dynamic_init_order_tester {
static int order_hash;
template<int N> struct nth {
nth(){ order_hash = (order_hash<<4)+N; }
};
static nth<2> second;
static nth<3> third;
};
int static_objects_dynamic_init_order_tester::order_hash=1;
static_objects_dynamic_init_order_tester::nth<2> static_objects_dynamic_init_order_tester::second;
static_objects_dynamic_init_order_tester::nth<3> static_objects_dynamic_init_order_tester::third;
void TestStaticsDynamicInitializationOrder(){
ASSERT(static_objects_dynamic_init_order_tester::order_hash==0x123,"Statics dynamic initialization order is broken? ");
}
template<typename T>
void TestStaticInit();
namespace auto_registered_tests_helper {
template<typename T>
struct type_name ;
#define REGISTER_TYPE_NAME(T) \
namespace auto_registered_tests_helper{ \
template<> \
struct type_name<T> { \
static const char* name; \
}; \
const char* type_name<T>::name = #T; \
} \
typedef void (* p_test_function_type)();
static std::vector<p_test_function_type> const_expr_tests;
template <typename T>
struct registration{
registration(){const_expr_tests.push_back(&TestStaticInit<T>);}
};
}
//according to ISO C++11 [basic.start.init], static data fields of class template have unordered
//initialization unless it is an explicit specialization
template<typename T>
struct tester;
#define TESTER_SPECIALIZATION(T,ct_value) \
template<> \
struct tester<T> { \
struct static_before; \
static bool result; \
static static_before static_before_; \
static tbb::atomic<T> static_atomic; \
\
static auto_registered_tests_helper::registration<T> registered; \
}; \
bool tester<T>::result = false; \
\
struct tester<T>::static_before { \
static_before(){ result = (static_atomic==ct_value); } \
} ; \
\
typename tester<T>::static_before tester<T>::static_before_; \
tbb::atomic<T> tester<T>::static_atomic(ct_value); \
\
auto_registered_tests_helper::registration<T> tester<T>::registered; \
REGISTER_TYPE_NAME(T) \
template<typename T>
void TestStaticInit(){
//TODO: add printing of values to the assertion
std::string type_name = auto_registered_tests_helper::type_name<T>::name;
ASSERT(tester<T>::result,("Static initialization failed for atomic " + type_name).c_str());
}
void CallExprInitTests(){
using namespace auto_registered_tests_helper;
for (size_t i =0; i<const_expr_tests.size(); ++i){
(*const_expr_tests[i])();
}
REMARK("ran %d consrexpr static init test \n",const_expr_tests.size());
}
//TODO: unify somehow list of tested types with one in TestMain
//TODO: add specializations for:
//T,T(-T(1)
//T,1
# if __TBB_64BIT_ATOMICS
TESTER_SPECIALIZATION(long long,8LL)
TESTER_SPECIALIZATION(unsigned long long,8ULL)
# endif
TESTER_SPECIALIZATION(unsigned long,8UL)
TESTER_SPECIALIZATION(long,8L)
TESTER_SPECIALIZATION(unsigned int,8U)
TESTER_SPECIALIZATION(int,8)
TESTER_SPECIALIZATION(unsigned short,8)
TESTER_SPECIALIZATION(short,8)
TESTER_SPECIALIZATION(unsigned char,8)
TESTER_SPECIALIZATION(signed char,8)
TESTER_SPECIALIZATION(char,8)
TESTER_SPECIALIZATION(wchar_t,8)
int dummy;
TESTER_SPECIALIZATION(void*,&dummy);
TESTER_SPECIALIZATION(bool,false);
//TODO: add test for constexpt initialization of floating types
//for some unknown reasons 0.1 becomes 0.10000001 and equality comparison fails
enum written_number_enum{one=2,two};
TESTER_SPECIALIZATION(written_number_enum,one);
//TODO: add test for ArrayElement<> as in TestMain
}
void TestConstExprInitializationOfGlobalObjects(){
//first assert that assumption the test based on are correct
TestConstExprInitializationOfGlobalObjectsHelper::TestStaticsDynamicInitializationOrder();
TestConstExprInitializationOfGlobalObjectsHelper::CallExprInitTests();
}
#endif //__TBB_ATOMIC_CTORS
template<typename T>
void TestOperations( T i, T j, T k ) {
TestValueInitialization<T>();
TestDefaultInitialization<T>();
# if __TBB_ATOMIC_CTORS
TestConstExprInitializationIsTranslationTime();
TestDirectInitialization<T>(i);
TestDirectInitialization<T>(j);
TestDirectInitialization<T>(k);
# endif
TestConst(i);
TestCompareAndSwap(i,j,k);
TestFetchAndStore(i,k); // Pass i,k instead of i,j, because callee requires two distinct values.
}
template<typename T>
void TestParallel( const char* name );
bool ParallelError;
template<typename T>
struct AlignmentChecker {
char c;
tbb::atomic<T> i;
};
//TODO: candidate for test_compiler?
template<typename T>
void TestAlignment( const char* name ) {
AlignmentChecker<T> ac;
tbb::atomic<T> x;
x = T(0);
bool is_stack_variable_aligned = tbb::internal::is_aligned(&x,sizeof(T));
bool is_member_variable_aligned = tbb::internal::is_aligned(&ac.i,sizeof(T));
bool is_struct_size_correct = (sizeof(AlignmentChecker<T>)==2*sizeof(tbb::atomic<T>));
bool known_issue_condition = __TBB_FORCE_64BIT_ALIGNMENT_BROKEN && ( sizeof(T)==8);
//TODO: replace these ifs with KNOWN_ISSUE macro when it available
if (!is_stack_variable_aligned){
std::string msg = "Compiler failed to properly align local atomic variable?; size:"+to_string(sizeof(T)) + " type: "
+to_string(name) + " location:" + to_string(&x) +"\n";
if (known_issue_condition) {
REPORT(("Known issue: "+ msg).c_str());
}else{
ASSERT(false,msg.c_str());
}
}
if (!is_member_variable_aligned){
std::string msg = "Compiler failed to properly align atomic member variable?; size:"+to_string(sizeof(T)) + " type: "
+to_string(name) + " location:" + to_string(&ac.i) +"\n";
if (known_issue_condition) {
REPORT(("Known issue: "+ msg).c_str());
}else{
ASSERT(false,msg.c_str());
}
}
if (!is_struct_size_correct){
std::string msg = "Compiler failed to properly add padding to structure with atomic member variable?; Structure size:"+to_string(sizeof(AlignmentChecker<T>))
+ " atomic size:"+to_string(sizeof(tbb::atomic<T>)) + " type: " + to_string(name) +"\n";
if (known_issue_condition) {
REPORT(("Known issue: "+ msg).c_str());
}else{
ASSERT(false,msg.c_str());
}
}
AlignmentChecker<T> array[5];
for( int k=0; k<5; ++k ) {
bool is_member_variable_in_array_aligned = tbb::internal::is_aligned(&array[k].i,sizeof(T));
if (!is_member_variable_in_array_aligned) {
std::string msg = "Compiler failed to properly align atomic member variable inside an array?; size:"+to_string(sizeof(T)) + " type:"+to_string(name)
+ " location:" + to_string(&array[k].i) + "\n";
if (known_issue_condition){
REPORT(("Known issue: "+ msg).c_str());
}else{
ASSERT(false,msg.c_str());
}
}
}
}
#if _MSC_VER && !defined(__INTEL_COMPILER)
// unary minus operator applied to unsigned type, result still unsigned
#pragma warning( disable: 4146 )
#endif
/** T is an integral type. */
template<typename T>
void TestAtomicInteger( const char* name ) {
REMARK("testing atomic<%s> (size=%d)\n",name,sizeof(tbb::atomic<T>));
TestAlignment<T>(name);
TestOperations<T>(0L,T(-T(1)),T(1));
for( int k=0; k<int(sizeof(long))*8-1; ++k ) {
TestOperations<T>(T(1L<<k),T(~(1L<<k)),T(1-(1L<<k)));
TestOperations<T>(T(-1L<<k),T(~(-1L<<k)),T(1-(-1L<<k)));
TestFetchAndAdd<T>(T(-1L<<k));
}
TestParallel<T>( name );
}
namespace test_indirection_helpers {
template<typename T>
struct Foo {
T x, y, z;
};
}
template<typename T>
void TestIndirection() {
using test_indirection_helpers::Foo;
Foo<T> item;
tbb::atomic<Foo<T>*> pointer;
pointer = &item;
for( int k=-10; k<=10; ++k ) {
// Test various syntaxes for indirection to fields with non-zero offset.
T value1=T(), value2=T();
for( size_t j=0; j<sizeof(T); ++j ) {
((char*)&value1)[j] = char(k^j);
((char*)&value2)[j] = char(k^j*j);
}
pointer->y = value1;
(*pointer).z = value2;
T result1 = (*pointer).y;
T result2 = pointer->z;
ASSERT( memcmp(&value1,&result1,sizeof(T))==0, NULL );
ASSERT( memcmp(&value2,&result2,sizeof(T))==0, NULL );
}
#if __TBB_ICC_BUILTIN_ATOMICS_POINTER_ALIASING_BROKEN
//prevent ICC compiler from assuming 'item' is unused and reusing it's storage
item.x = item.y=item.z;
#endif
}
//! Test atomic<T*>
template<typename T>
void TestAtomicPointer() {
REMARK("testing atomic pointer (%d)\n",int(sizeof(T)));
T array[1000];
TestOperations<T*>(&array[500],&array[250],&array[750]);
TestFetchAndAdd<T*>(&array[500]);
TestIndirection<T>();
TestParallel<T*>( "pointer" );
}
//! Test atomic<Ptr> where Ptr is a pointer to a type of unknown size
template<typename Ptr>
void TestAtomicPointerToTypeOfUnknownSize( const char* name ) {
REMARK("testing atomic<%s>\n",name);
char array[1000];
TestOperations<Ptr>((Ptr)(void*)&array[500],(Ptr)(void*)&array[250],(Ptr)(void*)&array[750]);
TestParallel<Ptr>( name );
}
void TestAtomicBool() {
REMARK("testing atomic<bool>\n");
TestOperations<bool>(true,true,false);
TestOperations<bool>(false,false,true);
TestParallel<bool>( "bool" );
}
template<typename EnumType>
struct HasImplicitConversionToInt {
typedef bool yes;
typedef int no;
__TBB_STATIC_ASSERT( sizeof(yes) != sizeof(no), "The helper needs two types of different sizes to work." );
static yes detect( int );
static no detect( ... );
enum { value = (sizeof(yes) == sizeof(detect( EnumType() ))) };
};
enum Color {Red=0,Green=1,Blue=-1};
void TestAtomicEnum() {
REMARK("testing atomic<Color>\n");
TestOperations<Color>(Red,Green,Blue);
TestParallel<Color>( "Color" );
__TBB_STATIC_ASSERT( HasImplicitConversionToInt< tbb::atomic<Color> >::value, "The implicit conversion is expected." );
}
#if __TBB_SCOPED_ENUM_PRESENT
enum class ScopedColor1 {ScopedRed,ScopedGreen,ScopedBlue=-1};
// TODO: extend the test to cover 2 byte scoped enum as well
#if __TBB_ICC_SCOPED_ENUM_WITH_UNDERLYING_TYPE_NEGATIVE_VALUE_BROKEN
enum class ScopedColor2 : char {ScopedZero, ScopedOne,ScopedRed=42,ScopedGreen=-1,ScopedBlue=127};
#else
enum class ScopedColor2 : char {ScopedZero, ScopedOne,ScopedRed=-128,ScopedGreen=-1,ScopedBlue=127};
#endif
// TODO: replace the hack of getting symbolic enum name with a better implementation
std::string enum_strings[] = {"ScopedZero","ScopedOne","ScopedRed","ScopedGreen","ScopedBlue"};
template<>
std::string to_string<ScopedColor1>(const ScopedColor1& a){
return enum_strings[a==ScopedColor1::ScopedBlue? 4 : (int)a+2];
}
template<>
std::string to_string<ScopedColor2>(const ScopedColor2& a){
return enum_strings[a==ScopedColor2::ScopedRed? 2 :
a==ScopedColor2::ScopedGreen? 3 : a==ScopedColor2::ScopedBlue? 4 : (int)a ];
}
void TestAtomicScopedEnum() {
REMARK("testing atomic<ScopedColor>\n");
TestOperations<ScopedColor1>(ScopedColor1::ScopedRed,ScopedColor1::ScopedGreen,ScopedColor1::ScopedBlue);
TestParallel<ScopedColor1>( "ScopedColor1" );
#if __TBB_ICC_SCOPED_ENUM_WITH_UNDERLYING_TYPE_ATOMIC_LOAD_BROKEN
REPORT("Known issue: the operation tests for a scoped enum with a specified underlying type are skipped.\n");
#else
TestOperations<ScopedColor2>(ScopedColor2::ScopedRed,ScopedColor2::ScopedGreen,ScopedColor2::ScopedBlue);
TestParallel<ScopedColor2>( "ScopedColor2" );
#endif
__TBB_STATIC_ASSERT( !HasImplicitConversionToInt< tbb::atomic<ScopedColor1> >::value, "The implicit conversion is not expected." );
__TBB_STATIC_ASSERT( !HasImplicitConversionToInt< tbb::atomic<ScopedColor1> >::value, "The implicit conversion is not expected." );
__TBB_STATIC_ASSERT( sizeof(tbb::atomic<ScopedColor1>) == sizeof(ScopedColor1), "tbb::atomic instantiated with scoped enum should have the same size as scoped enum." );
__TBB_STATIC_ASSERT( sizeof(tbb::atomic<ScopedColor2>) == sizeof(ScopedColor2), "tbb::atomic instantiated with scoped enum should have the same size as scoped enum." );
}
#endif /* __TBB_SCOPED_ENUM_PRESENT */
template<typename T>
void TestAtomicFloat( const char* name ) {
REMARK("testing atomic<%s>\n", name );
TestAlignment<T>(name);
TestOperations<T>(0.5,3.25,10.75);
TestParallel<T>( name );
}
#define __TBB_TEST_GENERIC_PART_WORD_CAS (__TBB_ENDIANNESS!=__TBB_ENDIAN_UNSUPPORTED)
#if __TBB_TEST_GENERIC_PART_WORD_CAS
void TestEndianness() {
// Test for pure endianness (assumed by simpler probe in __TBB_MaskedCompareAndSwap()).
bool is_big_endian = true, is_little_endian = true;
const tbb::internal::uint32_t probe = 0x03020100;
ASSERT (tbb::internal::is_aligned(&probe,4), NULL);
for( const char *pc_begin = reinterpret_cast<const char*>(&probe)
, *pc = pc_begin, *pc_end = pc_begin + sizeof(probe)
; pc != pc_end; ++pc) {
if (*pc != pc_end-1-pc) is_big_endian = false;
if (*pc != pc-pc_begin) is_little_endian = false;
}
ASSERT (!is_big_endian || !is_little_endian, NULL);
#if __TBB_ENDIANNESS==__TBB_ENDIAN_DETECT
ASSERT (is_big_endian || is_little_endian, "__TBB_ENDIANNESS should be set to __TBB_ENDIAN_UNSUPPORTED");
#elif __TBB_ENDIANNESS==__TBB_ENDIAN_BIG
ASSERT (is_big_endian, "__TBB_ENDIANNESS should NOT be set to __TBB_ENDIAN_BIG");
#elif __TBB_ENDIANNESS==__TBB_ENDIAN_LITTLE
ASSERT (is_little_endian, "__TBB_ENDIANNESS should NOT be set to __TBB_ENDIAN_LITTLE");
#elif __TBB_ENDIANNESS==__TBB_ENDIAN_UNSUPPORTED
#error Generic implementation of part-word CAS may not be used: unsupported endianness
#else
#error Unexpected value of __TBB_ENDIANNESS
#endif
}
namespace masked_cas_helpers {
const int numMaskedOperations = 100000;
const int testSpaceSize = 8;
int prime[testSpaceSize] = {3,5,7,11,13,17,19,23};
template<typename T>
class TestMaskedCAS_Body: NoAssign {
T* test_space_uncontended;
T* test_space_contended;
public:
TestMaskedCAS_Body( T* _space1, T* _space2 ) : test_space_uncontended(_space1), test_space_contended(_space2) {}
void operator()( int my_idx ) const {
using tbb::internal::__TBB_MaskedCompareAndSwap;
const volatile T my_prime = T(prime[my_idx]); // 'volatile' prevents erroneous optimizations by SunCC
T* const my_ptr = test_space_uncontended+my_idx;
T old_value=0;
for( int i=0; i<numMaskedOperations; ++i, old_value+=my_prime ){
T result;
// Test uncontended case
T new_value = old_value + my_prime;
// The following CAS should always fail
result = __TBB_MaskedCompareAndSwap<T>(my_ptr,new_value,old_value-1);
ASSERT(result!=old_value-1, "masked CAS succeeded while it should fail");
ASSERT(result==*my_ptr, "masked CAS result mismatch with real value");
// The following one should succeed
result = __TBB_MaskedCompareAndSwap<T>(my_ptr,new_value,old_value);
ASSERT(result==old_value && *my_ptr==new_value, "masked CAS failed while it should succeed");
// The following one should fail again
result = __TBB_MaskedCompareAndSwap<T>(my_ptr,new_value,old_value);
ASSERT(result!=old_value, "masked CAS succeeded while it should fail");
ASSERT(result==*my_ptr, "masked CAS result mismatch with real value");
// Test contended case
for( int j=0; j<testSpaceSize; ++j ){
// try adding my_prime until success
T value;
do {
value = test_space_contended[j];
result = __TBB_MaskedCompareAndSwap<T>(test_space_contended+j,value+my_prime,value);
} while( result!=value );
}
}
}
};
template<typename T>
struct intptr_as_array_of
{
static const int how_many_Ts = sizeof(intptr_t)/sizeof(T);
union {
intptr_t result;
T space[ how_many_Ts ];
};
};
template<typename T>
intptr_t getCorrectUncontendedValue(int slot_idx) {
intptr_as_array_of<T> slot;
slot.result = 0;
for( int i=0; i<slot.how_many_Ts; ++i ) {
const T my_prime = T(prime[slot_idx*slot.how_many_Ts + i]);
for( int j=0; j<numMaskedOperations; ++j )
slot.space[i] += my_prime;
}
return slot.result;
}
template<typename T>
intptr_t getCorrectContendedValue() {
intptr_as_array_of<T> slot;
slot.result = 0;
for( int i=0; i<slot.how_many_Ts; ++i )
for( int primes=0; primes<testSpaceSize; ++primes )
for( int j=0; j<numMaskedOperations; ++j )
slot.space[i] += prime[primes];
return slot.result;
}
} // namespace masked_cas_helpers
template<typename T>
void TestMaskedCAS() {
using namespace masked_cas_helpers;
REMARK("testing masked CAS<%d>\n",int(sizeof(T)));
const int num_slots = sizeof(T)*testSpaceSize/sizeof(intptr_t);
intptr_t arr1[num_slots+2]; // two more "canary" slots at boundaries
intptr_t arr2[num_slots+2];
for(int i=0; i<num_slots+2; ++i)
arr2[i] = arr1[i] = 0;
T* test_space_uncontended = (T*)(arr1+1);
T* test_space_contended = (T*)(arr2+1);
NativeParallelFor( testSpaceSize, TestMaskedCAS_Body<T>(test_space_uncontended, test_space_contended) );
ASSERT( arr1[0]==0 && arr1[num_slots+1]==0 && arr2[0]==0 && arr2[num_slots+1]==0 , "adjacent memory was overwritten" );
const intptr_t correctContendedValue = getCorrectContendedValue<T>();
for(int i=0; i<num_slots; ++i) {
ASSERT( arr1[i+1]==getCorrectUncontendedValue<T>(i), "unexpected value in an uncontended slot" );
ASSERT( arr2[i+1]==correctContendedValue, "unexpected value in a contended slot" );
}
}
#endif // __TBB_TEST_GENERIC_PART_WORD_CAS
template <typename T>
class TestRelaxedLoadStorePlainBody {
static T s_turn,
s_ready;
public:
static unsigned s_count1,
s_count2;
void operator() ( int id ) const {
using tbb::internal::__TBB_load_relaxed;
using tbb::internal::__TBB_store_relaxed;
if ( id == 0 ) {
while ( !__TBB_load_relaxed(s_turn) ) {
++s_count1;
__TBB_store_relaxed(s_ready, 1);
}
}
else {
while ( !__TBB_load_relaxed(s_ready) ) {
++s_count2;
continue;
}
__TBB_store_relaxed(s_turn, 1);
}
}
}; // class TestRelaxedLoadStorePlainBody<T>
template <typename T> T TestRelaxedLoadStorePlainBody<T>::s_turn = 0;
template <typename T> T TestRelaxedLoadStorePlainBody<T>::s_ready = 0;
template <typename T> unsigned TestRelaxedLoadStorePlainBody<T>::s_count1 = 0;
template <typename T> unsigned TestRelaxedLoadStorePlainBody<T>::s_count2 = 0;
template <typename T>
class TestRelaxedLoadStoreAtomicBody {
static tbb::atomic<T> s_turn,
s_ready;
public:
static unsigned s_count1,
s_count2;
void operator() ( int id ) const {
if ( id == 0 ) {
while ( s_turn.template load<tbb::relaxed>() == 0 ) {
++s_count1;
s_ready.template store<tbb::relaxed>(1);
}
}
else {
while ( s_ready.template load<tbb::relaxed>() == 0 ) {
++s_count2;
continue;
}
s_turn.template store<tbb::relaxed>(1);
}
}
}; // class TestRelaxedLoadStoreAtomicBody<T>
template <typename T> tbb::atomic<T> TestRelaxedLoadStoreAtomicBody<T>::s_turn;
template <typename T> tbb::atomic<T> TestRelaxedLoadStoreAtomicBody<T>::s_ready;
template <typename T> unsigned TestRelaxedLoadStoreAtomicBody<T>::s_count1 = 0;
template <typename T> unsigned TestRelaxedLoadStoreAtomicBody<T>::s_count2 = 0;
template <typename T>
void TestRegisterPromotionSuppression () {
REMARK("testing register promotion suppression (size=%d)\n", (int)sizeof(T));
NativeParallelFor( 2, TestRelaxedLoadStorePlainBody<T>() );
NativeParallelFor( 2, TestRelaxedLoadStoreAtomicBody<T>() );
}
template<unsigned N>
class ArrayElement {
char item[N];
};
#include "harness_barrier.h"
namespace bit_operation_test_suite{
struct fixture : NoAssign{
static const uintptr_t zero = 0;
const uintptr_t random_value ;
const uintptr_t inverted_random_value ;
fixture():
random_value (tbb::internal::select_size_t_constant<0x9E3779B9,0x9E3779B97F4A7C15ULL>::value),
inverted_random_value ( ~random_value)
{}
};
struct TestAtomicORSerially : fixture {
void operator()(){
//these additional variable are needed to get more meaningful expression in the assert
uintptr_t initial_value = zero;
uintptr_t atomic_or_result = initial_value;
uintptr_t atomic_or_operand = random_value;
__TBB_AtomicOR(&atomic_or_result,atomic_or_operand);
ASSERT(atomic_or_result == (initial_value | atomic_or_operand),"AtomicOR should do the OR operation");
}
};
struct TestAtomicANDSerially : fixture {
void operator()(){
//these additional variable are needed to get more meaningful expression in the assert
uintptr_t initial_value = inverted_random_value;
uintptr_t atomic_and_result = initial_value;
uintptr_t atomic_and_operand = random_value;
__TBB_AtomicAND(&atomic_and_result,atomic_and_operand);
ASSERT(atomic_and_result == (initial_value & atomic_and_operand),"AtomicAND should do the AND operation");