-
-
Notifications
You must be signed in to change notification settings - Fork 5.5k
/
ccall.cpp
2067 lines (1919 loc) · 78 KB
/
ccall.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
// This file is a part of Julia. License is MIT: http://julialang.org/license
// --- the ccall, cglobal, and llvm intrinsics ---
// Map from symbol name (in a certain library) to its GV in sysimg and the
// DL handle address in the current session.
typedef StringMap<std::pair<GlobalVariable*,void*>> SymMapGV;
static StringMap<std::pair<GlobalVariable*,SymMapGV>> libMapGV;
#ifdef _OS_WINDOWS_
static SymMapGV symMapExe;
static SymMapGV symMapDl;
#endif
static SymMapGV symMapDefault;
template<typename Func>
struct LazyModule {
Func func;
Module *m;
template<typename Func2>
LazyModule(Func2 &&func)
: func(std::forward<Func2>(func)),
m(nullptr)
{}
Module *get()
{
if (!m)
m = func();
return m;
}
Module &operator*()
{
return *get();
}
};
template<typename Func>
static LazyModule<typename std::remove_reference<Func>::type>
lazyModule(Func &&func)
{
return LazyModule<typename std::remove_reference<Func>::type>(
std::forward<Func>(func));
}
// Find or create the GVs for the library and symbol lookup.
// Return `runtime_lib` (whether the library name is a string)
// Optionally return the symbol address in the current session
// when `symaddr != nullptr`.
// The `lib` and `sym` GV returned may not be in the current module.
template<typename MT>
static bool runtime_sym_gvs(const char *f_lib, const char *f_name, MT &&M,
GlobalVariable *&lib, GlobalVariable *&sym,
void **symaddr=nullptr)
{
void *libsym = NULL;
bool runtime_lib = false;
GlobalVariable *libptrgv;
SymMapGV *symMap;
#ifdef _OS_WINDOWS_
if ((intptr_t)f_lib == 1) {
libptrgv = jlexe_var;
libsym = jl_exe_handle;
symMap = &symMapExe;
}
else if ((intptr_t)f_lib == 2) {
libptrgv = jldll_var;
libsym = jl_dl_handle;
symMap = &symMapDl;
}
else
#endif
if (f_lib == NULL) {
libptrgv = jlRTLD_DEFAULT_var;
libsym = jl_RTLD_DEFAULT_handle;
symMap = &symMapDefault;
}
else {
std::string name = "ccalllib_";
name += f_lib;
runtime_lib = true;
auto iter = libMapGV.find(f_lib);
if (iter == libMapGV.end()) {
libptrgv = new GlobalVariable(*M, T_pint8, false,
GlobalVariable::ExternalLinkage,
NULL, name);
auto &libgv = libMapGV[f_lib];
libgv = std::make_pair(global_proto(libptrgv), SymMapGV());
symMap = &libgv.second;
libsym = jl_get_library(f_lib);
assert(libsym != NULL);
*(void**)jl_emit_and_add_to_shadow(libptrgv) = libsym;
}
else {
libptrgv = iter->second.first;
symMap = &iter->second.second;
}
}
if (libsym == NULL) {
libsym = *(void**)jl_get_global(libptrgv);
}
assert(libsym != NULL);
GlobalVariable *llvmgv;
auto sym_iter = symMap->find(f_name);
if (sym_iter == symMap->end()) {
// MCJIT forces this to have external linkage eventually, so we would clobber
// the symbol of the actual function.
std::string name = "ccall_";
name += f_name;
name += "_";
name += std::to_string(globalUnique++);
llvmgv = new GlobalVariable(*M, T_pvoidfunc, false,
GlobalVariable::ExternalLinkage, NULL, name);
llvmgv = global_proto(llvmgv);
void *addr = jl_dlsym_e(libsym, f_name);
(*symMap)[f_name] = std::make_pair(llvmgv, addr);
if (symaddr)
*symaddr = addr;
*(void**)jl_emit_and_add_to_shadow(llvmgv) = addr;
}
else {
if (symaddr)
*symaddr = sym_iter->second.second;
llvmgv = sym_iter->second.first;
}
lib = libptrgv;
sym = llvmgv;
return runtime_lib;
}
static Value *runtime_sym_lookup(PointerType *funcptype, const char *f_lib,
const char *f_name, Function *f,
GlobalVariable *libptrgv,
GlobalVariable *llvmgv, bool runtime_lib)
{
// in pseudo-code, this function emits the following:
// global HMODULE *libptrgv
// global void **llvmgv
// if (*llvmgv == NULL) {
// *llvmgv = jl_load_and_lookup(f_lib, f_name, libptrgv);
// }
// return (*llvmgv)
BasicBlock *enter_bb = builder.GetInsertBlock();
BasicBlock *dlsym_lookup = BasicBlock::Create(jl_LLVMContext, "dlsym");
BasicBlock *ccall_bb = BasicBlock::Create(jl_LLVMContext, "ccall");
Constant *initnul = ConstantPointerNull::get((PointerType*)T_pvoidfunc);
LoadInst *llvmf_orig = builder.CreateAlignedLoad(llvmgv, sizeof(void*));
// This in principle needs a consume ordering so that load from
// this pointer sees a valid value. However, this is not supported by
// LLVM (or agreed on in the C/C++ standard FWIW) and should be
// almost impossible to happen on every platform we support since this
// ordering is enforced by the hardware and LLVM has to speculate an
// invalid load from the `cglobal` but doesn't depend on the `cglobal`
// value for this to happen.
// llvmf_orig->setAtomic(AtomicOrdering::Consume);
builder.CreateCondBr(builder.CreateICmpNE(llvmf_orig, initnul),
ccall_bb, dlsym_lookup);
assert(f->getParent() != NULL);
f->getBasicBlockList().push_back(dlsym_lookup);
builder.SetInsertPoint(dlsym_lookup);
Value *libname;
if (runtime_lib) {
libname = stringConstPtr(builder, f_lib);
}
else {
libname = literal_static_pointer_val(f_lib, T_pint8);
}
#if JL_LLVM_VERSION >= 30700
Value *llvmf = builder.CreateCall(prepare_call(builder, jldlsym_func), { libname, stringConstPtr(builder, f_name), libptrgv });
#else
Value *llvmf = builder.CreateCall3(prepare_call(builder, jldlsym_func), libname, stringConstPtr(builder, f_name), libptrgv);
#endif
auto store = builder.CreateAlignedStore(llvmf, llvmgv, sizeof(void*));
# if JL_LLVM_VERSION >= 30900
store->setAtomic(AtomicOrdering::Release);
# else
store->setAtomic(Release);
# endif
builder.CreateBr(ccall_bb);
f->getBasicBlockList().push_back(ccall_bb);
builder.SetInsertPoint(ccall_bb);
PHINode *p = builder.CreatePHI(T_pvoidfunc, 2);
p->addIncoming(llvmf_orig, enter_bb);
p->addIncoming(llvmf, dlsym_lookup);
return builder.CreatePointerCast(p, funcptype);
}
static Value *runtime_sym_lookup(PointerType *funcptype, const char *f_lib,
const char *f_name, Function *f)
{
GlobalVariable *libptrgv;
GlobalVariable *llvmgv;
bool runtime_lib = runtime_sym_gvs(f_lib, f_name, f->getParent(),
libptrgv, llvmgv);
libptrgv = prepare_global(libptrgv);
llvmgv = prepare_global(llvmgv);
return runtime_sym_lookup(funcptype, f_lib, f_name, f, libptrgv, llvmgv,
runtime_lib);
}
// Map from distinct callee's to its GOT entry.
// In principle the attribute, function type and calling convention
// don't need to be part of the key but it seems impossible to forward
// all the arguments without writing assembly directly.
// This doesn't matter too much in reality since a single function is usually
// not called with multiple signatures.
static DenseMap<AttributeSet,
std::map<std::tuple<GlobalVariable*,FunctionType*,
CallingConv::ID>,GlobalVariable*>> allPltMap;
// Emit a "PLT" entry that will be lazily initialized
// when being called the first time.
static GlobalVariable *emit_plt_thunk(Module *M, FunctionType *functype, const AttributeSet &attrs,
CallingConv::ID cc, const char *f_lib, const char *f_name,
GlobalVariable *libptrgv, GlobalVariable *llvmgv,
void *symaddr, bool runtime_lib)
{
PointerType *funcptype = PointerType::get(functype, 0);
libptrgv = prepare_global(libptrgv, M);
llvmgv = prepare_global(llvmgv, M);
BasicBlock *old = builder.GetInsertBlock();
DebugLoc olddl = builder.getCurrentDebugLocation();
DebugLoc noDbg;
builder.SetCurrentDebugLocation(noDbg);
std::stringstream funcName;
funcName << "jlplt_" << f_name << "_" << globalUnique++;
auto fname = funcName.str();
Function *plt = Function::Create(functype,
GlobalVariable::ExternalLinkage,
fname, M);
jl_init_function(plt);
plt->setAttributes(attrs);
if (cc != CallingConv::C)
plt->setCallingConv(cc);
funcName << "_got";
auto gname = funcName.str();
GlobalVariable *got = new GlobalVariable(*M, T_pvoidfunc, false,
GlobalVariable::ExternalLinkage,
nullptr, gname);
*(void**)jl_emit_and_add_to_shadow(got) = symaddr;
BasicBlock *b0 = BasicBlock::Create(jl_LLVMContext, "top", plt);
builder.SetInsertPoint(b0);
Value *ptr = runtime_sym_lookup(funcptype, f_lib, f_name, plt, libptrgv,
llvmgv, runtime_lib);
auto store = builder.CreateAlignedStore(builder.CreateBitCast(ptr, T_pvoidfunc), got, sizeof(void*));
#if JL_LLVM_VERSION >= 30900
store->setAtomic(AtomicOrdering::Release);
#else
store->setAtomic(Release);
#endif
SmallVector<Value*, 16> args;
for (Function::arg_iterator arg = plt->arg_begin(), arg_e = plt->arg_end(); arg != arg_e; ++arg)
args.push_back(&*arg);
CallInst *ret = builder.CreateCall(ptr, ArrayRef<Value*>(args));
ret->setAttributes(attrs);
if (cc != CallingConv::C)
ret->setCallingConv(cc);
// NoReturn function can trigger LLVM verifier error when declared as
// MustTail since other passes might replace the `ret` with
// `unreachable` (LLVM should probably accept `unreachable`).
if (attrs.hasAttribute(AttributeSet::FunctionIndex,
Attribute::NoReturn)) {
builder.CreateUnreachable();
}
else {
// musttail support is very bad on ARM, PPC, PPC64 (as of LLVM 3.9)
// Known failures includes vararg (not needed here) and sret.
#if JL_LLVM_VERSION >= 30700 && (defined(_CPU_X86_) || defined(_CPU_X86_64_) || \
defined(_CPU_AARCH64_))
ret->setTailCallKind(CallInst::TCK_MustTail);
#endif
if (functype->getReturnType() == T_void) {
builder.CreateRetVoid();
}
else {
builder.CreateRet(ret);
}
}
builder.SetInsertPoint(old);
builder.SetCurrentDebugLocation(olddl);
got = global_proto(got); // exchange got for the permanent global before jl_finalize_module destroys it
jl_finalize_module(M, true);
auto shadowgot =
cast<GlobalVariable>(shadow_output->getNamedValue(gname));
auto shadowplt = cast<Function>(shadow_output->getNamedValue(fname));
shadowgot->setInitializer(ConstantExpr::getBitCast(shadowplt,
T_pvoidfunc));
return got;
}
static Value *emit_plt(FunctionType *functype, const AttributeSet &attrs,
CallingConv::ID cc, const char *f_lib, const char *f_name)
{
assert(imaging_mode);
// Don't do this for vararg functions so that the `musttail` is only
// an optimization and is not required to function correctly.
assert(!functype->isVarArg());
GlobalVariable *libptrgv;
GlobalVariable *llvmgv;
void *symaddr;
auto LM = lazyModule([&] {
Module *m = new Module(f_name, jl_LLVMContext);
jl_setup_module(m);
return m;
});
bool runtime_lib = runtime_sym_gvs(f_lib, f_name, LM,
libptrgv, llvmgv, &symaddr);
PointerType *funcptype = PointerType::get(functype, 0);
auto &pltMap = allPltMap[attrs];
auto key = std::make_tuple(llvmgv, functype, cc);
GlobalVariable *&shadowgot = pltMap[key];
if (!shadowgot) {
shadowgot = emit_plt_thunk(LM.get(), functype, attrs, cc, f_lib, f_name, libptrgv, llvmgv, symaddr, runtime_lib);
}
else {
// `runtime_sym_gvs` shouldn't have created anything in a new module
// if it returns a GV that already exists.
assert(!LM.m);
}
GlobalVariable *got = prepare_global(shadowgot);
LoadInst *got_val = builder.CreateAlignedLoad(got, sizeof(void*));
// See comment in `runtime_sym_lookup` above. This in principle needs a
// consume ordering too. This is even less likely to cause issues though
// since the only thing we do to this loaded pointer is to call it
// immediately.
// got_val->setAtomic(AtomicOrdering::Consume);
return builder.CreateBitCast(got_val, funcptype);
}
// --- ABI Implementations ---
// Partially based on the LDC ABI implementations licensed under the BSD 3-clause license
class AbiLayout {
public:
virtual ~AbiLayout() {}
virtual bool use_sret(jl_datatype_t *ty) = 0;
virtual bool needPassByRef(jl_datatype_t *ty, AttrBuilder&) = 0;
virtual Type *preferred_llvm_type(jl_datatype_t *ty, bool isret) const = 0;
};
// Determine if object of bitstype ty maps to a native x86 SIMD type (__m128, __m256, or __m512) in C
static bool is_native_simd_type(jl_datatype_t *dt) {
size_t size = jl_datatype_size(dt);
if (size != 16 && size != 32 && size != 64)
// Wrong size for xmm, ymm, or zmm register.
return false;
uint32_t n = jl_datatype_nfields(dt);
if (n<2)
// Not mapped to SIMD register.
return false;
jl_value_t *ft0 = jl_field_type(dt, 0);
for (uint32_t i = 1; i < n; ++i)
if (jl_field_type(dt, i) != ft0)
// Not homogeneous
return false;
// Type is homogeneous. Check if it maps to LLVM vector.
return jl_special_vector_alignment(n, ft0) != 0;
}
#include "abi_llvm.cpp"
#include "abi_arm.cpp"
#include "abi_aarch64.cpp"
#include "abi_ppc64le.cpp"
#include "abi_win32.cpp"
#include "abi_win64.cpp"
#include "abi_x86_64.cpp"
#include "abi_x86.cpp"
#if defined ABI_LLVM
typedef ABI_LLVMLayout DefaultAbiState;
#elif defined _CPU_X86_64_
# if defined _OS_WINDOWS_
typedef ABI_Win64Layout DefaultAbiState;
# else
typedef ABI_x86_64Layout DefaultAbiState;
# endif
#elif defined _CPU_X86_
# if defined _OS_WINDOWS_
typedef ABI_Win32Layout DefaultAbiState;
# else
typedef ABI_x86Layout DefaultAbiState;
# endif
#elif defined _CPU_ARM_
typedef ABI_ARMLayout DefaultAbiState;
#elif defined _CPU_AARCH64_
typedef ABI_AArch64Layout DefaultAbiState;
#elif defined _CPU_PPC64_
typedef ABI_PPC64leLayout DefaultAbiState;
#else
# warning "ccall is defaulting to llvm ABI, since no platform ABI has been defined for this CPU/OS combination"
typedef ABI_LLVMLayout DefaultAbiState;
#endif
// basic type widening and cast conversions
static Value *llvm_type_rewrite(
Value *v, Type *target_type,
bool issigned, /* determines whether an integer value should be zero or sign extended */
jl_codectx_t *ctx)
{
Type *from_type = v->getType();
if (target_type == from_type)
return v;
if (from_type == T_void || isa<UndefValue>(v))
return UndefValue::get(target_type); // convert undef (unreachable) -> undef (target_type)
assert(from_type->isPointerTy() == target_type->isPointerTy()); // expect that all ABIs consider all pointers to be equivalent
if (target_type->isPointerTy())
return emit_bitcast(v, target_type);
// simple integer and float widening & conversion cases
if (from_type->getPrimitiveSizeInBits() > 0 &&
target_type->getPrimitiveSizeInBits() == from_type->getPrimitiveSizeInBits())
return emit_bitcast(v, target_type);
if (target_type->isFloatingPointTy() && from_type->isFloatingPointTy()) {
if (target_type->getPrimitiveSizeInBits() > from_type->getPrimitiveSizeInBits())
return builder.CreateFPExt(v, target_type);
else if (target_type->getPrimitiveSizeInBits() < from_type->getPrimitiveSizeInBits())
return builder.CreateFPTrunc(v, target_type);
else
return v;
}
if (target_type->isIntegerTy() && from_type->isIntegerTy()) {
if (issigned)
return builder.CreateSExtOrTrunc(v, target_type);
else
return builder.CreateZExtOrTrunc(v, target_type);
}
// one or both of from_type and target_type is a VectorType or AggregateType
// LLVM doesn't allow us to cast these values directly, so
// we need to use this alloca copy trick instead
// On ARM and AArch64, the ABI requires casting through memory to different
// sizes.
Value *from;
Value *to;
#if JL_LLVM_VERSION >= 30600
const DataLayout &DL = jl_ExecutionEngine->getDataLayout();
#else
const DataLayout &DL = *jl_ExecutionEngine->getDataLayout();
#endif
if (DL.getTypeAllocSize(target_type) >= DL.getTypeAllocSize(from_type)) {
to = emit_static_alloca(target_type, ctx);
from = emit_bitcast(to, from_type->getPointerTo());
}
else {
from = emit_static_alloca(from_type, ctx);
to = emit_bitcast(from, target_type->getPointerTo());
}
builder.CreateStore(v, from);
return builder.CreateLoad(to);
}
// --- argument passing and scratch space utilities ---
static Value *runtime_apply_type(jl_value_t *ty, jl_unionall_t *unionall, jl_codectx_t *ctx)
{
// box if concrete type was not statically known
Value *args[3];
args[0] = literal_pointer_val(ty);
args[1] = literal_pointer_val((jl_value_t*)ctx->linfo->def->sig);
args[2] = builder.CreateInBoundsGEP(
LLVM37_param(T_pjlvalue)
emit_bitcast(ctx->spvals_ptr, T_ppjlvalue),
ConstantInt::get(T_size, sizeof(jl_svec_t) / sizeof(jl_value_t*)));
return builder.CreateCall(prepare_call(jlapplytype_func), makeArrayRef(args));
}
static void typeassert_input(const jl_cgval_t &jvinfo, jl_value_t *jlto, jl_unionall_t *jlto_env, int argn, bool addressOf, jl_codectx_t *ctx)
{
if (jlto != (jl_value_t*)jl_any_type && !jl_subtype(jvinfo.typ, jlto)) {
if (!addressOf && jlto == (jl_value_t*)jl_voidpointer_type) {
// allow a bit more flexibility for what can be passed to (void*) due to Ref{T} conversion behavior in input
if (!jl_is_cpointer_type(jvinfo.typ)) {
// emit a typecheck, if not statically known to be correct
std::stringstream msg;
msg << "ccall argument ";
msg << argn;
emit_cpointercheck(jvinfo, msg.str(), ctx);
}
}
else {
// emit a typecheck, if not statically known to be correct
std::stringstream msg;
msg << "ccall argument ";
msg << argn;
if (!jlto_env || !jl_has_typevar_from_unionall(jlto, jlto_env)) {
emit_typecheck(jvinfo, jlto, msg.str(), ctx);
}
else {
jl_cgval_t jlto_runtime = mark_julia_type(runtime_apply_type(jlto, jlto_env, ctx), true, jl_any_type, ctx);
Value *vx = boxed(jvinfo, ctx);
Value *istype = builder.
CreateICmpNE(
#if JL_LLVM_VERSION >= 30700
builder.CreateCall(prepare_call(jlisa_func), { vx, boxed(jlto_runtime, ctx) }),
#else
builder.CreateCall2(prepare_call(jlisa_func), vx, boxed(jlto_runtime, ctx)),
#endif
ConstantInt::get(T_int32, 0));
BasicBlock *failBB = BasicBlock::Create(jl_LLVMContext, "fail", ctx->f);
BasicBlock *passBB = BasicBlock::Create(jl_LLVMContext, "pass", ctx->f);
builder.CreateCondBr(istype, passBB, failBB);
builder.SetInsertPoint(failBB);
emit_type_error(mark_julia_type(vx, true, jl_any_type, ctx), boxed(jlto_runtime, ctx), msg.str(), ctx);
builder.CreateUnreachable();
builder.SetInsertPoint(passBB);
}
}
}
}
static Value *julia_to_address(Type *to, jl_value_t *jlto, jl_unionall_t *jlto_env, const jl_cgval_t &jvinfo,
int argn, jl_codectx_t *ctx, bool *needStackRestore)
{
assert(jl_is_datatype(jlto) && julia_struct_has_layout((jl_datatype_t*)jlto, jlto_env));
if (!jl_is_cpointer_type(jlto) || !to->isPointerTy()) {
emit_error("ccall: & on argument was not matched by Ptr{T} argument type", ctx);
return UndefValue::get(to);
}
jl_value_t *ety;
if (jlto == (jl_value_t*)jl_voidpointer_type) {
ety = jvinfo.typ; // skip the type-check
}
else {
ety = jl_tparam0(jlto);
typeassert_input(jvinfo, ety, jlto_env, argn, true, ctx);
}
assert(to->isPointerTy());
if (jvinfo.isboxed) {
if (!jl_is_abstracttype(ety)) {
if (jl_is_mutable_datatype(ety)) {
// no copy, just reference the data field
return data_pointer(jvinfo, ctx, to);
}
else if (jl_is_immutable_datatype(ety) && jlto != (jl_value_t*)jl_voidpointer_type) {
// yes copy
Value *nbytes;
AllocaInst *ai;
if (jl_is_leaf_type(ety) || jl_is_primitivetype(ety)) {
int nb = jl_datatype_size(ety);
nbytes = ConstantInt::get(T_int32, nb);
ai = emit_static_alloca(T_int8, nb, ctx);
}
else {
nbytes = emit_datatype_size(emit_typeof_boxed(jvinfo,ctx));
ai = builder.CreateAlloca(T_int8, nbytes);
*needStackRestore = true;
}
ai->setAlignment(16);
builder.CreateMemCpy(ai, data_pointer(jvinfo, ctx, T_pint8), nbytes, sizeof(void*)); // minimum gc-alignment in julia is pointer size
return emit_bitcast(ai, to);
}
}
// emit maybe copy
*needStackRestore = true;
Value *jvt = emit_typeof_boxed(jvinfo, ctx);
BasicBlock *mutableBB = BasicBlock::Create(jl_LLVMContext, "is-mutable", ctx->f);
BasicBlock *immutableBB = BasicBlock::Create(jl_LLVMContext, "is-immutable", ctx->f);
BasicBlock *afterBB = BasicBlock::Create(jl_LLVMContext, "after", ctx->f);
Value *ismutable = emit_datatype_mutabl(jvt);
builder.CreateCondBr(ismutable, mutableBB, immutableBB);
builder.SetInsertPoint(mutableBB);
Value *p1 = data_pointer(jvinfo, ctx, to);
builder.CreateBr(afterBB);
builder.SetInsertPoint(immutableBB);
Value *nbytes = emit_datatype_size(jvt);
AllocaInst *ai = builder.CreateAlloca(T_int8, nbytes);
ai->setAlignment(16);
builder.CreateMemCpy(ai, data_pointer(jvinfo, ctx, T_pint8), nbytes, sizeof(void*)); // minimum gc-alignment in julia is pointer size
Value *p2 = emit_bitcast(ai, to);
builder.CreateBr(afterBB);
builder.SetInsertPoint(afterBB);
PHINode *p = builder.CreatePHI(to, 2);
p->addIncoming(p1, mutableBB);
p->addIncoming(p2, immutableBB);
return p;
}
Type *slottype = julia_struct_to_llvm(jvinfo.typ, NULL, NULL);
// pass the address of an alloca'd thing, not a box
// since those are immutable.
Value *slot = emit_static_alloca(slottype, ctx);
if (!jvinfo.ispointer()) {
builder.CreateStore(emit_unbox(slottype, jvinfo, ety), slot);
}
else {
builder.CreateMemCpy(slot,
data_pointer(jvinfo, ctx, slot->getType()),
(uint64_t)jl_datatype_size(ety),
(uint64_t)((jl_datatype_t*)ety)->layout->alignment);
mark_gc_use(jvinfo);
}
if (slot->getType() != to)
slot = emit_bitcast(slot, to);
return slot;
}
// Emit code to convert argument to form expected by C ABI
// to = desired LLVM type
// jlto = Julia type of formal argument
// jvinfo = value of actual argument
static Value *julia_to_native(Type *to, bool toboxed, jl_value_t *jlto, jl_unionall_t *jlto_env,
const jl_cgval_t &jvinfo,
bool byRef, int argn, jl_codectx_t *ctx,
bool *needStackRestore)
{
// We're passing Any
if (toboxed) {
assert(!byRef); // don't expect any ABI to pass pointers by pointer
return boxed(jvinfo, ctx);
}
assert(jl_is_datatype(jlto) && julia_struct_has_layout((jl_datatype_t*)jlto, jlto_env));
typeassert_input(jvinfo, jlto, jlto_env, argn, false, ctx);
if (!byRef)
return emit_unbox(to, jvinfo, jlto);
// pass the address of an alloca'd thing, not a box
// since those are immutable.
Value *slot = emit_static_alloca(to, ctx);
if (!jvinfo.ispointer()) {
builder.CreateStore(emit_unbox(to, jvinfo, jlto), slot);
}
else {
builder.CreateMemCpy(slot,
data_pointer(jvinfo, ctx, slot->getType()),
(uint64_t)jl_datatype_size(jlto),
(uint64_t)((jl_datatype_t*)jlto)->layout->alignment);
mark_gc_use(jvinfo);
}
return slot;
}
typedef struct {
Value *jl_ptr; // if the argument is a run-time computed pointer
void (*fptr)(void); // if the argument is a constant pointer
const char *f_name; // if the symbol name is known
const char *f_lib; // if a library name is specified
jl_value_t *gcroot;
} native_sym_arg_t;
// --- parse :sym or (:sym, :lib) argument into address info ---
static void interpret_symbol_arg(native_sym_arg_t &out, jl_value_t *arg, jl_codectx_t *ctx, const char *fname, bool llvmcall)
{
Value *&jl_ptr = out.jl_ptr;
void (*&fptr)(void) = out.fptr;
const char *&f_name = out.f_name;
const char *&f_lib = out.f_lib;
jl_value_t *ptr = static_eval(arg, ctx, true);
if (ptr == NULL) {
jl_value_t *ptr_ty = expr_type(arg, ctx);
jl_cgval_t arg1 = emit_expr(arg, ctx);
if (!jl_is_cpointer_type(ptr_ty)) {
emit_cpointercheck(arg1,
!strcmp(fname,"ccall") ?
"ccall: first argument not a pointer or valid constant expression" :
"cglobal: first argument not a pointer or valid constant expression",
ctx);
}
arg1 = update_julia_type(arg1, (jl_value_t*)jl_voidpointer_type, ctx);
jl_ptr = emit_unbox(T_size, arg1, (jl_value_t*)jl_voidpointer_type);
}
else {
out.gcroot = ptr;
if (jl_is_tuple(ptr) && jl_nfields(ptr) == 1) {
ptr = jl_fieldref(ptr, 0);
}
if (jl_is_symbol(ptr))
f_name = jl_symbol_name((jl_sym_t*)ptr);
else if (jl_is_string(ptr))
f_name = jl_string_data(ptr);
if (f_name != NULL) {
// just symbol, default to JuliaDLHandle
// will look in process symbol table
#ifdef _OS_WINDOWS_
if (!llvmcall)
f_lib = jl_dlfind_win32(f_name);
#endif
}
else if (jl_is_cpointer_type(jl_typeof(ptr))) {
fptr = *(void(**)(void))jl_data_ptr(ptr);
}
else if (jl_is_tuple(ptr) && jl_nfields(ptr) > 1) {
jl_value_t *t0 = jl_fieldref(ptr, 0);
if (jl_is_symbol(t0))
f_name = jl_symbol_name((jl_sym_t*)t0);
else if (jl_is_string(t0))
f_name = jl_string_data(t0);
else
JL_TYPECHKS(fname, symbol, t0);
jl_value_t *t1 = jl_fieldref(ptr, 1);
if (jl_is_symbol(t1))
f_lib = jl_symbol_name((jl_sym_t*)t1);
else if (jl_is_string(t1))
f_lib = jl_string_data(t1);
else
JL_TYPECHKS(fname, symbol, t1);
}
else {
JL_TYPECHKS(fname, pointer, ptr);
}
}
}
static jl_value_t* try_eval(jl_value_t *ex, jl_codectx_t *ctx, const char *failure, bool compiletime=false)
{
jl_value_t *constant = NULL;
constant = static_eval(ex, ctx, true, true);
if (constant || jl_is_ssavalue(ex))
return constant;
JL_TRY {
size_t last_age = jl_get_ptls_states()->world_age;
jl_get_ptls_states()->world_age = ctx->world;
constant = jl_interpret_toplevel_expr_in(ctx->module, ex, ctx->source, ctx->linfo->sparam_vals);
jl_get_ptls_states()->world_age = last_age;
}
JL_CATCH {
if (compiletime)
jl_rethrow_with_add(failure);
if (failure)
emit_error(failure, ctx);
constant = NULL;
}
return constant;
}
// --- code generator for cglobal ---
static jl_cgval_t emit_runtime_call(JL_I::intrinsic f, const jl_cgval_t *argv, size_t nargs, jl_codectx_t *ctx);
static jl_cgval_t emit_cglobal(jl_value_t **args, size_t nargs, jl_codectx_t *ctx)
{
JL_NARGS(cglobal, 1, 2);
jl_value_t *rt = NULL;
Value *res;
native_sym_arg_t sym = {};
JL_GC_PUSH2(&rt, &sym.gcroot);
if (nargs == 2) {
rt = static_eval(args[2], ctx, true, true);
if (rt == NULL) {
JL_GC_POP();
jl_cgval_t argv[2];
argv[0] = emit_expr(args[0], ctx);
argv[1] = emit_expr(args[1], ctx);
return emit_runtime_call(JL_I::cglobal, argv, nargs, ctx);
}
JL_TYPECHK(cglobal, type, rt);
rt = (jl_value_t*)jl_apply_type1((jl_value_t*)jl_pointer_type, rt);
}
else {
rt = (jl_value_t*)jl_voidpointer_type;
}
Type *lrt = julia_type_to_llvm(rt);
if (lrt == NULL)
lrt = T_pint8;
interpret_symbol_arg(sym, args[1], ctx, "cglobal", false);
if (sym.jl_ptr != NULL) {
res = builder.CreateIntToPtr(sym.jl_ptr, lrt);
}
else if (sym.fptr != NULL) {
res = literal_static_pointer_val((void*)(uintptr_t)sym.fptr, lrt);
if (imaging_mode)
jl_printf(JL_STDERR,"WARNING: literal address used in cglobal for %s; code cannot be statically compiled\n", sym.f_name);
}
else {
if (imaging_mode) {
res = runtime_sym_lookup((PointerType*)lrt, sym.f_lib, sym.f_name, ctx->f);
}
else {
void *symaddr = jl_dlsym_e(jl_get_library(sym.f_lib), sym.f_name);
if (symaddr == NULL) {
std::stringstream msg;
msg << "cglobal: could not find symbol ";
msg << sym.f_name;
if (sym.f_lib != NULL) {
#ifdef _OS_WINDOWS_
assert((intptr_t)sym.f_lib != 1 && (intptr_t)sym.f_lib != 2);
#endif
msg << " in library ";
msg << sym.f_lib;
}
emit_error(msg.str(), ctx);
}
// since we aren't saving this code, there's no sense in
// putting anything complicated here: just JIT the address of the cglobal
res = literal_static_pointer_val(symaddr, lrt);
}
}
JL_GC_POP();
return mark_julia_type(res, false, rt, ctx);
}
#ifdef USE_MCJIT
class FunctionMover final : public ValueMaterializer
{
public:
FunctionMover(llvm::Module *dest,llvm::Module *src) :
ValueMaterializer(), VMap(), destModule(dest), srcModule(src),
LazyFunctions(0)
{
}
ValueToValueMapTy VMap;
llvm::Module *destModule;
llvm::Module *srcModule;
std::vector<Function *> LazyFunctions;
Function *CloneFunctionProto(Function *F)
{
assert(!F->isDeclaration());
Function *NewF = Function::Create(F->getFunctionType(),
Function::ExternalLinkage,
F->getName(),
destModule);
LazyFunctions.push_back(F);
VMap[F] = NewF;
return NewF;
}
void CloneFunctionBody(Function *F)
{
Function *NewF = (Function*)(Value*)VMap[F];
assert(NewF != NULL);
Function::arg_iterator DestI = NewF->arg_begin();
for (Function::const_arg_iterator I = F->arg_begin(), E = F->arg_end(); I != E; ++I) {
DestI->setName(I->getName()); // Copy the name over...
VMap[&*I] = &*(DestI++); // Add mapping to VMap
}
#if JL_LLVM_VERSION >= 30600
// Clone debug info - Not yet public API
// llvm::CloneDebugInfoMetadata(NewF,F,VMap);
#endif
SmallVector<ReturnInst*, 8> Returns;
llvm::CloneFunctionInto(NewF,F,VMap,true,Returns,"",NULL,NULL,this);
NewF->setComdat(nullptr);
NewF->setSection("");
}
Function *CloneFunction(Function *F)
{
Function *NewF = (llvm::Function*)MapValue(F,VMap,RF_None,NULL,this);
ResolveLazyFunctions();
return NewF;
}
void ResolveLazyFunctions()
{
while (!LazyFunctions.empty()) {
Function *F = LazyFunctions.back();
LazyFunctions.pop_back();
CloneFunctionBody(F);
}
}
Value *InjectFunctionProto(Function *F)
{
Function *NewF = destModule->getFunction(F->getName());
if (!NewF) {
NewF = function_proto(F);
NewF->setComdat(nullptr);
destModule->getFunctionList().push_back(NewF);
}
return NewF;
}
#if JL_LLVM_VERSION >= 30900
Value *materialize(Value *V) override
#elif JL_LLVM_VERSION >= 30800
Value *materializeDeclFor(Value *V) override
#else
Value *materializeValueFor (Value *V) override
#endif
{
Function *F = dyn_cast<Function>(V);
if (F) {
if (isIntrinsicFunction(F)) {
return destModule->getOrInsertFunction(F->getName(),F->getFunctionType());
}
if (F->isDeclaration() || F->getParent() != destModule) {
if (F->getName().empty())
return CloneFunctionProto(F);
Function *shadow = srcModule->getFunction(F->getName());
if (shadow != NULL && !shadow->isDeclaration()) {
Function *oldF = destModule->getFunction(F->getName());
if (oldF)
return oldF;
#ifdef USE_ORCJIT
if (jl_ExecutionEngine->findSymbol(F->getName(), false))
return InjectFunctionProto(F);
#endif
return CloneFunctionProto(shadow);
}
else if (!F->isDeclaration()) {
return CloneFunctionProto(F);
}
}
// Still a declaration and still in a different module
if (F->isDeclaration() && F->getParent() != destModule) {
// Create forward declaration in current module
return InjectFunctionProto(F);
}
}
else if (isa<GlobalVariable>(V)) {
GlobalVariable *GV = cast<GlobalVariable>(V);
assert(GV != NULL);
GlobalVariable *oldGV = destModule->getGlobalVariable(GV->getName());
if (oldGV != NULL)
return oldGV;
GlobalVariable *newGV = new GlobalVariable(*destModule,
GV->getType()->getElementType(),
GV->isConstant(),
GlobalVariable::ExternalLinkage,
NULL,
GV->getName(),
NULL,
GV->getThreadLocalMode(),
GV->getType()->getPointerAddressSpace());
newGV->copyAttributesFrom(GV);
newGV->setComdat(nullptr);
if (GV->isDeclaration())
return newGV;
if (!GV->getName().empty()) {
uint64_t addr = jl_ExecutionEngine->getGlobalValueAddress(GV->getName());
if (addr != 0) {
newGV->setExternallyInitialized(true);
return newGV;
}
}
if (GV->hasInitializer()) {
Value *C = MapValue(GV->getInitializer(),VMap,RF_None,NULL,this);
newGV->setInitializer(cast<Constant>(C));
}
return newGV;
}
return NULL;
};
};
#endif
// llvmcall(ir, (rettypes...), (argtypes...), args...)
static jl_cgval_t emit_llvmcall(jl_value_t **args, size_t nargs, jl_codectx_t *ctx)
{
JL_NARGSV(llvmcall, 3);
jl_value_t *rt = NULL, *at = NULL, *ir = NULL, *decl = NULL;
jl_svec_t *stt = NULL;
JL_GC_PUSH5(&ir, &rt, &at, &stt, &decl);
at = try_eval(args[3], ctx, "error statically evaluating llvmcall argument tuple", true);
rt = try_eval(args[2], ctx, "error statically evaluating llvmcall return type", true);
ir = try_eval(args[1], ctx, "error statically evaluating llvm IR argument", true);
int i = 1;
if (jl_is_tuple(ir)) {
// if the IR is a tuple, we expect (declarations, ir)
if (jl_nfields(ir) != 2)
jl_error("Tuple as first argument to llvmcall must have exactly two children");
decl = jl_fieldref(ir,0);
ir = jl_fieldref(ir,1);
if (!jl_is_string(decl))
jl_error("Declarations passed to llvmcall must be a string");
}
bool isString = jl_is_string(ir);
bool isPtr = jl_is_cpointer(ir);
if (!isString && !isPtr) {
jl_error("IR passed to llvmcall must be a string or pointer to an LLVM Function");
}
JL_TYPECHK(llvmcall, type, rt);
JL_TYPECHK(llvmcall, type, at);
std::stringstream ir_stream;
stt = jl_alloc_svec(nargs - 3);