]> git.lizzy.rs Git - rust.git/blob - src/abi.rs
3093ad69eb9ac8c9618c7d0e8e4cb7821fe59845
[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         // Take stack_addr in advance to avoid many duplicate instructions
363         CPlace::Addr(place.to_addr(fx), None, layout)
364     };
365
366     let prev_place = fx.local_map.insert(local, place);
367     debug_assert!(prev_place.is_none());
368     fx.local_map[&local]
369 }
370
371 fn cvalue_for_param<'a, 'tcx: 'a>(
372     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
373     start_ebb: Ebb,
374     local: mir::Local,
375     local_field: Option<usize>,
376     arg_ty: Ty<'tcx>,
377     ssa_flags: crate::analyze::Flags,
378 ) -> CValue<'tcx> {
379     let layout = fx.layout_of(arg_ty);
380     let pass_mode = get_pass_mode(fx.tcx, arg_ty, false);
381     let clif_type = pass_mode.get_param_ty(fx);
382     let ebb_param = fx.bcx.append_ebb_param(start_ebb, clif_type);
383
384     #[cfg(debug_assertions)]
385     add_arg_comment(fx, "arg", local, local_field, Some(ebb_param), pass_mode, ssa_flags, arg_ty);
386
387     match pass_mode {
388         PassMode::NoPass => unimplemented!("pass mode nopass"),
389         PassMode::ByVal(_) => CValue::ByVal(ebb_param, layout),
390         PassMode::ByRef => CValue::ByRef(ebb_param, layout),
391     }
392 }
393
394 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
395     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
396     start_ebb: Ebb,
397 ) {
398     let ssa_analyzed = crate::analyze::analyze(fx);
399
400     #[cfg(debug_assertions)]
401     fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
402
403     let ret_layout = fx.layout_of(fx.return_type());
404     let output_pass_mode = get_pass_mode(fx.tcx, fx.return_type(), true);
405     let ret_param = match output_pass_mode {
406         PassMode::NoPass => None,
407         PassMode::ByVal(_) => None,
408         PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.pointer_type)),
409     };
410
411     #[cfg(debug_assertions)]
412     {
413         add_local_header_comment(fx);
414         add_arg_comment(fx, "ret", RETURN_PLACE, None, ret_param, output_pass_mode, ssa_analyzed[&RETURN_PLACE], ret_layout.ty);
415     }
416
417     enum ArgKind<'tcx> {
418         Normal(CValue<'tcx>),
419         Spread(Vec<CValue<'tcx>>),
420     }
421
422     let func_params = fx
423         .mir
424         .args_iter()
425         .map(|local| {
426             let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
427
428             // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
429             if Some(local) == fx.mir.spread_arg {
430                 // This argument (e.g. the last argument in the "rust-call" ABI)
431                 // is a tuple that was spread at the ABI level and now we have
432                 // to reconstruct it into a tuple local variable, from multiple
433                 // individual function arguments.
434
435                 let tupled_arg_tys = match arg_ty.sty {
436                     ty::Tuple(ref tys) => tys,
437                     _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
438                 };
439
440                 let mut params = Vec::new();
441                 for (i, arg_ty) in tupled_arg_tys.iter().enumerate() {
442                     let param = cvalue_for_param(fx, start_ebb, local, Some(i), arg_ty, ssa_analyzed[&local]);
443                     params.push(param);
444                 }
445
446                 (local, ArgKind::Spread(params), arg_ty)
447             } else {
448                 let param = cvalue_for_param(fx, start_ebb, local, None, arg_ty, ssa_analyzed[&local]);
449                 (
450                     local,
451                     ArgKind::Normal(param),
452                     arg_ty,
453                 )
454             }
455         })
456         .collect::<Vec<(Local, ArgKind, Ty)>>();
457
458     fx.bcx.switch_to_block(start_ebb);
459
460     match output_pass_mode {
461         PassMode::NoPass => {
462             fx.local_map.insert(RETURN_PLACE, CPlace::NoPlace(ret_layout));
463         }
464         PassMode::ByVal(_) => {
465             let is_ssa = !ssa_analyzed
466                 .get(&RETURN_PLACE)
467                 .unwrap()
468                 .contains(crate::analyze::Flags::NOT_SSA);
469
470             local_place(fx, RETURN_PLACE, ret_layout, is_ssa);
471         }
472         PassMode::ByRef => {
473             fx.local_map.insert(
474                 RETURN_PLACE,
475                 CPlace::Addr(ret_param.unwrap(), None, ret_layout),
476             );
477         }
478     }
479
480     for (local, arg_kind, ty) in func_params {
481         let layout = fx.layout_of(ty);
482
483         let is_ssa = !ssa_analyzed
484             .get(&local)
485             .unwrap()
486             .contains(crate::analyze::Flags::NOT_SSA);
487
488         let place = local_place(fx, local, layout, is_ssa);
489
490         match arg_kind {
491             ArgKind::Normal(param) => {
492                 place.write_cvalue(fx, param);
493             }
494             ArgKind::Spread(params) => {
495                 for (i, param) in params.into_iter().enumerate() {
496                     place.place_field(fx, mir::Field::new(i)).write_cvalue(fx, param);
497                 }
498             }
499         }
500     }
501
502     for local in fx.mir.vars_and_temps_iter() {
503         let ty = fx.mir.local_decls[local].ty;
504         let layout = fx.layout_of(ty);
505
506         let is_ssa = !ssa_analyzed
507             .get(&local)
508             .unwrap()
509             .contains(crate::analyze::Flags::NOT_SSA);
510
511         local_place(fx, local, layout, is_ssa);
512     }
513
514     fx.bcx
515         .ins()
516         .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
517 }
518
519 pub fn codegen_terminator_call<'a, 'tcx: 'a>(
520     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
521     func: &Operand<'tcx>,
522     args: &[Operand<'tcx>],
523     destination: &Option<(Place<'tcx>, BasicBlock)>,
524 ) {
525     let fn_ty = fx.monomorphize(&func.ty(fx.mir, fx.tcx));
526     let sig = ty_fn_sig(fx.tcx, fn_ty);
527
528     // Unpack arguments tuple for closures
529     let args = if sig.abi == Abi::RustCall {
530         assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
531         let self_arg = trans_operand(fx, &args[0]);
532         let pack_arg = trans_operand(fx, &args[1]);
533         let mut args = Vec::new();
534         args.push(self_arg);
535         match pack_arg.layout().ty.sty {
536             ty::Tuple(ref tupled_arguments) => {
537                 for (i, _) in tupled_arguments.iter().enumerate() {
538                     args.push(pack_arg.value_field(fx, mir::Field::new(i)));
539                 }
540             }
541             _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
542         }
543         args
544     } else {
545         args.into_iter()
546             .map(|arg| trans_operand(fx, arg))
547             .collect::<Vec<_>>()
548     };
549
550     let destination = destination
551         .as_ref()
552         .map(|&(ref place, bb)| (trans_place(fx, place), bb));
553
554     if let ty::FnDef(def_id, substs) = fn_ty.sty {
555         let instance = ty::Instance::resolve(
556             fx.tcx,
557             ty::ParamEnv::reveal_all(),
558             def_id,
559             substs,
560         ).unwrap();
561
562         match instance.def {
563             InstanceDef::Intrinsic(_) => {
564                 crate::intrinsics::codegen_intrinsic_call(fx, def_id, substs, args, destination);
565                 return;
566             }
567             InstanceDef::DropGlue(_, None) => {
568                 // empty drop glue - a nop.
569                 let (_, dest) = destination.expect("Non terminating drop_in_place_real???");
570                 let ret_ebb = fx.get_ebb(dest);
571                 fx.bcx.ins().jump(ret_ebb, &[]);
572                 return;
573             }
574             _ => {}
575         }
576     }
577
578     codegen_call_inner(
579         fx,
580         Some(func),
581         fn_ty,
582         args,
583         destination.map(|(place, _)| place),
584     );
585
586     if let Some((_, dest)) = destination {
587         let ret_ebb = fx.get_ebb(dest);
588         fx.bcx.ins().jump(ret_ebb, &[]);
589     } else {
590         trap_unreachable(&mut fx.bcx);
591     }
592 }
593
594 pub fn codegen_call_inner<'a, 'tcx: 'a>(
595     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
596     func: Option<&Operand<'tcx>>,
597     fn_ty: Ty<'tcx>,
598     args: Vec<CValue<'tcx>>,
599     ret_place: Option<CPlace<'tcx>>,
600 ) {
601     let fn_sig = ty_fn_sig(fx.tcx, fn_ty);
602
603     let ret_layout = fx.layout_of(fn_sig.output());
604
605     let output_pass_mode = get_pass_mode(fx.tcx, fn_sig.output(), true);
606     let return_ptr = match output_pass_mode {
607         PassMode::NoPass => None,
608         PassMode::ByRef => match ret_place {
609             Some(ret_place) => Some(ret_place.to_addr(fx)),
610             None => Some(fx.bcx.ins().iconst(fx.pointer_type, 0)),
611         },
612         PassMode::ByVal(_) => None,
613     };
614
615     let instance = match fn_ty.sty {
616         ty::FnDef(def_id, substs) => {
617             Some(Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap())
618         }
619         _ => None,
620     };
621
622     let func_ref: Option<Value>; // Indirect call target
623
624     let first_arg = {
625         if let Some(Instance {
626             def: InstanceDef::Virtual(_, idx),
627             ..
628         }) = instance
629         {
630             let (ptr, method) = crate::vtable::get_ptr_and_method_ref(fx, args[0], idx);
631             func_ref = Some(method);
632             Some(ptr)
633         } else {
634             func_ref = if instance.is_none() {
635                 let func = trans_operand(fx, func.expect("indirect call without func Operand"));
636                 Some(func.load_scalar(fx))
637             } else {
638                 None
639             };
640
641             args.get(0).map(|arg| adjust_arg_for_abi(fx, *arg))
642         }
643         .into_iter()
644     };
645
646     let call_args: Vec<Value> = return_ptr
647         .into_iter()
648         .chain(first_arg)
649         .chain(
650             args.into_iter()
651                 .skip(1)
652                 .map(|arg| adjust_arg_for_abi(fx, arg)),
653         )
654         .collect::<Vec<_>>();
655
656     let call_inst = if let Some(func_ref) = func_ref {
657         let sig = fx.bcx.import_signature(clif_sig_from_fn_sig(fx.tcx, fn_sig));
658         fx.bcx.ins().call_indirect(sig, func_ref, &call_args)
659     } else {
660         let func_ref = fx.get_function_ref(instance.expect("non-indirect call on non-FnDef type"));
661         fx.bcx.ins().call(func_ref, &call_args)
662     };
663
664     match output_pass_mode {
665         PassMode::NoPass => {}
666         PassMode::ByVal(_) => {
667             if let Some(ret_place) = ret_place {
668                 let results = fx.bcx.inst_results(call_inst);
669                 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
670             }
671         }
672         PassMode::ByRef => {}
673     }
674 }
675
676 pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
677     match get_pass_mode(fx.tcx, fx.return_type(), true) {
678         PassMode::NoPass | PassMode::ByRef => {
679             fx.bcx.ins().return_(&[]);
680         }
681         PassMode::ByVal(_) => {
682             let place = fx.get_local_place(RETURN_PLACE);
683             let ret_val = place.to_cvalue(fx).load_scalar(fx);
684             fx.bcx.ins().return_(&[ret_val]);
685         }
686     }
687 }