]> git.proxmox.com Git - rustc.git/blob - src/librustc_typeck/check/intrinsic.rs
New upstream version 1.20.0+dfsg1
[rustc.git] / src / librustc_typeck / check / intrinsic.rs
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.
4 //
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.
10
11 //! Type-checking for the rust-intrinsic and platform-intrinsic
12 //! intrinsics that the compiler exposes.
13
14 use intrinsics;
15 use rustc::traits::{ObligationCause, ObligationCauseCode};
16 use rustc::ty::{self, TyCtxt, Ty};
17 use rustc::util::nodemap::FxHashMap;
18 use require_same_types;
19
20 use syntax::abi::Abi;
21 use syntax::ast;
22 use syntax::symbol::Symbol;
23 use syntax_pos::Span;
24
25 use rustc::hir;
26
27 use std::iter;
28
29 fn equate_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
30 it: &hir::ForeignItem,
31 n_tps: usize,
32 abi: Abi,
33 inputs: Vec<Ty<'tcx>>,
34 output: Ty<'tcx>) {
35 let def_id = tcx.hir.local_def_id(it.id);
36
37 match it.node {
38 hir::ForeignItemFn(..) => {}
39 _ => {
40 struct_span_err!(tcx.sess, it.span, E0622,
41 "intrinsic must be a function")
42 .span_label(it.span, "expected a function")
43 .emit();
44 return;
45 }
46 }
47
48 let i_n_tps = tcx.generics_of(def_id).types.len();
49 if i_n_tps != n_tps {
50 let span = match it.node {
51 hir::ForeignItemFn(_, _, ref generics) => generics.span,
52 _ => bug!()
53 };
54
55 struct_span_err!(tcx.sess, span, E0094,
56 "intrinsic has wrong number of type \
57 parameters: found {}, expected {}",
58 i_n_tps, n_tps)
59 .span_label(span, format!("expected {} type parameter", n_tps))
60 .emit();
61 return;
62 }
63
64 let fty = tcx.mk_fn_ptr(ty::Binder(tcx.mk_fn_sig(
65 inputs.into_iter(),
66 output,
67 false,
68 hir::Unsafety::Unsafe,
69 abi
70 )));
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);
73 }
74
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");
84
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)),
88 param(0),
89 param(0)],
90 tcx.intern_tup(&[param(0), tcx.types.bool], false)),
91 "load" => (1, vec![tcx.mk_imm_ptr(param(0))],
92 param(0)),
93 "store" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)],
94 tcx.mk_nil()),
95
96 "xchg" | "xadd" | "xsub" | "and" | "nand" | "or" | "xor" | "max" |
97 "min" | "umax" | "umin" => {
98 (1, vec![tcx.mk_mut_ptr(param(0)), param(0)],
99 param(0))
100 }
101 "fence" | "singlethreadfence" => {
102 (0, Vec::new(), tcx.mk_nil())
103 }
104 op => {
105 struct_span_err!(tcx.sess, it.span, E0092,
106 "unrecognized atomic operation function: `{}`", op)
107 .span_label(it.span, "unrecognized atomic operation")
108 .emit();
109 return;
110 }
111 };
112 (n_tps, inputs, output)
113 } else if &name[..] == "abort" || &name[..] == "unreachable" {
114 (0, Vec::new(), tcx.types.never)
115 } else {
116 let (n_tps, inputs, output) = match &name[..] {
117 "breakpoint" => (0, Vec::new(), tcx.mk_nil()),
118 "size_of" |
119 "pref_align_of" | "min_align_of" => (1, Vec::new(), tcx.types.usize),
120 "size_of_val" | "min_align_of_val" => {
121 (1, vec![
122 tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1),
123 ty::BrAnon(0))),
124 param(0))
125 ], tcx.types.usize)
126 }
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)),
131 "move_val_init" => {
132 (1,
133 vec![
134 tcx.mk_mut_ptr(param(0)),
135 param(0)
136 ],
137 tcx.mk_nil())
138 }
139 "prefetch_read_data" | "prefetch_write_data" |
140 "prefetch_read_instruction" | "prefetch_write_instruction" => {
141 (1, vec![tcx.mk_ptr(ty::TypeAndMut {
142 ty: param(0),
143 mutbl: hir::MutImmutable
144 }), tcx.types.i32],
145 tcx.mk_nil())
146 }
147 "drop_in_place" => {
148 (1, vec![tcx.mk_mut_ptr(param(0))], tcx.mk_nil())
149 }
150 "needs_drop" => (1, Vec::new(), tcx.types.bool),
151
152 "type_name" => (1, Vec::new(), tcx.mk_static_str()),
153 "type_id" => (1, Vec::new(), tcx.types.u64),
154 "offset" | "arith_offset" => {
155 (1,
156 vec![
157 tcx.mk_ptr(ty::TypeAndMut {
158 ty: param(0),
159 mutbl: hir::MutImmutable
160 }),
161 tcx.types.isize
162 ],
163 tcx.mk_ptr(ty::TypeAndMut {
164 ty: param(0),
165 mutbl: hir::MutImmutable
166 }))
167 }
168 "copy" | "copy_nonoverlapping" => {
169 (1,
170 vec![
171 tcx.mk_ptr(ty::TypeAndMut {
172 ty: param(0),
173 mutbl: hir::MutImmutable
174 }),
175 tcx.mk_ptr(ty::TypeAndMut {
176 ty: param(0),
177 mutbl: hir::MutMutable
178 }),
179 tcx.types.usize,
180 ],
181 tcx.mk_nil())
182 }
183 "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => {
184 (1,
185 vec![
186 tcx.mk_ptr(ty::TypeAndMut {
187 ty: param(0),
188 mutbl: hir::MutMutable
189 }),
190 tcx.mk_ptr(ty::TypeAndMut {
191 ty: param(0),
192 mutbl: hir::MutImmutable
193 }),
194 tcx.types.usize,
195 ],
196 tcx.mk_nil())
197 }
198 "write_bytes" | "volatile_set_memory" => {
199 (1,
200 vec![
201 tcx.mk_ptr(ty::TypeAndMut {
202 ty: param(0),
203 mutbl: hir::MutMutable
204 }),
205 tcx.types.u8,
206 tcx.types.usize,
207 ],
208 tcx.mk_nil())
209 }
210 "sqrtf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
211 "sqrtf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
212 "powif32" => {
213 (0,
214 vec![ tcx.types.f32, tcx.types.i32 ],
215 tcx.types.f32)
216 }
217 "powif64" => {
218 (0,
219 vec![ tcx.types.f64, tcx.types.i32 ],
220 tcx.types.f64)
221 }
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),
226 "powf32" => {
227 (0,
228 vec![ tcx.types.f32, tcx.types.f32 ],
229 tcx.types.f32)
230 }
231 "powf64" => {
232 (0,
233 vec![ tcx.types.f64, tcx.types.f64 ],
234 tcx.types.f64)
235 }
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),
246 "fmaf32" => {
247 (0,
248 vec![ tcx.types.f32, tcx.types.f32, tcx.types.f32 ],
249 tcx.types.f32)
250 }
251 "fmaf64" => {
252 (0,
253 vec![ tcx.types.f64, tcx.types.f64, tcx.types.f64 ],
254 tcx.types.f64)
255 }
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),
272
273 "volatile_load" =>
274 (1, vec![ tcx.mk_imm_ptr(param(0)) ], param(0)),
275 "volatile_store" =>
276 (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_nil()),
277
278 "ctpop" | "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" | "bswap" =>
279 (1, vec![param(0)], param(0)),
280
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)),
284
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)),
289
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)),
294
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),
298
299 "discriminant_value" => (1, vec![
300 tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::DebruijnIndex::new(1),
301 ty::BrAnon(0))),
302 param(0))], tcx.types.u64),
303
304 "try" => {
305 let mut_u8 = tcx.mk_mut_ptr(tcx.types.u8);
306 let fn_ty = ty::Binder(tcx.mk_fn_sig(
307 iter::once(mut_u8),
308 tcx.mk_nil(),
309 false,
310 hir::Unsafety::Normal,
311 Abi::Rust,
312 ));
313 (0, vec![tcx.mk_fn_ptr(fn_ty), mut_u8, mut_u8], tcx.types.i32)
314 }
315
316 ref other => {
317 struct_span_err!(tcx.sess, it.span, E0093,
318 "unrecognized intrinsic function: `{}`",
319 *other)
320 .span_label(it.span, "unrecognized intrinsic")
321 .emit();
322 return;
323 }
324 };
325 (n_tps, inputs, output)
326 };
327 equate_intrinsic_type(tcx, it, n_tps, Abi::RustIntrinsic, inputs, output)
328 }
329
330 /// Type-check `extern "platform-intrinsic" { ... }` functions.
331 pub fn check_platform_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
332 it: &hir::ForeignItem) {
333 let param = |n| {
334 let name = Symbol::intern(&format!("P{}", n));
335 tcx.mk_param(n, name)
336 };
337
338 let def_id = tcx.hir.local_def_id(it.id);
339 let i_n_tps = tcx.generics_of(def_id).types.len();
340 let name = it.name.as_str();
341
342 let (n_tps, inputs, output) = match &*name {
343 "simd_eq" | "simd_ne" | "simd_lt" | "simd_le" | "simd_gt" | "simd_ge" => {
344 (2, vec![param(0), param(0)], param(1))
345 }
346 "simd_add" | "simd_sub" | "simd_mul" |
347 "simd_div" | "simd_shl" | "simd_shr" |
348 "simd_and" | "simd_or" | "simd_xor" => {
349 (1, vec![param(0), param(0)], param(0))
350 }
351 "simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)),
352 "simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)),
353 "simd_cast" => (2, vec![param(0)], param(1)),
354 name if name.starts_with("simd_shuffle") => {
355 match name["simd_shuffle".len()..].parse() {
356 Ok(n) => {
357 let params = vec![param(0), param(0),
358 tcx.mk_ty(ty::TyArray(tcx.types.u32, n))];
359 (2, params, param(1))
360 }
361 Err(_) => {
362 span_err!(tcx.sess, it.span, E0439,
363 "invalid `simd_shuffle`, needs length: `{}`", name);
364 return
365 }
366 }
367 }
368 _ => {
369 match intrinsics::Intrinsic::find(&name) {
370 Some(intr) => {
371 // this function is a platform specific intrinsic
372 if i_n_tps != 0 {
373 span_err!(tcx.sess, it.span, E0440,
374 "platform-specific intrinsic has wrong number of type \
375 parameters: found {}, expected 0",
376 i_n_tps);
377 return
378 }
379
380 let mut structural_to_nomimal = FxHashMap();
381
382 let sig = tcx.fn_sig(def_id);
383 let sig = tcx.no_late_bound_regions(&sig).unwrap();
384 if intr.inputs.len() != sig.inputs().len() {
385 span_err!(tcx.sess, it.span, E0444,
386 "platform-specific intrinsic has invalid number of \
387 arguments: found {}, expected {}",
388 sig.inputs().len(), intr.inputs.len());
389 return
390 }
391 let input_pairs = intr.inputs.iter().zip(sig.inputs());
392 for (i, (expected_arg, arg)) in input_pairs.enumerate() {
393 match_intrinsic_type_to_type(tcx, &format!("argument {}", i + 1), it.span,
394 &mut structural_to_nomimal, expected_arg, arg);
395 }
396 match_intrinsic_type_to_type(tcx, "return value", it.span,
397 &mut structural_to_nomimal,
398 &intr.output, sig.output());
399 return
400 }
401 None => {
402 span_err!(tcx.sess, it.span, E0441,
403 "unrecognized platform-specific intrinsic function: `{}`", name);
404 return;
405 }
406 }
407 }
408 };
409
410 equate_intrinsic_type(tcx, it, n_tps, Abi::PlatformIntrinsic,
411 inputs, output)
412 }
413
414 // walk the expected type and the actual type in lock step, checking they're
415 // the same, in a kinda-structural way, i.e. `Vector`s have to be simd structs with
416 // exactly the right element type
417 fn match_intrinsic_type_to_type<'a, 'tcx>(
418 tcx: TyCtxt<'a, 'tcx, 'tcx>,
419 position: &str,
420 span: Span,
421 structural_to_nominal: &mut FxHashMap<&'a intrinsics::Type, ty::Ty<'tcx>>,
422 expected: &'a intrinsics::Type, t: ty::Ty<'tcx>)
423 {
424 use intrinsics::Type::*;
425
426 let simple_error = |real: &str, expected: &str| {
427 span_err!(tcx.sess, span, E0442,
428 "intrinsic {} has wrong type: found {}, expected {}",
429 position, real, expected)
430 };
431
432 match *expected {
433 Void => match t.sty {
434 ty::TyTuple(ref v, _) if v.is_empty() => {},
435 _ => simple_error(&format!("`{}`", t), "()"),
436 },
437 // (The width we pass to LLVM doesn't concern the type checker.)
438 Integer(signed, bits, _llvm_width) => match (signed, bits, &t.sty) {
439 (true, 8, &ty::TyInt(ast::IntTy::I8)) |
440 (false, 8, &ty::TyUint(ast::UintTy::U8)) |
441 (true, 16, &ty::TyInt(ast::IntTy::I16)) |
442 (false, 16, &ty::TyUint(ast::UintTy::U16)) |
443 (true, 32, &ty::TyInt(ast::IntTy::I32)) |
444 (false, 32, &ty::TyUint(ast::UintTy::U32)) |
445 (true, 64, &ty::TyInt(ast::IntTy::I64)) |
446 (false, 64, &ty::TyUint(ast::UintTy::U64)) |
447 (true, 128, &ty::TyInt(ast::IntTy::I128)) |
448 (false, 128, &ty::TyUint(ast::UintTy::U128)) => {},
449 _ => simple_error(&format!("`{}`", t),
450 &format!("`{}{n}`",
451 if signed {"i"} else {"u"},
452 n = bits)),
453 },
454 Float(bits) => match (bits, &t.sty) {
455 (32, &ty::TyFloat(ast::FloatTy::F32)) |
456 (64, &ty::TyFloat(ast::FloatTy::F64)) => {},
457 _ => simple_error(&format!("`{}`", t),
458 &format!("`f{n}`", n = bits)),
459 },
460 Pointer(ref inner_expected, ref _llvm_type, const_) => {
461 match t.sty {
462 ty::TyRawPtr(ty::TypeAndMut { ty, mutbl }) => {
463 if (mutbl == hir::MutImmutable) != const_ {
464 simple_error(&format!("`{}`", t),
465 if const_ {"const pointer"} else {"mut pointer"})
466 }
467 match_intrinsic_type_to_type(tcx, position, span, structural_to_nominal,
468 inner_expected, ty)
469 }
470 _ => simple_error(&format!("`{}`", t), "raw pointer"),
471 }
472 }
473 Vector(ref inner_expected, ref _llvm_type, len) => {
474 if !t.is_simd() {
475 simple_error(&format!("non-simd type `{}`", t), "simd type");
476 return;
477 }
478 let t_len = t.simd_size(tcx);
479 if len as usize != t_len {
480 simple_error(&format!("vector with length {}", t_len),
481 &format!("length {}", len));
482 return;
483 }
484 let t_ty = t.simd_type(tcx);
485 {
486 // check that a given structural type always has the same an intrinsic definition
487 let previous = structural_to_nominal.entry(expected).or_insert(t);
488 if *previous != t {
489 // this gets its own error code because it is non-trivial
490 span_err!(tcx.sess, span, E0443,
491 "intrinsic {} has wrong type: found `{}`, expected `{}` which \
492 was used for this vector type previously in this signature",
493 position,
494 t,
495 *previous);
496 return;
497 }
498 }
499 match_intrinsic_type_to_type(tcx,
500 position,
501 span,
502 structural_to_nominal,
503 inner_expected,
504 t_ty)
505 }
506 Aggregate(_flatten, ref expected_contents) => {
507 match t.sty {
508 ty::TyTuple(contents, _) => {
509 if contents.len() != expected_contents.len() {
510 simple_error(&format!("tuple with length {}", contents.len()),
511 &format!("tuple with length {}", expected_contents.len()));
512 return
513 }
514 for (e, c) in expected_contents.iter().zip(contents) {
515 match_intrinsic_type_to_type(tcx, position, span, structural_to_nominal,
516 e, c)
517 }
518 }
519 _ => simple_error(&format!("`{}`", t),
520 "tuple"),
521 }
522 }
523 }
524 }