forked from JuliaLang/julia
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcodegen.cpp
4178 lines (3937 loc) · 156 KB
/
codegen.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
#include "platform.h"
#include "julia.h"
#include "julia_internal.h"
/*
* We include <mathimf.h> here, because somewhere below <math.h> is included also.
* As a result, Intel C++ Composer generates an error. To prevent this error, we
* include <mathimf.h> as soon as possible. <mathimf.h> defines several macros
* (like _INC_MATH, __MATH_H_INCLUDED, __COMPLEX_H_INCLUDED) that prevent
* including <math.h> (or rather its content).
*/
#if defined(_OS_WINDOWS_)
#define NOMINMAX
#include <malloc.h>
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#if defined(_COMPILER_INTEL_)
#include <mathimf.h>
#else
#include <math.h>
#endif
#endif
#ifndef __STDC_LIMIT_MACROS
#define __STDC_LIMIT_MACROS
#define __STDC_CONSTANT_MACROS
#endif
#include "llvm/ExecutionEngine/ExecutionEngine.h"
#include "llvm/ExecutionEngine/JIT.h"
#include "llvm/ExecutionEngine/JITEventListener.h"
#include "llvm/ExecutionEngine/JITMemoryManager.h"
#include "llvm/PassManager.h"
#include "llvm/Analysis/Passes.h"
#include "llvm/Bitcode/ReaderWriter.h"
#if defined(LLVM_VERSION_MAJOR) && LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 5
#define LLVM35 1
#include "llvm/IR/Verifier.h"
#else
#include "llvm/Analysis/Verifier.h"
#endif
#if defined(LLVM_VERSION_MAJOR) && LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 4
#define LLVM34 1
#define USE_MCJIT 1
#include "llvm/ExecutionEngine/MCJIT.h"
#include "llvm/ExecutionEngine/SectionMemoryManager.h"
#include "llvm/ADT/DenseMapInfo.h"
#endif
#if defined(LLVM_VERSION_MAJOR) && LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 3
#include "llvm/IR/DerivedTypes.h"
#include "llvm/IR/LLVMContext.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/Intrinsics.h"
#include "llvm/IR/Attributes.h"
#include "llvm/IR/IRBuilder.h"
#define LLVM33 1
#else
#include "llvm/DerivedTypes.h"
#include "llvm/LLVMContext.h"
#include "llvm/Module.h"
#include "llvm/Intrinsics.h"
#include "llvm/Attributes.h"
#endif
#if defined(LLVM_VERSION_MAJOR) && LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 2
#include "llvm/DebugInfo.h"
#include "llvm/DIBuilder.h"
#ifndef LLVM33
#include "llvm/IRBuilder.h"
#endif
#define LLVM32 1
#else
#include "llvm/Analysis/DebugInfo.h"
#include "llvm/Analysis/DIBuilder.h"
#include "llvm/Target/TargetData.h"
#include "llvm/Support/IRBuilder.h"
#endif
#include "llvm/Target/TargetOptions.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/BasicBlockUtils.h"
#if defined(LLVM_VERSION_MAJOR) && LLVM_VERSION_MAJOR == 3 && LLVM_VERSION_MINOR >= 1
#include "llvm/Transforms/Vectorize.h"
#endif
#include "llvm/Support/TargetSelect.h"
#include "llvm/Support/raw_ostream.h"
#include "llvm/Support/FormattedStream.h"
#include "llvm/Support/DynamicLibrary.h"
#include "llvm/Config/llvm-config.h"
#include "llvm/Transforms/Utils/Cloning.h"
#include <setjmp.h>
#include <string>
#include <sstream>
#include <fstream>
#include <map>
#include <vector>
#include <set>
#include <cstdio>
#include <cassert>
using namespace llvm;
extern "C" {
#include "builtin_proto.h"
void *__stack_chk_guard = NULL;
#if defined(_OS_WINDOWS_) && !defined(_COMPILER_MINGW_)
void __stack_chk_fail()
#else
void __attribute__(()) __stack_chk_fail()
#endif
{
/* put your panic function or similar in here */
fprintf(stderr, "warning: stack corruption detected\n");
//assert(0 && "stack corruption detected");
//abort();
}
}
#define DISABLE_FLOAT16
// llvm state
static LLVMContext &jl_LLVMContext = getGlobalContext();
static IRBuilder<> builder(getGlobalContext());
static bool nested_compile=false;
static ExecutionEngine *jl_ExecutionEngine;
#ifdef USE_MCJIT
static Module *shadow_module;
static RTDyldMemoryManager *jl_mcjmm;
#define jl_Module (builder.GetInsertBlock()->getParent()->getParent())
#else
static Module *jl_Module;
#endif
static std::map<int, std::string> argNumberStrings;
static FunctionPassManager *FPM;
#ifdef LLVM35
static DataLayoutPass *jl_data_layout;
#elif defined(LLVM32)
static DataLayout *jl_data_layout;
#else
static TargetData *jl_data_layout;
#endif
// for image reloading
static bool imaging_mode = false;
// types
static Type *jl_value_llvmt;
static Type *jl_pvalue_llvmt;
static Type *jl_ppvalue_llvmt;
static FunctionType *jl_func_sig;
static Type *jl_fptr_llvmt;
static Type *T_int1;
static Type *T_int8;
static Type *T_pint8;
static Type *T_uint8;
static Type *T_int16;
static Type *T_pint16;
static Type *T_uint16;
static Type *T_int32;
static Type *T_pint32;
static Type *T_uint32;
static Type *T_int64;
static Type *T_pint64;
static Type *T_uint64;
static Type *T_char;
static Type *T_size;
static Type *T_psize;
static Type *T_float32;
static Type *T_pfloat32;
static Type *T_float64;
static Type *T_pfloat64;
static Type *T_void;
// constants
static Value *V_null;
// global vars
static GlobalVariable *jltrue_var;
static GlobalVariable *jlfalse_var;
static GlobalVariable *jlnull_var;
static GlobalVariable *jlfloattemp_var;
#ifdef JL_GC_MARKSWEEP
static GlobalVariable *jlpgcstack_var;
#endif
static GlobalVariable *jlexc_var;
static GlobalVariable *jldiverr_var;
static GlobalVariable *jlundeferr_var;
static GlobalVariable *jldomerr_var;
static GlobalVariable *jlovferr_var;
static GlobalVariable *jlinexacterr_var;
static GlobalVariable *jlboundserr_var;
static GlobalVariable *jlstderr_var;
static GlobalVariable *jlRTLD_DEFAULT_var;
#ifdef _OS_WINDOWS_
static GlobalVariable *jlexe_var;
static GlobalVariable *jldll_var;
#endif
// important functions
static Function *jlnew_func;
static Function *jlthrow_func;
static Function *jlthrow_line_func;
static Function *jlerror_func;
static Function *jltypeerror_func;
static Function *jlundefvarerror_func;
static Function *jlcheckassign_func;
static Function *jldeclareconst_func;
static Function *jltopeval_func;
static Function *jlcopyast_func;
static Function *jltuple_func;
static Function *jlntuple_func;
static Function *jlapplygeneric_func;
static Function *jlgetfield_func;
static Function *jlbox_func;
static Function *jlclosure_func;
static Function *jlmethod_func;
static Function *jlenter_func;
static Function *jlleave_func;
static Function *jlegal_func;
static Function *jlallocobj_func;
static Function *jlalloc2w_func;
static Function *jlalloc3w_func;
static Function *jl_alloc_tuple_func;
static Function *setjmp_func;
static Function *box_int8_func;
static Function *box_uint8_func;
static Function *box_int16_func;
static Function *box_uint16_func;
static Function *box_int32_func;
static Function *box_char_func;
static Function *box_uint32_func;
static Function *box_int64_func;
static Function *box_uint64_func;
static Function *box_float32_func;
static Function *box_float64_func;
static Function *box8_func;
static Function *box16_func;
static Function *box32_func;
static Function *box64_func;
static Function *jlputs_func;
static Function *jldlsym_func;
static Function *jlnewbits_func;
//static Function *jlgetnthfield_func;
static Function *jlgetnthfieldchecked_func;
//static Function *jlsetnthfield_func;
#ifdef _OS_WINDOWS_
static Function *resetstkoflw_func;
#endif
// --- code generation ---
// per-local-variable information
struct jl_varinfo_t {
Value *memvalue; // an address, if the var is alloca'd
Value *SAvalue; // register, if the var is SSA
Value *passedAs; // if an argument, the original passed value
int closureidx; // index in closure env, or -1
bool isAssigned;
bool isCaptured;
bool isSA;
bool isVolatile;
bool isArgument;
bool isGhost; // Has size 0 and is thus never actually allocated
bool hasGCRoot;
bool escapes;
bool usedUndef;
bool used;
jl_value_t *declType;
jl_value_t *initExpr; // initializing expression for SSA variables
jl_varinfo_t() : memvalue(NULL), SAvalue(NULL), passedAs(NULL), closureidx(-1),
isAssigned(true), isCaptured(false), isSA(false), isVolatile(false),
isArgument(false), isGhost(false), hasGCRoot(false), escapes(true),
usedUndef(false), used(false),
declType((jl_value_t*)jl_any_type), initExpr(NULL)
{
}
};
// --- helpers for reloading IR image
static void jl_gen_llvm_gv_array();
extern "C"
void jl_dump_bitcode(char* fname)
{
std::string err;
#ifdef LLVM35
raw_fd_ostream OS(fname, err, sys::fs::F_None);
#else
raw_fd_ostream OS(fname, err);
#endif
jl_gen_llvm_gv_array();
#ifdef USE_MCJIT
WriteBitcodeToFile(shadow_module, OS);
#else
WriteBitcodeToFile(jl_Module, OS);
#endif
}
// aggregate of array metadata
typedef struct {
Value *dataptr;
Value *len;
std::vector<Value*> sizes;
jl_value_t *ty;
} jl_arrayvar_t;
// information about the context of a piece of code: its enclosing
// function and module, and visible local variables and labels.
typedef struct {
Function *f;
// local var info. globals are not in here.
// NOTE: you must be careful not to access vars[s] before you are sure "s" is
// a local, since otherwise this will add it to the map.
std::map<jl_sym_t*, jl_varinfo_t> vars;
std::map<jl_sym_t*, jl_arrayvar_t> *arrayvars;
std::map<int, BasicBlock*> *labels;
std::map<int, Value*> *handlers;
jl_module_t *module;
jl_expr_t *ast;
jl_tuple_t *sp;
jl_lambda_info_t *linfo;
Value *envArg;
Value *argArray;
Value *argCount;
Instruction *argTemp;
int argDepth;
int maxDepth;
int argSpaceOffs;
std::string funcName;
jl_sym_t *vaName; // name of vararg argument
bool vaStack; // varargs stack-allocated
int nReqArgs;
int lineno;
std::vector<bool> boundsCheck;
#ifdef JL_GC_MARKSWEEP
Instruction *gcframe ;
Instruction *argSpaceInits;
StoreInst *storeFrameSize;
#endif
BasicBlock::iterator first_gcframe_inst;
BasicBlock::iterator last_gcframe_inst;
llvm::DIBuilder *dbuilder;
std::vector<Instruction*> gc_frame_pops;
std::vector<CallInst*> to_inline;
} jl_codectx_t;
static Value *emit_expr(jl_value_t *expr, jl_codectx_t *ctx, bool boxed=true,
bool valuepos=true);
static Value *emit_unboxed(jl_value_t *e, jl_codectx_t *ctx);
static int is_global(jl_sym_t *s, jl_codectx_t *ctx);
static Value *make_gcroot(Value *v, jl_codectx_t *ctx);
static Value *global_binding_pointer(jl_module_t *m, jl_sym_t *s,
jl_binding_t **pbnd, bool assign);
static Value *emit_checked_var(Value *bp, jl_sym_t *name, jl_codectx_t *ctx);
static bool might_need_root(jl_value_t *ex);
static Value *emit_condition(jl_value_t *cond, const std::string &msg, jl_codectx_t *ctx);
// NoopType
static Type *NoopType;
// --- utilities ---
extern "C" {
int globalUnique = 0;
}
#include "cgutils.cpp"
static void jl_rethrow_with_add(const char *fmt, ...)
{
if (jl_typeis(jl_exception_in_transit, jl_errorexception_type)) {
char *str = jl_string_data(jl_fieldref(jl_exception_in_transit,0));
char buf[1024];
va_list args;
va_start(args, fmt);
int nc = vsnprintf(buf, sizeof(buf), fmt, args);
va_end(args);
nc += snprintf(buf+nc, sizeof(buf)-nc, ": %s", str);
jl_value_t *msg = jl_pchar_to_string(buf, nc);
JL_GC_PUSH1(&msg);
jl_throw(jl_new_struct(jl_errorexception_type, msg));
}
jl_rethrow();
}
// --- entry point ---
//static int n_emit=0;
static Function *emit_function(jl_lambda_info_t *lam, bool cstyle);
//static int n_compile=0;
static Function *to_function(jl_lambda_info_t *li, bool cstyle)
{
JL_SIGATOMIC_BEGIN();
assert(!li->inInference);
BasicBlock *old = nested_compile ? builder.GetInsertBlock() : NULL;
DebugLoc olddl = builder.getCurrentDebugLocation();
bool last_n_c = nested_compile;
nested_compile = true;
Function *f = NULL;
JL_TRY {
f = emit_function(li, cstyle);
//JL_PRINTF(JL_STDOUT, "emit %s\n", li->name->name);
//n_emit++;
}
JL_CATCH {
li->functionObject = NULL;
li->cFunctionObject = NULL;
nested_compile = last_n_c;
if (old != NULL) {
builder.SetInsertPoint(old);
builder.SetCurrentDebugLocation(olddl);
}
JL_SIGATOMIC_END();
jl_rethrow_with_add("error compiling %s", li->name->name);
}
assert(f != NULL);
nested_compile = last_n_c;
#ifdef DEBUG
#ifndef LLVM35
if (verifyFunction(*f,PrintMessageAction)) {
#else
llvm::raw_fd_ostream out(1,false);
if (verifyFunction(*f,&out))
{
#endif
f->dump();
abort();
}
#endif
FPM->run(*f);
//n_compile++;
// print out the function's LLVM code
//ios_printf(ios_stderr, "%s:%d\n",
// ((jl_sym_t*)li->file)->name, li->line);
//if (verifyFunction(*f,PrintMessageAction)) {
// f->dump();
// abort();
//}
if (old != NULL) {
builder.SetInsertPoint(old);
builder.SetCurrentDebugLocation(olddl);
}
JL_SIGATOMIC_END();
return f;
}
extern "C" jl_function_t *jl_get_specialization(jl_function_t *f, jl_tuple_t *types);
static void jl_setup_module(Module *m, bool add)
{
m->addModuleFlag(llvm::Module::Warning, "Dwarf Version",4);
#ifdef LLVM34
m->addModuleFlag(llvm::Module::Error, "Debug Info Version",
llvm::DEBUG_METADATA_VERSION);
#endif
if (add)
jl_ExecutionEngine->addModule(m);
}
extern "C" void jl_generate_fptr(jl_function_t *f)
{
// objective: assign li->fptr
jl_lambda_info_t *li = f->linfo;
assert(li->functionObject);
if (li->fptr == &jl_trampoline) {
JL_SIGATOMIC_BEGIN();
#ifdef USE_MCJIT
if (imaging_mode) {
// Copy the function out of the shadow module
Module *m = new Module("julia", jl_LLVMContext);
jl_setup_module(m,true);
FunctionMover mover(m,shadow_module);
li->functionObject = MapValue((Function*)li->functionObject,mover.VMap,RF_None,NULL,&mover);
if (li->cFunctionObject != NULL)
li->cFunctionObject = MapValue((Function*)li->cFunctionObject,mover.VMap,RF_None,NULL,&mover);
}
#endif
Function *llvmf = (Function*)li->functionObject;
#ifdef USE_MCJIT
li->fptr = (jl_fptr_t)jl_ExecutionEngine->getFunctionAddress(llvmf->getName());
#else
li->fptr = (jl_fptr_t)jl_ExecutionEngine->getPointerToFunction(llvmf);
#endif
assert(li->fptr != NULL);
if (li->cFunctionObject != NULL) {
#ifdef USE_MCJIT
(void)jl_ExecutionEngine->getFunctionAddress(((Function*)li->cFunctionObject)->getName());
#else
(void)jl_ExecutionEngine->getPointerToFunction((Function*)li->cFunctionObject);
#endif
}
JL_SIGATOMIC_END();
if (!imaging_mode) {
llvmf->deleteBody();
if (li->cFunctionObject != NULL)
((Function*)li->cFunctionObject)->deleteBody();
}
}
f->fptr = li->fptr;
}
extern "C" void jl_compile(jl_function_t *f)
{
jl_lambda_info_t *li = f->linfo;
if (li->functionObject == NULL) {
// objective: assign li->functionObject
li->inCompile = 1;
(void)to_function(li, false);
li->inCompile = 0;
}
}
void jl_cstyle_compile(jl_function_t *f)
{
jl_lambda_info_t *li = f->linfo;
if (li->cFunctionObject == NULL) {
// objective: assign li->cFunctionObject
li->inCompile = 1;
(void)to_function(li, true);
li->inCompile = 0;
}
}
extern "C" DLLEXPORT
void *jl_function_ptr(jl_function_t *f, jl_value_t *rt, jl_value_t *argt)
{
JL_TYPECHK(jl_function_ptr, type, rt);
JL_TYPECHK(jl_function_ptr, tuple, argt);
JL_TYPECHK(jl_function_ptr, type, argt);
if (jl_is_gf(f) && (jl_is_leaf_type(rt) || rt == (jl_value_t*)jl_bottom_type) && jl_is_leaf_type(argt)) {
jl_function_t *ff = jl_get_specialization(f, (jl_tuple_t*)argt);
if (ff != NULL && ff->env==(jl_value_t*)jl_null && ff->linfo != NULL) {
if (ff->linfo->cFunctionObject == NULL) {
jl_cstyle_compile(ff);
}
if (ff->linfo->cFunctionObject != NULL) {
jl_lambda_info_t *li = ff->linfo;
jl_value_t *astrt = jl_ast_rettype(li, li->ast);
if (!jl_types_equal((jl_value_t*)li->specTypes, argt)) {
jl_errorf("cfunction: type signature of %s does not match",
li->name->name);
}
if (!jl_types_equal(astrt, rt) &&
!(astrt==(jl_value_t*)jl_nothing->type && rt==(jl_value_t*)jl_bottom_type)) {
if (astrt == (jl_value_t*)jl_bottom_type) {
jl_errorf("cfunction: %s does not return", li->name->name);
}
else {
jl_errorf("cfunction: return type of %s does not match",
li->name->name);
}
}
return jl_ExecutionEngine->getPointerToFunction((Function*)ff->linfo->cFunctionObject);
}
}
}
jl_error("function is not yet c-callable");
return NULL;
}
// --- native code info, and dump function to IR and ASM ---
#include "debuginfo.cpp"
#include "disasm.cpp"
const jl_value_t *jl_dump_llvmf(void *f, bool dumpasm)
{
std::string code;
llvm::raw_string_ostream stream(code);
llvm::formatted_raw_ostream fstream(stream);
Function *llvmf = (Function*)f;
if (dumpasm == false) {
llvmf->print(stream);
}
else {
size_t fptr = (size_t)jl_ExecutionEngine->getPointerToFunction(llvmf);
assert(fptr != 0);
std::map<size_t, FuncInfo> &fmap = jl_jit_events->getMap();
std::map<size_t, FuncInfo>::iterator fit = fmap.find(fptr);
if (fit == fmap.end()) {
JL_PRINTF(JL_STDERR, "Warning: Unable to find function pointer\n");
return jl_cstr_to_string(const_cast<char*>(""));
}
jl_dump_function_asm((void*)fptr, fit->second.lengthAdr, fit->second.lines, fstream);
fstream.flush();
}
return jl_cstr_to_string(const_cast<char*>(stream.str().c_str()));
}
extern "C" DLLEXPORT
const jl_value_t *jl_dump_function(jl_function_t *f, jl_tuple_t *types, bool dumpasm, bool dumpwrapper)
{
jl_function_t *sf = f;
if (types != NULL) {
if (!jl_is_function(f) || !jl_is_gf(f))
return jl_cstr_to_string(const_cast<char*>(""));
sf = jl_get_specialization(f, types);
}
if (sf == NULL || sf->linfo == NULL) {
sf = jl_method_lookup_by_type(jl_gf_mtable(f), types, 0, 0);
if (sf == jl_bottom_func)
return jl_cstr_to_string(const_cast<char*>(""));
JL_PRINTF(JL_STDERR,
"Warning: Returned code may not match what actually runs.\n");
}
Function *llvmf;
if (sf->linfo->functionObject == NULL) {
jl_compile(sf);
}
if (sf->fptr == &jl_trampoline) {
if (!dumpwrapper && sf->linfo->cFunctionObject != NULL)
llvmf = (Function*)sf->linfo->cFunctionObject;
else
llvmf = (Function*)sf->linfo->functionObject;
}
else {
llvmf = to_function(sf->linfo, false);
}
return jl_dump_llvmf(llvmf,dumpasm);
}
// --- code gen for intrinsic functions ---
#include "intrinsics.cpp"
// --- constant determination ---
// try to statically evaluate, NULL if not possible
static jl_value_t *static_eval(jl_value_t *ex, jl_codectx_t *ctx, bool sparams,
bool allow_alloc)
{
if (jl_is_symbolnode(ex))
ex = (jl_value_t*)jl_symbolnode_sym(ex);
if (jl_is_symbol(ex)) {
jl_sym_t *sym = (jl_sym_t*)ex;
if (is_global(sym, ctx)) {
size_t i;
if (sparams) {
for(i=0; i < jl_tuple_len(ctx->sp); i+=2) {
if (sym == (jl_sym_t*)jl_tupleref(ctx->sp, i)) {
// static parameter
return jl_tupleref(ctx->sp, i+1);
}
}
}
if (jl_is_const(ctx->module, sym))
return jl_get_global(ctx->module, sym);
}
return NULL;
}
if (jl_is_topnode(ex)) {
jl_binding_t *b = jl_get_binding(topmod(ctx),
(jl_sym_t*)jl_fieldref(ex,0));
if (b == NULL) return NULL;
if (b->constp)
return b->value;
}
if (jl_is_quotenode(ex))
return jl_fieldref(ex,0);
if (jl_is_lambda_info(ex))
return NULL;
jl_module_t *m = NULL;
jl_sym_t *s = NULL;
if (jl_is_getfieldnode(ex)) {
m = (jl_module_t*)static_eval(jl_fieldref(ex,0),ctx,sparams,allow_alloc);
s = (jl_sym_t*)jl_fieldref(ex,1);
if (m && jl_is_module(m) && s && jl_is_symbol(s)) {
jl_binding_t *b = jl_get_binding(m, s);
if (b && b->constp)
return b->value;
}
return NULL;
}
if (jl_is_expr(ex)) {
jl_expr_t *e = (jl_expr_t*)ex;
if (e->head == call_sym || e->head == call1_sym) {
jl_value_t *f = static_eval(jl_exprarg(e,0),ctx,sparams,allow_alloc);
if (f && jl_is_function(f)) {
jl_fptr_t fptr = ((jl_function_t*)f)->fptr;
if (fptr == &jl_apply_generic) {
if (f == jl_get_global(jl_base_module, jl_symbol("dlsym")) ||
f == jl_get_global(jl_base_module, jl_symbol("dlopen"))) {
size_t i;
size_t n = jl_array_dim0(e->args);
jl_value_t **v;
JL_GC_PUSHARGS(v, n);
memset(v, 0, n*sizeof(jl_value_t*));
v[0] = f;
for (i = 1; i < n; i++) {
v[i] = static_eval(jl_exprarg(e,i),ctx,sparams,allow_alloc);
if (v[i] == NULL) {
JL_GC_POP();
return NULL;
}
}
jl_value_t *result = jl_apply_generic(f, v+1, (uint32_t)n-1);
JL_GC_POP();
return result;
}
}
else if (jl_array_dim0(e->args) == 3 && fptr == &jl_f_get_field) {
m = (jl_module_t*)static_eval(jl_exprarg(e,1),ctx,sparams,allow_alloc);
s = (jl_sym_t*)static_eval(jl_exprarg(e,2),ctx,sparams,allow_alloc);
if (m && jl_is_module(m) && s && jl_is_symbol(s)) {
jl_binding_t *b = jl_get_binding(m, s);
if (b && b->constp)
return b->value;
}
}
else if (fptr == &jl_f_tuple) {
size_t i;
size_t n = jl_array_dim0(e->args)-1;
if (n==0) return (jl_value_t*)jl_null;
if (!allow_alloc)
return NULL;
jl_value_t **v;
JL_GC_PUSHARGS(v, n);
memset(v, 0, n*sizeof(jl_value_t*));
for (i = 0; i < n; i++) {
v[i] = static_eval(jl_exprarg(e,i+1),ctx,sparams,allow_alloc);
if (v[i] == NULL) {
JL_GC_POP();
return NULL;
}
}
jl_tuple_t *tup = jl_alloc_tuple_uninit(n);
for(i=0; i < n; i++) {
jl_tupleset(tup, i, v[i]);
}
JL_GC_POP();
return (jl_value_t*)tup;
}
}
// The next part is probably valid, but it is untested
//} else if (e->head == tuple_sym) {
// size_t i;
// for (i = 0; i < jl_array_dim0(e->args); i++)
// if (static_eval(jl_exprarg(e,i), ctx, sparams, allow_alloc) == NULL)
// return NULL;
// return ex;
}
return NULL;
}
return ex;
}
static bool is_constant(jl_value_t *ex, jl_codectx_t *ctx, bool sparams=true)
{
return static_eval(ex,ctx,sparams) != NULL;
}
static bool symbol_eq(jl_value_t *e, jl_sym_t *sym)
{
return ((jl_is_symbol(e) && ((jl_sym_t*)e)==sym) ||
(jl_is_symbolnode(e) && jl_symbolnode_sym(e)==sym));
}
// --- find volatile variables ---
// assigned in a try block and used outside that try block
static bool local_var_occurs(jl_value_t *e, jl_sym_t *s)
{
if (jl_is_symbol(e) || jl_is_symbolnode(e)) {
if (symbol_eq(e, s))
return true;
}
else if (jl_is_expr(e)) {
jl_expr_t *ex = (jl_expr_t*)e;
size_t alength = jl_array_dim0(ex->args);
for(int i=0; i < (int)alength; i++) {
if (local_var_occurs(jl_exprarg(ex,i),s))
return true;
}
}
else if (jl_is_getfieldnode(e)) {
if (local_var_occurs(jl_fieldref(e,0),s))
return true;
}
return false;
}
static std::set<jl_sym_t*> assigned_in_try(jl_array_t *stmts, int s, long l,
int *pend)
{
std::set<jl_sym_t*> av;
size_t slength = jl_array_dim0(stmts);
for(int i=s; i < (int)slength; i++) {
jl_value_t *st = jl_arrayref(stmts,i);
if (jl_is_expr(st)) {
if (((jl_expr_t*)st)->head == assign_sym) {
jl_sym_t *sy;
jl_value_t *ar = jl_exprarg(st, 0);
if (jl_is_symbolnode(ar)) {
sy = jl_symbolnode_sym(ar);
}
else {
assert(jl_is_symbol(ar));
sy = (jl_sym_t*)ar;
}
av.insert(sy);
}
}
if (jl_is_labelnode(st)) {
if (jl_labelnode_label(st) == l) {
*pend = i;
break;
}
}
}
return av;
}
static void mark_volatile_vars(jl_array_t *stmts, std::map<jl_sym_t*,jl_varinfo_t> &vars)
{
size_t slength = jl_array_dim0(stmts);
for(int i=0; i < (int)slength; i++) {
jl_value_t *st = jl_arrayref(stmts,i);
if (jl_is_expr(st)) {
if (((jl_expr_t*)st)->head == enter_sym) {
int last = (int)slength-1;
std::set<jl_sym_t*> as =
assigned_in_try(stmts, i+1,
jl_unbox_long(jl_exprarg(st,0)), &last);
for(int j=0; j < (int)slength; j++) {
if (j < i || j > last) {
std::set<jl_sym_t*>::iterator it = as.begin();
for(; it != as.end(); it++) {
if (vars.find(*it) != vars.end() &&
local_var_occurs(jl_arrayref(stmts,j), *it)) {
vars[*it].isVolatile = true;
}
}
}
}
}
}
}
}
// --- escape analysis ---
static bool expr_is_symbol(jl_value_t *e)
{
return (jl_is_symbol(e) || jl_is_symbolnode(e) || jl_is_topnode(e));
}
// a very simple, conservative escape analysis that is sufficient for
// eliding allocation of varargs tuples.
// "esc" means "in escaping context"
static void simple_escape_analysis(jl_value_t *expr, bool esc, jl_codectx_t *ctx)
{
if (jl_is_expr(expr)) {
esc = true;
jl_expr_t *e = (jl_expr_t*)expr;
size_t i;
if (e->head == call_sym || e->head == call1_sym || e->head == new_sym) {
int alen = jl_array_dim0(e->args);
jl_value_t *f = jl_exprarg(e,0);
simple_escape_analysis(f, esc, ctx);
if (expr_is_symbol(f)) {
if (is_constant(f, ctx, false)) {
jl_value_t *fv =
jl_interpret_toplevel_expr_in(ctx->module, f, NULL, 0);
if (jl_typeis(fv, jl_intrinsic_type)) {
esc = false;
JL_I::intrinsic fi = (JL_I::intrinsic)jl_unbox_int32(fv);
if (fi == JL_I::ccall) {
esc = true;
simple_escape_analysis(jl_exprarg(e,1), esc, ctx);
// 2nd and 3d arguments are static
for(i=4; i < (size_t)alen; i+=2) {
simple_escape_analysis(jl_exprarg(e,i), esc, ctx);
}
return;
}
}
else if (jl_is_function(fv)) {
jl_function_t *ff = (jl_function_t*)fv;
if (ff->fptr == jl_f_tuplelen ||
ff->fptr == jl_f_tupleref ||
(ff->fptr == jl_f_apply && alen==3 &&
expr_type(jl_exprarg(e,1),ctx) == (jl_value_t*)jl_function_type)) {
esc = false;
}
}
}
}
for(i=1; i < (size_t)alen; i++) {
simple_escape_analysis(jl_exprarg(e,i), esc, ctx);
}
}
else if (e->head == method_sym) {
simple_escape_analysis(jl_exprarg(e,0), esc, ctx);
simple_escape_analysis(jl_exprarg(e,1), esc, ctx);
simple_escape_analysis(jl_exprarg(e,2), esc, ctx);
}
else if (e->head != line_sym) {
size_t elen = jl_array_dim0(e->args);
for(i=0; i < elen; i++) {
simple_escape_analysis(jl_exprarg(e,i), esc, ctx);
}
}
return;
}
jl_value_t *ty = expr_type(expr, ctx);
if (jl_is_symbolnode(expr)) {
expr = (jl_value_t*)jl_symbolnode_sym(expr);
}
if (jl_is_symbol(expr)) {
jl_sym_t *vname = ((jl_sym_t*)expr);
if (ctx->vars.find(vname) != ctx->vars.end()) {
jl_varinfo_t &vi = ctx->vars[vname];
vi.escapes |= esc;
vi.usedUndef |= (jl_subtype((jl_value_t*)jl_undef_type,ty,0)!=0);
if (!ctx->linfo->inferred)
vi.usedUndef = true;
vi.used = true;
}
}
}
// --- gc root utils ---
static Value *make_gcroot(Value *v, jl_codectx_t *ctx)
{
Value *froot = builder.CreateGEP(ctx->argTemp,
ConstantInt::get(T_size,
ctx->argSpaceOffs +
ctx->argDepth));
builder.CreateStore(v, froot);
ctx->argDepth++;
if (ctx->argDepth > ctx->maxDepth)
ctx->maxDepth = ctx->argDepth;
return froot;
}
// test whether getting a field from the given type using the given
// field expression would not allocate memory
static bool is_getfield_nonallocating(jl_datatype_t *ty, jl_value_t *fld)
{
if (!jl_is_leaf_type((jl_value_t*)ty))
return false;
jl_sym_t *name = NULL;
if (jl_is_quotenode(fld) && jl_is_symbol(jl_fieldref(fld,0))) {
name = (jl_sym_t*)jl_fieldref(fld,0);
}
for(size_t i=0; i < jl_tuple_len(ty->types); i++) {
if (!(ty->fields[i].isptr ||
(name && name != (jl_sym_t*)jl_tupleref(ty->names,i)))) {
return false;
}
}
return true;
}
static bool jltupleisbits(jl_value_t *jt, bool allow_unsized)
{
if (!jl_is_tuple(jt))
return jl_isbits(jt) && jl_is_leaf_type(jt) && (allow_unsized ||
((jl_is_bitstype(jt) && jl_datatype_size(jt) > 0) ||
(jl_is_datatype(jt) && jl_tuple_len(((jl_datatype_t*)jt)->names)>0)));
size_t ntypes = jl_tuple_len(jt);
if (ntypes == 0)
return allow_unsized;
for (size_t i = 0; i < ntypes; ++i)
if (!jltupleisbits(jl_tupleref(jt,i),allow_unsized))
return false;
return true;
}
static bool jl_tupleref_nonallocating(jl_value_t *ty, jl_value_t *idx)
{
if (!jl_is_tuple(ty))
return false;
if (jltupleisbits(ty))
return false;
return true;
}
// does "ex" compute something that doesn't need a root over the whole function?
static bool is_stable_expr(jl_value_t *ex, jl_codectx_t *ctx)
{
if (jl_is_symbolnode(ex))
ex = (jl_value_t*)jl_symbolnode_sym(ex);
if (jl_is_symbol(ex)) {
if (ctx->vars.find((jl_sym_t*)ex) != ctx->vars.end()) {
// arguments and SSA vars are stable
jl_varinfo_t &rhs = ctx->vars[(jl_sym_t*)ex];
if ((rhs.isArgument && !rhs.isAssigned) || rhs.isSA)
return true;
}
}
if (static_eval(ex, ctx, true, false) != NULL)