]> git.lizzy.rs Git - rust.git/blob - src/abi/mod.rs
Sync from rust a0d66b54fb3acc2125972b88ff543a2c04d14af5
[rust.git] / src / abi / mod.rs
1 //! Handling of everything related to the calling convention. Also fills `fx.local_map`.
2
3 #[cfg(debug_assertions)]
4 mod comments;
5 mod pass_mode;
6 mod returning;
7
8 use rustc_middle::middle::codegen_fn_attrs::CodegenFnAttrFlags;
9 use rustc_middle::ty::layout::FnAbiExt;
10 use rustc_target::abi::call::{Conv, FnAbi};
11 use rustc_target::spec::abi::Abi;
12
13 use cranelift_codegen::ir::AbiParam;
14 use smallvec::smallvec;
15
16 use self::pass_mode::*;
17 use crate::prelude::*;
18
19 pub(crate) use self::returning::{can_return_to_ssa_var, codegen_return};
20
21 fn clif_sig_from_fn_abi<'tcx>(
22     tcx: TyCtxt<'tcx>,
23     triple: &target_lexicon::Triple,
24     fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
25 ) -> Signature {
26     let call_conv = match fn_abi.conv {
27         Conv::Rust | Conv::C => CallConv::triple_default(triple),
28         Conv::X86_64SysV => CallConv::SystemV,
29         Conv::X86_64Win64 => CallConv::WindowsFastcall,
30         Conv::ArmAapcs
31         | Conv::CCmseNonSecureCall
32         | Conv::Msp430Intr
33         | Conv::PtxKernel
34         | Conv::X86Fastcall
35         | Conv::X86Intr
36         | Conv::X86Stdcall
37         | Conv::X86ThisCall
38         | Conv::X86VectorCall
39         | Conv::AmdGpuKernel
40         | Conv::AvrInterrupt
41         | Conv::AvrNonBlockingInterrupt => todo!("{:?}", fn_abi.conv),
42     };
43     let inputs = fn_abi
44         .args
45         .iter()
46         .map(|arg_abi| arg_abi.get_abi_param(tcx).into_iter())
47         .flatten();
48
49     let (return_ptr, returns) = fn_abi.ret.get_abi_return(tcx);
50     // Sometimes the first param is an pointer to the place where the return value needs to be stored.
51     let params: Vec<_> = return_ptr.into_iter().chain(inputs).collect();
52
53     Signature {
54         params,
55         returns,
56         call_conv,
57     }
58 }
59
60 pub(crate) fn get_function_sig<'tcx>(
61     tcx: TyCtxt<'tcx>,
62     triple: &target_lexicon::Triple,
63     inst: Instance<'tcx>,
64 ) -> Signature {
65     assert!(!inst.substs.needs_infer());
66     clif_sig_from_fn_abi(
67         tcx,
68         triple,
69         &FnAbi::of_instance(&RevealAllLayoutCx(tcx), inst, &[]),
70     )
71 }
72
73 /// Instance must be monomorphized
74 pub(crate) fn import_function<'tcx>(
75     tcx: TyCtxt<'tcx>,
76     module: &mut dyn Module,
77     inst: Instance<'tcx>,
78 ) -> FuncId {
79     let name = tcx.symbol_name(inst).name.to_string();
80     let sig = get_function_sig(tcx, module.isa().triple(), inst);
81     module
82         .declare_function(&name, Linkage::Import, &sig)
83         .unwrap()
84 }
85
86 impl<'tcx> FunctionCx<'_, '_, 'tcx> {
87     /// Instance must be monomorphized
88     pub(crate) fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
89         let func_id = import_function(self.tcx, self.cx.module, inst);
90         let func_ref = self
91             .cx
92             .module
93             .declare_func_in_func(func_id, &mut self.bcx.func);
94
95         #[cfg(debug_assertions)]
96         self.add_comment(func_ref, format!("{:?}", inst));
97
98         func_ref
99     }
100
101     pub(crate) fn lib_call(
102         &mut self,
103         name: &str,
104         params: Vec<AbiParam>,
105         returns: Vec<AbiParam>,
106         args: &[Value],
107     ) -> &[Value] {
108         let sig = Signature {
109             params,
110             returns,
111             call_conv: CallConv::triple_default(self.triple()),
112         };
113         let func_id = self
114             .cx
115             .module
116             .declare_function(&name, Linkage::Import, &sig)
117             .unwrap();
118         let func_ref = self
119             .cx
120             .module
121             .declare_func_in_func(func_id, &mut self.bcx.func);
122         let call_inst = self.bcx.ins().call(func_ref, args);
123         #[cfg(debug_assertions)]
124         {
125             self.add_comment(call_inst, format!("easy_call {}", name));
126         }
127         let results = self.bcx.inst_results(call_inst);
128         assert!(results.len() <= 2, "{}", results.len());
129         results
130     }
131
132     pub(crate) fn easy_call(
133         &mut self,
134         name: &str,
135         args: &[CValue<'tcx>],
136         return_ty: Ty<'tcx>,
137     ) -> CValue<'tcx> {
138         let (input_tys, args): (Vec<_>, Vec<_>) = args
139             .iter()
140             .map(|arg| {
141                 (
142                     AbiParam::new(self.clif_type(arg.layout().ty).unwrap()),
143                     arg.load_scalar(self),
144                 )
145             })
146             .unzip();
147         let return_layout = self.layout_of(return_ty);
148         let return_tys = if let ty::Tuple(tup) = return_ty.kind() {
149             tup.types()
150                 .map(|ty| AbiParam::new(self.clif_type(ty).unwrap()))
151                 .collect()
152         } else {
153             vec![AbiParam::new(self.clif_type(return_ty).unwrap())]
154         };
155         let ret_vals = self.lib_call(name, input_tys, return_tys, &args);
156         match *ret_vals {
157             [] => CValue::by_ref(
158                 Pointer::const_addr(self, i64::from(self.pointer_type.bytes())),
159                 return_layout,
160             ),
161             [val] => CValue::by_val(val, return_layout),
162             [val, extra] => CValue::by_val_pair(val, extra, return_layout),
163             _ => unreachable!(),
164         }
165     }
166 }
167
168 /// Make a [`CPlace`] capable of holding value of the specified type.
169 fn make_local_place<'tcx>(
170     fx: &mut FunctionCx<'_, '_, 'tcx>,
171     local: Local,
172     layout: TyAndLayout<'tcx>,
173     is_ssa: bool,
174 ) -> CPlace<'tcx> {
175     let place = if is_ssa {
176         if let rustc_target::abi::Abi::ScalarPair(_, _) = layout.abi {
177             CPlace::new_var_pair(fx, local, layout)
178         } else {
179             CPlace::new_var(fx, local, layout)
180         }
181     } else {
182         CPlace::new_stack_slot(fx, layout)
183     };
184
185     #[cfg(debug_assertions)]
186     self::comments::add_local_place_comments(fx, place, local);
187
188     place
189 }
190
191 pub(crate) fn codegen_fn_prelude<'tcx>(fx: &mut FunctionCx<'_, '_, 'tcx>, start_block: Block) {
192     fx.bcx.append_block_params_for_function_params(start_block);
193
194     fx.bcx.switch_to_block(start_block);
195     fx.bcx.ins().nop();
196
197     let ssa_analyzed = crate::analyze::analyze(fx);
198
199     #[cfg(debug_assertions)]
200     self::comments::add_args_header_comment(fx);
201
202     let mut block_params_iter = fx
203         .bcx
204         .func
205         .dfg
206         .block_params(start_block)
207         .to_vec()
208         .into_iter();
209     let ret_place =
210         self::returning::codegen_return_param(fx, &ssa_analyzed, &mut block_params_iter);
211     assert_eq!(fx.local_map.push(ret_place), RETURN_PLACE);
212
213     // None means pass_mode == NoPass
214     enum ArgKind<'tcx> {
215         Normal(Option<CValue<'tcx>>),
216         Spread(Vec<Option<CValue<'tcx>>>),
217     }
218
219     let fn_abi = fx.fn_abi.take().unwrap();
220     let mut arg_abis_iter = fn_abi.args.iter();
221
222     let func_params = fx
223         .mir
224         .args_iter()
225         .map(|local| {
226             let arg_ty = fx.monomorphize(fx.mir.local_decls[local].ty);
227
228             // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
229             if Some(local) == fx.mir.spread_arg {
230                 // This argument (e.g. the last argument in the "rust-call" ABI)
231                 // is a tuple that was spread at the ABI level and now we have
232                 // to reconstruct it into a tuple local variable, from multiple
233                 // individual function arguments.
234
235                 let tupled_arg_tys = match arg_ty.kind() {
236                     ty::Tuple(ref tys) => tys,
237                     _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
238                 };
239
240                 let mut params = Vec::new();
241                 for (i, _arg_ty) in tupled_arg_tys.types().enumerate() {
242                     let arg_abi = arg_abis_iter.next().unwrap();
243                     let param =
244                         cvalue_for_param(fx, Some(local), Some(i), arg_abi, &mut block_params_iter);
245                     params.push(param);
246                 }
247
248                 (local, ArgKind::Spread(params), arg_ty)
249             } else {
250                 let arg_abi = arg_abis_iter.next().unwrap();
251                 let param =
252                     cvalue_for_param(fx, Some(local), None, arg_abi, &mut block_params_iter);
253                 (local, ArgKind::Normal(param), arg_ty)
254             }
255         })
256         .collect::<Vec<(Local, ArgKind<'tcx>, Ty<'tcx>)>>();
257
258     assert!(fx.caller_location.is_none());
259     if fx.instance.def.requires_caller_location(fx.tcx) {
260         // Store caller location for `#[track_caller]`.
261         let arg_abi = arg_abis_iter.next().unwrap();
262         fx.caller_location =
263             Some(cvalue_for_param(fx, None, None, arg_abi, &mut block_params_iter).unwrap());
264     }
265
266     assert!(arg_abis_iter.next().is_none(), "ArgAbi left behind");
267     fx.fn_abi = Some(fn_abi);
268     assert!(block_params_iter.next().is_none(), "arg_value left behind");
269
270     #[cfg(debug_assertions)]
271     self::comments::add_locals_header_comment(fx);
272
273     for (local, arg_kind, ty) in func_params {
274         let layout = fx.layout_of(ty);
275
276         let is_ssa = ssa_analyzed[local] == crate::analyze::SsaKind::Ssa;
277
278         // While this is normally an optimization to prevent an unnecessary copy when an argument is
279         // not mutated by the current function, this is necessary to support unsized arguments.
280         if let ArgKind::Normal(Some(val)) = arg_kind {
281             if let Some((addr, meta)) = val.try_to_ptr() {
282                 let local_decl = &fx.mir.local_decls[local];
283                 //                       v this ! is important
284                 let internally_mutable = !val.layout().ty.is_freeze(
285                     fx.tcx.at(local_decl.source_info.span),
286                     ParamEnv::reveal_all(),
287                 );
288                 if local_decl.mutability == mir::Mutability::Not && !internally_mutable {
289                     // We wont mutate this argument, so it is fine to borrow the backing storage
290                     // of this argument, to prevent a copy.
291
292                     let place = if let Some(meta) = meta {
293                         CPlace::for_ptr_with_extra(addr, meta, val.layout())
294                     } else {
295                         CPlace::for_ptr(addr, val.layout())
296                     };
297
298                     #[cfg(debug_assertions)]
299                     self::comments::add_local_place_comments(fx, place, local);
300
301                     assert_eq!(fx.local_map.push(place), local);
302                     continue;
303                 }
304             }
305         }
306
307         let place = make_local_place(fx, local, layout, is_ssa);
308         assert_eq!(fx.local_map.push(place), local);
309
310         match arg_kind {
311             ArgKind::Normal(param) => {
312                 if let Some(param) = param {
313                     place.write_cvalue(fx, param);
314                 }
315             }
316             ArgKind::Spread(params) => {
317                 for (i, param) in params.into_iter().enumerate() {
318                     if let Some(param) = param {
319                         place
320                             .place_field(fx, mir::Field::new(i))
321                             .write_cvalue(fx, param);
322                     }
323                 }
324             }
325         }
326     }
327
328     for local in fx.mir.vars_and_temps_iter() {
329         let ty = fx.monomorphize(fx.mir.local_decls[local].ty);
330         let layout = fx.layout_of(ty);
331
332         let is_ssa = ssa_analyzed[local] == crate::analyze::SsaKind::Ssa;
333
334         let place = make_local_place(fx, local, layout, is_ssa);
335         assert_eq!(fx.local_map.push(place), local);
336     }
337
338     fx.bcx
339         .ins()
340         .jump(*fx.block_map.get(START_BLOCK).unwrap(), &[]);
341 }
342
343 pub(crate) fn codegen_terminator_call<'tcx>(
344     fx: &mut FunctionCx<'_, '_, 'tcx>,
345     span: Span,
346     current_block: Block,
347     func: &Operand<'tcx>,
348     args: &[Operand<'tcx>],
349     destination: Option<(Place<'tcx>, BasicBlock)>,
350 ) {
351     let fn_ty = fx.monomorphize(func.ty(fx.mir, fx.tcx));
352     let fn_sig = fx
353         .tcx
354         .normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), fn_ty.fn_sig(fx.tcx));
355
356     let destination = destination.map(|(place, bb)| (codegen_place(fx, place), bb));
357
358     // Handle special calls like instrinsics and empty drop glue.
359     let instance = if let ty::FnDef(def_id, substs) = *fn_ty.kind() {
360         let instance = ty::Instance::resolve(fx.tcx, ty::ParamEnv::reveal_all(), def_id, substs)
361             .unwrap()
362             .unwrap()
363             .polymorphize(fx.tcx);
364
365         if fx.tcx.symbol_name(instance).name.starts_with("llvm.") {
366             crate::intrinsics::codegen_llvm_intrinsic_call(
367                 fx,
368                 &fx.tcx.symbol_name(instance).name,
369                 substs,
370                 args,
371                 destination,
372             );
373             return;
374         }
375
376         match instance.def {
377             InstanceDef::Intrinsic(_) => {
378                 crate::intrinsics::codegen_intrinsic_call(fx, instance, args, destination, span);
379                 return;
380             }
381             InstanceDef::DropGlue(_, None) => {
382                 // empty drop glue - a nop.
383                 let (_, dest) = destination.expect("Non terminating drop_in_place_real???");
384                 let ret_block = fx.get_block(dest);
385                 fx.bcx.ins().jump(ret_block, &[]);
386                 return;
387             }
388             _ => Some(instance),
389         }
390     } else {
391         None
392     };
393
394     let extra_args = &args[fn_sig.inputs().len()..];
395     let extra_args = extra_args
396         .iter()
397         .map(|op_arg| fx.monomorphize(op_arg.ty(fx.mir, fx.tcx)))
398         .collect::<Vec<_>>();
399     let fn_abi = if let Some(instance) = instance {
400         FnAbi::of_instance(&RevealAllLayoutCx(fx.tcx), instance, &extra_args)
401     } else {
402         FnAbi::of_fn_ptr(
403             &RevealAllLayoutCx(fx.tcx),
404             fn_ty.fn_sig(fx.tcx),
405             &extra_args,
406         )
407     };
408
409     let is_cold = instance
410         .map(|inst| {
411             fx.tcx
412                 .codegen_fn_attrs(inst.def_id())
413                 .flags
414                 .contains(CodegenFnAttrFlags::COLD)
415         })
416         .unwrap_or(false);
417     if is_cold {
418         fx.cold_blocks.insert(current_block);
419     }
420
421     // Unpack arguments tuple for closures
422     let args = if fn_sig.abi == Abi::RustCall {
423         assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
424         let self_arg = codegen_operand(fx, &args[0]);
425         let pack_arg = codegen_operand(fx, &args[1]);
426
427         let tupled_arguments = match pack_arg.layout().ty.kind() {
428             ty::Tuple(ref tupled_arguments) => tupled_arguments,
429             _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
430         };
431
432         let mut args = Vec::with_capacity(1 + tupled_arguments.len());
433         args.push(self_arg);
434         for i in 0..tupled_arguments.len() {
435             args.push(pack_arg.value_field(fx, mir::Field::new(i)));
436         }
437         args
438     } else {
439         args.iter()
440             .map(|arg| codegen_operand(fx, arg))
441             .collect::<Vec<_>>()
442     };
443
444     //   | indirect call target
445     //   |         | the first argument to be passed
446     //   v         v
447     let (func_ref, first_arg) = match instance {
448         // Trait object call
449         Some(Instance {
450             def: InstanceDef::Virtual(_, idx),
451             ..
452         }) => {
453             #[cfg(debug_assertions)]
454             {
455                 let nop_inst = fx.bcx.ins().nop();
456                 fx.add_comment(
457                     nop_inst,
458                     format!("virtual call; self arg pass mode: {:?}", &fn_abi.args[0],),
459                 );
460             }
461             let (ptr, method) = crate::vtable::get_ptr_and_method_ref(fx, args[0], idx);
462             (Some(method), smallvec![ptr])
463         }
464
465         // Normal call
466         Some(_) => (
467             None,
468             args.get(0)
469                 .map(|arg| adjust_arg_for_abi(fx, *arg, &fn_abi.args[0]))
470                 .unwrap_or(smallvec![]),
471         ),
472
473         // Indirect call
474         None => {
475             #[cfg(debug_assertions)]
476             {
477                 let nop_inst = fx.bcx.ins().nop();
478                 fx.add_comment(nop_inst, "indirect call");
479             }
480             let func = codegen_operand(fx, func).load_scalar(fx);
481             (
482                 Some(func),
483                 args.get(0)
484                     .map(|arg| adjust_arg_for_abi(fx, *arg, &fn_abi.args[0]))
485                     .unwrap_or(smallvec![]),
486             )
487         }
488     };
489
490     let ret_place = destination.map(|(place, _)| place);
491     let (call_inst, call_args) = self::returning::codegen_with_call_return_arg(
492         fx,
493         &fn_abi.ret,
494         ret_place,
495         |fx, return_ptr| {
496             let regular_args_count = args.len();
497             let mut call_args: Vec<Value> = return_ptr
498                 .into_iter()
499                 .chain(first_arg.into_iter())
500                 .chain(
501                     args.into_iter()
502                         .enumerate()
503                         .skip(1)
504                         .map(|(i, arg)| adjust_arg_for_abi(fx, arg, &fn_abi.args[i]).into_iter())
505                         .flatten(),
506                 )
507                 .collect::<Vec<_>>();
508
509             if instance
510                 .map(|inst| inst.def.requires_caller_location(fx.tcx))
511                 .unwrap_or(false)
512             {
513                 // Pass the caller location for `#[track_caller]`.
514                 let caller_location = fx.get_caller_location(span);
515                 call_args.extend(
516                     adjust_arg_for_abi(fx, caller_location, &fn_abi.args[regular_args_count])
517                         .into_iter(),
518                 );
519                 assert_eq!(fn_abi.args.len(), regular_args_count + 1);
520             } else {
521                 assert_eq!(fn_abi.args.len(), regular_args_count);
522             }
523
524             let call_inst = if let Some(func_ref) = func_ref {
525                 let sig = clif_sig_from_fn_abi(fx.tcx, fx.triple(), &fn_abi);
526                 let sig = fx.bcx.import_signature(sig);
527                 fx.bcx.ins().call_indirect(sig, func_ref, &call_args)
528             } else {
529                 let func_ref =
530                     fx.get_function_ref(instance.expect("non-indirect call on non-FnDef type"));
531                 fx.bcx.ins().call(func_ref, &call_args)
532             };
533
534             (call_inst, call_args)
535         },
536     );
537
538     // FIXME find a cleaner way to support varargs
539     if fn_sig.c_variadic {
540         if fn_sig.abi != Abi::C {
541             fx.tcx.sess.span_fatal(
542                 span,
543                 &format!("Variadic call for non-C abi {:?}", fn_sig.abi),
544             );
545         }
546         let sig_ref = fx.bcx.func.dfg.call_signature(call_inst).unwrap();
547         let abi_params = call_args
548             .into_iter()
549             .map(|arg| {
550                 let ty = fx.bcx.func.dfg.value_type(arg);
551                 if !ty.is_int() {
552                     // FIXME set %al to upperbound on float args once floats are supported
553                     fx.tcx
554                         .sess
555                         .span_fatal(span, &format!("Non int ty {:?} for variadic call", ty));
556                 }
557                 AbiParam::new(ty)
558             })
559             .collect::<Vec<AbiParam>>();
560         fx.bcx.func.dfg.signatures[sig_ref].params = abi_params;
561     }
562
563     if let Some((_, dest)) = destination {
564         let ret_block = fx.get_block(dest);
565         fx.bcx.ins().jump(ret_block, &[]);
566     } else {
567         trap_unreachable(fx, "[corruption] Diverging function returned");
568     }
569 }
570
571 pub(crate) fn codegen_drop<'tcx>(
572     fx: &mut FunctionCx<'_, '_, 'tcx>,
573     span: Span,
574     drop_place: CPlace<'tcx>,
575 ) {
576     let ty = drop_place.layout().ty;
577     let drop_instance = Instance::resolve_drop_in_place(fx.tcx, ty).polymorphize(fx.tcx);
578
579     if let ty::InstanceDef::DropGlue(_, None) = drop_instance.def {
580         // we don't actually need to drop anything
581     } else {
582         match ty.kind() {
583             ty::Dynamic(..) => {
584                 let (ptr, vtable) = drop_place.to_ptr_maybe_unsized();
585                 let ptr = ptr.get_addr(fx);
586                 let drop_fn = crate::vtable::drop_fn_of_obj(fx, vtable.unwrap());
587
588                 // FIXME(eddyb) perhaps move some of this logic into
589                 // `Instance::resolve_drop_in_place`?
590                 let virtual_drop = Instance {
591                     def: ty::InstanceDef::Virtual(drop_instance.def_id(), 0),
592                     substs: drop_instance.substs,
593                 };
594                 let fn_abi = FnAbi::of_instance(&RevealAllLayoutCx(fx.tcx), virtual_drop, &[]);
595
596                 let sig = clif_sig_from_fn_abi(fx.tcx, fx.triple(), &fn_abi);
597                 let sig = fx.bcx.import_signature(sig);
598                 fx.bcx.ins().call_indirect(sig, drop_fn, &[ptr]);
599             }
600             _ => {
601                 assert!(!matches!(drop_instance.def, InstanceDef::Virtual(_, _)));
602
603                 let fn_abi = FnAbi::of_instance(&RevealAllLayoutCx(fx.tcx), drop_instance, &[]);
604
605                 let arg_value = drop_place.place_ref(
606                     fx,
607                     fx.layout_of(fx.tcx.mk_ref(
608                         &ty::RegionKind::ReErased,
609                         TypeAndMut {
610                             ty,
611                             mutbl: crate::rustc_hir::Mutability::Mut,
612                         },
613                     )),
614                 );
615                 let arg_value = adjust_arg_for_abi(fx, arg_value, &fn_abi.args[0]);
616
617                 let mut call_args: Vec<Value> = arg_value.into_iter().collect::<Vec<_>>();
618
619                 if drop_instance.def.requires_caller_location(fx.tcx) {
620                     // Pass the caller location for `#[track_caller]`.
621                     let caller_location = fx.get_caller_location(span);
622                     call_args.extend(
623                         adjust_arg_for_abi(fx, caller_location, &fn_abi.args[1]).into_iter(),
624                     );
625                 }
626
627                 let func_ref = fx.get_function_ref(drop_instance);
628                 fx.bcx.ins().call(func_ref, &call_args);
629             }
630         }
631     }
632 }