1 // Copyright 2012-2015 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 //! Type-checking for the rust-intrinsic and platform-intrinsic
12 //! intrinsics that the compiler exposes.
15 use rustc::traits::{ObligationCause, ObligationCauseCode};
16 use rustc::ty::{self, TyCtxt, Ty};
17 use rustc::util::nodemap::FxHashMap;
18 use require_same_types;
22 use syntax::symbol::Symbol;
29 fn equate_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
30 it: &hir::ForeignItem,
33 inputs: Vec<Ty<'tcx>>,
35 let def_id = tcx.hir.local_def_id(it.id);
38 hir::ForeignItemFn(..) => {}
40 struct_span_err!(tcx.sess, it.span, E0622,
41 "intrinsic must be a function")
42 .span_label(it.span, "expected a function")
48 let i_n_tps = tcx.generics_of(def_id).types.len();
50 let span = match it.node {
51 hir::ForeignItemFn(_, _, ref generics) => generics.span,
55 struct_span_err!(tcx.sess, span, E0094,
56 "intrinsic has wrong number of type \
57 parameters: found {}, expected {}",
59 .span_label(span, format!("expected {} type parameter", n_tps))
64 let fty = tcx.mk_fn_ptr(ty::Binder(tcx.mk_fn_sig(
68 hir::Unsafety::Unsafe,
71 let cause = ObligationCause::new(it.span, it.id, ObligationCauseCode::IntrinsicType);
72 require_same_types(tcx, &cause, tcx.mk_fn_ptr(tcx.fn_sig(def_id)), fty);
75 /// Remember to add all intrinsics here, in librustc_trans/trans/intrinsic.rs,
76 /// and in libcore/intrinsics.rs
77 pub fn check_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
78 it: &hir::ForeignItem) {
79 let param = |n| tcx.mk_param(n, Symbol::intern(&format!("P{}", n)));
80 let name = it.name.as_str();
81 let (n_tps, inputs, output) = if name.starts_with("atomic_") {
82 let split : Vec<&str> = name.split('_').collect();
83 assert!(split.len() >= 2, "Atomic intrinsic not correct format");
85 //We only care about the operation here
86 let (n_tps, inputs, output) = match split[1] {
87 "cxchg" | "cxchgweak" => (1, vec![tcx.mk_mut_ptr(param(0)),
90 tcx.intern_tup(&[param(0), tcx.types.bool], false)),
91 "load" => (1, vec![tcx.mk_imm_ptr(param(0))],
93 "store" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)],
96 "xchg" | "xadd" | "xsub" | "and" | "nand" | "or" | "xor" | "max" |
97 "min" | "umax" | "umin" => {
98 (1, vec![tcx.mk_mut_ptr(param(0)), param(0)],
101 "fence" | "singlethreadfence" => {
102 (0, Vec::new(), tcx.mk_nil())
105 struct_span_err!(tcx.sess, it.span, E0092,
106 "unrecognized atomic operation function: `{}`", op)
107 .span_label(it.span, "unrecognized atomic operation")
112 (n_tps, inputs, output)
113 } else if &name[..] == "abort" || &name[..] == "unreachable" {
114 (0, Vec::new(), tcx.types.never)
116 let (n_tps, inputs, output) = match &name[..] {
117 "breakpoint" => (0, Vec::new(), tcx.mk_nil()),
119 "pref_align_of" | "min_align_of" => (1, Vec::new(), tcx.types.usize),
120 "size_of_val" | "min_align_of_val" => {
122 tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1),
127 "rustc_peek" => (1, vec![param(0)], param(0)),
128 "init" => (1, Vec::new(), param(0)),
129 "uninit" => (1, Vec::new(), param(0)),
130 "transmute" => (2, vec![ param(0) ], param(1)),
134 tcx.mk_mut_ptr(param(0)),
139 "prefetch_read_data" | "prefetch_write_data" |
140 "prefetch_read_instruction" | "prefetch_write_instruction" => {
141 (1, vec![tcx.mk_ptr(ty::TypeAndMut {
143 mutbl: hir::MutImmutable
148 (1, vec![tcx.mk_mut_ptr(param(0))], tcx.mk_nil())
150 "needs_drop" => (1, Vec::new(), tcx.types.bool),
152 "type_name" => (1, Vec::new(), tcx.mk_static_str()),
153 "type_id" => (1, Vec::new(), tcx.types.u64),
154 "offset" | "arith_offset" => {
157 tcx.mk_ptr(ty::TypeAndMut {
159 mutbl: hir::MutImmutable
163 tcx.mk_ptr(ty::TypeAndMut {
165 mutbl: hir::MutImmutable
168 "copy" | "copy_nonoverlapping" => {
171 tcx.mk_ptr(ty::TypeAndMut {
173 mutbl: hir::MutImmutable
175 tcx.mk_ptr(ty::TypeAndMut {
177 mutbl: hir::MutMutable
183 "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => {
186 tcx.mk_ptr(ty::TypeAndMut {
188 mutbl: hir::MutMutable
190 tcx.mk_ptr(ty::TypeAndMut {
192 mutbl: hir::MutImmutable
198 "write_bytes" | "volatile_set_memory" => {
201 tcx.mk_ptr(ty::TypeAndMut {
203 mutbl: hir::MutMutable
210 "sqrtf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
211 "sqrtf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
214 vec![ tcx.types.f32, tcx.types.i32 ],
219 vec![ tcx.types.f64, tcx.types.i32 ],
222 "sinf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
223 "sinf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
224 "cosf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
225 "cosf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
228 vec![ tcx.types.f32, tcx.types.f32 ],
233 vec![ tcx.types.f64, tcx.types.f64 ],
236 "expf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
237 "expf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
238 "exp2f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
239 "exp2f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
240 "logf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
241 "logf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
242 "log10f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
243 "log10f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
244 "log2f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
245 "log2f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
248 vec![ tcx.types.f32, tcx.types.f32, tcx.types.f32 ],
253 vec![ tcx.types.f64, tcx.types.f64, tcx.types.f64 ],
256 "fabsf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
257 "fabsf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
258 "copysignf32" => (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32),
259 "copysignf64" => (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64),
260 "floorf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
261 "floorf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
262 "ceilf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
263 "ceilf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
264 "truncf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
265 "truncf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
266 "rintf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
267 "rintf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
268 "nearbyintf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
269 "nearbyintf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
270 "roundf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
271 "roundf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
274 (1, vec![ tcx.mk_imm_ptr(param(0)) ], param(0)),
276 (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_nil()),
278 "ctpop" | "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "bswap" =>
279 (1, vec![param(0)], param(0)),
281 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" =>
282 (1, vec![param(0), param(0)],
283 tcx.intern_tup(&[param(0), tcx.types.bool], false)),
285 "unchecked_div" | "unchecked_rem" =>
286 (1, vec![param(0), param(0)], param(0)),
287 "unchecked_shl" | "unchecked_shr" =>
288 (1, vec![param(0), param(0)], param(0)),
290 "overflowing_add" | "overflowing_sub" | "overflowing_mul" =>
291 (1, vec![param(0), param(0)], param(0)),
292 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" =>
293 (1, vec![param(0), param(0)], param(0)),
295 "assume" => (0, vec![tcx.types.bool], tcx.mk_nil()),
296 "likely" => (0, vec![tcx.types.bool], tcx.types.bool),
297 "unlikely" => (0, vec![tcx.types.bool], tcx.types.bool),
299 "discriminant_value" => (1, vec![
300 tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1),
302 param(0))], tcx.types.u64),
305 let mut_u8 = tcx.mk_mut_ptr(tcx.types.u8);
306 let fn_ty = ty::Binder(tcx.mk_fn_sig(
310 hir::Unsafety::Normal,
313 (0, vec![tcx.mk_fn_ptr(fn_ty), mut_u8, mut_u8], tcx.types.i32)
317 let ptr_ty = tcx.mk_imm_ptr(tcx.mk_nil());
318 (0, vec![ptr_ty, tcx.types.usize], tcx.types.usize)
321 "nontemporal_store" => {
322 (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_nil())
326 struct_span_err!(tcx.sess, it.span, E0093,
327 "unrecognized intrinsic function: `{}`",
329 .span_label(it.span, "unrecognized intrinsic")
334 (n_tps, inputs, output)
336 equate_intrinsic_type(tcx, it, n_tps, Abi::RustIntrinsic, inputs, output)
339 /// Type-check `extern "platform-intrinsic" { ... }` functions.
340 pub fn check_platform_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
341 it: &hir::ForeignItem) {
343 let name = Symbol::intern(&format!("P{}", n));
344 tcx.mk_param(n, name)
347 let def_id = tcx.hir.local_def_id(it.id);
348 let i_n_tps = tcx.generics_of(def_id).types.len();
349 let name = it.name.as_str();
351 let (n_tps, inputs, output) = match &*name {
352 "simd_eq" | "simd_ne" | "simd_lt" | "simd_le" | "simd_gt" | "simd_ge" => {
353 (2, vec![param(0), param(0)], param(1))
355 "simd_add" | "simd_sub" | "simd_mul" | "simd_rem" |
356 "simd_div" | "simd_shl" | "simd_shr" |
357 "simd_and" | "simd_or" | "simd_xor" => {
358 (1, vec![param(0), param(0)], param(0))
360 "simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)),
361 "simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)),
362 "simd_cast" => (2, vec![param(0)], param(1)),
363 name if name.starts_with("simd_shuffle") => {
364 match name["simd_shuffle".len()..].parse() {
366 let params = vec![param(0), param(0),
367 tcx.mk_array(tcx.types.u32, n)];
368 (2, params, param(1))
371 span_err!(tcx.sess, it.span, E0439,
372 "invalid `simd_shuffle`, needs length: `{}`", name);
378 match intrinsics::Intrinsic::find(&name) {
380 // this function is a platform specific intrinsic
382 span_err!(tcx.sess, it.span, E0440,
383 "platform-specific intrinsic has wrong number of type \
384 parameters: found {}, expected 0",
389 let mut structural_to_nomimal = FxHashMap();
391 let sig = tcx.fn_sig(def_id);
392 let sig = tcx.no_late_bound_regions(&sig).unwrap();
393 if intr.inputs.len() != sig.inputs().len() {
394 span_err!(tcx.sess, it.span, E0444,
395 "platform-specific intrinsic has invalid number of \
396 arguments: found {}, expected {}",
397 sig.inputs().len(), intr.inputs.len());
400 let input_pairs = intr.inputs.iter().zip(sig.inputs());
401 for (i, (expected_arg, arg)) in input_pairs.enumerate() {
402 match_intrinsic_type_to_type(tcx, &format!("argument {}", i + 1), it.span,
403 &mut structural_to_nomimal, expected_arg, arg);
405 match_intrinsic_type_to_type(tcx, "return value", it.span,
406 &mut structural_to_nomimal,
407 &intr.output, sig.output());
411 span_err!(tcx.sess, it.span, E0441,
412 "unrecognized platform-specific intrinsic function: `{}`", name);
419 equate_intrinsic_type(tcx, it, n_tps, Abi::PlatformIntrinsic,
423 // walk the expected type and the actual type in lock step, checking they're
424 // the same, in a kinda-structural way, i.e. `Vector`s have to be simd structs with
425 // exactly the right element type
426 fn match_intrinsic_type_to_type<'a, 'tcx>(
427 tcx: TyCtxt<'a, 'tcx, 'tcx>,
430 structural_to_nominal: &mut FxHashMap<&'a intrinsics::Type, Ty<'tcx>>,
431 expected: &'a intrinsics::Type, t: Ty<'tcx>)
433 use intrinsics::Type::*;
435 let simple_error = |real: &str, expected: &str| {
436 span_err!(tcx.sess, span, E0442,
437 "intrinsic {} has wrong type: found {}, expected {}",
438 position, real, expected)
442 Void => match t.sty {
443 ty::TyTuple(ref v, _) if v.is_empty() => {},
444 _ => simple_error(&format!("`{}`", t), "()"),
446 // (The width we pass to LLVM doesn't concern the type checker.)
447 Integer(signed, bits, _llvm_width) => match (signed, bits, &t.sty) {
448 (true, 8, &ty::TyInt(ast::IntTy::I8)) |
449 (false, 8, &ty::TyUint(ast::UintTy::U8)) |
450 (true, 16, &ty::TyInt(ast::IntTy::I16)) |
451 (false, 16, &ty::TyUint(ast::UintTy::U16)) |
452 (true, 32, &ty::TyInt(ast::IntTy::I32)) |
453 (false, 32, &ty::TyUint(ast::UintTy::U32)) |
454 (true, 64, &ty::TyInt(ast::IntTy::I64)) |
455 (false, 64, &ty::TyUint(ast::UintTy::U64)) |
456 (true, 128, &ty::TyInt(ast::IntTy::I128)) |
457 (false, 128, &ty::TyUint(ast::UintTy::U128)) => {},
458 _ => simple_error(&format!("`{}`", t),
460 if signed {"i"} else {"u"},
463 Float(bits) => match (bits, &t.sty) {
464 (32, &ty::TyFloat(ast::FloatTy::F32)) |
465 (64, &ty::TyFloat(ast::FloatTy::F64)) => {},
466 _ => simple_error(&format!("`{}`", t),
467 &format!("`f{n}`", n = bits)),
469 Pointer(ref inner_expected, ref _llvm_type, const_) => {
471 ty::TyRawPtr(ty::TypeAndMut { ty, mutbl }) => {
472 if (mutbl == hir::MutImmutable) != const_ {
473 simple_error(&format!("`{}`", t),
474 if const_ {"const pointer"} else {"mut pointer"})
476 match_intrinsic_type_to_type(tcx, position, span, structural_to_nominal,
479 _ => simple_error(&format!("`{}`", t), "raw pointer"),
482 Vector(ref inner_expected, ref _llvm_type, len) => {
484 simple_error(&format!("non-simd type `{}`", t), "simd type");
487 let t_len = t.simd_size(tcx);
488 if len as usize != t_len {
489 simple_error(&format!("vector with length {}", t_len),
490 &format!("length {}", len));
493 let t_ty = t.simd_type(tcx);
495 // check that a given structural type always has the same an intrinsic definition
496 let previous = structural_to_nominal.entry(expected).or_insert(t);
498 // this gets its own error code because it is non-trivial
499 span_err!(tcx.sess, span, E0443,
500 "intrinsic {} has wrong type: found `{}`, expected `{}` which \
501 was used for this vector type previously in this signature",
508 match_intrinsic_type_to_type(tcx,
511 structural_to_nominal,
515 Aggregate(_flatten, ref expected_contents) => {
517 ty::TyTuple(contents, _) => {
518 if contents.len() != expected_contents.len() {
519 simple_error(&format!("tuple with length {}", contents.len()),
520 &format!("tuple with length {}", expected_contents.len()));
523 for (e, c) in expected_contents.iter().zip(contents) {
524 match_intrinsic_type_to_type(tcx, position, span, structural_to_nominal,
528 _ => simple_error(&format!("`{}`", t),