]> git.lizzy.rs Git - rust.git/blob - src/abi.rs
Implement returning `!` for "C" abi
[rust.git] / src / abi.rs
1 use std::iter;
2
3 use rustc::hir;
4 use rustc_target::spec::abi::Abi;
5
6 use crate::prelude::*;
7
8 #[derive(Debug)]
9 enum PassMode {
10     NoPass,
11     ByVal(Type),
12     ByRef,
13 }
14
15 impl PassMode {
16     fn get_param_ty(self, fx: &FunctionCx<impl Backend>) -> Type {
17         match self {
18             PassMode::NoPass => unimplemented!("pass mode nopass"),
19             PassMode::ByVal(cton_type) => cton_type,
20             PassMode::ByRef => fx.module.pointer_type(),
21         }
22     }
23 }
24
25 fn get_pass_mode<'a, 'tcx: 'a>(
26     tcx: TyCtxt<'a, 'tcx, 'tcx>,
27     abi: Abi,
28     ty: Ty<'tcx>,
29     is_return: bool,
30 ) -> PassMode {
31     assert!(
32         !tcx.layout_of(ParamEnv::reveal_all().and(ty))
33             .unwrap()
34             .is_unsized()
35     );
36     if let ty::Never = ty.sty {
37         if is_return {
38             PassMode::NoPass
39         } else {
40             PassMode::ByRef
41         }
42     } else if ty.sty == tcx.mk_unit().sty {
43         if is_return {
44             PassMode::NoPass
45         } else {
46             PassMode::ByRef
47         }
48     } else if let Some(ret_ty) = crate::common::cton_type_from_ty(tcx, ty) {
49         PassMode::ByVal(ret_ty)
50     } else {
51         if abi == Abi::C {
52             unimplemented!("Non scalars are not yet supported for \"C\" abi");
53         }
54         PassMode::ByRef
55     }
56 }
57
58 fn adjust_arg_for_abi<'a, 'tcx: 'a>(
59     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
60     sig: FnSig<'tcx>,
61     arg: CValue<'tcx>,
62 ) -> Value {
63     match get_pass_mode(fx.tcx, sig.abi, arg.layout().ty, false) {
64         PassMode::NoPass => unimplemented!("pass mode nopass"),
65         PassMode::ByVal(_) => arg.load_value(fx),
66         PassMode::ByRef => arg.force_stack(fx),
67     }
68 }
69
70 pub fn cton_sig_from_fn_ty<'a, 'tcx: 'a>(
71     tcx: TyCtxt<'a, 'tcx, 'tcx>,
72     fn_ty: Ty<'tcx>,
73 ) -> Signature {
74     let sig = ty_fn_sig(tcx, fn_ty);
75     assert!(!sig.variadic, "Variadic function are not yet supported");
76     let (call_conv, inputs, output): (CallConv, Vec<Ty>, Ty) = match sig.abi {
77         Abi::Rust => (CallConv::Fast, sig.inputs().to_vec(), sig.output()),
78         Abi::C => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
79         Abi::RustCall => {
80             assert_eq!(sig.inputs().len(), 2);
81             let extra_args = match sig.inputs().last().unwrap().sty {
82                 ty::Tuple(ref tupled_arguments) => tupled_arguments,
83                 _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
84             };
85             let mut inputs: Vec<Ty> = vec![sig.inputs()[0]];
86             inputs.extend(extra_args.into_iter());
87             (CallConv::Fast, inputs, sig.output())
88         }
89         Abi::System => bug!("system abi should be selected elsewhere"),
90         Abi::RustIntrinsic => (CallConv::SystemV, sig.inputs().to_vec(), sig.output()),
91         _ => unimplemented!("unsupported abi {:?}", sig.abi),
92     };
93
94     let inputs = inputs
95         .into_iter()
96         .filter_map(|ty| match get_pass_mode(tcx, sig.abi, ty, false) {
97             PassMode::ByVal(cton_ty) => Some(cton_ty),
98             PassMode::NoPass => unimplemented!("pass mode nopass"),
99             PassMode::ByRef => Some(pointer_ty(tcx)),
100         });
101
102     let (params, returns) = match get_pass_mode(tcx, sig.abi, output, true) {
103         PassMode::NoPass => (inputs.map(AbiParam::new).collect(), vec![]),
104         PassMode::ByVal(ret_ty) => (
105             inputs.map(AbiParam::new).collect(),
106             vec![AbiParam::new(ret_ty)],
107         ),
108         PassMode::ByRef => {
109             (
110                 Some(pointer_ty(tcx)) // First param is place to put return val
111                     .into_iter()
112                     .chain(inputs)
113                     .map(AbiParam::new)
114                     .collect(),
115                 vec![],
116             )
117         }
118     };
119
120     Signature {
121         params,
122         returns,
123         call_conv,
124     }
125 }
126
127 fn ty_fn_sig<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>, ty: Ty<'tcx>) -> ty::FnSig<'tcx> {
128     let sig = match ty.sty {
129         ty::FnDef(..) |
130         // Shims currently have type TyFnPtr. Not sure this should remain.
131         ty::FnPtr(_) => ty.fn_sig(tcx),
132         ty::Closure(def_id, substs) => {
133             let sig = substs.closure_sig(def_id, tcx);
134
135             let env_ty = tcx.closure_env_ty(def_id, substs).unwrap();
136             sig.map_bound(|sig| tcx.mk_fn_sig(
137                 iter::once(*env_ty.skip_binder()).chain(sig.inputs().iter().cloned()),
138                 sig.output(),
139                 sig.variadic,
140                 sig.unsafety,
141                 sig.abi
142             ))
143         }
144         ty::Generator(def_id, substs, _) => {
145             let sig = substs.poly_sig(def_id, tcx);
146
147             let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
148             let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
149
150             sig.map_bound(|sig| {
151                 let state_did = tcx.lang_items().gen_state().unwrap();
152                 let state_adt_ref = tcx.adt_def(state_did);
153                 let state_substs = tcx.intern_substs(&[
154                     sig.yield_ty.into(),
155                     sig.return_ty.into(),
156                 ]);
157                 let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
158
159                 tcx.mk_fn_sig(iter::once(env_ty),
160                     ret_ty,
161                     false,
162                     hir::Unsafety::Normal,
163                     Abi::Rust
164                 )
165             })
166         }
167         _ => bug!("unexpected type {:?} to ty_fn_sig", ty)
168     };
169     tcx.normalize_erasing_late_bound_regions(ParamEnv::reveal_all(), &sig)
170 }
171
172 pub fn get_function_name_and_sig<'a, 'tcx>(
173     tcx: TyCtxt<'a, 'tcx, 'tcx>,
174     inst: Instance<'tcx>,
175 ) -> (String, Signature) {
176     assert!(!inst.substs.needs_infer() && !inst.substs.has_param_types());
177     let fn_ty = inst.ty(tcx);
178     let sig = cton_sig_from_fn_ty(tcx, fn_ty);
179     (tcx.symbol_name(inst).as_str().to_string(), sig)
180 }
181
182 impl<'a, 'tcx: 'a, B: Backend + 'a> FunctionCx<'a, 'tcx, B> {
183     /// Instance must be monomorphized
184     pub fn get_function_id(&mut self, inst: Instance<'tcx>) -> FuncId {
185         let (name, sig) = get_function_name_and_sig(self.tcx, inst);
186         self.module
187             .declare_function(&name, Linkage::Import, &sig)
188             .unwrap()
189     }
190
191     /// Instance must be monomorphized
192     pub fn get_function_ref(&mut self, inst: Instance<'tcx>) -> FuncRef {
193         let func_id = self.get_function_id(inst);
194         self.module
195             .declare_func_in_func(func_id, &mut self.bcx.func)
196     }
197
198     fn lib_call(
199         &mut self,
200         name: &str,
201         input_tys: Vec<types::Type>,
202         output_ty: Option<types::Type>,
203         args: &[Value],
204     ) -> Option<Value> {
205         let sig = Signature {
206             params: input_tys.iter().cloned().map(AbiParam::new).collect(),
207             returns: output_ty
208                 .map(|output_ty| vec![AbiParam::new(output_ty)])
209                 .unwrap_or(Vec::new()),
210             call_conv: CallConv::SystemV,
211         };
212         let func_id = self
213             .module
214             .declare_function(&name, Linkage::Import, &sig)
215             .unwrap();
216         let func_ref = self
217             .module
218             .declare_func_in_func(func_id, &mut self.bcx.func);
219         let call_inst = self.bcx.ins().call(func_ref, args);
220         if output_ty.is_none() {
221             return None;
222         }
223         let results = self.bcx.inst_results(call_inst);
224         assert_eq!(results.len(), 1);
225         Some(results[0])
226     }
227
228     pub fn easy_call(
229         &mut self,
230         name: &str,
231         args: &[CValue<'tcx>],
232         return_ty: Ty<'tcx>,
233     ) -> CValue<'tcx> {
234         let (input_tys, args): (Vec<_>, Vec<_>) = args
235             .into_iter()
236             .map(|arg| {
237                 (
238                     self.cton_type(arg.layout().ty).unwrap(),
239                     arg.load_value(self),
240                 )
241             }).unzip();
242         let return_layout = self.layout_of(return_ty);
243         let return_ty = if let ty::Tuple(tup) = return_ty.sty {
244             if !tup.is_empty() {
245                 bug!("easy_call( (...) -> <non empty tuple> ) is not allowed");
246             }
247             None
248         } else {
249             Some(self.cton_type(return_ty).unwrap())
250         };
251         if let Some(val) = self.lib_call(name, input_tys, return_ty, &args) {
252             CValue::ByVal(val, return_layout)
253         } else {
254             CValue::ByRef(
255                 self.bcx.ins().iconst(self.module.pointer_type(), 0),
256                 return_layout,
257             )
258         }
259     }
260
261     fn self_sig(&self) -> FnSig<'tcx> {
262         ty_fn_sig(self.tcx, self.instance.ty(self.tcx))
263     }
264
265     fn return_type(&self) -> Ty<'tcx> {
266         self.self_sig().output()
267     }
268 }
269
270 pub fn codegen_fn_prelude<'a, 'tcx: 'a>(
271     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
272     start_ebb: Ebb,
273 ) {
274     let ssa_analyzed = crate::analyze::analyze(fx);
275
276     let ret_layout = fx.layout_of(fx.return_type());
277     let output_pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true);
278     let ret_param = match output_pass_mode {
279         PassMode::NoPass => None,
280         PassMode::ByVal(_) => None,
281         PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.module.pointer_type())),
282     };
283
284     enum ArgKind {
285         Normal(Value),
286         Spread(Vec<Value>),
287     }
288
289     let func_params = fx
290         .mir
291         .args_iter()
292         .map(|local| {
293             let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
294
295             // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
296             if Some(local) == fx.mir.spread_arg {
297                 // This argument (e.g. the last argument in the "rust-call" ABI)
298                 // is a tuple that was spread at the ABI level and now we have
299                 // to reconstruct it into a tuple local variable, from multiple
300                 // individual function arguments.
301
302                 let tupled_arg_tys = match arg_ty.sty {
303                     ty::Tuple(ref tys) => tys,
304                     _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
305                 };
306
307                 let mut ebb_params = Vec::new();
308                 for arg_ty in tupled_arg_tys.iter() {
309                     let cton_type =
310                         get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
311                     ebb_params.push(fx.bcx.append_ebb_param(start_ebb, cton_type));
312                 }
313
314                 (local, ArgKind::Spread(ebb_params), arg_ty)
315             } else {
316                 let cton_type =
317                     get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
318                 (
319                     local,
320                     ArgKind::Normal(fx.bcx.append_ebb_param(start_ebb, cton_type)),
321                     arg_ty,
322                 )
323             }
324         }).collect::<Vec<(Local, ArgKind, Ty)>>();
325
326     fx.bcx.switch_to_block(start_ebb);
327
328     fx.top_nop = Some(fx.bcx.ins().nop());
329     fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
330
331     match output_pass_mode {
332         PassMode::NoPass => {
333             let null = fx.bcx.ins().iconst(fx.module.pointer_type(), 0);
334             //unimplemented!("pass mode nopass");
335             fx.local_map.insert(
336                 RETURN_PLACE,
337                 CPlace::Addr(null, None, fx.layout_of(fx.return_type())),
338             );
339         }
340         PassMode::ByVal(ret_ty) => {
341             fx.bcx.declare_var(mir_var(RETURN_PLACE), ret_ty);
342             fx.local_map
343                 .insert(RETURN_PLACE, CPlace::Var(RETURN_PLACE, ret_layout));
344         }
345         PassMode::ByRef => {
346             fx.local_map.insert(
347                 RETURN_PLACE,
348                 CPlace::Addr(ret_param.unwrap(), None, ret_layout),
349             );
350         }
351     }
352
353     for (local, arg_kind, ty) in func_params {
354         let layout = fx.layout_of(ty);
355
356         if let ArgKind::Normal(ebb_param) = arg_kind {
357             if !ssa_analyzed
358                 .get(&local)
359                 .unwrap()
360                 .contains(crate::analyze::Flags::NOT_SSA)
361             {
362                 fx.bcx
363                     .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
364                 match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false) {
365                     PassMode::NoPass => unimplemented!("pass mode nopass"),
366                     PassMode::ByVal(_) => fx.bcx.def_var(mir_var(local), ebb_param),
367                     PassMode::ByRef => {
368                         let val = CValue::ByRef(ebb_param, fx.layout_of(ty)).load_value(fx);
369                         fx.bcx.def_var(mir_var(local), val);
370                     }
371                 }
372                 fx.local_map.insert(local, CPlace::Var(local, layout));
373                 continue;
374             }
375         }
376
377         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
378             kind: StackSlotKind::ExplicitSlot,
379             size: layout.size.bytes() as u32,
380             offset: None,
381         });
382
383         let place = CPlace::from_stack_slot(fx, stack_slot, ty);
384
385         match arg_kind {
386             ArgKind::Normal(ebb_param) => match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false)
387             {
388                 PassMode::NoPass => unimplemented!("pass mode nopass"),
389                 PassMode::ByVal(_) => {
390                     place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()))
391                 }
392                 PassMode::ByRef => place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout())),
393             },
394             ArgKind::Spread(ebb_params) => {
395                 for (i, ebb_param) in ebb_params.into_iter().enumerate() {
396                     let sub_place = place.place_field(fx, mir::Field::new(i));
397                     match get_pass_mode(fx.tcx, fx.self_sig().abi, sub_place.layout().ty, false) {
398                         PassMode::NoPass => unimplemented!("pass mode nopass"),
399                         PassMode::ByVal(_) => {
400                             sub_place.write_cvalue(fx, CValue::ByVal(ebb_param, sub_place.layout()))
401                         }
402                         PassMode::ByRef => {
403                             sub_place.write_cvalue(fx, CValue::ByRef(ebb_param, sub_place.layout()))
404                         }
405                     }
406                 }
407             }
408         }
409         fx.local_map.insert(local, place);
410     }
411
412     for local in fx.mir.vars_and_temps_iter() {
413         let ty = fx.mir.local_decls[local].ty;
414         let layout = fx.layout_of(ty);
415
416         let place = if ssa_analyzed
417             .get(&local)
418             .unwrap()
419             .contains(crate::analyze::Flags::NOT_SSA)
420         {
421             let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
422                 kind: StackSlotKind::ExplicitSlot,
423                 size: layout.size.bytes() as u32,
424                 offset: None,
425             });
426             CPlace::from_stack_slot(fx, stack_slot, ty)
427         } else {
428             fx.bcx
429                 .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
430             CPlace::Var(local, layout)
431         };
432
433         fx.local_map.insert(local, place);
434     }
435
436     fx.bcx
437         .ins()
438         .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
439 }
440
441 pub fn codegen_terminator_call<'a, 'tcx: 'a>(
442     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
443     func: &Operand<'tcx>,
444     args: &[Operand<'tcx>],
445     destination: &Option<(Place<'tcx>, BasicBlock)>,
446 ) {
447     let fn_ty = fx.monomorphize(&func.ty(&fx.mir.local_decls, fx.tcx));
448     let sig = ty_fn_sig(fx.tcx, fn_ty);
449
450     // Unpack arguments tuple for closures
451     let args = if sig.abi == Abi::RustCall {
452         assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
453         let self_arg = trans_operand(fx, &args[0]);
454         let pack_arg = trans_operand(fx, &args[1]);
455         let mut args = Vec::new();
456         args.push(self_arg);
457         match pack_arg.layout().ty.sty {
458             ty::Tuple(ref tupled_arguments) => {
459                 for (i, _) in tupled_arguments.iter().enumerate() {
460                     args.push(pack_arg.value_field(fx, mir::Field::new(i)));
461                 }
462             }
463             _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
464         }
465         args
466     } else {
467         args.into_iter()
468             .map(|arg| trans_operand(fx, arg))
469             .collect::<Vec<_>>()
470     };
471
472     let destination = destination
473         .as_ref()
474         .map(|&(ref place, bb)| (trans_place(fx, place), bb));
475
476     if !codegen_intrinsic_call(fx, fn_ty, &args, destination) {
477         codegen_call_inner(
478             fx,
479             Some(func),
480             fn_ty,
481             args,
482             destination.map(|(place, _)| place),
483         );
484
485         if let Some((_, dest)) = destination {
486             let ret_ebb = fx.get_ebb(dest);
487             fx.bcx.ins().jump(ret_ebb, &[]);
488         } else {
489             fx.bcx.ins().trap(TrapCode::User(!0));
490         }
491     }
492 }
493
494 pub fn codegen_call_inner<'a, 'tcx: 'a>(
495     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
496     func: Option<&Operand<'tcx>>,
497     fn_ty: Ty<'tcx>,
498     args: Vec<CValue<'tcx>>,
499     ret_place: Option<CPlace<'tcx>>,
500 ) {
501     let sig = ty_fn_sig(fx.tcx, fn_ty);
502
503     let ret_layout = fx.layout_of(sig.output());
504
505     let output_pass_mode = get_pass_mode(fx.tcx, sig.abi, sig.output(), true);
506     let return_ptr = match output_pass_mode {
507         PassMode::NoPass => None,
508         PassMode::ByRef => match ret_place {
509             Some(ret_place) => Some(ret_place.expect_addr()),
510             None => Some(fx.bcx.ins().iconst(fx.module.pointer_type(), 0)),
511         },
512         PassMode::ByVal(_) => None,
513     };
514
515     let instance = match fn_ty.sty {
516         ty::FnDef(def_id, substs) => {
517             Some(Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap())
518         }
519         _ => None,
520     };
521
522     let func_ref: Option<Value>; // Indirect call target
523
524     let first_arg = {
525         if let Some(Instance {
526             def: InstanceDef::Virtual(_, idx),
527             ..
528         }) = instance
529         {
530             let (ptr, method) = crate::vtable::get_ptr_and_method_ref(fx, args[0], idx);
531             func_ref = Some(method);
532             Some(ptr)
533         } else {
534             func_ref = if instance.is_none() {
535                 let func = trans_operand(fx, func.expect("indirect call without func Operand"));
536                 Some(func.load_value(fx))
537             } else {
538                 None
539             };
540
541             args.get(0).map(|arg| adjust_arg_for_abi(fx, sig, *arg))
542         }.into_iter()
543     };
544
545     let call_args: Vec<Value> = return_ptr
546         .into_iter()
547         .chain(first_arg)
548         .chain(
549             args.into_iter()
550                 .skip(1)
551                 .map(|arg| adjust_arg_for_abi(fx, sig, arg)),
552         ).collect::<Vec<_>>();
553
554     let sig = fx.bcx.import_signature(cton_sig_from_fn_ty(fx.tcx, fn_ty));
555     let call_inst = if let Some(func_ref) = func_ref {
556         fx.bcx.ins().call_indirect(sig, func_ref, &call_args)
557     } else {
558         let func_ref = fx.get_function_ref(instance.expect("non-indirect call on non-FnDef type"));
559         fx.bcx.ins().call(func_ref, &call_args)
560     };
561
562     match output_pass_mode {
563         PassMode::NoPass => {}
564         PassMode::ByVal(_) => {
565             if let Some(ret_place) = ret_place {
566                 let results = fx.bcx.inst_results(call_inst);
567                 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
568             }
569         }
570         PassMode::ByRef => {}
571     }
572 }
573
574 pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
575     match get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true) {
576         PassMode::NoPass | PassMode::ByRef => {
577             fx.bcx.ins().return_(&[]);
578         }
579         PassMode::ByVal(_) => {
580             let place = fx.get_local_place(RETURN_PLACE);
581             let ret_val = place.to_cvalue(fx).load_value(fx);
582             fx.bcx.ins().return_(&[ret_val]);
583         }
584     }
585 }
586
587 fn codegen_intrinsic_call<'a, 'tcx: 'a>(
588     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
589     fn_ty: Ty<'tcx>,
590     args: &[CValue<'tcx>],
591     destination: Option<(CPlace<'tcx>, BasicBlock)>,
592 ) -> bool {
593     if let ty::FnDef(def_id, substs) = fn_ty.sty {
594         let sig = ty_fn_sig(fx.tcx, fn_ty);
595
596         if sig.abi == Abi::RustIntrinsic {
597             let intrinsic = fx.tcx.item_name(def_id).as_str();
598             let intrinsic = &intrinsic[..];
599
600             let ret = match destination {
601                 Some((place, _)) => place,
602                 None => {
603                     // Insert non returning intrinsics here
604                     match intrinsic {
605                         "abort" => {
606                             fx.bcx.ins().trap(TrapCode::User(!0 - 1));
607                         }
608                         "unreachable" => {
609                             fx.bcx.ins().trap(TrapCode::User(!0 - 1));
610                         }
611                         _ => unimplemented!("unsupported instrinsic {}", intrinsic),
612                     }
613                     return true;
614                 }
615             };
616
617             let nil_ty = fx.tcx.mk_unit();
618             let u64_layout = fx.layout_of(fx.tcx.types.u64);
619             let usize_layout = fx.layout_of(fx.tcx.types.usize);
620
621             match intrinsic {
622                 "assume" => {
623                     assert_eq!(args.len(), 1);
624                 }
625                 "arith_offset" => {
626                     assert_eq!(args.len(), 2);
627                     let base = args[0].load_value(fx);
628                     let offset = args[1].load_value(fx);
629                     let res = fx.bcx.ins().iadd(base, offset);
630                     let res = CValue::ByVal(res, ret.layout());
631                     ret.write_cvalue(fx, res);
632                 }
633                 "likely" | "unlikely" => {
634                     assert_eq!(args.len(), 1);
635                     ret.write_cvalue(fx, args[0]);
636                 }
637                 "copy" | "copy_nonoverlapping" => {
638                     let elem_ty = substs.type_at(0);
639                     let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
640                     let elem_size = fx
641                         .bcx
642                         .ins()
643                         .iconst(fx.module.pointer_type(), elem_size as i64);
644                     assert_eq!(args.len(), 3);
645                     let src = args[0];
646                     let dst = args[1];
647                     let count = args[2].load_value(fx);
648                     let byte_amount = fx.bcx.ins().imul(count, elem_size);
649                     fx.easy_call(
650                         "memmove",
651                         &[dst, src, CValue::ByVal(byte_amount, usize_layout)],
652                         nil_ty,
653                     );
654                 }
655                 "discriminant_value" => {
656                     assert_eq!(args.len(), 1);
657                     let discr = crate::base::trans_get_discriminant(fx, args[0], ret.layout());
658                     ret.write_cvalue(fx, discr);
659                 }
660                 "size_of" => {
661                     assert_eq!(args.len(), 0);
662                     let size_of = fx.layout_of(substs.type_at(0)).size.bytes();
663                     let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
664                     ret.write_cvalue(fx, size_of);
665                 }
666                 "size_of_val" => {
667                     assert_eq!(args.len(), 1);
668                     let layout = fx.layout_of(substs.type_at(0));
669                     let size = match &layout.ty.sty {
670                         _ if !layout.is_unsized() => {
671                             fx.bcx.ins().iconst(fx.module.pointer_type(), layout.size.bytes() as i64)
672                         }
673                         ty::Slice(elem) => {
674                             let len = args[0].load_value_pair(fx).1;
675                             let elem_size = fx.layout_of(elem).size.bytes();
676                             fx.bcx.ins().imul_imm(len, elem_size as i64)
677                         }
678                         ty::Dynamic(..) => crate::vtable::size_of_obj(fx, args[0]),
679                         ty => unimplemented!("size_of_val for {:?}", ty),
680                     };
681                     ret.write_cvalue(fx, CValue::ByVal(size, usize_layout));
682                 }
683                 "min_align_of" => {
684                     assert_eq!(args.len(), 0);
685                     let min_align = fx.layout_of(substs.type_at(0)).align.abi();
686                     let min_align = CValue::const_val(fx, usize_layout.ty, min_align as i64);
687                     ret.write_cvalue(fx, min_align);
688                 }
689                 "min_align_of_val" => {
690                     assert_eq!(args.len(), 1);
691                     let layout = fx.layout_of(substs.type_at(0));
692                     let align = match &layout.ty.sty {
693                         _ if !layout.is_unsized() => {
694                             fx.bcx.ins().iconst(fx.module.pointer_type(), layout.align.abi() as i64)
695                         }
696                         ty::Slice(elem) => {
697                             let align = fx.layout_of(elem).align.abi() as i64;
698                             fx.bcx.ins().iconst(fx.module.pointer_type(), align)
699                         }
700                         ty::Dynamic(..) => crate::vtable::min_align_of_obj(fx, args[0]),
701                         ty => unimplemented!("min_align_of_val for {:?}", ty),
702                     };
703                     ret.write_cvalue(fx, CValue::ByVal(align, usize_layout));
704                 }
705                 "type_id" => {
706                     assert_eq!(args.len(), 0);
707                     let type_id = fx.tcx.type_id_hash(substs.type_at(0));
708                     let type_id = CValue::const_val(fx, u64_layout.ty, type_id as i64);
709                     ret.write_cvalue(fx, type_id);
710                 }
711                 _ if intrinsic.starts_with("unchecked_") => {
712                     assert_eq!(args.len(), 2);
713                     let bin_op = match intrinsic {
714                         "unchecked_div" => BinOp::Div,
715                         "unchecked_rem" => BinOp::Rem,
716                         "unchecked_shl" => BinOp::Shl,
717                         "unchecked_shr" => BinOp::Shr,
718                         _ => unimplemented!("intrinsic {}", intrinsic),
719                     };
720                     let res = match ret.layout().ty.sty {
721                         ty::Uint(_) => crate::base::trans_int_binop(
722                             fx,
723                             bin_op,
724                             args[0],
725                             args[1],
726                             ret.layout().ty,
727                             false,
728                         ),
729                         ty::Int(_) => crate::base::trans_int_binop(
730                             fx,
731                             bin_op,
732                             args[0],
733                             args[1],
734                             ret.layout().ty,
735                             true,
736                         ),
737                         _ => panic!(),
738                     };
739                     ret.write_cvalue(fx, res);
740                 }
741                 _ if intrinsic.ends_with("_with_overflow") => {
742                     assert_eq!(args.len(), 2);
743                     assert_eq!(args[0].layout().ty, args[1].layout().ty);
744                     let bin_op = match intrinsic {
745                         "add_with_overflow" => BinOp::Add,
746                         "sub_with_overflow" => BinOp::Sub,
747                         "mul_with_overflow" => BinOp::Mul,
748                         _ => unimplemented!("intrinsic {}", intrinsic),
749                     };
750                     let res = match args[0].layout().ty.sty {
751                         ty::Uint(_) => crate::base::trans_checked_int_binop(
752                             fx,
753                             bin_op,
754                             args[0],
755                             args[1],
756                             ret.layout().ty,
757                             false,
758                         ),
759                         ty::Int(_) => crate::base::trans_checked_int_binop(
760                             fx,
761                             bin_op,
762                             args[0],
763                             args[1],
764                             ret.layout().ty,
765                             true,
766                         ),
767                         _ => panic!(),
768                     };
769                     ret.write_cvalue(fx, res);
770                 }
771                 _ if intrinsic.starts_with("overflowing_") => {
772                     assert_eq!(args.len(), 2);
773                     assert_eq!(args[0].layout().ty, args[1].layout().ty);
774                     let bin_op = match intrinsic {
775                         "overflowing_add" => BinOp::Add,
776                         "overflowing_sub" => BinOp::Sub,
777                         "overflowing_mul" => BinOp::Mul,
778                         _ => unimplemented!("intrinsic {}", intrinsic),
779                     };
780                     let res = match args[0].layout().ty.sty {
781                         ty::Uint(_) => crate::base::trans_int_binop(
782                             fx,
783                             bin_op,
784                             args[0],
785                             args[1],
786                             ret.layout().ty,
787                             false,
788                         ),
789                         ty::Int(_) => crate::base::trans_int_binop(
790                             fx,
791                             bin_op,
792                             args[0],
793                             args[1],
794                             ret.layout().ty,
795                             true,
796                         ),
797                         _ => panic!(),
798                     };
799                     ret.write_cvalue(fx, res);
800                 }
801                 "offset" => {
802                     assert_eq!(args.len(), 2);
803                     let base = args[0].load_value(fx);
804                     let offset = args[1].load_value(fx);
805                     let res = fx.bcx.ins().iadd(base, offset);
806                     ret.write_cvalue(fx, CValue::ByVal(res, args[0].layout()));
807                 }
808                 "transmute" => {
809                     assert_eq!(args.len(), 1);
810                     let src_ty = substs.type_at(0);
811                     let dst_ty = substs.type_at(1);
812                     assert_eq!(args[0].layout().ty, src_ty);
813                     let addr = args[0].force_stack(fx);
814                     let dst_layout = fx.layout_of(dst_ty);
815                     ret.write_cvalue(fx, CValue::ByRef(addr, dst_layout))
816                 }
817                 "uninit" => {
818                     assert_eq!(args.len(), 0);
819                     let ty = substs.type_at(0);
820                     let layout = fx.layout_of(ty);
821                     let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
822                         kind: StackSlotKind::ExplicitSlot,
823                         size: layout.size.bytes() as u32,
824                         offset: None,
825                     });
826
827                     let uninit_place = CPlace::from_stack_slot(fx, stack_slot, ty);
828                     let uninit_val = uninit_place.to_cvalue(fx);
829                     ret.write_cvalue(fx, uninit_val);
830                 }
831                 "ctlz" | "ctlz_nonzero" => {
832                     assert_eq!(args.len(), 1);
833                     let arg = args[0].load_value(fx);
834                     let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
835                     ret.write_cvalue(fx, res);
836                 }
837                 "cttz" | "cttz_nonzero" => {
838                     assert_eq!(args.len(), 1);
839                     let arg = args[0].load_value(fx);
840                     let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
841                     ret.write_cvalue(fx, res);
842                 }
843                 "ctpop" => {
844                     assert_eq!(args.len(), 1);
845                     let arg = args[0].load_value(fx);
846                     let res = CValue::ByVal(fx.bcx.ins().popcnt(arg), args[0].layout());
847                     ret.write_cvalue(fx, res);
848                 }
849                 "needs_drop" => {
850                     assert_eq!(args.len(), 0);
851                     let ty = substs.type_at(0);
852                     let needs_drop = if ty.needs_drop(fx.tcx, ParamEnv::reveal_all()) {
853                         1
854                     } else {
855                         0
856                     };
857                     let needs_drop = CValue::const_val(fx, fx.tcx.types.bool, needs_drop);
858                     ret.write_cvalue(fx, needs_drop);
859                 }
860                 _ => unimpl!("unsupported intrinsic {}", intrinsic),
861             }
862
863             if let Some((_, dest)) = destination {
864                 let ret_ebb = fx.get_ebb(dest);
865                 fx.bcx.ins().jump(ret_ebb, &[]);
866             } else {
867                 fx.bcx.ins().trap(TrapCode::User(!0));
868             }
869             return true;
870         }
871     }
872
873     false
874 }