-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathVirtualMachine.cpp
2279 lines (1837 loc) · 73.9 KB
/
VirtualMachine.cpp
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
/*=====================================================================
VirtualMachine.cpp
------------------
Copyright Glare Technologies Limited 2018 -
Generated at Mon Sep 13 22:23:44 +1200 2010
=====================================================================*/
#include "VirtualMachine.h"
#include "Linker.h"
#include "Value.h"
#include "CompiledValue.h"
#include "TokenBase.h"
#include "wnt_Lexer.h"
#include "wnt_LangParser.h"
#include "wnt_RefCounting.h"
#include "wnt_ASTNode.h"
#include "LLVMTypeUtils.h"
#include "utils/FileUtils.h"
#include "utils/StringUtils.h"
#include "utils/UTF8Utils.h"
#include "utils/ContainerUtils.h"
#include "utils/TaskManager.h"
#include "utils/Exception.h"
#include "utils/Timer.h"
#include "utils/ConPrint.h"
#include "utils/PlatformUtils.h"
#ifdef _MSC_VER // If compiling with Visual C++
#pragma warning(push, 0) // Disable warnings
#endif
#include "llvm/IR/Module.h"
#include "llvm/IR/Verifier.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/LegacyPassManager.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/IPO.h"
#include "llvm/IR/IRBuilder.h"
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/FileSystem.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/CommandLine.h"
#include "llvm/Support/ManagedStatic.h"
#include "llvm/Transforms/IPO/PassManagerBuilder.h"
#include "llvm/Analysis/TargetLibraryInfo.h"
#include "llvm/Target/TargetMachine.h"
#include "llvm/ADT/Triple.h"
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/ExecutionEngine/JITEventListener.h"
#include "llvm/MC/MCInst.h"
#include "llvm/MC/MCSubtargetInfo.h"
#include "llvm/MC/MCAsmInfo.h"
#include "llvm/MC/MCStreamer.h"
#include "llvm/MC/MCContext.h"
#include "llvm/MC/MCObjectFileInfo.h"
#include "llvm/MC/MCInstPrinter.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/Support/Host.h"
#include "llvm/Support/SourceMgr.h"
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Analysis/Lint.h"
#include "llvm/Support/ErrorHandling.h"
#include "llvm/IR/DiagnosticHandler.h"
#include "llvm/IR/DiagnosticPrinter.h"
#include "llvm/IR/DiagnosticInfo.h"
#ifdef _MSC_VER
#pragma warning(pop) // Re-enable warnings
#endif
#include <cassert>
#include <fstream>
#include <unordered_map>
#include "math.h"
using std::vector;
using std::string;
#if !defined(TARGET_LLVM_VERSION)
#error Target LLVM Version must be defined via TARGET_LLVM_VERSION
#endif
namespace Winter
{
// Dumps to "unoptimised_module_IR.txt", "optimised_module_IR.txt" in current working dir.
// Also dumps to "module_assembly.txt" in current working dir.
static const bool DUMP_MODULE_IR_AND_ASSEMBLY = false;
// Dumps optimised Winter code to optimised_src.win.
static const bool DUMP_OPTIMISED_WINTER_CODE = false;
//=====================================================================================
static const std::string& getStringArg(const vector<ValueRef>& arg_values, int i)
{
assert(arg_values[i]->valueType() == Value::ValueType_String);
return static_cast<const StringValue*>(arg_values[i].getPointer())->value;
}
static int64 getInt64Arg(const vector<ValueRef>& arg_values, int i)
{
assert(arg_values[i]->valueType() == Value::ValueType_Int);
return static_cast<const IntValue*>(arg_values[i].getPointer())->value;
}
static const std::string& getCharArg(const vector<ValueRef>& arg_values, int i)
{
assert(arg_values[i]->valueType() == Value::ValueType_Char);
return static_cast<const CharValue*>(arg_values[i].getPointer())->value;
}
static int64 closure_count = 0;//TEMP
// Returns number of unicode chars in the string.
static int64 stringLength(StringRep* str)
{
const uint64 num_bytes = str->len;
const char* const data = (const char*)str + sizeof(StringRep);
return (int64)UTF8Utils::numCodePointsInString(data, num_bytes);
}
static ValueRef stringLengthInterpreted(const vector<ValueRef>& args)
{
return new IntValue( (int64)UTF8Utils::numCodePointsInString(getStringArg(args, 0)), /*is_signed=*/true );
}
static StringRep* concatStrings(StringRep* a, StringRep* b, void* env)
{
const uint64 new_len = a->len + b->len;
StringRep* new_s = allocateStringWithLen(new_len);
new_s->refcount = 1;
std::memcpy((uint8*)new_s + sizeof(StringRep), (uint8*)a + sizeof(StringRep), a->len);
std::memcpy((uint8*)new_s + sizeof(StringRep) + a->len, (uint8*)b + sizeof(StringRep), b->len);
return new_s;
}
static ValueRef concatStringsInterpreted(const vector<ValueRef>& args)
{
return new StringValue( getStringArg(args, 0) + getStringArg(args, 1) );
}
static bool compareEqualString(StringRep* a, StringRep* b, void* env)
{
if(a->len != b->len)
return false;
return std::memcmp((uint8*)a + sizeof(StringRep), (uint8*)b + sizeof(StringRep), a->len) == 0;
}
static ValueRef compareEqualStringInterpreted(const vector<ValueRef>& args)
{
return new BoolValue(getStringArg(args, 0) == getStringArg(args, 1));
}
static bool compareNotEqualString(StringRep* a, StringRep* b, void* env)
{
if(a->len != b->len)
return true;
return std::memcmp((uint8*)a + sizeof(StringRep), (uint8*)b + sizeof(StringRep), a->len) != 0;
}
static ValueRef compareNotEqualStringInterpreted(const vector<ValueRef>& args)
{
return new BoolValue(getStringArg(args, 0) != getStringArg(args, 1));
}
static StringRep* charToString(uint32 c, void* env)
{
// Work out number of bytes used
const int num_bytes = (int)UTF8Utils::numBytesForChar((uint8)(c & 0xFF));
StringRep* new_s = allocateStringWithLen(num_bytes);
new_s->refcount = 1;
std::memcpy((uint8*)new_s + sizeof(StringRep), &c, num_bytes); // Copy data
return new_s;
}
static ValueRef charToStringInterpreted(const vector<ValueRef>& args)
{
return new StringValue(getCharArg(args, 0));
}
// codePoint(char c) int
static int codePoint(uint32 c, void* env)
{
return (int)UTF8Utils::codePointForUTF8Char(c);
}
static ValueRef codePointInterpreted(const vector<ValueRef>& args)
{
return new IntValue(UTF8Utils::codePointForUTF8CharString(getCharArg(args, 0)), /*is_signed=*/true);
}
static int stringElem(StringRep* s, uint64 index)
{
try
{
const uint8* data = (const uint8*)s + sizeof(StringRep);
return (int)UTF8Utils::charAt(data, s->len, index);
}
catch(glare::Exception&)
{
assert(0); // Out of bounds read
return 0;
}
}
static ValueRef stringElemInterpreted(const vector<ValueRef>& args)
{
try
{
const std::string& s = getStringArg(args, 0);
const int64 index = getInt64Arg(args, 1);
const uint32 c = UTF8Utils::charAt((const uint8*)s.c_str(), s.size(), index);
return new CharValue(UTF8Utils::charString(c));
}
catch(glare::Exception& e)
{
// Out of bounds read.
throw BaseException(e.what());
}
}
//=====================================================================================
// In-memory string representation for a Winter Closure
class ClosureRep
{
public:
uint64 refcount;
uint64 len; // not used currently.
uint64 flags;
// Data follows..
};
static ClosureRep* allocateClosure(uint64 size_B)
{
closure_count++;//TEMP
// Allocate space for the reference count, length, flags, and data.
ClosureRep* closure = (ClosureRep*)malloc(size_B);
closure->refcount = 666;
closure->len = 666;
closure->flags = 666;
//closure->flags = 1; // heap allocated
return closure;
}
static ValueRef allocateClosureInterpreted(const vector<ValueRef>& args)
{
assert(0);
return NULL;
}
// NOTE: just return an int here as all external funcs need to return something (non-void).
static int freeClosure(ClosureRep* closure)
{
closure_count--;//TEMP
assert(closure->refcount == 1);
::free(closure);
return 0;
}
//=====================================================================================
// #define WINTER_GLOBAL_TASK_SUPPORT 1
#if WINTER_GLOBAL_TASK_SUPPORT
class ExecArrayMapTask;
static glare::TaskManager* winter_global_task_manager = NULL;
static std::vector<Reference<ExecArrayMapTask> > exec_array_map_tasks;
typedef void (WINTER_JIT_CALLING_CONV * VARRAY_WORK_FUNCTION) (uint64* output, uint64* input, size_t begin, size_t end); // Winter code
class ExecMapTask : public glare::Task
{
public:
virtual void run(size_t thread_index)
{
// Call back into Winter JITed code to compute the map on this slice.
work_function(output, input, begin, end);
}
uint64* output;
uint64* input;
size_t begin;
size_t end;
VARRAY_WORK_FUNCTION work_function;
};
void execVArrayMap(uint64* output, uint64* input, VARRAY_WORK_FUNCTION work_function)
{
const size_t input_len = input[1];
assert(output[1] == input_len);
const size_t num_threads = winter_global_task_manager->getNumThreads();
size_t slice_size = input_len / num_threads;
if(slice_size * num_threads < input_len) // If slice_size was rounded down:
slice_size++;
for(size_t i=0; i<num_threads; ++i)
{
Reference<ExecMapTask> t = new ExecMapTask();
t->begin = i*slice_size;
t->end = myMin(input_len, (i+1)*slice_size);
t->work_function = work_function;
winter_global_task_manager->addTask(t);
}
winter_global_task_manager->waitForTasksToComplete();
}
typedef void (WINTER_JIT_CALLING_CONV * ARRAY_WORK_FUNCTION) (void* output, void* input, void* map_function, size_t begin, size_t end); // Winter code
class ExecArrayMapTask : public glare::Task
{
public:
virtual void run(size_t thread_index)
{
// Call back into Winter JITed code to compute the map on this slice.
//work_function(output, input, map_function, begin, end);
work_function( (float*)output + begin, (float*)input + begin, map_function, 0, end - begin);
}
void* output;
void* input;
void* map_function;
size_t begin;
size_t end;
ARRAY_WORK_FUNCTION work_function;
};
void execArrayMap(void* output, void* input, size_t array_size, void* map_function, ARRAY_WORK_FUNCTION work_function)
{
const size_t input_len = array_size;
const size_t num_threads = winter_global_task_manager->getNumThreads();
size_t slice_size = input_len / num_threads;
if(slice_size * num_threads < input_len) // If slice_size was rounded down:
slice_size++;
for(size_t i=0; i<num_threads; ++i)
{
Reference<ExecArrayMapTask> t = exec_array_map_tasks[i]; // new ExecArrayMapTask();
t->output = output;
t->input = input;
t->map_function = map_function;
t->begin = i*slice_size;
t->end = myMin(input_len, (i+1)*slice_size);
t->work_function = work_function;
winter_global_task_manager->addTask(t);
}
winter_global_task_manager->waitForTasksToComplete();
}
#endif // WINTER_GLOBAL_TASK_SUPPORT
//=====================================================================================
static void tracePrintFloat(const char* var_name, float x)
{
conPrint(std::string(var_name) + " = " + toString(x));
}
// We need to define our own memory manager so that we can supply our own getPointerToNamedFunction() method, that will return pointers to external functions.
// This seems to be necessary when using MCJIT.
class WinterMemoryManager : public llvm::SectionMemoryManager
{
public:
virtual ~WinterMemoryManager() {}
bool use_small_code_model;
std::vector<VirtualMachine::AllocationBlock> blocks;
uint8_t* allocateSection(void* suggested_addr, uintptr_t Size, unsigned Alignment)
{
#ifdef _WIN32
uint8_t* p = (uint8_t*)::VirtualAlloc(
suggested_addr,
Size, // size
MEM_RESERVE | MEM_COMMIT, // allocation type
PAGE_READWRITE // memory protection flags
);
if(p)
{
blocks.push_back(VirtualMachine::AllocationBlock());
blocks.back().alloced_mem = p;
blocks.back().size = Size;
}
else
throw Winter::BaseException("allocateSection(): Allocation failed.");
return p;
#else
throw Winter::BaseException("allocateSection(): not implemented.");
#endif
}
virtual uint8_t* allocateCodeSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID,
llvm::StringRef SectionName)
{
if(use_small_code_model)
{
const size_t desired_addr = 0x80000000 + blocks.size() * 0x100000;
uint8* p = allocateSection(
(void*)desired_addr, // desired starting address
Size, Alignment);
return p;
}
else
return llvm::SectionMemoryManager::allocateCodeSection(Size, Alignment, SectionID, SectionName);
}
virtual uint8_t* allocateDataSection(uintptr_t Size, unsigned Alignment,
unsigned SectionID,
llvm::StringRef SectionName,
bool isReadOnly)
{
if(use_small_code_model)
{
const size_t desired_addr = 0x81000000 + blocks.size() * 0x100000;
uint8* p = allocateSection(
(void*)desired_addr, // desired starting address
Size, Alignment);
return p;
}
else
return llvm::SectionMemoryManager::allocateDataSection(Size, Alignment, SectionID, SectionName, isReadOnly);
}
virtual bool finalizeMemory(std::string *ErrMsg = 0)
{
if(use_small_code_model)
{
#ifdef _WIN32
for(size_t i=0; i<blocks.size(); ++i)
{
DWORD OldFlags;
if(!VirtualProtect(blocks[i].alloced_mem, blocks[i].size, PAGE_EXECUTE_READ, &OldFlags))
throw Winter::BaseException("VirtualProtect failed.");
FlushInstructionCache(GetCurrentProcess(), blocks[i].alloced_mem, blocks[i].size);
}
#endif
return false;
}
else
return llvm::SectionMemoryManager::finalizeMemory(ErrMsg);
}
virtual uint64_t getSymbolAddress(const std::string& name)
{
std::unordered_map<std::string, void*>::iterator res = func_map->find(name);
if(res != func_map->end())
return (uint64_t)res->second;
// We generally want to explictly find and return the function pointer here, instead of falling back to using
// llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(). This is because SearchForAddressOfSymbol() just does
// a search through loaded DLLs, which may be slow, and may not give the symbol that we want.
// For example "sin" looked up with SearchForAddressOfSymbol() was returning a sin function from ucrtbase(d).dll,
// which is slower than the sin function explicitly returned below.
#if WINTER_GLOBAL_TASK_SUPPORT
if(name == "execArrayMap")
return (uint64_t)execArrayMap;
#endif
if(name == "tracePrintFloat")
return (uint64_t)tracePrintFloat;
if(name == "sinf")
return (uint64_t)sinf;
else if(name == "cosf")
return (uint64_t)cosf;
else if(name == "powf")
return (uint64_t)powf;
else if(name == "expf")
return (uint64_t)expf;
#if !defined(_MSC_VER) || (_MSC_VER >= 1900) // Visual Studio versions before 2015 don't define exp2f.
else if(name == "exp2f")
return (uint64_t)exp2f;
#endif
else if(name == "logf")
return (uint64_t)logf;
#if defined(__APPLE__)
else if(name == "___sincosf_stret")
return (uint64)__sincosf_stret;
#endif
else if(name == "sin")
return (uint64_t)static_cast<double(*)(double)>(sin); // Use static_cast to pick the correct overload.
else if(name == "cos")
return (uint64_t)static_cast<double(*)(double)>(cos);
else if(name == "pow")
return (uint64_t)static_cast<double(*)(double, double)>(pow);
else if(name == "exp")
return (uint64_t)static_cast<double(*)(double)>(exp);
#if !defined(_MSC_VER) || (_MSC_VER >= 1900) // Visual Studio versions before 2015 don't define exp2.
else if(name == "exp2")
return (uint64_t)static_cast<double(*)(double)>(exp2);
#endif
else if(name == "log")
return (uint64_t)static_cast<double(*)(double)>(log);
else if(name == "memcpy")
return (uint64_t)memcpy;
// For OS X:
if(name == "_sinf")
return (uint64_t)sinf;
else if(name == "_cosf")
return (uint64_t)cosf;
else if(name == "_powf")
return (uint64_t)powf;
else if(name == "_expf")
return (uint64_t)expf;
#if !defined(_MSC_VER) || (_MSC_VER >= 1900) // Visual Studio versions before 2015 don't define exp2f.
else if(name == "_exp2f")
return (uint64_t)exp2f;
#endif
else if(name == "_logf")
return (uint64_t)logf;
else if(name == "_fmodf")
return (uint64_t)fmodf;
else if(name == "_memcpy")
return (uint64_t)memcpy;
// OS X double precision functions:
else if(name == "_sin")
return (uint64_t)static_cast<double(*)(double)>(sin); // Use static_cast to pick the correct overload.
else if(name == "_cos")
return (uint64_t)static_cast<double(*)(double)>(cos);
else if(name == "_pow")
return (uint64_t)static_cast<double(*)(double, double)>(pow);
else if(name == "_exp")
return (uint64_t)static_cast<double(*)(double)>(exp);
#if !defined(_MSC_VER) || (_MSC_VER >= 1900) // Visual Studio versions before 2015 don't define exp2.
else if(name == "_exp2")
return (uint64_t)static_cast<double(*)(double)>(exp2);
#endif
else if(name == "_log")
return (uint64_t)static_cast<double(*)(double)>(log);
else if(name == "_fmod")
return (uint64_t)static_cast<double(*)(double, double)>(fmod);
#if defined(__APPLE__)
else if(name == "___sincos_stret")
return (uint64)__sincos_stret;
else if(name == "_memset_pattern16")
return (uint64_t)memset_pattern16;
#endif
// If function was not in func_map (i.e. was not an 'external' function), then use normal symbol resolution, for functions like sinf, cosf etc..
// conPrint("Warning, falling back to DynamicLibrary::SearchForAddressOfSymbol() for name '" + name + "'...");
void* f = llvm::sys::DynamicLibrary::SearchForAddressOfSymbol(name);
//assert(f);
if(!f)
throw BaseException("Internal error: failed to find symbol '" + name + "'");
return (uint64_t)f;
}
std::unordered_map<std::string, void*>* func_map;
};
VirtualMachine::VirtualMachine(const VMConstructionArgs& args)
: linker(
args.try_coerce_int_to_double_first,
args.emit_in_bound_asserts,
args.real_is_double,
args.optimise_for_opencl
),
llvm_context(NULL),
llvm_module(NULL),
llvm_exec_engine(NULL),
vm_args(args)
{
assert(closure_count == 0);
stats.initial_num_llvm_function_calls = 0;
stats.final_num_llvm_function_calls = 0;
stats.num_heap_allocation_calls = 0;
stats.num_closure_allocations = 0;
stats.num_free_vars_stored = 0;
#if WINTER_GLOBAL_TASK_SUPPORT
if(!winter_global_task_manager)
{
const size_t num_threads = 8;
winter_global_task_manager = new glare::TaskManager(num_threads);
exec_array_map_tasks.resize(num_threads);
for(size_t i=0; i<num_threads; ++i)
exec_array_map_tasks[i] = new ExecArrayMapTask();
}
#endif
try
{
this->external_functions = args.external_functions;
// Add allocateString
{
external_functions.push_back(new ExternalFunction(
(void*)allocateString,
allocateStringInterpreted, // interpreted func
FunctionSignature("allocateString", vector<TypeVRef>(1, new OpaqueType())),
new String() // return type
));
external_functions.back()->has_side_effects = true;
external_functions.back()->is_allocation_function = true;
}
// Add freeString
{
vector<TypeVRef> arg_types(1, new String());
//arg_types.push_back(new VoidPtrType());
external_functions.push_back(new ExternalFunction(
(void*)(int (*)(StringRep*))free,
NULL, // interpreted func TEMP
FunctionSignature("freeString", arg_types),
new Int() // return type
));
external_functions.back()->has_side_effects = true;
}
// Add length (stringLength)
external_functions.push_back(new ExternalFunction(
(void*)stringLength,
stringLengthInterpreted, // interpreted func
FunctionSignature("length", vector<TypeVRef>(1, new String())),
new Int(64), // return type
ExternalFunction::unknownTimeBound(), // time bound
1024, // stack space bound
0 // heap space bound
));
// Add concatStrings
external_functions.push_back(new ExternalFunction(
(void*)concatStrings,
concatStringsInterpreted, // interpreted func
FunctionSignature("concatStrings", vector<TypeVRef>(2, new String())),
new String() // return type
));
// Add toString(char)
external_functions.push_back(new ExternalFunction(
(void*)charToString,
charToStringInterpreted, // interpreted func
FunctionSignature("toString", vector<TypeVRef>(1, new CharType())),
new String(), // return type
1000, // time bound
1024, // stack size bound
sizeof(StringRep) + 4 // heap size bound - a single char may take up to 4 bytes to store.
));
// Add codePoint(char c) int
external_functions.push_back(new ExternalFunction(
(void*)codePoint,
codePointInterpreted, // interpreted func
FunctionSignature("codePoint", vector<TypeVRef>(1, new CharType())),
new Int(), // return type
16, // time bound
1024, // stack space bound
0 // heap space bound
));
// Add elem(string s, uint64 index) char
external_functions.push_back(new ExternalFunction(
(void*)stringElem,
stringElemInterpreted, // interpreted func
FunctionSignature("elem", typePair(new String(), new Int(64))),
new CharType(), // return type
ExternalFunction::unknownTimeBound(), // time bound
1024, // stack space bound
0 // heap space bound
));
// Add compareEqualString
external_functions.push_back(new ExternalFunction(
(void*)compareEqualString,
compareEqualStringInterpreted, // interpreted func
FunctionSignature("compareEqualString", std::vector<TypeVRef>(2, new String())),
new Bool(), // return type
1024, // stack space bound
0 // heap space bound
));
// Add compareNotEqualString
external_functions.push_back(new ExternalFunction(
(void*)compareNotEqualString,
compareNotEqualStringInterpreted, // interpreted func
FunctionSignature("compareNotEqualString", std::vector<TypeVRef>(2, new String())),
new Bool(), // return type
1024, // stack space bound
0 // heap space bound
));
// Add allocateVArray
{
external_functions.push_back(new ExternalFunction(
(void*)allocateVArray,
allocateVArrayInterpreted, // interpreted func
FunctionSignature("allocateVArray", vector<TypeVRef>(2, new Int(64))),
new VArrayType(new Int()) //new OpaqueType() // return type. Just make this a void*, will cast return value to correct type
));
external_functions.back()->has_side_effects = true;
external_functions.back()->is_allocation_function = true;
}
// Add freeVArray
{
external_functions.push_back(new ExternalFunction(
(void*)(int (*)(VArrayRep*))free,
NULL, // interpreted func TEMP
FunctionSignature("freeVArray", vector<TypeVRef>(1, new VArrayType(new Int()))), // new OpaqueType())),
new Int() // return type
));
external_functions.back()->has_side_effects = true;
}
const TypeVRef dummy_func_type = Function::dummyFunctionType();
// Add allocateClosure
{
external_functions.push_back(new ExternalFunction(
(void*)allocateClosure,
allocateClosureInterpreted, // interpreted func
FunctionSignature("allocateClosure", vector<TypeVRef>(1, new Int(64))),
dummy_func_type // return type
));
external_functions.back()->has_side_effects = true;
external_functions.back()->is_allocation_function = true;
}
// Add freeClosure
{
external_functions.push_back(new ExternalFunction(
(void*)freeClosure,
NULL, // interpreted func TEMP
FunctionSignature("freeClosure", vector<TypeVRef>(1, dummy_func_type)),
new Int() // return type
));
external_functions.back()->has_side_effects = true;
}
// Load source buffers
loadSource(args, args.source_buffers, args.preconstructed_func_defs);
if(args.build_llvm_code)
{
this->llvm_context = new llvm::LLVMContext();
this->llvm_module = new llvm::Module("WinterModule", *this->llvm_context);
llvm::EngineBuilder engine_builder(std::unique_ptr<llvm::Module>(this->llvm_module));
engine_builder.setEngineKind(llvm::EngineKind::JIT);
if(args.small_code_model)
engine_builder.setCodeModel(llvm::CodeModel::Small);
WinterMemoryManager* mem_manager = new WinterMemoryManager();
mem_manager->use_small_code_model = args.small_code_model;
mem_manager->func_map = &func_map;
engine_builder.setMCJITMemoryManager(std::unique_ptr<llvm::SectionMemoryManager>(mem_manager));
// OSX_DEPLOYMENT_TARGET should correspond to the version number in the -mmacosx-version-min
// flag passed to the compiler.
#if defined(OSX_DEPLOYMENT_TARGET)
#if defined(__x86_64__) || defined(_M_X64)
this->triple = "x86_64-apple-macosx" + std::string(OSX_DEPLOYMENT_TARGET);
#else
this->triple = "aarch64-apple-macosx" + std::string(OSX_DEPLOYMENT_TARGET);
#endif
#else // else if !defined(OSX_DEPLOYMENT_TARGET):
this->triple = llvm::sys::getProcessTriple();
#endif
#if defined(__x86_64__) || defined(_M_X64)
this->triple.append("-elf"); // MCJIT requires the -elf suffix currently, see https://groups.google.com/forum/#!topic/llvm-dev/DOmHEXhNNWw
// However -elf causes miscompilation on Apple M1: https://discourse.llvm.org/t/crash-calling-back-into-a-c-function-on-a-mac-m1/71784
#endif
// PlatformUtils::CPUInfo cpu_info;
// PlatformUtils::getCPUInfo(cpu_info);
// There is an issue with older LLVMs, that if it encounters a newer CPU model than it knows about, then it just returns
// "x86-64" or "generic", which have less feature support than we actually have. So in this case just use "corei7" which should give us the features we need.
// This issue seems to have been fixed in LLVM 6, which tries to autodetect a suitable cpu if it doesn't have an exact match.
//
// Failing to detect a CPU properly will result in an error like "LLVM encountered a fatal error: Cannot select: intrinsic %llvm.x86.sse41.dpps".
//
// Some example CPUs that are not detected properly by LLVM 3.4:
//
// Ryzen 3300x:
// cpu_info.family: 23
// cpu_info.model: 113
//
// Threadripper:
// cpu_info.family: 23
// cpu_info.model: 1
std::string cpu_name = (std::string)llvm::sys::getHostCPUName();
#if defined(__x86_64__) || defined(_M_X64)
if(cpu_name == "generic" || cpu_name == "x86-64") // If LLVM can't detect it, it's probably something pretty new, so just consider it >= to a corei7 in terms of capabilities.
cpu_name = "corei7";
#else // Else on ARM64:
#endif
std::string error_string;
engine_builder.setErrorStr(&error_string);
// Select the host computer architecture as the target.
llvm::SmallVector<std::string, 4> mattr;
#if defined(__x86_64__) || defined(_M_X64) // If on x64 architecture:
if(!vm_args.allow_AVX)
mattr.push_back("-avx"); // -avx disables AVX support
#endif
this->target_machine = engine_builder.selectTarget(
llvm::Triple(this->triple), // target triple
"", // march
cpu_name, // mcpu - e.g. "corei7", "core-avx2"
mattr);
if(this->target_machine == NULL)
throw BaseException("Winter::VirtualMachine(): Failed to select target: " + error_string);
// Enable floating point op fusion, to allow for FMA codegen.
this->target_machine->Options.AllowFPOpFusion = llvm::FPOpFusion::Fast;
this->llvm_exec_engine = engine_builder.create(target_machine);
this->llvm_exec_engine->DisableLazyCompilation();
for(unsigned int i=0; i<this->external_functions.size(); ++i)
addExternalFunction(this->external_functions[i], *this->llvm_context, *this->llvm_module);
this->build(args);
jit_mem_blocks.insert(jit_mem_blocks.end(), mem_manager->blocks.begin(), mem_manager->blocks.end());
}
}
catch(ExceptionWithPosition& e)
{
// Since we threw an exception in the constructor, VirtualMachine destructor will not be run.
// So we need to delete these objects now.
delete this->llvm_exec_engine;
delete this->llvm_context;
throw e; // Re-throw exception
}
catch(BaseException& e)
{
// Since we threw an exception in the constructor, VirtualMachine destructor will not be run.
// So we need to delete these objects now.
delete this->llvm_exec_engine;
delete this->llvm_context;
throw e; // Re-throw exception
}
}
VirtualMachine::~VirtualMachine()
{
// llvm_exec_engine will delete llvm_module.
assert(closure_count == 0);
delete this->llvm_exec_engine;
delete this->llvm_context;
for(size_t i=0; i<jit_mem_blocks.size(); ++i)
{
#ifdef _WIN32
if(::VirtualFree(jit_mem_blocks[i].alloced_mem, 0, MEM_RELEASE) == 0)
conPrint("Error: VirtualFree failed: " + PlatformUtils::getLastErrorString());
#endif
}
}
static void fatalErrorHandler(void *user_data,
#if TARGET_LLVM_VERSION >= 150
const char *reason,
#else
const std::string& reason,
#endif
bool gen_crash_diag)
{
stdErrPrint("LLVM encountered a fatal error: " + std::string(reason));
throw BaseException("LLVM encountered a fatal error: " + std::string(reason));
}
void VirtualMachine::init()
{
llvm::install_fatal_error_handler(fatalErrorHandler, /*user data=*/NULL);
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
// In LLVM 15.0 + (and maybe earlier), -warn-stack-size was removed and made into a function attribute.
#if TARGET_LLVM_VERSION < 150
// Clear any previously parsed options. We need to do this because the results of a previous call to
// llvm::cl::ParseCommandLineOptions() might hang around, if this code is called in a .so that has dlclose() called on it,
// but is not actually unloaded. When the dlopen() is called on the .so again, the global variables will still be around.
// See https://stackoverflow.com/questions/24467404/dlclose-doesnt-really-unload-shared-object-no-matter-how-many-times-it-is-call
llvm::cl::ResetAllOptionOccurrences();
// Enable -warn-stack-size= option.
// We use this to get the stack size for compiled functions -
// see use of llvm::DiagnosticInfoStackSize below.
// The option boolean is a global static, so set it once here.
const char* argv[] = { "dummyprogname", "-warn-stack-size=0" };
std::string msg;
llvm::raw_string_ostream stream(msg);
const bool res = llvm::cl::ParseCommandLineOptions(2, argv, /*overview=*/"", &stream);
if(!res)
throw BaseException("VirtualMachine::init(): Failed to set command line options: " + stream.str());
#endif
}
void VirtualMachine::shutdown() // Calls llvm_shutdown()
{
// NOTE: We can't call llvm::llvm_shutdown() because it will delete all LLVM managed statics, including options handling, which
// will cause subsequent llvm::cl::ParseCommandLineOptions() to fail.
// llvm::llvm_shutdown(); // This calls llvm::llvm_stop_multithreaded() as well (on <= LLVM 3.4 at least).
llvm::remove_fatal_error_handler();
}
void VirtualMachine::addExternalFunction(const ExternalFunctionRef& f, llvm::LLVMContext& context, llvm::Module& module)
{
llvm::FunctionType* llvm_f_type = LLVMTypeUtils::llvmFunctionType(