-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathLanguageTestUtils.cpp
More file actions
2153 lines (1632 loc) · 64.6 KB
/
LanguageTestUtils.cpp
File metadata and controls
2153 lines (1632 loc) · 64.6 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
#include "LanguageTestUtils.h"
#if BUILD_TESTS
#include "wnt_Lexer.h"
#include "TokenBase.h"
#include "wnt_LangParser.h"
#include "wnt_ASTNode.h"
#include "wnt_MathsFuncs.h"
#include "VMState.h"
#include "Linker.h"
#include "Value.h"
#include "CompiledValue.h"
#include <TestUtils.h>
#include <StandardPrintOutput.h>
#include <Mutex.h>
#include <Lock.h>
#include <Exception.h>
#include <Vector.h>
#include <ConPrint.h>
#include <Platform.h>
#include <FileUtils.h>
#include <StringUtils.h>
#include <ContainerUtils.h>
#include <PlatformUtils.h>
#include <Timer.h>
#include <cassert>
#include <fstream>
#ifdef _WIN32
#include <intrin.h>
#endif
//#include "utils/Obfuscator.h"
#if WINTER_OPENCL_SUPPORT
#define WINTER_OPENCL_TESTS 1
#endif
static const bool DUMP_OPENCL_C_SOURCE = false; // Dumps to opencl_source.c
static const bool PRINT_MEM_BOUNDS_AND_USAGE = false;
// Checking stack size usage doesn't seem to be working properly on macOS yet.
#if defined(__APPLE__)
static const bool CHECK_STACK_USAGE = false;
#else
static const bool CHECK_STACK_USAGE = true;
#endif
// OpenCL:
#if WINTER_OPENCL_SUPPORT && WINTER_OPENCL_TESTS
#include <opencl/OpenCL.h>
#include <opencl/OpenCLBuffer.h>
#include <opencl/OpenCLKernel.h>
#include <opencl/OpenCLContext.h>
#include <opencl/OpenCLProgram.h>
#include <opencl/OpenCLCommandQueue.h>
#endif
namespace Winter
{
/*
Example of stack marked zone:
stack info for current func
sp ---------------
0x12
0x45
0x3a
0x42
sp - 4 --------------------
0xab
0xa6
sp - 6
0xEE
0xEE
sp - 8-------------------
0xEE
0xEE
0xEE
0xEE
In this case, sp - 6 contains the lowest byte that is not 0xEE.
*/
// Stack marking stuff is causing a crash on macOS currently, also in VS2019. So just disable for now.
#if 1
#define MARK_STACK
#define GET_TOUCHED_STACK_SIZE(touched_stack_size_out) touched_stack_size_out = 0;
#else
static const int MARKED_ZONE_SIZE = 1000;
// Put some special byte patterns on the stack
// Store 0xEE for MARKED_ZONE_SIZE bytes below the current stack
#define MARK_STACK \
uint8* _sp = (uint8*)getStackPointer(); \
for(uint8* p = _sp - MARKED_ZONE_SIZE; p < _sp; ++p) \
*p = 0xEE;
// Try and detect how much stack we actually used.
// We will do this by finding the lowest byte in the marked area that is not 0xEE.
#define GET_TOUCHED_STACK_SIZE(touched_stack_size_out) \
touched_stack_size_out = 0; \
for(uint8* p = _sp - MARKED_ZONE_SIZE; p < _sp; ++p) \
{ \
if(*p != 0xEE) \
{ \
touched_stack_size_out = _sp - p; \
break; \
} \
}
// Returns the stack pointer (value in RSP register) of the calling function.
static GLARE_NO_INLINE void* getStackPointer()
{
// The return address of this function is stored immediately below where RSP for the calling function points to.
#ifdef _WIN32
return (void*)((char*)_AddressOfReturnAddress() + sizeof(void*));
#else
return (void*)((char*)__builtin_frame_address(0) + sizeof(void*));
#endif
}
#endif
static bool epsEqual(float x, float y)
{
return std::fabs(x - y) < 1.0e-5f;
}
static bool epsEqual(double x, double y)
{
return std::fabs(x - y) < 1.0e-5;
}
struct TestEnv
{
float val;
};
static void testPrint(const std::string& s)
{
// Actually printing out stuff makes the tests dramatically slower to run (like 1.7s -> 6s)
// conPrint(s);
}
typedef float(WINTER_JIT_CALLING_CONV * float_void_func)();
TestResults testMainFloat(const std::string& src, float target_return_val)
{
testPrint("===================== Winter testMainFloat() =====================");
try
{
VMConstructionArgs vm_args;
vm_args.source_buffers.push_back(new SourceBuffer("buffer", src));
vm_args.floating_point_literals_default_to_double = false;
vm_args.real_is_double = false;
const FunctionSignature mainsig("main", std::vector<TypeVRef>());
vm_args.entry_point_sigs.push_back(mainsig);
VirtualMachineRef vm = new VirtualMachine(vm_args);
// Get main function
Reference<FunctionDefinition> maindef = vm->findMatchingFunction(mainsig);
void* f = vm->getJittedFunction(mainsig);
//// cast to correct type
float_void_func mainf = (float_void_func)f;
//// Call the JIT'd function
const float jitted_result = mainf();
// Check JIT'd result.
if(!epsEqual(jitted_result, target_return_val))
{
failTest("Test failed: JIT'd main returned " + toString(jitted_result) + ", target was " + toString(target_return_val));
}
VMState vmstate(/*value allocator=*/nullptr);
vmstate.func_args_start.push_back(0);
ValueRef retval = maindef->invoke(vmstate);
// assert(vmstate.argument_stack.size() == 1);
//delete vmstate.argument_stack[0];
vmstate.func_args_start.pop_back();
if(retval->valueType() != Value::ValueType_Float)
failTest("main() Return value was of unexpected type.");
FloatValue* val = static_cast<FloatValue*>(retval.getPointer());
if(!epsEqual(val->value, target_return_val))
failTest("Test failed: main returned " + toString(val->value) + ", target was " + toString(target_return_val));
TestResults res;
res.stats = vm->getProgramStats();
res.maindef = maindef;
return res;
}
catch(Winter::BaseException& e)
{
failTest(e.what());
exit(1);
}
}
void testMainFloatArgInvalidProgram(const std::string& src)
{
testPrint("===================== Winter testMainFloatArgInvalidProgram() =====================");
try
{
VMConstructionArgs vm_args;
vm_args.source_buffers.push_back(SourceBufferRef(new SourceBuffer("buffer", src)));
vm_args.real_is_double = false;
const FunctionSignature mainsig("main", std::vector<TypeVRef>(1, new Float()));
vm_args.entry_point_sigs.push_back(mainsig);
VirtualMachine vm(vm_args);
// Get main function
Reference<FunctionDefinition> maindef = vm.findMatchingFunction(mainsig);
//if(maindef.isNull())
// throw BaseException("Failed to find function " + mainsig.toString());
//if(maindef->returnType()->getType() != Type::FloatType)
// throw BaseException("main did not return float.");
vm.getJittedFunction(mainsig);
failTest("Test failed: Expected compilation failure.");
}
catch(Winter::BaseException& e)
{
// Expected.
testPrint("Expected exception occurred: " + e.messageWithPosition());
}
}
static TestResults doTestMainFloatArg(const std::string& src, float argument, float target_return_val,
bool check_constant_folded_to_literal, uint32 test_flags, const std::vector<ExternalFunctionRef>* external_funcs)
{
testPrint("===================== Winter testMainFloatArg() =====================");
try
{
/*Obfuscator obfusctor(
true, // collapse_whitespace
true, // remove_comments
true, // change tokens
Obfuscator::Lang_Winter
);
const std::string obfuscated_src = obfusctor.obfuscateWinterSource(src);
std::cout << "==================== original src: =====================" << std::endl;
std::cout << src << std::endl;
std::cout << "==================== obfuscated_src: =====================" << std::endl;
std::cout << obfuscated_src << std::endl;
std::cout << "==========================================================" << std::endl;*/
VMConstructionArgs vm_args;
vm_args.source_buffers.push_back(SourceBufferRef(new SourceBuffer("buffer", src)));
vm_args.allow_unsafe_operations = (test_flags & ALLOW_UNSAFE) != 0;
vm_args.floating_point_literals_default_to_double = false;
vm_args.try_coerce_int_to_double_first = false;
vm_args.real_is_double = false;
vm_args.opencl_double_support = false; // This will allow this test to run on an OpenCL device without double fp support.
if(test_flags & DISABLE_CONSTANT_FOLDING)
vm_args.do_constant_folding = false;
if(test_flags & INCLUDE_EXTERNAL_MATHS_FUNCS)
MathsFuncs::appendExternalMathsFuncs(vm_args.external_functions);
if(external_funcs)
ContainerUtils::append(vm_args.external_functions, *external_funcs);
const FunctionSignature mainsig("main", std::vector<TypeVRef>(1, new Float()));
vm_args.entry_point_sigs.push_back(mainsig);
const FunctionSignature entryPoint2sig("entryPoint2", std::vector<TypeVRef>(1, new Float()));
vm_args.entry_point_sigs.push_back(entryPoint2sig);
VirtualMachine vm(vm_args);
// Get main function
Reference<FunctionDefinition> maindef = vm.findMatchingFunction(mainsig);
if(maindef.isNull())
throw BaseException("Failed to find function " + mainsig.toString());
if(maindef->returnType()->getType() != Type::FloatType)
throw BaseException("main did not return float.");
if(check_constant_folded_to_literal)
if(maindef->body.isNull() || maindef->body->nodeType() != ASTNode::FloatLiteralType) // body may be null if it is a built-in function (e.g. elem())
throw BaseException("main was not folded to a float literal.");
float(WINTER_JIT_CALLING_CONV*f)(float) = (float(WINTER_JIT_CALLING_CONV*)(float))vm.getJittedFunction(mainsig);
resetMemUsageStats();
// Put some special byte patterns on the stack
MARK_STACK;
//================= Call the JIT'd function ====================
const float jitted_result = f(argument);
// Try and detect how much stack we actually used.
size_t touched_stack_size;
GET_TOUCHED_STACK_SIZE(touched_stack_size);
// Check JIT'd result.
if(!epsEqual(jitted_result, target_return_val))
failTest("Test failed: JIT'd main returned " + toString(jitted_result) + ", target was " + toString(target_return_val));
testAssert(getCurrentHeapMemUsage() == 0);
try
{
GetSpaceBoundParams params;
GetSpaceBoundResults space_bounds = maindef->getSpaceBound(params);
// Compute space bounds for arg
const size_t arg_heap_size = 0;
const size_t total_allowed_heap = space_bounds.heap_space + arg_heap_size;
if(PRINT_MEM_BOUNDS_AND_USAGE)
{
conPrint("stack space bound: " + toString(space_bounds.stack_space));
conPrint("stack used: " + toString(touched_stack_size));
conPrint("heap space bound: " + toString(total_allowed_heap));
conPrint("heap used: " + toString(getMaxHeapMemUsage()));
conPrint("");
}
testAssert(getMaxHeapMemUsage() <= total_allowed_heap);
if(CHECK_STACK_USAGE) testAssert(touched_stack_size <= space_bounds.stack_space);
}
catch(BaseException& e)
{
conPrint("Failed to get space bound: " + e.messageWithPosition());
if((test_flags & ALLOW_SPACE_BOUND_FAILURE) == 0)
failTest("Failed to get space bound: " + e.messageWithPosition());
}
try
{
GetTimeBoundParams params;
const size_t time_bound = maindef->getTimeBound(params);
if(time_bound > (1 << 22)) // Just do something with the time bound so it doesn't get compiled away.
failTest("Time bound too large.");
}
catch(BaseException& e)
{
conPrint("Failed to get time bound: " + e.messageWithPosition());
if((test_flags & ALLOW_TIME_BOUND_FAILURE) == 0)
failTest("Failed to get time bound: " + e.messageWithPosition());
}
VMState vmstate(/*value allocator=*/nullptr);
vmstate.func_args_start.push_back(0);
vmstate.argument_stack.push_back(new FloatValue(argument));
ValueRef retval = maindef->invoke(vmstate);
vmstate.func_args_start.pop_back();
if(retval->valueType() != Value::ValueType_Float)
failTest("main() Return value was of unexpected type.");
FloatValue* val = static_cast<FloatValue*>(retval.getPointer());
if(!epsEqual(val->value, target_return_val))
failTest("Test failed: main returned " + toString(val->value) + ", target was " + toString(target_return_val));
//delete retval;
//============================= New: test with OpenCL ==============================
if(!(test_flags & INVALID_OPENCL))
{
#if WINTER_OPENCL_TESTS
if(::getGlobalOpenCL() && !::getGlobalOpenCL()->getOpenCLDevices().empty())
{
Winter::VirtualMachine::BuildOpenCLCodeArgs opencl_args;
std::string opencl_code = vm.buildOpenCLCodeCombined(opencl_args);
std::string extended_source = opencl_code + "\n" + "__kernel void main_kernel(float x, __global float * const restrict output_buffer) { \n" +
" output_buffer[0] = main_float_(x); \n" +
" }";
if(false)
{
conPrint("!!! USING SRC FROM test_opencl_source.c !!!");
extended_source = FileUtils::readEntireFileTextMode("test_opencl_source.c");
}
else
{
if(DUMP_OPENCL_C_SOURCE)
{
std::ofstream file("opencl_source.c");
file << extended_source;
conPrint("Dumped OpenCL C source to " + PlatformUtils::getCurrentWorkingDirPath() + "/opencl_source.c.");
}
}
const OpenCLDeviceRef device = ::getGlobalOpenCL()->getOpenCLDevices()[0];
std::vector<OpenCLDeviceRef> devices(1, device);
OpenCLContextRef context = new OpenCLContext(device->opencl_platform_id);
OpenCLCommandQueueRef command_queue = new OpenCLCommandQueue(context, device->opencl_device_id, /*profiling=*/false);
std::string build_log;
OpenCLProgramRef program;
try
{
program = ::getGlobalOpenCL()->buildProgram(
extended_source,
context,
devices,
"", //"-cl-nv-verbose", // options
build_log
);
}
catch(glare::Exception& e)
{
failTest("Build failed: " + e.what() + "\nOpenCL device: " + device->description() + "\nbuild_log:\n" + build_log);
}
if(DUMP_OPENCL_C_SOURCE)
{
// Print build log:
const std::string log = ::getGlobalOpenCL()->getBuildLog(program->getProgram(), device->opencl_device_id);
conPrint("build_log: \n" + log);
// Dump program binary:
std::vector<OpenCLProgram::Binary> binaries;
program->getProgramBinaries(binaries);
for(size_t i=0; i<binaries.size(); ++i)
{
const std::string path = "binary_" + toString(i) + ".txt";
FileUtils::writeEntireFile(path, (const char*)binaries[i].data.data(), binaries[i].data.size());
conPrint("Wrote program binary to '" + path + "'.");
}
}
OpenCLKernelRef kernel = new OpenCLKernel(program, "main_kernel", device->opencl_device_id, /*profile=*/false);
OpenCLBuffer output_buffer(context, sizeof(float), CL_MEM_READ_WRITE);
kernel->setKernelArgFloat(0, argument);
kernel->setKernelArgBuffer(1, output_buffer.getDevicePtr());
// Launch the kernel
const size_t global_work_size = 1;
kernel->launchKernel(command_queue->getCommandQueue(), global_work_size);
SSE_ALIGN float host_output_buffer[1];
// Read back result
cl_int result = ::getGlobalOpenCL()->clEnqueueReadBuffer(
command_queue->getCommandQueue(),
output_buffer.getDevicePtr(), // buffer
CL_TRUE, // blocking read
0, // offset
sizeof(float), // size in bytes
host_output_buffer, // host buffer pointer
0, // num events in wait list
NULL, // wait list
NULL // event
);
if(result != CL_SUCCESS)
throw glare::Exception("clEnqueueReadBuffer failed: " + OpenCL::errorString(result));
const float opencl_result = host_output_buffer[0];
if(!epsEqual(opencl_result, target_return_val))
failTest("Test failed: OpenCL returned " + toString(opencl_result) + ", target was " + toString(target_return_val));
}
#endif // #if WINTER_OPENCL_TESTS
}
TestResults res;
res.stats = vm.getProgramStats();
res.maindef = maindef;
return res;
}
catch(Winter::BaseException& e)
{
failTest(e.messageWithPosition());
}
catch(glare::Exception& e)
{
failTest(e.what());
}
exit(1);
}
size_t getTimeBoundForMainFloatArg(const std::string& src, uint32 test_flags)
{
testPrint("===================== Winter getTimeBoundForMainFloatArg() =====================");
try
{
VMConstructionArgs vm_args;
vm_args.source_buffers.push_back(new SourceBuffer("buffer", src));
vm_args.allow_unsafe_operations = (test_flags & ALLOW_UNSAFE) != 0;
vm_args.floating_point_literals_default_to_double = false;
vm_args.try_coerce_int_to_double_first = false;
vm_args.real_is_double = false;
if(test_flags & DISABLE_CONSTANT_FOLDING)
vm_args.do_constant_folding = false;
if(test_flags & INCLUDE_EXTERNAL_MATHS_FUNCS)
MathsFuncs::appendExternalMathsFuncs(vm_args.external_functions);
const FunctionSignature mainsig("main", std::vector<TypeVRef>(1, new Float()));
vm_args.entry_point_sigs.push_back(mainsig);
Timer timer;
VirtualMachine vm(vm_args);
conPrint("Virtual machine build time: " + timer.elapsedString());
// Get main function
Reference<FunctionDefinition> maindef = vm.findMatchingFunction(mainsig);
if(maindef.isNull()) throw BaseException("Failed to find function " + mainsig.toString());
if(maindef->returnType()->getType() != Type::FloatType) throw BaseException("main did not return float.");
timer.reset();
GetTimeBoundParams params;
const size_t bound = maindef->getTimeBound(params);
conPrint("Computing time bound took " + timer.elapsedString());
return bound;
}
catch(Winter::BaseException& e)
{
failTest(e.what());
exit(1);
}
}
void testTimeBoundInvalidForMainFloatArg(const std::string& src, uint32 test_flags)
{
testPrint("===================== Winter testTimeBoundInvalidForMainFloatArg() =====================");
try
{
VMConstructionArgs vm_args;
vm_args.source_buffers.push_back(new SourceBuffer("buffer", src));
vm_args.allow_unsafe_operations = (test_flags & ALLOW_UNSAFE) != 0;
vm_args.floating_point_literals_default_to_double = false;
vm_args.try_coerce_int_to_double_first = false;
vm_args.real_is_double = false;
if(test_flags & DISABLE_CONSTANT_FOLDING)
vm_args.do_constant_folding = false;
if(test_flags & INCLUDE_EXTERNAL_MATHS_FUNCS)
MathsFuncs::appendExternalMathsFuncs(vm_args.external_functions);
const FunctionSignature mainsig("main", std::vector<TypeVRef>(1, new Float()));
vm_args.entry_point_sigs.push_back(mainsig);
Timer timer;
VirtualMachine vm(vm_args);
conPrint("Virtual machine build time: " + timer.elapsedString());
// Get main function
Reference<FunctionDefinition> maindef = vm.findMatchingFunction(mainsig);
if(maindef.isNull()) throw BaseException("Failed to find function " + mainsig.toString());
if(maindef->returnType()->getType() != Type::FloatType) throw BaseException("main did not return float.");
timer.reset();
try
{
GetTimeBoundParams params;
maindef->getTimeBound(params);
failTest("Error: expected getTimeBound() to throw an exception.");
}
catch(Winter::BaseException& e)
{
conPrint("Caught expected exception from getTimeBound(): " + e.messageWithPosition());
conPrint("Computing time bound took " + timer.elapsedString());
}
}
catch(Winter::BaseException& e)
{
failTest(e.what());
}
}
static TestResults doTestMainDoubleArg(const std::string& src, double argument, double target_return_val, bool check_constant_folded_to_literal, uint32 test_flags)
{
testPrint("===================== Winter doTestMainDoubleArg() =====================");
try
{
VMConstructionArgs vm_args;
vm_args.source_buffers.push_back(SourceBufferRef(new SourceBuffer("buffer", src)));
vm_args.allow_unsafe_operations = (test_flags & ALLOW_UNSAFE) != 0;
vm_args.floating_point_literals_default_to_double = true;
vm_args.real_is_double = true;
vm_args.opencl_double_support = true;
if(test_flags & DISABLE_CONSTANT_FOLDING)
vm_args.do_constant_folding = false;
if(test_flags & INCLUDE_EXTERNAL_MATHS_FUNCS)
MathsFuncs::appendExternalMathsFuncs(vm_args.external_functions);
/*{
ExternalFunctionRef f(new ExternalFunction());
f->func = (void*)testExternalFunc;
f->interpreted_func = testExternalFuncInterpreted;
f->return_type = TypeRef(new Float());
f->sig = FunctionSignature("testExternalFunc", std::vector<TypeVRef>(1, new Float()));
vm_args.external_functions.push_back(f);
}*/
const FunctionSignature mainsig("main", std::vector<TypeVRef>(1, new Double()));
vm_args.entry_point_sigs.push_back(mainsig);
VirtualMachine vm(vm_args);
// Get main function
Reference<FunctionDefinition> maindef = vm.findMatchingFunction(mainsig);
if(maindef.isNull())
throw BaseException("Failed to find function " + mainsig.toString());
if(maindef->returnType()->getType() != Type::DoubleType)
throw BaseException("main did not return double.");
//if(check_constant_folded_to_literal)
// if(maindef->body.isNull() || maindef->body->nodeType() != ASTNode::DoubleLiteralType) // body may be null if it is a built-in function (e.g. elem())
// throw BaseException("main was not folded to a float literal.");
double(WINTER_JIT_CALLING_CONV*f)(double) = (double(WINTER_JIT_CALLING_CONV*)(double))vm.getJittedFunction(mainsig);
// Call the JIT'd function
const double jitted_result = f(argument);
// Check JIT'd result.
if(!epsEqual(jitted_result, target_return_val))
failTest("Test failed: JIT'd main returned " + toString(jitted_result) + ", target was " + toString(target_return_val));
VMState vmstate(/*value allocator=*/nullptr);
vmstate.func_args_start.push_back(0);
vmstate.argument_stack.push_back(new DoubleValue(argument));
ValueRef retval = maindef->invoke(vmstate);
vmstate.func_args_start.pop_back();
if(retval->valueType() != Value::ValueType_Double)
failTest("main() Return value was of unexpected type.");
DoubleValue* val = static_cast<DoubleValue*>(retval.getPointer());
if(!epsEqual(val->value, target_return_val))
failTest("Test failed: main returned " + toString(val->value) + ", target was " + toString(target_return_val));
//delete retval;
//============================= New: test with OpenCL ==============================
if(!(test_flags & INVALID_OPENCL))
{
#if WINTER_OPENCL_TESTS
if(::getGlobalOpenCL() && !::getGlobalOpenCL()->getOpenCLDevices().empty())
{
// Look through the OpenCL devices for a device that supports doubles.
int device_index = -1;
for(size_t z=0; z<::getGlobalOpenCL()->getOpenCLDevices().size(); ++z)
if(::getGlobalOpenCL()->getOpenCLDevices()[z]->supports_doubles)
{
device_index = (int)z;
break;
}
if(device_index == -1)
{
conPrint("Skipping OpenCL tests in doTestMainDoubleArg() as could not find OpenCL device with double floating-point support.");
}
else
{
Winter::VirtualMachine::BuildOpenCLCodeArgs opencl_args;
std::string opencl_code = vm.buildOpenCLCodeCombined(opencl_args);
const std::string extended_source = opencl_code + "\n" + "__kernel void main_kernel(double x, __global double * const restrict output_buffer) { \n" +
" output_buffer[0] = main_double_(x); \n" +
" }";
if(DUMP_OPENCL_C_SOURCE)
{
std::ofstream file("opencl_source.c");
file << extended_source;
conPrint("Dumped OpenCL C source to opencl_source.c.");
}
const OpenCLDeviceRef& device = ::getGlobalOpenCL()->getOpenCLDevices()[device_index];
std::vector<OpenCLDeviceRef> devices(1, device);
OpenCLContextRef context = new OpenCLContext(device->opencl_platform_id);
OpenCLCommandQueueRef command_queue = new OpenCLCommandQueue(context, device->opencl_device_id, /*profile=*/false);
std::string build_log;
OpenCLProgramRef program;
try
{
program = ::getGlobalOpenCL()->buildProgram(
extended_source,
context,
devices,
"", // options
build_log
);
}
catch(glare::Exception& e)
{
failTest("Build failed: " + e.what() + "\nOpenCL device: " + device->description() + "\nbuild_log:\n" + build_log + "\nextended_source: \n" + extended_source);
}
//conPrint("build_log: \n" + build_log);
OpenCLKernelRef kernel = new OpenCLKernel(program, "main_kernel", device->opencl_device_id, /*profile=*/false);
OpenCLBuffer output_buffer(context, sizeof(double), CL_MEM_READ_WRITE);
kernel->setKernelArgDouble(0, argument);
kernel->setKernelArgBuffer(1, output_buffer.getDevicePtr());
const size_t global_work_size = 1;
kernel->launchKernel(command_queue->getCommandQueue(), global_work_size);
SSE_ALIGN double host_output_buffer[1];
// Read back result
cl_int result = ::getGlobalOpenCL()->clEnqueueReadBuffer(
command_queue->getCommandQueue(),
output_buffer.getDevicePtr(), // buffer
CL_TRUE, // blocking read
0, // offset
sizeof(double), // size in bytes
host_output_buffer, // host buffer pointer
0, // num events in wait list
NULL, // wait list
NULL // event
);
if(result != CL_SUCCESS)
throw glare::Exception("clEnqueueReadBuffer failed: " + OpenCL::errorString(result));
const double opencl_result = host_output_buffer[0];
if(!epsEqual(opencl_result, target_return_val))
{
failTest("Test failed: OpenCL returned " + toString(opencl_result) + ", target was " + toString(target_return_val));
}
}
}
#endif // #if WINTER_OPENCL_TESTS
}
TestResults res;
res.stats = vm.getProgramStats();
res.maindef = maindef;
return res;
}
catch(Winter::BaseException& e)
{
failTest(e.what());
}
catch(glare::Exception& e)
{
failTest(e.what());
}
exit(1);
}
TestResults testMainFloatArg(const std::string& src, float argument, float target_return_val, uint32 test_flags, const std::vector<ExternalFunctionRef>* external_funcs)
{
return doTestMainFloatArg(src, argument, target_return_val,
false, // check constant-folded to literal
test_flags,
external_funcs
);
}
TestResults testMainDoubleArg(const std::string& src, double argument, double target_return_val, uint32 test_flags)
{
return doTestMainDoubleArg(src, argument, target_return_val,
false, // check constant-folded to literal
test_flags
);
}
TestResults testMainFloatArgAllowUnsafe(const std::string& src, float argument, float target_return_val, uint32 test_flags)
{
return doTestMainFloatArg(src, argument, target_return_val,
false, // check constant-folded to literal
test_flags | ALLOW_UNSAFE,
NULL // external funcs
);
}
TestResults testMainFloatArgCheckConstantFolded(const std::string& src, float argument, float target_return_val, uint32 test_flags,
const std::vector<ExternalFunctionRef>* external_funcs)
{
return doTestMainFloatArg(src, argument, target_return_val,
true, // check constant-folded to literal
test_flags,
external_funcs
);
}
void testMainInteger(const std::string& src, int target_return_val)
{
testPrint("===================== Winter testMainInteger() =====================");
try
{
VMConstructionArgs vm_args;
vm_args.source_buffers.push_back(SourceBufferRef(new SourceBuffer("buffer", src)));
const FunctionSignature mainsig("main", std::vector<TypeVRef>());
vm_args.entry_point_sigs.push_back(mainsig);
VirtualMachine vm(vm_args);
// Get main function
Reference<FunctionDefinition> maindef = vm.findMatchingFunction(mainsig);
int (WINTER_JIT_CALLING_CONV *f)() = (int (WINTER_JIT_CALLING_CONV *)()) vm.getJittedFunction(mainsig);
// Call the JIT'd function
const int jitted_result = f();
// Check JIT'd result.
if(jitted_result != target_return_val)
failTest("Test failed: JIT'd main returned " + toString(jitted_result) + ", target was " + toString(target_return_val));
VMState vmstate(/*value allocator=*/nullptr);
vmstate.func_args_start.push_back(0);
ValueRef retval = maindef->invoke(vmstate);
vmstate.func_args_start.pop_back();
if(retval->valueType() != Value::ValueType_Int)
failTest("main() Return value was of unexpected type.");
IntValue* val = static_cast<IntValue*>(retval.getPointer());
if(val->value != target_return_val)
failTest("Test failed: main returned " + toString(val->value) + ", target was " + toString(target_return_val));
//delete retval;
}
catch(Winter::BaseException& e)
{
failTest(e.what());
}
}
void testMainStringArg(const std::string& src, const std::string& arg, const std::string& target_return_val, uint32 test_flags)
{
testPrint("===================== Winter testMainStringArg() =====================");
try
{
VMConstructionArgs vm_args;
vm_args.allow_unsafe_operations = (test_flags & ALLOW_UNSAFE) != 0;
vm_args.source_buffers.push_back(SourceBufferRef(new SourceBuffer("buffer", src)));
if(test_flags & DISABLE_CONSTANT_FOLDING)
vm_args.do_constant_folding = false;
const FunctionSignature mainsig("main", std::vector<TypeVRef>(1, new String()));
vm_args.entry_point_sigs.push_back(mainsig);
VirtualMachine vm(vm_args);
// Get main function
Reference<FunctionDefinition> maindef = vm.findMatchingFunction(mainsig);
StringRep* (WINTER_JIT_CALLING_CONV *f)(const StringRep*) = (StringRep* (WINTER_JIT_CALLING_CONV *)(const StringRep*)) vm.getJittedFunction(mainsig);
testAssert(getCurrentHeapMemUsage() == 0);
resetMemUsageStats();
size_t touched_stack_size = 0;
{ // Scope for CompiledValRefs
CompiledValRef<StringRep> arg_string_ref = allocateString(arg.c_str());
// Call the JIT'd function
MARK_STACK; // Put some special byte patterns on the stack
CompiledValRef<StringRep> jitted_result = f(arg_string_ref.getPointer());
// Try and detect how much stack we actually used.
GET_TOUCHED_STACK_SIZE(touched_stack_size);
jitted_result->refcount--; // The jitted func will return a result with refcount 1
// Check JIT'd result.
if(jitted_result->toStdString() != target_return_val)
failTest("Test failed: JIT'd main returned " + jitted_result->toStdString() + ", target was " + target_return_val);
testAssert(arg_string_ref->getRefCount() == 1);
testAssert(jitted_result->getRefCount() == 1);
}
testAssert(getCurrentHeapMemUsage() == 0);
try
{
GetSpaceBoundParams params;
GetSpaceBoundResults space_bounds = maindef->getSpaceBound(params);
// Compute space bounds for arg
const size_t arg_heap_size = sizeof(StringRep) + arg.size();
const size_t total_allowed_heap = space_bounds.heap_space + arg_heap_size;
if(PRINT_MEM_BOUNDS_AND_USAGE)
{
conPrint("stack space bound: " + toString(space_bounds.stack_space));
conPrint("stack used: " + toString(touched_stack_size));
conPrint("heap space bound: " + toString(total_allowed_heap));
conPrint("heap used: " + toString(getMaxHeapMemUsage()));
conPrint("");
}
testAssert(getMaxHeapMemUsage() <= total_allowed_heap);
if(CHECK_STACK_USAGE) testAssert(touched_stack_size <= space_bounds.stack_space);
}
catch(BaseException& e)
{
conPrint("Failed to get space bound: " + e.messageWithPosition());
if((test_flags & ALLOW_SPACE_BOUND_FAILURE) == 0)
failTest("Failed to get space bound: " + e.messageWithPosition());
}
try
{
GetTimeBoundParams params;
const size_t time_bound = maindef->getTimeBound(params);
if(time_bound > (1 << 22)) // Just do something with the time bound so it doesn't get compiled away.
failTest("Time bound too large.");
}
catch(BaseException& e)
{
conPrint("Failed to get time bound: " + e.messageWithPosition());
if((test_flags & ALLOW_TIME_BOUND_FAILURE) == 0)
failTest("Failed to get time bound: " + e.messageWithPosition());
}