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;
20 use rustc_target::spec::abi::Abi;
22 use syntax::symbol::Symbol;
29 fn equate_intrinsic_type<'a, 'tcx>(
30 tcx: TyCtxt<'a, 'tcx, 'tcx>,
31 it: &hir::ForeignItem,
34 safety: hir::Unsafety,
35 inputs: Vec<Ty<'tcx>>,
38 let def_id = tcx.hir.local_def_id(it.id);
41 hir::ForeignItemKind::Fn(..) => {}
43 struct_span_err!(tcx.sess, it.span, E0622,
44 "intrinsic must be a function")
45 .span_label(it.span, "expected a function")
51 let i_n_tps = tcx.generics_of(def_id).own_counts().types;
53 let span = match it.node {
54 hir::ForeignItemKind::Fn(_, _, ref generics) => generics.span,
58 struct_span_err!(tcx.sess, span, E0094,
59 "intrinsic has wrong number of type \
60 parameters: found {}, expected {}",
62 .span_label(span, format!("expected {} type parameter", n_tps))
67 let fty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
74 let cause = ObligationCause::new(it.span, it.id, ObligationCauseCode::IntrinsicType);
75 require_same_types(tcx, &cause, tcx.mk_fn_ptr(tcx.fn_sig(def_id)), fty);
78 /// Remember to add all intrinsics here, in librustc_codegen_llvm/intrinsic.rs,
79 /// and in libcore/intrinsics.rs
80 pub fn check_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
81 it: &hir::ForeignItem) {
82 let param = |n| tcx.mk_ty_param(n, Symbol::intern(&format!("P{}", n)).as_interned_str());
83 let name = it.name.as_str();
84 let (n_tps, inputs, output, unsafety) = if name.starts_with("atomic_") {
85 let split : Vec<&str> = name.split('_').collect();
86 assert!(split.len() >= 2, "Atomic intrinsic in an incorrect format");
88 //We only care about the operation here
89 let (n_tps, inputs, output) = match split[1] {
90 "cxchg" | "cxchgweak" => (1, vec![tcx.mk_mut_ptr(param(0)),
93 tcx.intern_tup(&[param(0), tcx.types.bool])),
94 "load" => (1, vec![tcx.mk_imm_ptr(param(0))],
96 "store" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)],
99 "xchg" | "xadd" | "xsub" | "and" | "nand" | "or" | "xor" | "max" |
100 "min" | "umax" | "umin" => {
101 (1, vec![tcx.mk_mut_ptr(param(0)), param(0)],
104 "fence" | "singlethreadfence" => {
105 (0, Vec::new(), tcx.mk_unit())
108 struct_span_err!(tcx.sess, it.span, E0092,
109 "unrecognized atomic operation function: `{}`", op)
110 .span_label(it.span, "unrecognized atomic operation")
115 (n_tps, inputs, output, hir::Unsafety::Unsafe)
116 } else if &name[..] == "abort" || &name[..] == "unreachable" {
117 (0, Vec::new(), tcx.types.never, hir::Unsafety::Unsafe)
119 let unsafety = match &name[..] {
120 "size_of" | "min_align_of" | "needs_drop" => hir::Unsafety::Normal,
121 _ => hir::Unsafety::Unsafe,
123 let (n_tps, inputs, output) = match &name[..] {
124 "breakpoint" => (0, Vec::new(), tcx.mk_unit()),
126 "pref_align_of" | "min_align_of" => (1, Vec::new(), tcx.types.usize),
127 "size_of_val" | "min_align_of_val" => {
129 tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::INNERMOST,
134 "rustc_peek" => (1, vec![param(0)], param(0)),
135 "init" => (1, Vec::new(), param(0)),
136 "uninit" => (1, Vec::new(), param(0)),
137 "forget" => (1, vec![param(0)], tcx.mk_unit()),
138 "transmute" => (2, vec![ param(0) ], param(1)),
142 tcx.mk_mut_ptr(param(0)),
147 "prefetch_read_data" | "prefetch_write_data" |
148 "prefetch_read_instruction" | "prefetch_write_instruction" => {
149 (1, vec![tcx.mk_ptr(ty::TypeAndMut {
151 mutbl: hir::MutImmutable
156 (1, vec![tcx.mk_mut_ptr(param(0))], tcx.mk_unit())
158 "needs_drop" => (1, Vec::new(), tcx.types.bool),
160 "type_name" => (1, Vec::new(), tcx.mk_static_str()),
161 "type_id" => (1, Vec::new(), tcx.types.u64),
162 "offset" | "arith_offset" => {
165 tcx.mk_ptr(ty::TypeAndMut {
167 mutbl: hir::MutImmutable
171 tcx.mk_ptr(ty::TypeAndMut {
173 mutbl: hir::MutImmutable
176 "copy" | "copy_nonoverlapping" => {
179 tcx.mk_ptr(ty::TypeAndMut {
181 mutbl: hir::MutImmutable
183 tcx.mk_ptr(ty::TypeAndMut {
185 mutbl: hir::MutMutable
191 "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => {
194 tcx.mk_ptr(ty::TypeAndMut {
196 mutbl: hir::MutMutable
198 tcx.mk_ptr(ty::TypeAndMut {
200 mutbl: hir::MutImmutable
206 "write_bytes" | "volatile_set_memory" => {
209 tcx.mk_ptr(ty::TypeAndMut {
211 mutbl: hir::MutMutable
218 "sqrtf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
219 "sqrtf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
222 vec![ tcx.types.f32, tcx.types.i32 ],
227 vec![ tcx.types.f64, tcx.types.i32 ],
230 "sinf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
231 "sinf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
232 "cosf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
233 "cosf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
236 vec![ tcx.types.f32, tcx.types.f32 ],
241 vec![ tcx.types.f64, tcx.types.f64 ],
244 "expf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
245 "expf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
246 "exp2f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
247 "exp2f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
248 "logf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
249 "logf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
250 "log10f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
251 "log10f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
252 "log2f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
253 "log2f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
256 vec![ tcx.types.f32, tcx.types.f32, tcx.types.f32 ],
261 vec![ tcx.types.f64, tcx.types.f64, tcx.types.f64 ],
264 "fabsf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
265 "fabsf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
266 "copysignf32" => (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32),
267 "copysignf64" => (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64),
268 "floorf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
269 "floorf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
270 "ceilf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
271 "ceilf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
272 "truncf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
273 "truncf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
274 "rintf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
275 "rintf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
276 "nearbyintf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
277 "nearbyintf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
278 "roundf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
279 "roundf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
281 "volatile_load" | "unaligned_volatile_load" =>
282 (1, vec![ tcx.mk_imm_ptr(param(0)) ], param(0)),
283 "volatile_store" | "unaligned_volatile_store" =>
284 (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_unit()),
286 "ctpop" | "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" |
287 "bswap" | "bitreverse" =>
288 (1, vec![param(0)], param(0)),
290 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" =>
291 (1, vec![param(0), param(0)],
292 tcx.intern_tup(&[param(0), tcx.types.bool])),
294 "unchecked_div" | "unchecked_rem" | "exact_div" =>
295 (1, vec![param(0), param(0)], param(0)),
296 "unchecked_shl" | "unchecked_shr" |
297 "rotate_left" | "rotate_right" =>
298 (1, vec![param(0), param(0)], param(0)),
300 "overflowing_add" | "overflowing_sub" | "overflowing_mul" =>
301 (1, vec![param(0), param(0)], param(0)),
302 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" =>
303 (1, vec![param(0), param(0)], param(0)),
305 "assume" => (0, vec![tcx.types.bool], tcx.mk_unit()),
306 "likely" => (0, vec![tcx.types.bool], tcx.types.bool),
307 "unlikely" => (0, vec![tcx.types.bool], tcx.types.bool),
309 "discriminant_value" => (1, vec![
310 tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::INNERMOST,
312 param(0))], tcx.types.u64),
315 let mut_u8 = tcx.mk_mut_ptr(tcx.types.u8);
316 let fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
320 hir::Unsafety::Normal,
323 (0, vec![tcx.mk_fn_ptr(fn_ty), mut_u8, mut_u8], tcx.types.i32)
326 "nontemporal_store" => {
327 (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_unit())
331 struct_span_err!(tcx.sess, it.span, E0093,
332 "unrecognized intrinsic function: `{}`",
334 .span_label(it.span, "unrecognized intrinsic")
339 (n_tps, inputs, output, unsafety)
341 equate_intrinsic_type(tcx, it, n_tps, Abi::RustIntrinsic, unsafety, inputs, output)
344 /// Type-check `extern "platform-intrinsic" { ... }` functions.
345 pub fn check_platform_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
346 it: &hir::ForeignItem) {
348 let name = Symbol::intern(&format!("P{}", n)).as_interned_str();
349 tcx.mk_ty_param(n, name)
352 let def_id = tcx.hir.local_def_id(it.id);
353 let i_n_tps = tcx.generics_of(def_id).own_counts().types;
354 let name = it.name.as_str();
356 let (n_tps, inputs, output) = match &*name {
357 "simd_eq" | "simd_ne" | "simd_lt" | "simd_le" | "simd_gt" | "simd_ge" => {
358 (2, vec![param(0), param(0)], param(1))
360 "simd_add" | "simd_sub" | "simd_mul" | "simd_rem" |
361 "simd_div" | "simd_shl" | "simd_shr" |
362 "simd_and" | "simd_or" | "simd_xor" |
363 "simd_fmin" | "simd_fmax" | "simd_fpow" => {
364 (1, vec![param(0), param(0)], param(0))
366 "simd_fsqrt" | "simd_fsin" | "simd_fcos" | "simd_fexp" | "simd_fexp2" |
367 "simd_flog2" | "simd_flog10" | "simd_flog" |
368 "simd_fabs" | "simd_floor" | "simd_ceil" => {
369 (1, vec![param(0)], param(0))
372 (1, vec![param(0), tcx.types.i32], param(0))
375 (1, vec![param(0), param(0), param(0)], param(0))
378 (3, vec![param(0), param(1), param(2)], param(0))
381 (3, vec![param(0), param(1), param(2)], tcx.mk_unit())
383 "simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)),
384 "simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)),
385 "simd_cast" => (2, vec![param(0)], param(1)),
386 "simd_select" => (2, vec![param(0), param(1), param(1)], param(1)),
387 "simd_reduce_all" | "simd_reduce_any" => (1, vec![param(0)], tcx.types.bool),
388 "simd_reduce_add_ordered" | "simd_reduce_mul_ordered"
389 => (2, vec![param(0), param(1)], param(1)),
390 "simd_reduce_add_unordered" | "simd_reduce_mul_unordered" |
391 "simd_reduce_and" | "simd_reduce_or" | "simd_reduce_xor" |
392 "simd_reduce_min" | "simd_reduce_max" |
393 "simd_reduce_min_nanless" | "simd_reduce_max_nanless"
394 => (2, vec![param(0)], param(1)),
395 name if name.starts_with("simd_shuffle") => {
396 match name["simd_shuffle".len()..].parse() {
398 let params = vec![param(0), param(0),
399 tcx.mk_array(tcx.types.u32, n)];
400 (2, params, param(1))
403 span_err!(tcx.sess, it.span, E0439,
404 "invalid `simd_shuffle`, needs length: `{}`", name);
410 match intrinsics::Intrinsic::find(&name) {
412 // this function is a platform specific intrinsic
414 span_err!(tcx.sess, it.span, E0440,
415 "platform-specific intrinsic has wrong number of type \
416 parameters: found {}, expected 0",
421 let mut structural_to_nomimal = FxHashMap::default();
423 let sig = tcx.fn_sig(def_id);
424 let sig = sig.no_bound_vars().unwrap();
425 if intr.inputs.len() != sig.inputs().len() {
426 span_err!(tcx.sess, it.span, E0444,
427 "platform-specific intrinsic has invalid number of \
428 arguments: found {}, expected {}",
429 sig.inputs().len(), intr.inputs.len());
432 let input_pairs = intr.inputs.iter().zip(sig.inputs());
433 for (i, (expected_arg, arg)) in input_pairs.enumerate() {
434 match_intrinsic_type_to_type(tcx, &format!("argument {}", i + 1), it.span,
435 &mut structural_to_nomimal, expected_arg, arg);
437 match_intrinsic_type_to_type(tcx, "return value", it.span,
438 &mut structural_to_nomimal,
439 &intr.output, sig.output());
443 span_err!(tcx.sess, it.span, E0441,
444 "unrecognized platform-specific intrinsic function: `{}`", name);
451 equate_intrinsic_type(tcx, it, n_tps, Abi::PlatformIntrinsic, hir::Unsafety::Unsafe,
455 // walk the expected type and the actual type in lock step, checking they're
456 // the same, in a kinda-structural way, i.e. `Vector`s have to be simd structs with
457 // exactly the right element type
458 fn match_intrinsic_type_to_type<'a, 'tcx>(
459 tcx: TyCtxt<'a, 'tcx, 'tcx>,
462 structural_to_nominal: &mut FxHashMap<&'a intrinsics::Type, Ty<'tcx>>,
463 expected: &'a intrinsics::Type, t: Ty<'tcx>)
465 use intrinsics::Type::*;
467 let simple_error = |real: &str, expected: &str| {
468 span_err!(tcx.sess, span, E0442,
469 "intrinsic {} has wrong type: found {}, expected {}",
470 position, real, expected)
474 Void => match t.sty {
475 ty::Tuple(ref v) if v.is_empty() => {},
476 _ => simple_error(&format!("`{}`", t), "()"),
478 // (The width we pass to LLVM doesn't concern the type checker.)
479 Integer(signed, bits, _llvm_width) => match (signed, bits, &t.sty) {
480 (true, 8, &ty::Int(ast::IntTy::I8)) |
481 (false, 8, &ty::Uint(ast::UintTy::U8)) |
482 (true, 16, &ty::Int(ast::IntTy::I16)) |
483 (false, 16, &ty::Uint(ast::UintTy::U16)) |
484 (true, 32, &ty::Int(ast::IntTy::I32)) |
485 (false, 32, &ty::Uint(ast::UintTy::U32)) |
486 (true, 64, &ty::Int(ast::IntTy::I64)) |
487 (false, 64, &ty::Uint(ast::UintTy::U64)) |
488 (true, 128, &ty::Int(ast::IntTy::I128)) |
489 (false, 128, &ty::Uint(ast::UintTy::U128)) => {},
490 _ => simple_error(&format!("`{}`", t),
492 if signed {"i"} else {"u"},
495 Float(bits) => match (bits, &t.sty) {
496 (32, &ty::Float(ast::FloatTy::F32)) |
497 (64, &ty::Float(ast::FloatTy::F64)) => {},
498 _ => simple_error(&format!("`{}`", t),
499 &format!("`f{n}`", n = bits)),
501 Pointer(ref inner_expected, ref _llvm_type, const_) => {
503 ty::RawPtr(ty::TypeAndMut { ty, mutbl }) => {
504 if (mutbl == hir::MutImmutable) != const_ {
505 simple_error(&format!("`{}`", t),
506 if const_ {"const pointer"} else {"mut pointer"})
508 match_intrinsic_type_to_type(tcx, position, span, structural_to_nominal,
511 _ => simple_error(&format!("`{}`", t), "raw pointer"),
514 Vector(ref inner_expected, ref _llvm_type, len) => {
516 simple_error(&format!("non-simd type `{}`", t), "simd type");
519 let t_len = t.simd_size(tcx);
520 if len as usize != t_len {
521 simple_error(&format!("vector with length {}", t_len),
522 &format!("length {}", len));
525 let t_ty = t.simd_type(tcx);
527 // check that a given structural type always has the same an intrinsic definition
528 let previous = structural_to_nominal.entry(expected).or_insert(t);
530 // this gets its own error code because it is non-trivial
531 span_err!(tcx.sess, span, E0443,
532 "intrinsic {} has wrong type: found `{}`, expected `{}` which \
533 was used for this vector type previously in this signature",
540 match_intrinsic_type_to_type(tcx,
543 structural_to_nominal,
547 Aggregate(_flatten, ref expected_contents) => {
549 ty::Tuple(contents) => {
550 if contents.len() != expected_contents.len() {
551 simple_error(&format!("tuple with length {}", contents.len()),
552 &format!("tuple with length {}", expected_contents.len()));
555 for (e, c) in expected_contents.iter().zip(contents) {
556 match_intrinsic_type_to_type(tcx, position, span, structural_to_nominal,
560 _ => simple_error(&format!("`{}`", t),