]> git.lizzy.rs Git - rust.git/blob - src/abi.rs
Misc changes to abi.rs
[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     match fx.self_sig().abi {
253         Abi::Rust | Abi::RustCall => {}
254         _ => unimplemented!("declared function with non \"rust\" or \"rust-call\" abi"),
255     }
256
257     let ret_layout = fx.layout_of(fx.return_type());
258     let output_pass_mode = get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true);
259     let ret_param = match output_pass_mode {
260         PassMode::NoPass => None,
261         PassMode::ByVal(_) => None,
262         PassMode::ByRef => Some(fx.bcx.append_ebb_param(start_ebb, fx.module.pointer_type())),
263     };
264
265     enum ArgKind {
266         Normal(Value),
267         Spread(Vec<Value>),
268     }
269
270     let func_params = fx
271         .mir
272         .args_iter()
273         .map(|local| {
274             let arg_ty = fx.monomorphize(&fx.mir.local_decls[local].ty);
275
276             // Adapted from https://github.com/rust-lang/rust/blob/145155dc96757002c7b2e9de8489416e2fdbbd57/src/librustc_codegen_llvm/mir/mod.rs#L442-L482
277             if Some(local) == fx.mir.spread_arg {
278                 // This argument (e.g. the last argument in the "rust-call" ABI)
279                 // is a tuple that was spread at the ABI level and now we have
280                 // to reconstruct it into a tuple local variable, from multiple
281                 // individual function arguments.
282
283                 let tupled_arg_tys = match arg_ty.sty {
284                     ty::Tuple(ref tys) => tys,
285                     _ => bug!("spread argument isn't a tuple?! but {:?}", arg_ty),
286                 };
287
288                 let mut ebb_params = Vec::new();
289                 for arg_ty in tupled_arg_tys.iter() {
290                     let cton_type =
291                         get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
292                     ebb_params.push(fx.bcx.append_ebb_param(start_ebb, cton_type));
293                 }
294
295                 (local, ArgKind::Spread(ebb_params), arg_ty)
296             } else {
297                 let cton_type =
298                     get_pass_mode(fx.tcx, fx.self_sig().abi, arg_ty, false).get_param_ty(fx);
299                 (
300                     local,
301                     ArgKind::Normal(fx.bcx.append_ebb_param(start_ebb, cton_type)),
302                     arg_ty,
303                 )
304             }
305         }).collect::<Vec<(Local, ArgKind, Ty)>>();
306
307     fx.bcx.switch_to_block(start_ebb);
308
309     fx.top_nop = Some(fx.bcx.ins().nop());
310     fx.add_global_comment(format!("ssa {:?}", ssa_analyzed));
311
312     match output_pass_mode {
313         PassMode::NoPass => {
314             let null = fx.bcx.ins().iconst(fx.module.pointer_type(), 0);
315             //unimplemented!("pass mode nopass");
316             fx.local_map.insert(
317                 RETURN_PLACE,
318                 CPlace::Addr(null, None, fx.layout_of(fx.return_type())),
319             );
320         }
321         PassMode::ByVal(ret_ty) => {
322             fx.bcx.declare_var(mir_var(RETURN_PLACE), ret_ty);
323             fx.local_map
324                 .insert(RETURN_PLACE, CPlace::Var(RETURN_PLACE, ret_layout));
325         }
326         PassMode::ByRef => {
327             fx.local_map.insert(
328                 RETURN_PLACE,
329                 CPlace::Addr(ret_param.unwrap(), None, ret_layout),
330             );
331         }
332     }
333
334     for (local, arg_kind, ty) in func_params {
335         let layout = fx.layout_of(ty);
336
337         if let ArgKind::Normal(ebb_param) = arg_kind {
338             if !ssa_analyzed
339                 .get(&local)
340                 .unwrap()
341                 .contains(crate::analyze::Flags::NOT_SSA)
342             {
343                 fx.bcx
344                     .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
345                 match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false) {
346                     PassMode::NoPass => unimplemented!("pass mode nopass"),
347                     PassMode::ByVal(_) => fx.bcx.def_var(mir_var(local), ebb_param),
348                     PassMode::ByRef => {
349                         let val = CValue::ByRef(ebb_param, fx.layout_of(ty)).load_value(fx);
350                         fx.bcx.def_var(mir_var(local), val);
351                     }
352                 }
353                 fx.local_map.insert(local, CPlace::Var(local, layout));
354                 continue;
355             }
356         }
357
358         let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
359             kind: StackSlotKind::ExplicitSlot,
360             size: layout.size.bytes() as u32,
361             offset: None,
362         });
363
364         let place = CPlace::from_stack_slot(fx, stack_slot, ty);
365
366         match arg_kind {
367             ArgKind::Normal(ebb_param) => match get_pass_mode(fx.tcx, fx.self_sig().abi, ty, false)
368             {
369                 PassMode::NoPass => unimplemented!("pass mode nopass"),
370                 PassMode::ByVal(_) => {
371                     place.write_cvalue(fx, CValue::ByVal(ebb_param, place.layout()))
372                 }
373                 PassMode::ByRef => place.write_cvalue(fx, CValue::ByRef(ebb_param, place.layout())),
374             },
375             ArgKind::Spread(ebb_params) => {
376                 for (i, ebb_param) in ebb_params.into_iter().enumerate() {
377                     let sub_place = place.place_field(fx, mir::Field::new(i));
378                     match get_pass_mode(fx.tcx, fx.self_sig().abi, sub_place.layout().ty, false) {
379                         PassMode::NoPass => unimplemented!("pass mode nopass"),
380                         PassMode::ByVal(_) => {
381                             sub_place.write_cvalue(fx, CValue::ByVal(ebb_param, sub_place.layout()))
382                         }
383                         PassMode::ByRef => {
384                             sub_place.write_cvalue(fx, CValue::ByRef(ebb_param, sub_place.layout()))
385                         }
386                     }
387                 }
388             }
389         }
390         fx.local_map.insert(local, place);
391     }
392
393     for local in fx.mir.vars_and_temps_iter() {
394         let ty = fx.mir.local_decls[local].ty;
395         let layout = fx.layout_of(ty);
396
397         let place = if ssa_analyzed
398             .get(&local)
399             .unwrap()
400             .contains(crate::analyze::Flags::NOT_SSA)
401         {
402             let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
403                 kind: StackSlotKind::ExplicitSlot,
404                 size: layout.size.bytes() as u32,
405                 offset: None,
406             });
407             CPlace::from_stack_slot(fx, stack_slot, ty)
408         } else {
409             fx.bcx
410                 .declare_var(mir_var(local), fx.cton_type(ty).unwrap());
411             CPlace::Var(local, layout)
412         };
413
414         fx.local_map.insert(local, place);
415     }
416
417     fx.bcx
418         .ins()
419         .jump(*fx.ebb_map.get(&START_BLOCK).unwrap(), &[]);
420 }
421
422 pub fn codegen_call<'a, 'tcx: 'a>(
423     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
424     func: &Operand<'tcx>,
425     args: &[Operand<'tcx>],
426     destination: &Option<(Place<'tcx>, BasicBlock)>,
427 ) {
428     let fn_ty = fx.monomorphize(&func.ty(&fx.mir.local_decls, fx.tcx));
429     let sig = ty_fn_sig(fx.tcx, fn_ty);
430
431     // Unpack arguments tuple for closures
432     let args = if sig.abi == Abi::RustCall {
433         assert_eq!(args.len(), 2, "rust-call abi requires two arguments");
434         let self_arg = trans_operand(fx, &args[0]);
435         let pack_arg = trans_operand(fx, &args[1]);
436         let mut args = Vec::new();
437         args.push(self_arg);
438         match pack_arg.layout().ty.sty {
439             ty::Tuple(ref tupled_arguments) => {
440                 for (i, _) in tupled_arguments.iter().enumerate() {
441                     args.push(pack_arg.value_field(fx, mir::Field::new(i)));
442                 }
443             }
444             _ => bug!("argument to function with \"rust-call\" ABI is not a tuple"),
445         }
446         args
447     } else {
448         args.into_iter()
449             .map(|arg| trans_operand(fx, arg))
450             .collect::<Vec<_>>()
451     };
452
453     let destination = destination
454         .as_ref()
455         .map(|(place, bb)| (trans_place(fx, place), *bb));
456
457     if codegen_intrinsic_call(fx, fn_ty, sig, &args, destination) {
458         return;
459     }
460
461     let ret_layout = fx.layout_of(sig.output());
462
463     let output_pass_mode = get_pass_mode(fx.tcx, sig.abi, sig.output(), true);
464     let return_ptr = match output_pass_mode {
465         PassMode::NoPass => None,
466         PassMode::ByRef => match destination {
467             Some((place, _)) => Some(place.expect_addr()),
468             None => Some(fx.bcx.ins().iconst(fx.module.pointer_type(), 0)),
469         },
470         PassMode::ByVal(_) => None,
471     };
472
473     let call_args: Vec<Value> = return_ptr
474         .into_iter()
475         .chain(args.into_iter().map(|arg| {
476             match get_pass_mode(fx.tcx, sig.abi, arg.layout().ty, false) {
477                 PassMode::NoPass => unimplemented!("pass mode nopass"),
478                 PassMode::ByVal(_) => arg.load_value(fx),
479                 PassMode::ByRef => arg.force_stack(fx),
480             }
481         })).collect::<Vec<_>>();
482
483     let call_inst = match fn_ty.sty {
484         ty::FnDef(def_id, substs) => {
485             let inst = Instance::resolve(fx.tcx, ParamEnv::reveal_all(), def_id, substs).unwrap();
486             let func_ref = fx.get_function_ref(inst);
487             fx.bcx.ins().call(func_ref, &call_args)
488         }
489         ty::FnPtr(_) => {
490             let func = trans_operand(fx, func);
491             let func = func.load_value(fx);
492             let sig = fx.bcx.import_signature(cton_sig_from_fn_ty(fx.tcx, fn_ty));
493             fx.bcx.ins().call_indirect(sig, func, &call_args)
494         }
495         _ => bug!("{:?}", fn_ty),
496     };
497
498     match output_pass_mode {
499         PassMode::NoPass => {}
500         PassMode::ByVal(_) => {
501             if let Some((ret_place, _)) = destination {
502                 let results = fx.bcx.inst_results(call_inst);
503                 ret_place.write_cvalue(fx, CValue::ByVal(results[0], ret_layout));
504             }
505         }
506         PassMode::ByRef => {}
507     }
508     if let Some((_, dest)) = destination {
509         let ret_ebb = fx.get_ebb(dest);
510         fx.bcx.ins().jump(ret_ebb, &[]);
511     } else {
512         fx.bcx.ins().trap(TrapCode::User(!0));
513     }
514 }
515
516 pub fn codegen_return(fx: &mut FunctionCx<impl Backend>) {
517     match get_pass_mode(fx.tcx, fx.self_sig().abi, fx.return_type(), true) {
518         PassMode::NoPass | PassMode::ByRef => {
519             fx.bcx.ins().return_(&[]);
520         }
521         PassMode::ByVal(_) => {
522             let place = fx.get_local_place(RETURN_PLACE);
523             let ret_val = place.to_cvalue(fx).load_value(fx);
524             fx.bcx.ins().return_(&[ret_val]);
525         }
526     }
527 }
528
529 fn codegen_intrinsic_call<'a, 'tcx: 'a>(
530     fx: &mut FunctionCx<'a, 'tcx, impl Backend>,
531     fn_ty: Ty<'tcx>,
532     sig: FnSig<'tcx>,
533     args: &[CValue<'tcx>],
534     destination: Option<(CPlace<'tcx>, BasicBlock)>,
535 ) -> bool {
536     if let ty::FnDef(def_id, substs) = fn_ty.sty {
537         if sig.abi == Abi::RustIntrinsic {
538             let intrinsic = fx.tcx.item_name(def_id).as_str();
539             let intrinsic = &intrinsic[..];
540
541             let ret = match destination {
542                 Some((place, _)) => place,
543                 None => {
544                     // Insert non returning intrinsics here
545                     match intrinsic {
546                         "abort" => {
547                             fx.bcx.ins().trap(TrapCode::User(!0 - 1));
548                         }
549                         "unreachable" => {
550                             fx.bcx.ins().trap(TrapCode::User(!0 - 1));
551                         }
552                         _ => unimplemented!("unsupported instrinsic {}", intrinsic),
553                     }
554                     return true;
555                 }
556             };
557
558             let nil_ty = fx.tcx.mk_nil();
559             let u64_layout = fx.layout_of(fx.tcx.types.u64);
560             let usize_layout = fx.layout_of(fx.tcx.types.usize);
561
562             match intrinsic {
563                 "assume" => {
564                     assert_eq!(args.len(), 1);
565                 }
566                 "arith_offset" => {
567                     assert_eq!(args.len(), 2);
568                     let base = args[0].load_value(fx);
569                     let offset = args[1].load_value(fx);
570                     let res = fx.bcx.ins().iadd(base, offset);
571                     let res = CValue::ByVal(res, ret.layout());
572                     ret.write_cvalue(fx, res);
573                 }
574                 "likely" | "unlikely" => {
575                     assert_eq!(args.len(), 1);
576                     ret.write_cvalue(fx, args[0]);
577                 }
578                 "copy" | "copy_nonoverlapping" => {
579                     let elem_ty = substs.type_at(0);
580                     let elem_size: u64 = fx.layout_of(elem_ty).size.bytes();
581                     let elem_size = fx
582                         .bcx
583                         .ins()
584                         .iconst(fx.module.pointer_type(), elem_size as i64);
585                     assert_eq!(args.len(), 3);
586                     let src = args[0];
587                     let dst = args[1];
588                     let count = args[2].load_value(fx);
589                     let byte_amount = fx.bcx.ins().imul(count, elem_size);
590                     fx.easy_call(
591                         "memmove",
592                         &[dst, src, CValue::ByVal(byte_amount, usize_layout)],
593                         nil_ty,
594                     );
595                 }
596                 "discriminant_value" => {
597                     assert_eq!(args.len(), 1);
598                     let discr = crate::base::trans_get_discriminant(fx, args[0], ret.layout());
599                     ret.write_cvalue(fx, discr);
600                 }
601                 "size_of" => {
602                     assert_eq!(args.len(), 0);
603                     let size_of = fx.layout_of(substs.type_at(0)).size.bytes();
604                     let size_of = CValue::const_val(fx, usize_layout.ty, size_of as i64);
605                     ret.write_cvalue(fx, size_of);
606                 }
607                 "size_of_val" => {
608                     assert_eq!(args.len(), 1);
609                     let size = match &substs.type_at(0).sty {
610                         ty::Slice(elem) => {
611                             let len = args[0].load_value_pair(fx).1;
612                             let elem_size = fx.layout_of(elem).size.bytes();
613                             fx.bcx.ins().imul_imm(len, elem_size as i64)
614                         },
615                         ty => unimplemented!("size_of_val for {:?}", ty),
616                     };
617                     ret.write_cvalue(fx, CValue::ByVal(size, usize_layout));
618                 }
619                 "type_id" => {
620                     assert_eq!(args.len(), 0);
621                     let type_id = fx.tcx.type_id_hash(substs.type_at(0));
622                     let type_id = CValue::const_val(fx, u64_layout.ty, type_id as i64);
623                     ret.write_cvalue(fx, type_id);
624                 }
625                 "min_align_of" => {
626                     assert_eq!(args.len(), 0);
627                     let min_align = fx.layout_of(substs.type_at(0)).align.abi();
628                     let min_align = CValue::const_val(fx, usize_layout.ty, min_align as i64);
629                     ret.write_cvalue(fx, min_align);
630                 }
631                 _ if intrinsic.starts_with("unchecked_") => {
632                     assert_eq!(args.len(), 2);
633                     let bin_op = match intrinsic {
634                         "unchecked_div" => BinOp::Div,
635                         "unchecked_rem" => BinOp::Rem,
636                         "unchecked_shl" => BinOp::Shl,
637                         "unchecked_shr" => BinOp::Shr,
638                         _ => unimplemented!("intrinsic {}", intrinsic),
639                     };
640                     let res = match ret.layout().ty.sty {
641                         ty::Uint(_) => crate::base::trans_int_binop(
642                             fx,
643                             bin_op,
644                             args[0],
645                             args[1],
646                             ret.layout().ty,
647                             false,
648                         ),
649                         ty::Int(_) => crate::base::trans_int_binop(
650                             fx,
651                             bin_op,
652                             args[0],
653                             args[1],
654                             ret.layout().ty,
655                             true,
656                         ),
657                         _ => panic!(),
658                     };
659                     ret.write_cvalue(fx, res);
660                 }
661                 _ if intrinsic.ends_with("_with_overflow") => {
662                     assert_eq!(args.len(), 2);
663                     assert_eq!(args[0].layout().ty, args[1].layout().ty);
664                     let bin_op = match intrinsic {
665                         "add_with_overflow" => BinOp::Add,
666                         "sub_with_overflow" => BinOp::Sub,
667                         "mul_with_overflow" => BinOp::Mul,
668                         _ => unimplemented!("intrinsic {}", intrinsic),
669                     };
670                     let res = match args[0].layout().ty.sty {
671                         ty::Uint(_) => crate::base::trans_checked_int_binop(
672                             fx,
673                             bin_op,
674                             args[0],
675                             args[1],
676                             ret.layout().ty,
677                             false,
678                         ),
679                         ty::Int(_) => crate::base::trans_checked_int_binop(
680                             fx,
681                             bin_op,
682                             args[0],
683                             args[1],
684                             ret.layout().ty,
685                             true,
686                         ),
687                         _ => panic!(),
688                     };
689                     ret.write_cvalue(fx, res);
690                 }
691                 _ if intrinsic.starts_with("overflowing_") => {
692                     assert_eq!(args.len(), 2);
693                     assert_eq!(args[0].layout().ty, args[1].layout().ty);
694                     let bin_op = match intrinsic {
695                         "overflowing_add" => BinOp::Add,
696                         "overflowing_sub" => BinOp::Sub,
697                         "overflowing_mul" => BinOp::Mul,
698                         _ => unimplemented!("intrinsic {}", intrinsic),
699                     };
700                     let res = match args[0].layout().ty.sty {
701                         ty::Uint(_) => crate::base::trans_int_binop(
702                             fx,
703                             bin_op,
704                             args[0],
705                             args[1],
706                             ret.layout().ty,
707                             false,
708                         ),
709                         ty::Int(_) => crate::base::trans_int_binop(
710                             fx,
711                             bin_op,
712                             args[0],
713                             args[1],
714                             ret.layout().ty,
715                             true,
716                         ),
717                         _ => panic!(),
718                     };
719                     ret.write_cvalue(fx, res);
720                 }
721                 "offset" => {
722                     assert_eq!(args.len(), 2);
723                     let base = args[0].load_value(fx);
724                     let offset = args[1].load_value(fx);
725                     let res = fx.bcx.ins().iadd(base, offset);
726                     ret.write_cvalue(fx, CValue::ByVal(res, args[0].layout()));
727                 }
728                 "transmute" => {
729                     assert_eq!(args.len(), 1);
730                     let src_ty = substs.type_at(0);
731                     let dst_ty = substs.type_at(1);
732                     assert_eq!(args[0].layout().ty, src_ty);
733                     let addr = args[0].force_stack(fx);
734                     let dst_layout = fx.layout_of(dst_ty);
735                     ret.write_cvalue(fx, CValue::ByRef(addr, dst_layout))
736                 }
737                 "uninit" => {
738                     assert_eq!(args.len(), 0);
739                     let ty = substs.type_at(0);
740                     let layout = fx.layout_of(ty);
741                     let stack_slot = fx.bcx.create_stack_slot(StackSlotData {
742                         kind: StackSlotKind::ExplicitSlot,
743                         size: layout.size.bytes() as u32,
744                         offset: None,
745                     });
746
747                     let uninit_place = CPlace::from_stack_slot(fx, stack_slot, ty);
748                     let uninit_val = uninit_place.to_cvalue(fx);
749                     ret.write_cvalue(fx, uninit_val);
750                 }
751                 "ctlz" | "ctlz_nonzero" => {
752                     assert_eq!(args.len(), 1);
753                     let arg = args[0].load_value(fx);
754                     let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
755                     ret.write_cvalue(fx, res);
756                 }
757                 "cttz" | "cttz_nonzero" => {
758                     assert_eq!(args.len(), 1);
759                     let arg = args[0].load_value(fx);
760                     let res = CValue::ByVal(fx.bcx.ins().clz(arg), args[0].layout());
761                     ret.write_cvalue(fx, res);
762                 }
763                 "ctpop" => {
764                     assert_eq!(args.len(), 1);
765                     let arg = args[0].load_value(fx);
766                     let res = CValue::ByVal(fx.bcx.ins().popcnt(arg), args[0].layout());
767                     ret.write_cvalue(fx, res);
768                 }
769                 _ => unimpl!("unsupported intrinsic {}", intrinsic),
770             }
771
772             if let Some((_, dest)) = destination {
773                 let ret_ebb = fx.get_ebb(dest);
774                 fx.bcx.ins().jump(ret_ebb, &[]);
775             } else {
776                 fx.bcx.ins().trap(TrapCode::User(!0));
777             }
778             return true;
779         }
780     }
781
782     false
783 }