1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 #![allow(non_upper_case_globals)]
13 use intrinsics::{self, Intrinsic};
17 use abi::{Abi, FnType};
19 use mir::lvalue::LvalueRef;
27 use rustc::ty::{self, Ty};
30 use syntax::symbol::Symbol;
33 use rustc::session::Session;
36 use std::cmp::Ordering;
39 fn get_simple_intrinsic(ccx: &CrateContext, name: &str) -> Option<ValueRef> {
40 let llvm_name = match name {
41 "sqrtf32" => "llvm.sqrt.f32",
42 "sqrtf64" => "llvm.sqrt.f64",
43 "powif32" => "llvm.powi.f32",
44 "powif64" => "llvm.powi.f64",
45 "sinf32" => "llvm.sin.f32",
46 "sinf64" => "llvm.sin.f64",
47 "cosf32" => "llvm.cos.f32",
48 "cosf64" => "llvm.cos.f64",
49 "powf32" => "llvm.pow.f32",
50 "powf64" => "llvm.pow.f64",
51 "expf32" => "llvm.exp.f32",
52 "expf64" => "llvm.exp.f64",
53 "exp2f32" => "llvm.exp2.f32",
54 "exp2f64" => "llvm.exp2.f64",
55 "logf32" => "llvm.log.f32",
56 "logf64" => "llvm.log.f64",
57 "log10f32" => "llvm.log10.f32",
58 "log10f64" => "llvm.log10.f64",
59 "log2f32" => "llvm.log2.f32",
60 "log2f64" => "llvm.log2.f64",
61 "fmaf32" => "llvm.fma.f32",
62 "fmaf64" => "llvm.fma.f64",
63 "fabsf32" => "llvm.fabs.f32",
64 "fabsf64" => "llvm.fabs.f64",
65 "copysignf32" => "llvm.copysign.f32",
66 "copysignf64" => "llvm.copysign.f64",
67 "floorf32" => "llvm.floor.f32",
68 "floorf64" => "llvm.floor.f64",
69 "ceilf32" => "llvm.ceil.f32",
70 "ceilf64" => "llvm.ceil.f64",
71 "truncf32" => "llvm.trunc.f32",
72 "truncf64" => "llvm.trunc.f64",
73 "rintf32" => "llvm.rint.f32",
74 "rintf64" => "llvm.rint.f64",
75 "nearbyintf32" => "llvm.nearbyint.f32",
76 "nearbyintf64" => "llvm.nearbyint.f64",
77 "roundf32" => "llvm.round.f32",
78 "roundf64" => "llvm.round.f64",
79 "assume" => "llvm.assume",
80 "abort" => "llvm.trap",
83 Some(ccx.get_intrinsic(&llvm_name))
86 /// Remember to add all intrinsics here, in librustc_typeck/check/mod.rs,
87 /// and in libcore/intrinsics.rs; if you need access to any llvm intrinsics,
88 /// add them to librustc_trans/trans/context.rs
89 pub fn trans_intrinsic_call<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
98 let (def_id, substs, fty) = match callee_ty.sty {
99 ty::TyFnDef(def_id, substs, ref fty) => (def_id, substs, fty),
100 _ => bug!("expected fn item type, found {}", callee_ty)
103 let sig = tcx.erase_late_bound_regions_and_normalize(&fty.sig);
104 let arg_tys = sig.inputs();
105 let ret_ty = sig.output();
106 let name = &*tcx.item_name(def_id).as_str();
108 let llret_ty = type_of::type_of(ccx, ret_ty);
110 let simple = get_simple_intrinsic(ccx, name);
111 let llval = match name {
112 _ if simple.is_some() => {
113 bcx.call(simple.unwrap(), &llargs, None)
119 let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
120 bcx.call(expect, &[llargs[0], C_bool(ccx, true)], None)
123 let expect = ccx.get_intrinsic(&("llvm.expect.i1"));
124 bcx.call(expect, &[llargs[0], C_bool(ccx, false)], None)
127 try_intrinsic(bcx, ccx, llargs[0], llargs[1], llargs[2], llresult);
131 let llfn = ccx.get_intrinsic(&("llvm.debugtrap"));
132 bcx.call(llfn, &[], None)
135 let tp_ty = substs.type_at(0);
136 let lltp_ty = type_of::type_of(ccx, tp_ty);
137 C_uint(ccx, machine::llsize_of_alloc(ccx, lltp_ty))
140 let tp_ty = substs.type_at(0);
141 if !bcx.ccx.shared().type_is_sized(tp_ty) {
143 glue::size_and_align_of_dst(bcx, tp_ty, llargs[1]);
146 let lltp_ty = type_of::type_of(ccx, tp_ty);
147 C_uint(ccx, machine::llsize_of_alloc(ccx, lltp_ty))
151 let tp_ty = substs.type_at(0);
152 C_uint(ccx, type_of::align_of(ccx, tp_ty))
154 "min_align_of_val" => {
155 let tp_ty = substs.type_at(0);
156 if !bcx.ccx.shared().type_is_sized(tp_ty) {
158 glue::size_and_align_of_dst(bcx, tp_ty, llargs[1]);
161 C_uint(ccx, type_of::align_of(ccx, tp_ty))
165 let tp_ty = substs.type_at(0);
166 let lltp_ty = type_of::type_of(ccx, tp_ty);
167 C_uint(ccx, machine::llalign_of_pref(ccx, lltp_ty))
170 let tp_ty = substs.type_at(0);
171 let ty_name = Symbol::intern(&tp_ty.to_string()).as_str();
172 C_str_slice(ccx, ty_name)
175 C_u64(ccx, ccx.tcx().type_id_hash(substs.type_at(0)))
178 let ty = substs.type_at(0);
179 if !type_is_zero_size(ccx, ty) {
180 // Just zero out the stack slot.
181 // If we store a zero constant, LLVM will drown in vreg allocation for large data
182 // structures, and the generated code will be awful. (A telltale sign of this is
183 // large quantities of `mov [byte ptr foo],0` in the generated code.)
184 memset_intrinsic(bcx, false, ty, llresult, C_u8(ccx, 0), C_uint(ccx, 1usize));
188 // Effectively no-ops
189 "uninit" | "forget" => {
193 let tp_ty = substs.type_at(0);
195 C_bool(ccx, bcx.ccx.shared().type_needs_drop(tp_ty))
199 let offset = llargs[1];
200 bcx.inbounds_gep(ptr, &[offset])
204 let offset = llargs[1];
205 bcx.gep(ptr, &[offset])
208 "copy_nonoverlapping" => {
209 copy_intrinsic(bcx, false, false, substs.type_at(0), llargs[1], llargs[0], llargs[2])
212 copy_intrinsic(bcx, true, false, substs.type_at(0), llargs[1], llargs[0], llargs[2])
215 memset_intrinsic(bcx, false, substs.type_at(0), llargs[0], llargs[1], llargs[2])
218 "volatile_copy_nonoverlapping_memory" => {
219 copy_intrinsic(bcx, false, true, substs.type_at(0), llargs[0], llargs[1], llargs[2])
221 "volatile_copy_memory" => {
222 copy_intrinsic(bcx, true, true, substs.type_at(0), llargs[0], llargs[1], llargs[2])
224 "volatile_set_memory" => {
225 memset_intrinsic(bcx, true, substs.type_at(0), llargs[0], llargs[1], llargs[2])
228 let tp_ty = substs.type_at(0);
229 let mut ptr = llargs[0];
230 if let Some(ty) = fn_ty.ret.cast {
231 ptr = bcx.pointercast(ptr, ty.ptr_to());
233 let load = bcx.volatile_load(ptr);
235 llvm::LLVMSetAlignment(load, type_of::align_of(ccx, tp_ty));
237 to_immediate(bcx, load, tp_ty)
239 "volatile_store" => {
240 let tp_ty = substs.type_at(0);
241 if type_is_fat_ptr(bcx.ccx, tp_ty) {
242 bcx.volatile_store(llargs[1], get_dataptr(bcx, llargs[0]));
243 bcx.volatile_store(llargs[2], get_meta(bcx, llargs[0]));
245 let val = if fn_ty.args[1].is_indirect() {
248 from_immediate(bcx, llargs[1])
250 let ptr = bcx.pointercast(llargs[0], val_ty(val).ptr_to());
251 let store = bcx.volatile_store(val, ptr);
253 llvm::LLVMSetAlignment(store, type_of::align_of(ccx, tp_ty));
259 "ctlz" | "cttz" | "ctpop" | "bswap" |
260 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" |
261 "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
262 "unchecked_div" | "unchecked_rem" => {
263 let sty = &arg_tys[0].sty;
264 match int_type_width_signed(sty, ccx) {
265 Some((width, signed)) =>
268 let y = C_bool(bcx.ccx, false);
269 let llfn = ccx.get_intrinsic(&format!("llvm.{}.i{}", name, width));
270 bcx.call(llfn, &[llargs[0], y], None)
272 "ctpop" => bcx.call(ccx.get_intrinsic(&format!("llvm.ctpop.i{}", width)),
276 llargs[0] // byte swap a u8/i8 is just a no-op
278 bcx.call(ccx.get_intrinsic(&format!("llvm.bswap.i{}", width)),
282 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" => {
283 let intrinsic = format!("llvm.{}{}.with.overflow.i{}",
284 if signed { 's' } else { 'u' },
286 let llfn = bcx.ccx.get_intrinsic(&intrinsic);
288 // Convert `i1` to a `bool`, and write it to the out parameter
289 let val = bcx.call(llfn, &[llargs[0], llargs[1]], None);
290 let result = bcx.extract_value(val, 0);
291 let overflow = bcx.zext(bcx.extract_value(val, 1), Type::bool(ccx));
292 bcx.store(result, bcx.struct_gep(llresult, 0), None);
293 bcx.store(overflow, bcx.struct_gep(llresult, 1), None);
297 "overflowing_add" => bcx.add(llargs[0], llargs[1]),
298 "overflowing_sub" => bcx.sub(llargs[0], llargs[1]),
299 "overflowing_mul" => bcx.mul(llargs[0], llargs[1]),
302 bcx.sdiv(llargs[0], llargs[1])
304 bcx.udiv(llargs[0], llargs[1])
308 bcx.srem(llargs[0], llargs[1])
310 bcx.urem(llargs[0], llargs[1])
315 span_invalid_monomorphization_error(
317 &format!("invalid monomorphization of `{}` intrinsic: \
318 expected basic integer type, found `{}`", name, sty));
324 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" => {
325 let sty = &arg_tys[0].sty;
326 match float_type_width(sty) {
329 "fadd_fast" => bcx.fadd_fast(llargs[0], llargs[1]),
330 "fsub_fast" => bcx.fsub_fast(llargs[0], llargs[1]),
331 "fmul_fast" => bcx.fmul_fast(llargs[0], llargs[1]),
332 "fdiv_fast" => bcx.fdiv_fast(llargs[0], llargs[1]),
333 "frem_fast" => bcx.frem_fast(llargs[0], llargs[1]),
337 span_invalid_monomorphization_error(
339 &format!("invalid monomorphization of `{}` intrinsic: \
340 expected basic float type, found `{}`", name, sty));
347 "discriminant_value" => {
348 let val_ty = substs.type_at(0);
350 ty::TyAdt(adt, ..) if adt.is_enum() => {
351 adt::trans_get_discr(bcx, val_ty, llargs[0],
352 Some(llret_ty), true)
354 _ => C_null(llret_ty)
357 name if name.starts_with("simd_") => {
358 generic_simd_intrinsic(bcx, name,
364 // This requires that atomic intrinsics follow a specific naming pattern:
365 // "atomic_<operation>[_<ordering>]", and no ordering means SeqCst
366 name if name.starts_with("atomic_") => {
367 use llvm::AtomicOrdering::*;
369 let split: Vec<&str> = name.split('_').collect();
371 let is_cxchg = split[1] == "cxchg" || split[1] == "cxchgweak";
372 let (order, failorder) = match split.len() {
373 2 => (SequentiallyConsistent, SequentiallyConsistent),
374 3 => match split[2] {
375 "unordered" => (Unordered, Unordered),
376 "relaxed" => (Monotonic, Monotonic),
377 "acq" => (Acquire, Acquire),
378 "rel" => (Release, Monotonic),
379 "acqrel" => (AcquireRelease, Acquire),
380 "failrelaxed" if is_cxchg =>
381 (SequentiallyConsistent, Monotonic),
382 "failacq" if is_cxchg =>
383 (SequentiallyConsistent, Acquire),
384 _ => ccx.sess().fatal("unknown ordering in atomic intrinsic")
386 4 => match (split[2], split[3]) {
387 ("acq", "failrelaxed") if is_cxchg =>
388 (Acquire, Monotonic),
389 ("acqrel", "failrelaxed") if is_cxchg =>
390 (AcquireRelease, Monotonic),
391 _ => ccx.sess().fatal("unknown ordering in atomic intrinsic")
393 _ => ccx.sess().fatal("Atomic intrinsic not in correct format"),
396 let invalid_monomorphization = |sty| {
397 span_invalid_monomorphization_error(tcx.sess, span,
398 &format!("invalid monomorphization of `{}` intrinsic: \
399 expected basic integer type, found `{}`", name, sty));
403 "cxchg" | "cxchgweak" => {
404 let sty = &substs.type_at(0).sty;
405 if int_type_width_signed(sty, ccx).is_some() {
406 let weak = if split[1] == "cxchgweak" { llvm::True } else { llvm::False };
407 let val = bcx.atomic_cmpxchg(llargs[0], llargs[1], llargs[2], order,
409 let result = bcx.extract_value(val, 0);
410 let success = bcx.zext(bcx.extract_value(val, 1), Type::bool(bcx.ccx));
411 bcx.store(result, bcx.struct_gep(llresult, 0), None);
412 bcx.store(success, bcx.struct_gep(llresult, 1), None);
414 invalid_monomorphization(sty);
420 let sty = &substs.type_at(0).sty;
421 if int_type_width_signed(sty, ccx).is_some() {
422 bcx.atomic_load(llargs[0], order)
424 invalid_monomorphization(sty);
430 let sty = &substs.type_at(0).sty;
431 if int_type_width_signed(sty, ccx).is_some() {
432 bcx.atomic_store(llargs[1], llargs[0], order);
434 invalid_monomorphization(sty);
440 bcx.atomic_fence(order, llvm::SynchronizationScope::CrossThread);
444 "singlethreadfence" => {
445 bcx.atomic_fence(order, llvm::SynchronizationScope::SingleThread);
449 // These are all AtomicRMW ops
451 let atom_op = match op {
452 "xchg" => llvm::AtomicXchg,
453 "xadd" => llvm::AtomicAdd,
454 "xsub" => llvm::AtomicSub,
455 "and" => llvm::AtomicAnd,
456 "nand" => llvm::AtomicNand,
457 "or" => llvm::AtomicOr,
458 "xor" => llvm::AtomicXor,
459 "max" => llvm::AtomicMax,
460 "min" => llvm::AtomicMin,
461 "umax" => llvm::AtomicUMax,
462 "umin" => llvm::AtomicUMin,
463 _ => ccx.sess().fatal("unknown atomic operation")
466 let sty = &substs.type_at(0).sty;
467 if int_type_width_signed(sty, ccx).is_some() {
468 bcx.atomic_rmw(atom_op, llargs[0], llargs[1], order)
470 invalid_monomorphization(sty);
478 let intr = match Intrinsic::find(&name) {
480 None => bug!("unknown intrinsic '{}'", name),
482 fn one<T>(x: Vec<T>) -> T {
483 assert_eq!(x.len(), 1);
484 x.into_iter().next().unwrap()
486 fn ty_to_type(ccx: &CrateContext, t: &intrinsics::Type,
487 any_changes_needed: &mut bool) -> Vec<Type> {
488 use intrinsics::Type::*;
490 Void => vec![Type::void(ccx)],
491 Integer(_signed, width, llvm_width) => {
492 *any_changes_needed |= width != llvm_width;
493 vec![Type::ix(ccx, llvm_width as u64)]
497 32 => vec![Type::f32(ccx)],
498 64 => vec![Type::f64(ccx)],
502 Pointer(ref t, ref llvm_elem, _const) => {
503 *any_changes_needed |= llvm_elem.is_some();
505 let t = llvm_elem.as_ref().unwrap_or(t);
506 let elem = one(ty_to_type(ccx, t, any_changes_needed));
509 Vector(ref t, ref llvm_elem, length) => {
510 *any_changes_needed |= llvm_elem.is_some();
512 let t = llvm_elem.as_ref().unwrap_or(t);
513 let elem = one(ty_to_type(ccx, t, any_changes_needed));
514 vec![Type::vector(&elem, length as u64)]
516 Aggregate(false, ref contents) => {
517 let elems = contents.iter()
518 .map(|t| one(ty_to_type(ccx, t, any_changes_needed)))
519 .collect::<Vec<_>>();
520 vec![Type::struct_(ccx, &elems, false)]
522 Aggregate(true, ref contents) => {
523 *any_changes_needed = true;
525 .flat_map(|t| ty_to_type(ccx, t, any_changes_needed))
531 // This allows an argument list like `foo, (bar, baz),
532 // qux` to be converted into `foo, bar, baz, qux`, integer
533 // arguments to be truncated as needed and pointers to be
535 fn modify_as_needed<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
536 t: &intrinsics::Type,
542 intrinsics::Type::Aggregate(true, ref contents) => {
543 // We found a tuple that needs squishing! So
544 // run over the tuple and load each field.
546 // This assumes the type is "simple", i.e. no
547 // destructors, and the contents are SIMD
549 assert!(!bcx.ccx.shared().type_needs_drop(arg_type));
550 let arg = LvalueRef::new_sized_ty(llarg, arg_type);
551 (0..contents.len()).map(|i| bcx.load(arg.trans_field_ptr(bcx, i))).collect()
553 intrinsics::Type::Pointer(_, Some(ref llvm_elem), _) => {
554 let llvm_elem = one(ty_to_type(bcx.ccx, llvm_elem, &mut false));
555 vec![bcx.pointercast(llarg, llvm_elem.ptr_to())]
557 intrinsics::Type::Vector(_, Some(ref llvm_elem), length) => {
558 let llvm_elem = one(ty_to_type(bcx.ccx, llvm_elem, &mut false));
559 vec![bcx.bitcast(llarg, Type::vector(&llvm_elem, length as u64))]
561 intrinsics::Type::Integer(_, width, llvm_width) if width != llvm_width => {
562 // the LLVM intrinsic uses a smaller integer
563 // size than the C intrinsic's signature, so
564 // we have to trim it down here.
565 vec![bcx.trunc(llarg, Type::ix(bcx.ccx, llvm_width as u64))]
572 let mut any_changes_needed = false;
573 let inputs = intr.inputs.iter()
574 .flat_map(|t| ty_to_type(ccx, t, &mut any_changes_needed))
575 .collect::<Vec<_>>();
577 let mut out_changes = false;
578 let outputs = one(ty_to_type(ccx, &intr.output, &mut out_changes));
579 // outputting a flattened aggregate is nonsense
580 assert!(!out_changes);
582 let llargs = if !any_changes_needed {
583 // no aggregates to flatten, so no change needed
586 // there are some aggregates that need to be flattened
587 // in the LLVM call, so we need to run over the types
588 // again to find them and extract the arguments
592 .flat_map(|((t, llarg), ty)| modify_as_needed(bcx, t, ty, *llarg))
595 assert_eq!(inputs.len(), llargs.len());
597 let val = match intr.definition {
598 intrinsics::IntrinsicDef::Named(name) => {
599 let f = declare::declare_cfn(ccx,
601 Type::func(&inputs, &outputs));
602 bcx.call(f, &llargs, None)
607 intrinsics::Type::Aggregate(flatten, ref elems) => {
608 // the output is a tuple so we need to munge it properly
611 for i in 0..elems.len() {
612 let val = bcx.extract_value(val, i);
613 bcx.store(val, bcx.struct_gep(llresult, i), None);
622 if val_ty(llval) != Type::void(ccx) && machine::llsize_of_alloc(ccx, val_ty(llval)) != 0 {
623 if let Some(ty) = fn_ty.ret.cast {
624 let ptr = bcx.pointercast(llresult, ty.ptr_to());
625 bcx.store(llval, ptr, Some(type_of::align_of(ccx, ret_ty)));
627 store_ty(bcx, llval, llresult, ret_ty);
632 fn copy_intrinsic<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
641 let lltp_ty = type_of::type_of(ccx, tp_ty);
642 let align = C_i32(ccx, type_of::align_of(ccx, tp_ty) as i32);
643 let size = machine::llsize_of(ccx, lltp_ty);
644 let int_size = machine::llbitsize_of_real(ccx, ccx.int_type());
646 let operation = if allow_overlap {
652 let name = format!("llvm.{}.p0i8.p0i8.i{}", operation, int_size);
654 let dst_ptr = bcx.pointercast(dst, Type::i8p(ccx));
655 let src_ptr = bcx.pointercast(src, Type::i8p(ccx));
656 let llfn = ccx.get_intrinsic(&name);
661 bcx.mul(size, count),
663 C_bool(ccx, volatile)],
667 fn memset_intrinsic<'a, 'tcx>(
668 bcx: &Builder<'a, 'tcx>,
676 let align = C_i32(ccx, type_of::align_of(ccx, ty) as i32);
677 let lltp_ty = type_of::type_of(ccx, ty);
678 let size = machine::llsize_of(ccx, lltp_ty);
679 let dst = bcx.pointercast(dst, Type::i8p(ccx));
680 call_memset(bcx, dst, val, bcx.mul(size, count), align, volatile)
683 fn try_intrinsic<'a, 'tcx>(
684 bcx: &Builder<'a, 'tcx>,
691 if bcx.sess().no_landing_pads() {
692 bcx.call(func, &[data], None);
693 bcx.store(C_null(Type::i8p(&bcx.ccx)), dest, None);
694 } else if wants_msvc_seh(bcx.sess()) {
695 trans_msvc_try(bcx, ccx, func, data, local_ptr, dest);
697 trans_gnu_try(bcx, ccx, func, data, local_ptr, dest);
701 // MSVC's definition of the `rust_try` function.
703 // This implementation uses the new exception handling instructions in LLVM
704 // which have support in LLVM for SEH on MSVC targets. Although these
705 // instructions are meant to work for all targets, as of the time of this
706 // writing, however, LLVM does not recommend the usage of these new instructions
707 // as the old ones are still more optimized.
708 fn trans_msvc_try<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
714 let llfn = get_rust_try_fn(ccx, &mut |bcx| {
717 bcx.set_personality_fn(bcx.ccx.eh_personality());
719 let normal = bcx.build_sibling_block("normal");
720 let catchswitch = bcx.build_sibling_block("catchswitch");
721 let catchpad = bcx.build_sibling_block("catchpad");
722 let caught = bcx.build_sibling_block("caught");
724 let func = llvm::get_param(bcx.llfn(), 0);
725 let data = llvm::get_param(bcx.llfn(), 1);
726 let local_ptr = llvm::get_param(bcx.llfn(), 2);
728 // We're generating an IR snippet that looks like:
730 // declare i32 @rust_try(%func, %data, %ptr) {
731 // %slot = alloca i64*
732 // invoke %func(%data) to label %normal unwind label %catchswitch
738 // %cs = catchswitch within none [%catchpad] unwind to caller
741 // %tok = catchpad within %cs [%type_descriptor, 0, %slot]
742 // %ptr[0] = %slot[0]
743 // %ptr[1] = %slot[1]
744 // catchret from %tok to label %caught
750 // This structure follows the basic usage of throw/try/catch in LLVM.
751 // For example, compile this C++ snippet to see what LLVM generates:
753 // #include <stdint.h>
755 // int bar(void (*foo)(void), uint64_t *ret) {
759 // } catch(uint64_t a[2]) {
766 // More information can be found in libstd's seh.rs implementation.
767 let i64p = Type::i64(ccx).ptr_to();
768 let slot = bcx.alloca(i64p, "slot");
769 bcx.invoke(func, &[data], normal.llbb(), catchswitch.llbb(),
772 normal.ret(C_i32(ccx, 0));
774 let cs = catchswitch.catch_switch(None, None, 1);
775 catchswitch.add_handler(cs, catchpad.llbb());
778 let tydesc = match tcx.lang_items.msvc_try_filter() {
779 Some(did) => ::consts::get_static(ccx, did),
780 None => bug!("msvc_try_filter not defined"),
782 let tok = catchpad.catch_pad(cs, &[tydesc, C_i32(ccx, 0), slot]);
783 let addr = catchpad.load(slot);
784 let arg1 = catchpad.load(addr);
785 let val1 = C_i32(ccx, 1);
786 let arg2 = catchpad.load(catchpad.inbounds_gep(addr, &[val1]));
787 let local_ptr = catchpad.bitcast(local_ptr, i64p);
788 catchpad.store(arg1, local_ptr, None);
789 catchpad.store(arg2, catchpad.inbounds_gep(local_ptr, &[val1]), None);
790 catchpad.catch_ret(tok, caught.llbb());
792 caught.ret(C_i32(ccx, 1));
795 // Note that no invoke is used here because by definition this function
796 // can't panic (that's what it's catching).
797 let ret = bcx.call(llfn, &[func, data, local_ptr], None);
798 bcx.store(ret, dest, None);
801 // Definition of the standard "try" function for Rust using the GNU-like model
802 // of exceptions (e.g. the normal semantics of LLVM's landingpad and invoke
805 // This translation is a little surprising because we always call a shim
806 // function instead of inlining the call to `invoke` manually here. This is done
807 // because in LLVM we're only allowed to have one personality per function
808 // definition. The call to the `try` intrinsic is being inlined into the
809 // function calling it, and that function may already have other personality
810 // functions in play. By calling a shim we're guaranteed that our shim will have
811 // the right personality function.
812 fn trans_gnu_try<'a, 'tcx>(bcx: &Builder<'a, 'tcx>,
818 let llfn = get_rust_try_fn(ccx, &mut |bcx| {
821 // Translates the shims described above:
824 // invoke %func(%args...) normal %normal unwind %catch
830 // (ptr, _) = landingpad
831 // store ptr, %local_ptr
834 // Note that the `local_ptr` data passed into the `try` intrinsic is
835 // expected to be `*mut *mut u8` for this to actually work, but that's
836 // managed by the standard library.
838 let then = bcx.build_sibling_block("then");
839 let catch = bcx.build_sibling_block("catch");
841 let func = llvm::get_param(bcx.llfn(), 0);
842 let data = llvm::get_param(bcx.llfn(), 1);
843 let local_ptr = llvm::get_param(bcx.llfn(), 2);
844 bcx.invoke(func, &[data], then.llbb(), catch.llbb(), None);
845 then.ret(C_i32(ccx, 0));
847 // Type indicator for the exception being thrown.
849 // The first value in this tuple is a pointer to the exception object
850 // being thrown. The second value is a "selector" indicating which of
851 // the landing pad clauses the exception's type had been matched to.
852 // rust_try ignores the selector.
853 let lpad_ty = Type::struct_(ccx, &[Type::i8p(ccx), Type::i32(ccx)],
855 let vals = catch.landing_pad(lpad_ty, bcx.ccx.eh_personality(), 1, catch.llfn());
856 catch.add_clause(vals, C_null(Type::i8p(ccx)));
857 let ptr = catch.extract_value(vals, 0);
858 catch.store(ptr, catch.bitcast(local_ptr, Type::i8p(ccx).ptr_to()), None);
859 catch.ret(C_i32(ccx, 1));
862 // Note that no invoke is used here because by definition this function
863 // can't panic (that's what it's catching).
864 let ret = bcx.call(llfn, &[func, data, local_ptr], None);
865 bcx.store(ret, dest, None);
868 // Helper function to give a Block to a closure to translate a shim function.
869 // This is currently primarily used for the `try` intrinsic functions above.
870 fn gen_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
872 inputs: Vec<Ty<'tcx>>,
874 trans: &mut for<'b> FnMut(Builder<'b, 'tcx>))
876 let sig = ccx.tcx().mk_fn_sig(inputs.into_iter(), output, false);
878 let rust_fn_ty = ccx.tcx().mk_fn_ptr(ccx.tcx().mk_bare_fn(ty::BareFnTy {
879 unsafety: hir::Unsafety::Unsafe,
883 let llfn = declare::define_internal_fn(ccx, name, rust_fn_ty);
884 let bcx = Builder::new_block(ccx, llfn, "entry-block");
889 // Helper function used to get a handle to the `__rust_try` function used to
892 // This function is only generated once and is then cached.
893 fn get_rust_try_fn<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
894 trans: &mut for<'b> FnMut(Builder<'b, 'tcx>))
896 if let Some(llfn) = ccx.rust_try_fn().get() {
900 // Define the type up front for the signature of the rust_try function.
902 let i8p = tcx.mk_mut_ptr(tcx.types.i8);
903 let fn_ty = tcx.mk_fn_ptr(tcx.mk_bare_fn(ty::BareFnTy {
904 unsafety: hir::Unsafety::Unsafe,
906 sig: ty::Binder(tcx.mk_fn_sig(iter::once(i8p), tcx.mk_nil(), false)),
908 let output = tcx.types.i32;
909 let rust_try = gen_fn(ccx, "__rust_try", vec![fn_ty, i8p, i8p], output, trans);
910 ccx.rust_try_fn().set(Some(rust_try));
914 fn span_invalid_monomorphization_error(a: &Session, b: Span, c: &str) {
915 span_err!(a, b, E0511, "{}", c);
918 fn generic_simd_intrinsic<'a, 'tcx>(
919 bcx: &Builder<'a, 'tcx>,
927 // macros for error handling:
928 macro_rules! emit_error {
932 ($msg: tt, $($fmt: tt)*) => {
933 span_invalid_monomorphization_error(
935 &format!(concat!("invalid monomorphization of `{}` intrinsic: ",
940 macro_rules! require {
941 ($cond: expr, $($fmt: tt)*) => {
943 emit_error!($($fmt)*);
944 return C_nil(bcx.ccx)
948 macro_rules! require_simd {
949 ($ty: expr, $position: expr) => {
950 require!($ty.is_simd(), "expected SIMD {} type, found non-SIMD `{}`", $position, $ty)
957 let sig = tcx.erase_late_bound_regions_and_normalize(callee_ty.fn_sig());
958 let arg_tys = sig.inputs();
960 // every intrinsic takes a SIMD vector as its first argument
961 require_simd!(arg_tys[0], "input");
962 let in_ty = arg_tys[0];
963 let in_elem = arg_tys[0].simd_type(tcx);
964 let in_len = arg_tys[0].simd_size(tcx);
966 let comparison = match name {
967 "simd_eq" => Some(hir::BiEq),
968 "simd_ne" => Some(hir::BiNe),
969 "simd_lt" => Some(hir::BiLt),
970 "simd_le" => Some(hir::BiLe),
971 "simd_gt" => Some(hir::BiGt),
972 "simd_ge" => Some(hir::BiGe),
976 if let Some(cmp_op) = comparison {
977 require_simd!(ret_ty, "return");
979 let out_len = ret_ty.simd_size(tcx);
980 require!(in_len == out_len,
981 "expected return type with length {} (same as input type `{}`), \
982 found `{}` with length {}",
985 require!(llret_ty.element_type().kind() == llvm::Integer,
986 "expected return type with integer elements, found `{}` with non-integer `{}`",
988 ret_ty.simd_type(tcx));
990 return compare_simd_types(bcx,
998 if name.starts_with("simd_shuffle") {
999 let n: usize = match name["simd_shuffle".len()..].parse() {
1001 Err(_) => span_bug!(span,
1002 "bad `simd_shuffle` instruction only caught in trans?")
1005 require_simd!(ret_ty, "return");
1007 let out_len = ret_ty.simd_size(tcx);
1008 require!(out_len == n,
1009 "expected return type of length {}, found `{}` with length {}",
1010 n, ret_ty, out_len);
1011 require!(in_elem == ret_ty.simd_type(tcx),
1012 "expected return element type `{}` (element of input `{}`), \
1013 found `{}` with element type `{}`",
1015 ret_ty, ret_ty.simd_type(tcx));
1017 let total_len = in_len as u128 * 2;
1019 let vector = llargs[2];
1021 let indices: Option<Vec<_>> = (0..n)
1024 let val = const_get_elt(vector, &[i as libc::c_uint]);
1025 match const_to_opt_u128(val, true) {
1027 emit_error!("shuffle index #{} is not a constant", arg_idx);
1030 Some(idx) if idx >= total_len => {
1031 emit_error!("shuffle index #{} is out of bounds (limit {})",
1032 arg_idx, total_len);
1035 Some(idx) => Some(C_i32(bcx.ccx, idx as i32)),
1039 let indices = match indices {
1041 None => return C_null(llret_ty)
1044 return bcx.shuffle_vector(llargs[0], llargs[1], C_vector(&indices))
1047 if name == "simd_insert" {
1048 require!(in_elem == arg_tys[2],
1049 "expected inserted type `{}` (element of input `{}`), found `{}`",
1050 in_elem, in_ty, arg_tys[2]);
1051 return bcx.insert_element(llargs[0], llargs[2], llargs[1])
1053 if name == "simd_extract" {
1054 require!(ret_ty == in_elem,
1055 "expected return type `{}` (element of input `{}`), found `{}`",
1056 in_elem, in_ty, ret_ty);
1057 return bcx.extract_element(llargs[0], llargs[1])
1060 if name == "simd_cast" {
1061 require_simd!(ret_ty, "return");
1062 let out_len = ret_ty.simd_size(tcx);
1063 require!(in_len == out_len,
1064 "expected return type with length {} (same as input type `{}`), \
1065 found `{}` with length {}",
1068 // casting cares about nominal type, not just structural type
1069 let out_elem = ret_ty.simd_type(tcx);
1071 if in_elem == out_elem { return llargs[0]; }
1073 enum Style { Float, Int(/* is signed? */ bool), Unsupported }
1075 let (in_style, in_width) = match in_elem.sty {
1076 // vectors of pointer-sized integers should've been
1077 // disallowed before here, so this unwrap is safe.
1078 ty::TyInt(i) => (Style::Int(true), i.bit_width().unwrap()),
1079 ty::TyUint(u) => (Style::Int(false), u.bit_width().unwrap()),
1080 ty::TyFloat(f) => (Style::Float, f.bit_width()),
1081 _ => (Style::Unsupported, 0)
1083 let (out_style, out_width) = match out_elem.sty {
1084 ty::TyInt(i) => (Style::Int(true), i.bit_width().unwrap()),
1085 ty::TyUint(u) => (Style::Int(false), u.bit_width().unwrap()),
1086 ty::TyFloat(f) => (Style::Float, f.bit_width()),
1087 _ => (Style::Unsupported, 0)
1090 match (in_style, out_style) {
1091 (Style::Int(in_is_signed), Style::Int(_)) => {
1092 return match in_width.cmp(&out_width) {
1093 Ordering::Greater => bcx.trunc(llargs[0], llret_ty),
1094 Ordering::Equal => llargs[0],
1095 Ordering::Less => if in_is_signed {
1096 bcx.sext(llargs[0], llret_ty)
1098 bcx.zext(llargs[0], llret_ty)
1102 (Style::Int(in_is_signed), Style::Float) => {
1103 return if in_is_signed {
1104 bcx.sitofp(llargs[0], llret_ty)
1106 bcx.uitofp(llargs[0], llret_ty)
1109 (Style::Float, Style::Int(out_is_signed)) => {
1110 return if out_is_signed {
1111 bcx.fptosi(llargs[0], llret_ty)
1113 bcx.fptoui(llargs[0], llret_ty)
1116 (Style::Float, Style::Float) => {
1117 return match in_width.cmp(&out_width) {
1118 Ordering::Greater => bcx.fptrunc(llargs[0], llret_ty),
1119 Ordering::Equal => llargs[0],
1120 Ordering::Less => bcx.fpext(llargs[0], llret_ty)
1123 _ => {/* Unsupported. Fallthrough. */}
1126 "unsupported cast from `{}` with element `{}` to `{}` with element `{}`",
1130 macro_rules! arith {
1131 ($($name: ident: $($($p: ident),* => $call: ident),*;)*) => {
1133 if name == stringify!($name) {
1137 return bcx.$call(llargs[0], llargs[1])
1143 "unsupported operation on `{}` with element `{}`",
1150 simd_add: TyUint, TyInt => add, TyFloat => fadd;
1151 simd_sub: TyUint, TyInt => sub, TyFloat => fsub;
1152 simd_mul: TyUint, TyInt => mul, TyFloat => fmul;
1153 simd_div: TyFloat => fdiv;
1154 simd_shl: TyUint, TyInt => shl;
1155 simd_shr: TyUint => lshr, TyInt => ashr;
1156 simd_and: TyUint, TyInt => and;
1157 simd_or: TyUint, TyInt => or;
1158 simd_xor: TyUint, TyInt => xor;
1160 span_bug!(span, "unknown SIMD intrinsic");
1163 // Returns the width of an int TypeVariant, and if it's signed or not
1164 // Returns None if the type is not an integer
1165 // FIXME: there’s multiple of this functions, investigate using some of the already existing
1167 fn int_type_width_signed<'tcx>(sty: &ty::TypeVariants<'tcx>, ccx: &CrateContext)
1168 -> Option<(u64, bool)> {
1169 use rustc::ty::{TyInt, TyUint};
1171 TyInt(t) => Some((match t {
1173 match &ccx.tcx().sess.target.target.target_pointer_width[..] {
1177 tws => bug!("Unsupported target word size for isize: {}", tws),
1180 ast::IntTy::I8 => 8,
1181 ast::IntTy::I16 => 16,
1182 ast::IntTy::I32 => 32,
1183 ast::IntTy::I64 => 64,
1184 ast::IntTy::I128 => 128,
1186 TyUint(t) => Some((match t {
1187 ast::UintTy::Us => {
1188 match &ccx.tcx().sess.target.target.target_pointer_width[..] {
1192 tws => bug!("Unsupported target word size for usize: {}", tws),
1195 ast::UintTy::U8 => 8,
1196 ast::UintTy::U16 => 16,
1197 ast::UintTy::U32 => 32,
1198 ast::UintTy::U64 => 64,
1199 ast::UintTy::U128 => 128,
1205 // Returns the width of a float TypeVariant
1206 // Returns None if the type is not a float
1207 fn float_type_width<'tcx>(sty: &ty::TypeVariants<'tcx>)
1209 use rustc::ty::TyFloat;
1211 TyFloat(t) => Some(match t {
1212 ast::FloatTy::F32 => 32,
1213 ast::FloatTy::F64 => 64,