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
pub use self::CalleeData::*;
use llvm::{self, ValueRef, get_params};
use rustc::hir::def_id::DefId;
use rustc::ty::subst::{Substs, Subst};
use rustc::traits;
use abi::{Abi, FnType};
use attributes;
use base;
use builder::Builder;
use common::{self, CrateContext};
use cleanup::CleanupScope;
use mir::lvalue::LvalueRef;
use consts;
use common::def_ty;
use declare;
use value::Value;
use meth;
use monomorphize::Instance;
use trans_item::TransItem;
use type_of;
use Disr;
use rustc::ty::{self, Ty, TypeFoldable};
use rustc::hir;
use std::iter;
use syntax_pos::DUMMY_SP;
use mir::lvalue::Alignment;
#[derive(Debug)]
pub enum CalleeData {
NamedTupleConstructor(Disr),
Fn(ValueRef),
Intrinsic,
Virtual(usize)
}
#[derive(Debug)]
pub struct Callee<'tcx> {
pub data: CalleeData,
pub ty: Ty<'tcx>
}
impl<'tcx> Callee<'tcx> {
pub fn ptr(llfn: ValueRef, ty: Ty<'tcx>) -> Callee<'tcx> {
Callee {
data: Fn(llfn),
ty: ty
}
}
pub fn def<'a>(ccx: &CrateContext<'a, 'tcx>, def_id: DefId, substs: &'tcx Substs<'tcx>)
-> Callee<'tcx> {
let tcx = ccx.tcx();
if let Some(trait_id) = tcx.trait_of_item(def_id) {
return Callee::trait_method(ccx, trait_id, def_id, substs);
}
let fn_ty = def_ty(ccx.shared(), def_id, substs);
if let ty::TyFnDef(.., f) = fn_ty.sty {
if f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic {
return Callee {
data: Intrinsic,
ty: fn_ty
};
}
}
if let Some(adt_def) = fn_ty.fn_ret().skip_binder().ty_adt_def() {
if let Some(i) = adt_def.variants.iter().position(|v| def_id == v.did) {
return Callee {
data: NamedTupleConstructor(Disr::for_variant(tcx, adt_def, i)),
ty: fn_ty
};
}
}
let (llfn, ty) = get_fn(ccx, def_id, substs);
Callee::ptr(llfn, ty)
}
pub fn trait_method<'a>(ccx: &CrateContext<'a, 'tcx>,
trait_id: DefId,
def_id: DefId,
substs: &'tcx Substs<'tcx>)
-> Callee<'tcx> {
let tcx = ccx.tcx();
let trait_ref = ty::TraitRef::from_method(tcx, trait_id, substs);
let trait_ref = tcx.normalize_associated_type(&ty::Binder(trait_ref));
match common::fulfill_obligation(ccx.shared(), DUMMY_SP, trait_ref) {
traits::VtableImpl(vtable_impl) => {
let name = tcx.item_name(def_id);
let (def_id, substs) = traits::find_method(tcx, name, substs, &vtable_impl);
let (llfn, ty) = get_fn(ccx, def_id, substs);
Callee::ptr(llfn, ty)
}
traits::VtableClosure(vtable_closure) => {
let trait_closure_kind = tcx.lang_items.fn_trait_kind(trait_id).unwrap();
let instance = Instance::new(def_id, substs);
let llfn = trans_closure_method(
ccx,
vtable_closure.closure_def_id,
vtable_closure.substs,
instance,
trait_closure_kind);
let method_ty = def_ty(ccx.shared(), def_id, substs);
Callee::ptr(llfn, method_ty)
}
traits::VtableFnPointer(vtable_fn_pointer) => {
let trait_closure_kind = tcx.lang_items.fn_trait_kind(trait_id).unwrap();
let instance = Instance::new(def_id, substs);
let llfn = trans_fn_pointer_shim(ccx, instance,
trait_closure_kind,
vtable_fn_pointer.fn_ty);
let method_ty = def_ty(ccx.shared(), def_id, substs);
Callee::ptr(llfn, method_ty)
}
traits::VtableObject(ref data) => {
Callee {
data: Virtual(tcx.get_vtable_index_of_object_method(data, def_id)),
ty: def_ty(ccx.shared(), def_id, substs)
}
}
vtable => {
bug!("resolved vtable bad vtable {:?} in trans", vtable);
}
}
}
pub fn direct_fn_type<'a>(&self, ccx: &CrateContext<'a, 'tcx>,
extra_args: &[Ty<'tcx>]) -> FnType {
let sig = ccx.tcx().erase_late_bound_regions_and_normalize(&self.ty.fn_sig());
let mut fn_ty = FnType::unadjusted(ccx, sig, extra_args);
if let Virtual(_) = self.data {
fn_ty.args[1].ignore();
}
fn_ty.adjust_for_abi(ccx, sig);
fn_ty
}
pub fn reify<'a>(self, ccx: &CrateContext<'a, 'tcx>) -> ValueRef {
match self.data {
Fn(llfn) => llfn,
Virtual(_) => meth::trans_object_shim(ccx, self),
NamedTupleConstructor(disr) => match self.ty.sty {
ty::TyFnDef(def_id, substs, _) => {
let instance = Instance::new(def_id, substs);
if let Some(&llfn) = ccx.instances().borrow().get(&instance) {
return llfn;
}
let sym = ccx.symbol_map().get_or_compute(ccx.shared(),
TransItem::Fn(instance));
assert!(!ccx.codegen_unit().contains_item(&TransItem::Fn(instance)));
let lldecl = declare::define_internal_fn(ccx, &sym, self.ty);
base::trans_ctor_shim(ccx, def_id, substs, disr, lldecl);
ccx.instances().borrow_mut().insert(instance, lldecl);
lldecl
}
_ => bug!("expected fn item type, found {}", self.ty)
},
Intrinsic => bug!("intrinsic {} getting reified", self.ty)
}
}
}
fn trans_closure_method<'a, 'tcx>(ccx: &'a CrateContext<'a, 'tcx>,
def_id: DefId,
substs: ty::ClosureSubsts<'tcx>,
method_instance: Instance<'tcx>,
trait_closure_kind: ty::ClosureKind)
-> ValueRef
{
let (llfn, _) = get_fn(ccx, def_id, substs.substs);
let llfn_closure_kind = ccx.tcx().closure_kind(def_id);
debug!("trans_closure_adapter_shim(llfn_closure_kind={:?}, \
trait_closure_kind={:?}, llfn={:?})",
llfn_closure_kind, trait_closure_kind, Value(llfn));
match needs_fn_once_adapter_shim(llfn_closure_kind, trait_closure_kind) {
Ok(true) => trans_fn_once_adapter_shim(ccx,
def_id,
substs,
method_instance,
llfn),
Ok(false) => llfn,
Err(()) => {
bug!("trans_closure_adapter_shim: cannot convert {:?} to {:?}",
llfn_closure_kind,
trait_closure_kind);
}
}
}
pub fn needs_fn_once_adapter_shim(actual_closure_kind: ty::ClosureKind,
trait_closure_kind: ty::ClosureKind)
-> Result<bool, ()>
{
match (actual_closure_kind, trait_closure_kind) {
(ty::ClosureKind::Fn, ty::ClosureKind::Fn) |
(ty::ClosureKind::FnMut, ty::ClosureKind::FnMut) |
(ty::ClosureKind::FnOnce, ty::ClosureKind::FnOnce) => {
Ok(false)
}
(ty::ClosureKind::Fn, ty::ClosureKind::FnMut) => {
Ok(false)
}
(ty::ClosureKind::Fn, ty::ClosureKind::FnOnce) |
(ty::ClosureKind::FnMut, ty::ClosureKind::FnOnce) => {
Ok(true)
}
_ => Err(()),
}
}
fn trans_fn_once_adapter_shim<'a, 'tcx>(
ccx: &'a CrateContext<'a, 'tcx>,
def_id: DefId,
substs: ty::ClosureSubsts<'tcx>,
method_instance: Instance<'tcx>,
llreffn: ValueRef)
-> ValueRef
{
if let Some(&llfn) = ccx.instances().borrow().get(&method_instance) {
return llfn;
}
debug!("trans_fn_once_adapter_shim(def_id={:?}, substs={:?}, llreffn={:?})",
def_id, substs, Value(llreffn));
let tcx = ccx.tcx();
let closure_ty = tcx.mk_closure_from_closure_substs(def_id, substs);
let ref_closure_ty = tcx.mk_imm_ref(tcx.mk_region(ty::ReErased), closure_ty);
let sig = tcx.closure_type(def_id).subst(tcx, substs.substs);
let sig = tcx.erase_late_bound_regions_and_normalize(&sig);
assert_eq!(sig.abi, Abi::RustCall);
let llref_fn_ty = tcx.mk_fn_ptr(ty::Binder(tcx.mk_fn_sig(
iter::once(ref_closure_ty).chain(sig.inputs().iter().cloned()),
sig.output(),
sig.variadic,
sig.unsafety,
Abi::RustCall
)));
debug!("trans_fn_once_adapter_shim: llref_fn_ty={:?}",
llref_fn_ty);
let sig = tcx.mk_fn_sig(
iter::once(closure_ty).chain(sig.inputs().iter().cloned()),
sig.output(),
sig.variadic,
sig.unsafety,
Abi::RustCall
);
let fn_ty = FnType::new(ccx, sig, &[]);
let llonce_fn_ty = tcx.mk_fn_ptr(ty::Binder(sig));
let function_name = method_instance.symbol_name(ccx.shared());
let lloncefn = declare::define_internal_fn(ccx, &function_name, llonce_fn_ty);
attributes::set_frame_pointer_elimination(ccx, lloncefn);
let orig_fn_ty = fn_ty;
let mut bcx = Builder::new_block(ccx, lloncefn, "entry-block");
let callee = Callee {
data: Fn(llreffn),
ty: llref_fn_ty
};
let mut llargs = get_params(lloncefn);
let fn_ret = callee.ty.fn_ret();
let fn_ty = callee.direct_fn_type(bcx.ccx, &[]);
let self_idx = fn_ty.ret.is_indirect() as usize;
let env_arg = &orig_fn_ty.args[0];
let env = if env_arg.is_indirect() {
LvalueRef::new_sized_ty(llargs[self_idx], closure_ty, Alignment::AbiAligned)
} else {
let scratch = LvalueRef::alloca(&bcx, closure_ty, "self");
let mut llarg_idx = self_idx;
env_arg.store_fn_arg(&bcx, &mut llarg_idx, scratch.llval);
scratch
};
debug!("trans_fn_once_adapter_shim: env={:?}", env);
if env_arg.is_ignore() {
llargs.insert(self_idx, env.llval);
} else {
llargs[self_idx] = env.llval;
}
let self_scope = CleanupScope::schedule_drop_mem(&bcx, env);
let llfn = callee.reify(bcx.ccx);
let llret;
if let Some(landing_pad) = self_scope.landing_pad {
let normal_bcx = bcx.build_sibling_block("normal-return");
llret = bcx.invoke(llfn, &llargs[..], normal_bcx.llbb(), landing_pad, None);
bcx = normal_bcx;
} else {
llret = bcx.call(llfn, &llargs[..], None);
}
fn_ty.apply_attrs_callsite(llret);
if fn_ret.0.is_never() {
bcx.unreachable();
} else {
self_scope.trans(&bcx);
if fn_ty.ret.is_indirect() || fn_ty.ret.is_ignore() {
bcx.ret_void();
} else {
bcx.ret(llret);
}
}
ccx.instances().borrow_mut().insert(method_instance, lloncefn);
lloncefn
}
fn trans_fn_pointer_shim<'a, 'tcx>(
ccx: &'a CrateContext<'a, 'tcx>,
method_instance: Instance<'tcx>,
closure_kind: ty::ClosureKind,
bare_fn_ty: Ty<'tcx>)
-> ValueRef
{
let tcx = ccx.tcx();
let bare_fn_ty = tcx.normalize_associated_type(&bare_fn_ty);
let is_by_ref = match closure_kind {
ty::ClosureKind::Fn | ty::ClosureKind::FnMut => true,
ty::ClosureKind::FnOnce => false,
};
let llfnpointer = match bare_fn_ty.sty {
ty::TyFnDef(def_id, substs, _) => {
let llfn = Callee::def(ccx, def_id, substs).reify(ccx);
if !is_by_ref {
return llfn;
}
Some(llfn)
}
_ => None
};
let bare_fn_ty_maybe_ref = if is_by_ref {
tcx.mk_imm_ref(tcx.mk_region(ty::ReErased), bare_fn_ty)
} else {
bare_fn_ty
};
if let Some(&llval) = ccx.fn_pointer_shims().borrow().get(&bare_fn_ty_maybe_ref) {
return llval;
}
debug!("trans_fn_pointer_shim(bare_fn_ty={:?})",
bare_fn_ty);
let sig = bare_fn_ty.fn_sig();
let sig = tcx.erase_late_bound_regions_and_normalize(&sig);
assert_eq!(sig.unsafety, hir::Unsafety::Normal);
assert_eq!(sig.abi, Abi::Rust);
let tuple_input_ty = tcx.intern_tup(sig.inputs(), false);
let sig = tcx.mk_fn_sig(
[bare_fn_ty_maybe_ref, tuple_input_ty].iter().cloned(),
sig.output(),
false,
hir::Unsafety::Normal,
Abi::RustCall
);
let fn_ty = FnType::new(ccx, sig, &[]);
let tuple_fn_ty = tcx.mk_fn_ptr(ty::Binder(sig));
debug!("tuple_fn_ty: {:?}", tuple_fn_ty);
let function_name = method_instance.symbol_name(ccx.shared());
let llfn = declare::define_internal_fn(ccx, &function_name, tuple_fn_ty);
attributes::set_frame_pointer_elimination(ccx, llfn);
let bcx = Builder::new_block(ccx, llfn, "entry-block");
let mut llargs = get_params(llfn);
let self_arg = llargs.remove(fn_ty.ret.is_indirect() as usize);
let llfnpointer = llfnpointer.unwrap_or_else(|| {
if is_by_ref {
bcx.load(self_arg, None)
} else {
self_arg
}
});
let callee = Callee {
data: Fn(llfnpointer),
ty: bare_fn_ty
};
let fn_ret = callee.ty.fn_ret();
let fn_ty = callee.direct_fn_type(ccx, &[]);
let llret = bcx.call(llfnpointer, &llargs, None);
fn_ty.apply_attrs_callsite(llret);
if fn_ret.0.is_never() {
bcx.unreachable();
} else {
if fn_ty.ret.is_indirect() || fn_ty.ret.is_ignore() {
bcx.ret_void();
} else {
bcx.ret(llret);
}
}
ccx.fn_pointer_shims().borrow_mut().insert(bare_fn_ty_maybe_ref, llfn);
llfn
}
fn get_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
def_id: DefId,
substs: &'tcx Substs<'tcx>)
-> (ValueRef, Ty<'tcx>) {
let tcx = ccx.tcx();
debug!("get_fn(def_id={:?}, substs={:?})", def_id, substs);
assert!(!substs.needs_infer());
assert!(!substs.has_escaping_regions());
assert!(!substs.has_param_types());
let substs = tcx.normalize_associated_type(&substs);
let instance = Instance::new(def_id, substs);
let fn_ty = common::def_ty(ccx.shared(), def_id, substs);
if let Some(&llfn) = ccx.instances().borrow().get(&instance) {
return (llfn, fn_ty);
}
let sym = ccx.symbol_map().get_or_compute(ccx.shared(),
TransItem::Fn(instance));
debug!("get_fn({:?}: {:?}) => {}", instance, fn_ty, sym);
let fn_ptr_ty = tcx.mk_fn_ptr(common::ty_fn_sig(ccx, fn_ty));
let llptrty = type_of::type_of(ccx, fn_ptr_ty);
let llfn = if let Some(llfn) = declare::get_declared_value(ccx, &sym) {
if common::val_ty(llfn) != llptrty {
debug!("get_fn: casting {:?} to {:?}", llfn, llptrty);
consts::ptrcast(llfn, llptrty)
} else {
debug!("get_fn: not casting pointer!");
llfn
}
} else {
let llfn = declare::declare_fn(ccx, &sym, fn_ty);
assert_eq!(common::val_ty(llfn), llptrty);
debug!("get_fn: not casting pointer!");
let attrs = ccx.tcx().get_attrs(def_id);
attributes::from_fn_attrs(ccx, &attrs, llfn);
let is_local_def = ccx.shared().translation_items().borrow()
.contains(&TransItem::Fn(instance));
if is_local_def {
attributes::unwind(llfn, true);
unsafe {
llvm::LLVMRustSetLinkage(llfn, llvm::Linkage::ExternalLinkage);
}
}
if ccx.use_dll_storage_attrs() && ccx.sess().cstore.is_dllimport_foreign_item(def_id) {
unsafe {
llvm::LLVMSetDLLStorageClass(llfn, llvm::DLLStorageClass::DllImport);
}
}
llfn
};
ccx.instances().borrow_mut().insert(instance, llfn);
(llfn, fn_ty)
}