]> git.lizzy.rs Git - rust.git/blob - src/abi.rs
Introduce CPlace::NoPlace for zst's
[rust.git] / src / abi.rs
1 use std::borrow::Cow;
2 use std::iter;
3
4 use rustc::hir;
5 use rustc::ty::layout::{Scalar, Primitive, Integer, FloatTy};
6 use rustc_target::spec::abi::Abi;
7
8 use crate::prelude::*;
9
10 #[derive(Copy, Clone, Debug)]
11 enum PassMode {
12     NoPass,
13     ByVal(Type),
14     ByRef,
15 }
16
17 impl PassMode {
18     fn get_param_ty(self, fx: &FunctionCx<impl Backend>) -> Type {
19         match self {
20             PassMode::NoPass => unimplemented!("pass mode nopass"),
21             PassMode::ByVal(clif_type) => clif_type,
22             PassMode::ByRef => fx.pointer_type,
23         }
24     }
25 }
26
27 pub fn scalar_to_clif_type(tcx: TyCtxt, scalar: Scalar) -> Type {
28     match scalar.value {
29         Primitive::Int(int, _sign) => match int {
30             Integer::I8 => types::I8,
31             Integer::I16 => types::I16,
32             Integer::I32 => types::I32,
33             Integer::I64 => types::I64,
34             Integer::I128 => unimpl!("u/i128"),
35         }
36         Primitive::Float(flt) => match flt {
37             FloatTy::F32 => types::F32,
38             FloatTy::F64 => types::F64,
39         }
40         Primitive::Pointer => pointer_ty(tcx),
41     }
42 }
43
44 fn get_pass_mode<'a, 'tcx: 'a>(
45     tcx: TyCtxt<'a, 'tcx, 'tcx>,
46     ty: Ty<'tcx>,
47     is_return: bool,
48 ) -> PassMode {
49     let layout = tcx
50         .layout_of(ParamEnv::reveal_all().and(ty))
51         .unwrap();
52     assert!(!layout.is_unsized());
53
54     if layout.size.bytes() == 0 {
55         if is_return {
56             PassMode::NoPass
57         } else {
58             PassMode::ByRef
59         }
60     } else {
61         match &layout.abi {
62             layout::Abi::Uninhabited => {
63                 if is_return {
64                     PassMode::NoPass
65                 } else {
66                     PassMode::ByRef
67                 }
68             }
69             layout::Abi::Scalar(scalar) => PassMode::ByVal(scalar_to_clif_type(tcx, scalar.clone())),
70
71             // FIXME implement ScalarPair and Vector Abi in a cg_llvm compatible way
72             layout::Abi::ScalarPair(_, _) => PassMode::ByRef,
73             layout::Abi::Vector { .. } => PassMode::ByRef,
74
75             layout::Abi::Aggregate { .. } => PassMode::ByRef,
76         }
77     }
78 }
79
80 fn adjust_arg_for_abi<'a, 'tcx: 'a>(
81     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
82     arg: CValue<'tcx>,
83 ) -> Value {
84     match get_pass_mode(fx.tcx, arg.layout().ty, false) {
85         PassMode::NoPass => unimplemented!("pass mode nopass"),
86         PassMode::ByVal(_) => arg.load_scalar(fx),
87         PassMode::ByRef => arg.force_stack(fx),
88     }
89 }
90
91 fn clif_sig_from_fn_sig<'a, 'tcx: 'a>(
92     tcx: TyCtxt<'a, 'tcx, 'tcx>,
93     sig: FnSig<'tcx>,
94 ) -> Signature {
95     let (call_conv, inputs, output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
96         Abi::Rust => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
97         Abi::C => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
98         Abi::RustCall => {
99             assert_eq!(sig.inputs().len(), 2);
100             let extra_args = match sig.inputs().last().unwrap().sty {
101                 ty::Tuple(ref tupled_arguments) => tupled_arguments,
102                 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
103             };
104             let mut inputs: Vec<Ty> = vec![sig.inputs()[0]];
105             inputs.extend(extra_args.into_iter());
106             (CallConv::SystemV, inputs, sig.output())
107         }
108         Abi::System => bug!("system abi should be selected elsewhere"),
109         Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
110         _ => unimplemented!("unsupported abi {:?}", sig.abi),
111     };
112
113     let inputs = inputs
114         .into_iter()
115         .filter_map(|ty| match get_pass_mode(tcx, ty, false) {
116             PassMode::ByVal(clif_ty) => Some(clif_ty),
117             PassMode::NoPass => unimplemented!("pass mode nopass"),
118             PassMode::ByRef => Some(pointer_ty(tcx)),
119         });
120
121     let (params, returns) = match get_pass_mode(tcx, output, true) {
122         PassMode::NoPass => (inputs.map(AbiParam::new).collect(), vec![]),
123         PassMode::ByVal(ret_ty) => (
124             inputs.map(AbiParam::new).collect(),
125             vec![AbiParam::new(ret_ty)],
126         ),
127         PassMode::ByRef => {
128             (
129                 Some(pointer_ty(tcx)) // First param is place to put return val
130                     .into_iter()
131                     .chain(inputs)
132                     .map(AbiParam::new)
133                     .collect(),
134                 vec![],
135             )
136         }
137     };
138
139     Signature {
140         params,
141         returns,
142         call_conv,
143     }
144 }
145
146 pub fn ty_fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> ty::FnSig<'tcx> {
147     let sig = match ty.sty {
148         ty::FnDef(..) |
149         // Shims currently have type TyFnPtr. Not sure this should remain.
150         ty::FnPtr(_) => ty.fn_sig(tcx),
151         ty::Closure(def_id, substs) => {
152             let sig = substs.closure_sig(def_id, tcx);
153
154             let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
155             sig.map_bound(|sig| tcx.mk_fn_sig(
156                 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
157                 sig.output(),
158                 sig.variadic,
159                 sig.unsafety,
160                 sig.abi
161             ))
162         }
163         ty::Generator(def_id, substs, _) => {
164             let sig = substs.poly_sig(def_id, tcx);
165
166             let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
167             let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
168
169             sig.map_bound(|sig| {
170                 let state_did = tcx.lang_items().gen_state().unwrap();
171                 let state_adt_ref = tcx.adt_def(state_did);
172                 let state_substs = tcx.intern_substs(&[
173                     sig.yield_ty.into(),
174                     sig.return_ty.into(),
175                 ]);
176                 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
177
178                 tcx.mk_fn_sig(iter::once(env_ty),
179                     ret_ty,
180                     false,
181                     hir::Unsafety::Normal,
182                     Abi::Rust
183                 )
184             })
185         }
186         _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
187     };
188     tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
189 }
190
191 pub fn get_function_name_and_sig<'a, 'tcx>(
192     tcx: TyCtxt<'a, 'tcx, 'tcx>,
193     inst: Instance<'tcx>,
194 ) -> (String, Signature) {
195     assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
196     let fn_ty = inst.ty(tcx);
197     let fn_sig = ty_fn_sig(tcx, fn_ty);
198     if fn_sig.variadic {
199         unimpl!("Variadic functions are not yet supported");
200     }
201     let sig = clif_sig_from_fn_sig(tcx, fn_sig);
202     (tcx.symbol_name(inst).as_str().to_string(), sig)
203 }
204
205 /// Instance must be monomorphized
206 pub fn import_function<'a, 'tcx: 'a>(
207     tcx: TyCtxt<'a, 'tcx, 'tcx>,
208     module: &mut Module<impl Backend>,
209     inst: Instance<'tcx>,
210 ) -> FuncId {
211     let (name, sig) = get_function_name_and_sig(tcx, inst);
212     module
213         .declare_function(&name, Linkage::Import, &sig)
214         .unwrap()
215 }
216
217 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
218     /// Instance must be monomorphized
219     pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
220         let func_id = import_function(self.tcx, self.module, inst);
221         let func_ref = self.module
222             .declare_func_in_func(func_id, &mut self.bcx.func);
223
224         #[cfg(debug_assertions)]
225         self.add_entity_comment(func_ref, format!("{:?}", inst));
226
227         func_ref
228     }
229
230     fn lib_call(
231         &mut self,
232         name: &str,
233         input_tys: Vec<types::Type>,
234         output_ty: Option<types::Type>,
235         args: &[Value],
236     ) -> Option<Value> {
237         let sig = Signature {
238             params: input_tys.iter().cloned().map(AbiParam::new).collect(),
239             returns: output_ty
240                 .map(|output_ty| vec![AbiParam::new(output_ty)])
241                 .unwrap_or(Vec::new()),
242             call_conv: CallConv::SystemV,
243         };
244         let func_id = self
245             .module
246             .declare_function(&name, Linkage::Import, &sig)
247             .unwrap();
248         let func_ref = self
249             .module
250             .declare_func_in_func(func_id, &mut self.bcx.func);
251         let call_inst = self.bcx.ins().call(func_ref, args);
252         if output_ty.is_none() {
253             return None;
254         }
255         let results = self.bcx.inst_results(call_inst);
256         assert_eq!(results.len(), 1);
257         Some(results[0])
258     }
259
260     pub fn easy_call(
261         &mut self,
262         name: &str,
263         args: &[CValue<'tcx>],
264         return_ty: Ty<'tcx>,
265     ) -> CValue<'tcx> {
266         let (input_tys, args): (Vec<_>, Vec<_>) = args
267             .into_iter()
268             .map(|arg| {
269                 (
270                     self.clif_type(arg.layout().ty).unwrap(),
271                     arg.load_scalar(self),
272                 )
273             })
274             .unzip();
275         let return_layout = self.layout_of(return_ty);
276         let return_ty = if let ty::Tuple(tup) = return_ty.sty {
277             if !tup.is_empty() {
278                 bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
279             }
280             None
281         } else {
282             Some(self.clif_type(return_ty).unwrap())
283         };
284         if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
285             CValue::ByVal(val, return_layout)
286         } else {
287             CValue::ByRef(self.bcx.ins().iconst(self.pointer_type, 0), return_layout)
288         }
289     }
290
291     fn self_sig(&self) -> FnSig<'tcx> {
292         ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
293     }
294
295     fn return_type(&self) -> Ty<'tcx> {
296         self.self_sig().output()
297     }
298 }
299
300 #[cfg(debug_assertions)]
301 fn add_arg_comment<'a, 'tcx: 'a>(
302     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
303     msg: &str,
304     local: mir::Local,
305     local_field: Option<usize>,
306     param: Option<Value>,
307     pass_mode: PassMode,
308     ssa: crate::analyze::Flags,
309     ty: Ty<'tcx>,
310 ) {
311     let local_field = if let Some(local_field) = local_field {
312         Cow::Owned(format!(".{}", local_field))
313     } else {
314         Cow::Borrowed("")
315     };
316     let param = if let Some(param) = param {
317         Cow::Owned(format!("= {:?}", param))
318     } else {
319         Cow::Borrowed("-")
320     };
321     let pass_mode = format!("{:?}", pass_mode);
322     fx.add_global_comment(format!(
323         "{msg:5} {local:>3}{local_field:<5} {param:10} {pass_mode:20} {ssa:10} {ty:?}",
324         msg=msg, local=format!("{:?}", local), local_field=local_field, param=param, pass_mode=pass_mode, ssa=format!("{:?}", ssa), ty=ty,
325     ));
326 }
327
328 #[cfg(debug_assertions)]
329 fn add_local_header_comment(fx: &mut FunctionCx<impl Backend>) {
330     fx.add_global_comment(format!("msg   loc.idx    param    pass mode            ssa flags  ty"));
331 }
332
333 fn local_place<'a, 'tcx: 'a>(
334     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
335     local: Local,
336     layout: TyLayout<'tcx>,
337     is_ssa: bool,
338 ) -> CPlace<'tcx> {
339     let place = if is_ssa {
340         fx.bcx.declare_var(mir_var(local), fx.clif_type(layout.ty).unwrap());
341         CPlace::Var(local, layout)
342     } else {
343         let place = CPlace::new_stack_slot(fx, layout.ty);
344
345         #[cfg(debug_assertions)]
346         {
347             let TyLayout { ty, details } = layout;
348             let ty::layout::LayoutDetails { size, align, abi: _, variants: _, fields: _ } = details;
349             match place {
350                 CPlace::Stack(stack_slot, _) => fx.add_entity_comment(stack_slot, format!(
351                     "{:?}: {:?} size={} align={},{}",
352                     local, ty, size.bytes(), align.abi.bytes(), align.pref.bytes(),
353                 )),
354                 CPlace::NoPlace(_) => fx.add_global_comment(format!(
355                     "zst    {:?}: {:?} size={} align={}, {}",
356                     local, ty, size.bytes(), align.abi.bytes(), align.pref.bytes(),
357                 )),
358                 _ => unreachable!(),
359             };
360
361         }
362
363         // Take stack_addr in advance to avoid many duplicate instructions
364         CPlace::Addr(place.to_addr(fx), None, layout)
365     };
366
367     let prev_place = fx.local_map.insert(local, place);
368     debug_assert!(prev_place.is_none());
369     fx.local_map[&local]
370 }
371
372 fn cvalue_for_param<'a, 'tcx: 'a>(
373     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
374     start_ebb: Ebb,
375     local: mir::Local,
376     local_field: Option<usize>,
377     arg_ty: Ty<'tcx>,
378     ssa_flags: crate::analyze::Flags,
379 ) -> CValue<'tcx> {
380     let layout = fx.layout_of(arg_ty);
381     let pass_mode = get_pass_mode(fx.tcx, arg_ty, false);
382     let clif_type = pass_mode.get_param_ty(fx);
383     let ebb_param = fx.bcx.append_ebb_param(start_ebb, clif_type);
384
385     #[cfg(debug_assertions)]
386     add_arg_comment(fx, "arg", local, local_field, Some(ebb_param), pass_mode, ssa_flags, arg_ty);
387
388     match pass_mode {
389         PassMode::NoPass => unimplemented!("pass mode nopass"),
390         PassMode::ByVal(_) => CValue::ByVal(ebb_param, layout),
391         PassMode::ByRef => CValue::ByRef(ebb_param, layout),
392     }
393 }
394
395 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
396     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
397     start_ebb: Ebb,
398 ) {
399     let ssa_analyzed = crate::analyze::analyze(fx);
400
401     #[cfg(debug_assertions)]
402     fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
403
404     let ret_layout = fx.layout_of(fx.return_type());
405     let output_pass_mode = get_pass_mode(fx.tcx, fx.return_type(), true);
406     let ret_param = match output_pass_mode {
407         PassMode::NoPass => None,
408         PassMode::ByVal(_) => None,
409         PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.pointer_type)),
410     };
411
412     #[cfg(debug_assertions)]
413     {
414         add_local_header_comment(fx);
415         add_arg_comment(fx, "ret", RETURN_PLACE, None, ret_param, output_pass_mode, ssa_analyzed[&RETURN_PLACE], ret_layout.ty);
416     }
417
418     enum ArgKind<'tcx> {
419         Normal(CValue<'tcx>),
420         Spread(Vec<CValue<'tcx>>),
421     }
422
423     let func_params = fx
424         .mir
425         .args_iter()
426         .map(|local| {
427             let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
428
429             // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
430             if Some(local) == fx.mir.spread_arg {
431                 // This argument (e.g. the last argument in the "rust-call" ABI)
432                 // is a tuple that was spread at the ABI level and now we have
433                 // to reconstruct it into a tuple local variable, from multiple
434                 // individual function arguments.
435
436                 let tupled_arg_tys = match arg_ty.sty {
437                     ty::Tuple(ref tys) => tys,
438                     _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
439                 };
440
441                 let mut params = Vec::new();
442                 for (i, arg_ty) in tupled_arg_tys.iter().enumerate() {
443                     let param = cvalue_for_param(fx, start_ebb, local, Some(i), arg_ty, ssa_analyzed[&local]);
444                     params.push(param);
445                 }
446
447                 (local, ArgKind::Spread(params), arg_ty)
448             } else {
449                 let param = cvalue_for_param(fx, start_ebb, local, None, arg_ty, ssa_analyzed[&local]);
450                 (
451                     local,
452                     ArgKind::Normal(param),
453                     arg_ty,
454                 )
455             }
456         })
457         .collect::<Vec<(Local, ArgKind, Ty)>>();
458
459     fx.bcx.switch_to_block(start_ebb);
460
461     match output_pass_mode {
462         PassMode::NoPass => {
463             fx.local_map.insert(RETURN_PLACE, CPlace::NoPlace(ret_layout));
464         }
465         PassMode::ByVal(_) => {
466             let is_ssa = !ssa_analyzed
467                 .get(&RETURN_PLACE)
468                 .unwrap()
469                 .contains(crate::analyze::Flags::NOT_SSA);
470
471             local_place(fx, RETURN_PLACE, ret_layout, is_ssa);
472         }
473         PassMode::ByRef => {
474             fx.local_map.insert(
475                 RETURN_PLACE,
476                 CPlace::Addr(ret_param.unwrap(), None, ret_layout),
477             );
478         }
479     }
480
481     for (local, arg_kind, ty) in func_params {
482         let layout = fx.layout_of(ty);
483
484         let is_ssa = !ssa_analyzed
485             .get(&local)
486             .unwrap()
487             .contains(crate::analyze::Flags::NOT_SSA);
488
489         let place = local_place(fx, local, layout, is_ssa);
490
491         match arg_kind {
492             ArgKind::Normal(param) => {
493                 place.write_cvalue(fx, param);
494             }
495             ArgKind::Spread(params) => {
496                 for (i, param) in params.into_iter().enumerate() {
497                     place.place_field(fx, mir::Field::new(i)).write_cvalue(fx, param);
498                 }
499             }
500         }
501     }
502
503     for local in fx.mir.vars_and_temps_iter() {
504         let ty = fx.mir.local_decls[local].ty;
505         let layout = fx.layout_of(ty);
506
507         let is_ssa = !ssa_analyzed
508             .get(&local)
509             .unwrap()
510             .contains(crate::analyze::Flags::NOT_SSA);
511
512         local_place(fx, local, layout, is_ssa);
513     }
514
515     fx.bcx
516         .ins()
517         .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
518 }
519
520 pub fn codegen_terminator_call<'a, 'tcx: 'a>(
521     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
522     func: &Operand<'tcx>,
523     args: &[Operand<'tcx>],
524     destination: &Option<(Place<'tcx>, BasicBlock)>,
525 ) {
526     let fn_ty = fx.monomorphize(&func.ty(fx.mir, fx.tcx));
527     let sig = ty_fn_sig(fx.tcx, fn_ty);
528
529     // Unpack arguments tuple for closures
530     let args = if sig.abi == Abi::RustCall {
531         assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
532         let self_arg = trans_operand(fx, &args[0]);
533         let pack_arg = trans_operand(fx, &args[1]);
534         let mut args = Vec::new();
535         args.push(self_arg);
536         match pack_arg.layout().ty.sty {
537             ty::Tuple(ref tupled_arguments) => {
538                 for (i, _) in tupled_arguments.iter().enumerate() {
539                     args.push(pack_arg.value_field(fx, mir::Field::new(i)));
540                 }
541             }
542             _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
543         }
544         args
545     } else {
546         args.into_iter()
547             .map(|arg| trans_operand(fx, arg))
548             .collect::<Vec<_>>()
549     };
550
551     let destination = destination
552         .as_ref()
553         .map(|&(ref place, bb)| (trans_place(fx, place), bb));
554
555     if let ty::FnDef(def_id, substs) = fn_ty.sty {
556         let instance = ty::Instance::resolve(
557             fx.tcx,
558             ty::ParamEnv::reveal_all(),
559             def_id,
560             substs,
561         ).unwrap();
562
563         match instance.def {
564             InstanceDef::Intrinsic(_) => {
565                 crate::intrinsics::codegen_intrinsic_call(fx, def_id, substs, args, destination);
566                 return;
567             }
568             InstanceDef::DropGlue(_, None) => {
569                 // empty drop glue - a nop.
570                 let (_, dest) = destination.expect("Non terminating drop_in_place_real???");
571                 let ret_ebb = fx.get_ebb(dest);
572                 fx.bcx.ins().jump(ret_ebb, &[]);
573                 return;
574             }
575             _ => {}
576         }
577     }
578
579     codegen_call_inner(
580         fx,
581         Some(func),
582         fn_ty,
583         args,
584         destination.map(|(place, _)| place),
585     );
586
587     if let Some((_, dest)) = destination {
588         let ret_ebb = fx.get_ebb(dest);
589         fx.bcx.ins().jump(ret_ebb, &[]);
590     } else {
591         trap_unreachable(&mut fx.bcx);
592     }
593 }
594
595 pub fn codegen_call_inner<'a, 'tcx: 'a>(
596     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
597     func: Option<&Operand<'tcx>>,
598     fn_ty: Ty<'tcx>,
599     args: Vec<CValue<'tcx>>,
600     ret_place: Option<CPlace<'tcx>>,
601 ) {
602     let fn_sig = ty_fn_sig(fx.tcx, fn_ty);
603
604     let ret_layout = fx.layout_of(fn_sig.output());
605
606     let output_pass_mode = get_pass_mode(fx.tcx, fn_sig.output(), true);
607     let return_ptr = match output_pass_mode {
608         PassMode::NoPass => None,
609         PassMode::ByRef => match ret_place {
610             Some(ret_place) => Some(ret_place.to_addr(fx)),
611             None => Some(fx.bcx.ins().iconst(fx.pointer_type, 0)),
612         },
613         PassMode::ByVal(_) => None,
614     };
615
616     let instance = match fn_ty.sty {
617         ty::FnDef(def_id, substs) => {
618             Some(Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap())
619         }
620         _ => None,
621     };
622
623     let func_ref: Option<Value>; // Indirect call target
624
625     let first_arg = {
626         if let Some(Instance {
627             def: InstanceDef::Virtual(_, idx),
628             ..
629         }) = instance
630         {
631             let (ptr, method) = crate::vtable::get_ptr_and_method_ref(fx, args[0], idx);
632             func_ref = Some(method);
633             Some(ptr)
634         } else {
635             func_ref = if instance.is_none() {
636                 let func = trans_operand(fx, func.expect("indirect call without func Operand"));
637                 Some(func.load_scalar(fx))
638             } else {
639                 None
640             };
641
642             args.get(0).map(|arg| adjust_arg_for_abi(fx, *arg))
643         }
644         .into_iter()
645     };
646
647     let call_args: Vec<Value> = return_ptr
648         .into_iter()
649         .chain(first_arg)
650         .chain(
651             args.into_iter()
652                 .skip(1)
653                 .map(|arg| adjust_arg_for_abi(fx, arg)),
654         )
655         .collect::<Vec<_>>();
656
657     let call_inst = if let Some(func_ref) = func_ref {
658         let sig = fx.bcx.import_signature(clif_sig_from_fn_sig(fx.tcx, fn_sig));
659         fx.bcx.ins().call_indirect(sig, func_ref, &call_args)
660     } else {
661         let func_ref = fx.get_function_ref(instance.expect("non-indirect call on non-FnDef type"));
662         fx.bcx.ins().call(func_ref, &call_args)
663     };
664
665     match output_pass_mode {
666         PassMode::NoPass => {}
667         PassMode::ByVal(_) => {
668             if let Some(ret_place) = ret_place {
669                 let results = fx.bcx.inst_results(call_inst);
670                 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
671             }
672         }
673         PassMode::ByRef => {}
674     }
675 }
676
677 pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
678     match get_pass_mode(fx.tcx, fx.return_type(), true) {
679         PassMode::NoPass | PassMode::ByRef => {
680             fx.bcx.ins().return_(&[]);
681         }
682         PassMode::ByVal(_) => {
683             let place = fx.get_local_place(RETURN_PLACE);
684             let ret_val = place.to_cvalue(fx).load_scalar(fx);
685             fx.bcx.ins().return_(&[ret_val]);
686         }
687     }
688 }