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