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