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::infer::TypeOrigin;
16 use rustc::ty::subst::{self, Substs};
18 use rustc::ty::{self, Ty};
19 use {CrateCtxt, require_same_types};
21 use std::collections::{HashMap};
24 use syntax::parse::token;
29 fn equate_intrinsic_type<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>,
30 it: &hir::ForeignItem,
33 inputs: Vec<ty::Ty<'tcx>>,
34 output: ty::FnOutput<'tcx>) {
36 let def_id = tcx.map.local_def_id(it.id);
37 let i_ty = tcx.lookup_item_type(def_id);
39 let mut substs = Substs::empty();
40 substs.types = i_ty.generics.types.map(|def| tcx.mk_param_from_def(def));
42 let fty = tcx.mk_fn_def(def_id, tcx.mk_substs(substs),
43 tcx.mk_bare_fn(ty::BareFnTy {
44 unsafety: hir::Unsafety::Unsafe,
46 sig: ty::Binder(FnSig {
52 let i_n_tps = i_ty.generics.types.len(subst::FnSpace);
54 span_err!(tcx.sess, it.span, E0094,
55 "intrinsic has wrong number of type \
56 parameters: found {}, expected {}",
59 require_same_types(ccx,
60 TypeOrigin::IntrinsicType(it.span),
66 /// Remember to add all intrinsics here, in librustc_trans/trans/intrinsic.rs,
67 /// and in libcore/intrinsics.rs
68 pub fn check_intrinsic_type(ccx: &CrateCtxt, it: &hir::ForeignItem) {
69 fn param<'a, 'tcx>(ccx: &CrateCtxt<'a, 'tcx>, n: u32) -> Ty<'tcx> {
70 let name = token::intern(&format!("P{}", n));
71 ccx.tcx.mk_param(subst::FnSpace, n, name)
75 let name = it.name.as_str();
76 let (n_tps, inputs, output) = if name.starts_with("atomic_") {
77 let split : Vec<&str> = name.split('_').collect();
78 assert!(split.len() >= 2, "Atomic intrinsic not correct format");
80 //We only care about the operation here
81 let (n_tps, inputs, output) = match split[1] {
82 "cxchg" | "cxchgweak" => (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)),
85 tcx.mk_tup(vec!(param(ccx, 0), tcx.types.bool))),
86 "load" => (1, vec!(tcx.mk_imm_ptr(param(ccx, 0))),
88 "store" => (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)),
91 "xchg" | "xadd" | "xsub" | "and" | "nand" | "or" | "xor" | "max" |
92 "min" | "umax" | "umin" => {
93 (1, vec!(tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0)),
96 "fence" | "singlethreadfence" => {
97 (0, Vec::new(), tcx.mk_nil())
100 span_err!(tcx.sess, it.span, E0092,
101 "unrecognized atomic operation function: `{}`", op);
105 (n_tps, inputs, ty::FnConverging(output))
106 } else if &name[..] == "abort" || &name[..] == "unreachable" {
107 (0, Vec::new(), ty::FnDiverging)
109 let (n_tps, inputs, output) = match &name[..] {
110 "breakpoint" => (0, Vec::new(), tcx.mk_nil()),
112 "pref_align_of" | "min_align_of" => (1, Vec::new(), ccx.tcx.types.usize),
113 "size_of_val" | "min_align_of_val" => {
115 tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1),
118 ], ccx.tcx.types.usize)
120 "rustc_peek" => (1, vec![param(ccx, 0)], param(ccx, 0)),
121 "init" | "init_dropped" => (1, Vec::new(), param(ccx, 0)),
122 "uninit" => (1, Vec::new(), param(ccx, 0)),
123 "forget" => (1, vec!( param(ccx, 0) ), tcx.mk_nil()),
124 "transmute" => (2, vec!( param(ccx, 0) ), param(ccx, 1)),
128 tcx.mk_mut_ptr(param(ccx, 0)),
134 (1, vec![tcx.mk_mut_ptr(param(ccx, 0))], tcx.mk_nil())
136 "needs_drop" => (1, Vec::new(), ccx.tcx.types.bool),
138 "type_name" => (1, Vec::new(), tcx.mk_static_str()),
139 "type_id" => (1, Vec::new(), ccx.tcx.types.u64),
140 "offset" | "arith_offset" => {
143 tcx.mk_ptr(ty::TypeAndMut {
145 mutbl: hir::MutImmutable
149 tcx.mk_ptr(ty::TypeAndMut {
151 mutbl: hir::MutImmutable
154 "copy" | "copy_nonoverlapping" => {
157 tcx.mk_ptr(ty::TypeAndMut {
159 mutbl: hir::MutImmutable
161 tcx.mk_ptr(ty::TypeAndMut {
163 mutbl: hir::MutMutable
169 "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => {
172 tcx.mk_ptr(ty::TypeAndMut {
174 mutbl: hir::MutMutable
176 tcx.mk_ptr(ty::TypeAndMut {
178 mutbl: hir::MutImmutable
184 "write_bytes" | "volatile_set_memory" => {
187 tcx.mk_ptr(ty::TypeAndMut {
189 mutbl: hir::MutMutable
196 "sqrtf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
197 "sqrtf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
200 vec!( tcx.types.f32, tcx.types.i32 ),
205 vec!( tcx.types.f64, tcx.types.i32 ),
208 "sinf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
209 "sinf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
210 "cosf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
211 "cosf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
214 vec!( tcx.types.f32, tcx.types.f32 ),
219 vec!( tcx.types.f64, tcx.types.f64 ),
222 "expf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
223 "expf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
224 "exp2f32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
225 "exp2f64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
226 "logf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
227 "logf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
228 "log10f32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
229 "log10f64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
230 "log2f32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
231 "log2f64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
234 vec!( tcx.types.f32, tcx.types.f32, tcx.types.f32 ),
239 vec!( tcx.types.f64, tcx.types.f64, tcx.types.f64 ),
242 "fabsf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
243 "fabsf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
244 "copysignf32" => (0, vec!( tcx.types.f32, tcx.types.f32 ), tcx.types.f32),
245 "copysignf64" => (0, vec!( tcx.types.f64, tcx.types.f64 ), tcx.types.f64),
246 "floorf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
247 "floorf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
248 "ceilf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
249 "ceilf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
250 "truncf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
251 "truncf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
252 "rintf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
253 "rintf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
254 "nearbyintf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
255 "nearbyintf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
256 "roundf32" => (0, vec!( tcx.types.f32 ), tcx.types.f32),
257 "roundf64" => (0, vec!( tcx.types.f64 ), tcx.types.f64),
260 (1, vec!( tcx.mk_imm_ptr(param(ccx, 0)) ), param(ccx, 0)),
262 (1, vec!( tcx.mk_mut_ptr(param(ccx, 0)), param(ccx, 0) ), tcx.mk_nil()),
264 "ctpop" | "ctlz" | "cttz" | "bswap" => (1, vec!(param(ccx, 0)), param(ccx, 0)),
266 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" =>
267 (1, vec!(param(ccx, 0), param(ccx, 0)),
268 tcx.mk_tup(vec!(param(ccx, 0), tcx.types.bool))),
270 "unchecked_div" | "unchecked_rem" =>
271 (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)),
273 "overflowing_add" | "overflowing_sub" | "overflowing_mul" =>
274 (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)),
275 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" =>
276 (1, vec![param(ccx, 0), param(ccx, 0)], param(ccx, 0)),
278 "assume" => (0, vec![tcx.types.bool], tcx.mk_nil()),
280 "discriminant_value" => (1, vec![
281 tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1),
283 param(ccx, 0))], tcx.types.u64),
286 let mut_u8 = tcx.mk_mut_ptr(tcx.types.u8);
287 let fn_ty = tcx.mk_bare_fn(ty::BareFnTy {
288 unsafety: hir::Unsafety::Normal,
290 sig: ty::Binder(FnSig {
291 inputs: vec![mut_u8],
292 output: ty::FnOutput::FnConverging(tcx.mk_nil()),
296 (0, vec![tcx.mk_fn_ptr(fn_ty), mut_u8, mut_u8], tcx.types.i32)
300 struct_span_err!(tcx.sess, it.span, E0093,
301 "unrecognized intrinsic function: `{}`",
303 .span_label(it.span, &format!("unrecognized intrinsic"))
308 (n_tps, inputs, ty::FnConverging(output))
310 equate_intrinsic_type(ccx, it, n_tps, Abi::RustIntrinsic, inputs, output)
313 /// Type-check `extern "platform-intrinsic" { ... }` functions.
314 pub fn check_platform_intrinsic_type(ccx: &CrateCtxt,
315 it: &hir::ForeignItem) {
317 let name = token::intern(&format!("P{}", n));
318 ccx.tcx.mk_param(subst::FnSpace, n, name)
322 let i_ty = tcx.lookup_item_type(tcx.map.local_def_id(it.id));
323 let i_n_tps = i_ty.generics.types.len(subst::FnSpace);
324 let name = it.name.as_str();
326 let (n_tps, inputs, output) = match &*name {
327 "simd_eq" | "simd_ne" | "simd_lt" | "simd_le" | "simd_gt" | "simd_ge" => {
328 (2, vec![param(0), param(0)], param(1))
330 "simd_add" | "simd_sub" | "simd_mul" |
331 "simd_div" | "simd_shl" | "simd_shr" |
332 "simd_and" | "simd_or" | "simd_xor" => {
333 (1, vec![param(0), param(0)], param(0))
335 "simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)),
336 "simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)),
337 "simd_cast" => (2, vec![param(0)], param(1)),
338 name if name.starts_with("simd_shuffle") => {
339 match name["simd_shuffle".len()..].parse() {
341 let params = vec![param(0), param(0),
342 tcx.mk_ty(ty::TyArray(tcx.types.u32, n))];
343 (2, params, param(1))
346 span_err!(tcx.sess, it.span, E0439,
347 "invalid `simd_shuffle`, needs length: `{}`", name);
353 match intrinsics::Intrinsic::find(&name) {
355 // this function is a platform specific intrinsic
357 span_err!(tcx.sess, it.span, E0440,
358 "platform-specific intrinsic has wrong number of type \
359 parameters: found {}, expected 0",
364 let mut structural_to_nomimal = HashMap::new();
366 let sig = tcx.no_late_bound_regions(i_ty.ty.fn_sig()).unwrap();
367 if intr.inputs.len() != sig.inputs.len() {
368 span_err!(tcx.sess, it.span, E0444,
369 "platform-specific intrinsic has invalid number of \
370 arguments: found {}, expected {}",
371 intr.inputs.len(), sig.inputs.len());
374 let input_pairs = intr.inputs.iter().zip(&sig.inputs);
375 for (i, (expected_arg, arg)) in input_pairs.enumerate() {
376 match_intrinsic_type_to_type(ccx, &format!("argument {}", i + 1), it.span,
377 &mut structural_to_nomimal, expected_arg, arg);
379 match_intrinsic_type_to_type(ccx, "return value", it.span,
380 &mut structural_to_nomimal,
381 &intr.output, sig.output.unwrap());
385 span_err!(tcx.sess, it.span, E0441,
386 "unrecognized platform-specific intrinsic function: `{}`", name);
393 equate_intrinsic_type(ccx, it, n_tps, Abi::PlatformIntrinsic,
394 inputs, ty::FnConverging(output))
397 // walk the expected type and the actual type in lock step, checking they're
398 // the same, in a kinda-structural way, i.e. `Vector`s have to be simd structs with
399 // exactly the right element type
400 fn match_intrinsic_type_to_type<'tcx, 'a>(
401 ccx: &CrateCtxt<'a, 'tcx>,
404 structural_to_nominal: &mut HashMap<&'a intrinsics::Type, ty::Ty<'tcx>>,
405 expected: &'a intrinsics::Type, t: ty::Ty<'tcx>)
407 use intrinsics::Type::*;
409 let simple_error = |real: &str, expected: &str| {
410 span_err!(ccx.tcx.sess, span, E0442,
411 "intrinsic {} has wrong type: found {}, expected {}",
412 position, real, expected)
416 Void => match t.sty {
417 ty::TyTuple(ref v) if v.is_empty() => {},
418 _ => simple_error(&format!("`{}`", t), "()"),
420 // (The width we pass to LLVM doesn't concern the type checker.)
421 Integer(signed, bits, _llvm_width) => match (signed, bits, &t.sty) {
422 (true, 8, &ty::TyInt(ast::IntTy::I8)) |
423 (false, 8, &ty::TyUint(ast::UintTy::U8)) |
424 (true, 16, &ty::TyInt(ast::IntTy::I16)) |
425 (false, 16, &ty::TyUint(ast::UintTy::U16)) |
426 (true, 32, &ty::TyInt(ast::IntTy::I32)) |
427 (false, 32, &ty::TyUint(ast::UintTy::U32)) |
428 (true, 64, &ty::TyInt(ast::IntTy::I64)) |
429 (false, 64, &ty::TyUint(ast::UintTy::U64)) => {},
430 _ => simple_error(&format!("`{}`", t),
432 if signed {"i"} else {"u"},
435 Float(bits) => match (bits, &t.sty) {
436 (32, &ty::TyFloat(ast::FloatTy::F32)) |
437 (64, &ty::TyFloat(ast::FloatTy::F64)) => {},
438 _ => simple_error(&format!("`{}`", t),
439 &format!("`f{n}`", n = bits)),
441 Pointer(ref inner_expected, ref _llvm_type, const_) => {
443 ty::TyRawPtr(ty::TypeAndMut { ty, mutbl }) => {
444 if (mutbl == hir::MutImmutable) != const_ {
445 simple_error(&format!("`{}`", t),
446 if const_ {"const pointer"} else {"mut pointer"})
448 match_intrinsic_type_to_type(ccx, position, span, structural_to_nominal,
451 _ => simple_error(&format!("`{}`", t), "raw pointer"),
454 Vector(ref inner_expected, ref _llvm_type, len) => {
456 simple_error(&format!("non-simd type `{}`", t), "simd type");
459 let t_len = t.simd_size(ccx.tcx);
460 if len as usize != t_len {
461 simple_error(&format!("vector with length {}", t_len),
462 &format!("length {}", len));
465 let t_ty = t.simd_type(ccx.tcx);
467 // check that a given structural type always has the same an intrinsic definition
468 let previous = structural_to_nominal.entry(expected).or_insert(t);
470 // this gets its own error code because it is non-trivial
471 span_err!(ccx.tcx.sess, span, E0443,
472 "intrinsic {} has wrong type: found `{}`, expected `{}` which \
473 was used for this vector type previously in this signature",
480 match_intrinsic_type_to_type(ccx,
483 structural_to_nominal,
487 Aggregate(_flatten, ref expected_contents) => {
489 ty::TyTuple(contents) => {
490 if contents.len() != expected_contents.len() {
491 simple_error(&format!("tuple with length {}", contents.len()),
492 &format!("tuple with length {}", expected_contents.len()));
495 for (e, c) in expected_contents.iter().zip(contents) {
496 match_intrinsic_type_to_type(ccx, position, span, structural_to_nominal,
500 _ => simple_error(&format!("`{}`", t),