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