]> git.proxmox.com Git - rustc.git/blob - src/librustc_typeck/check/intrinsic.rs
New upstream version 1.31.0~beta.4+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 rustc_target::spec::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>(
30 tcx: TyCtxt<'a, 'tcx, 'tcx>,
31 it: &hir::ForeignItem,
32 n_tps: usize,
33 abi: Abi,
34 safety: hir::Unsafety,
35 inputs: Vec<Ty<'tcx>>,
36 output: Ty<'tcx>,
37 ) {
38 let def_id = tcx.hir.local_def_id(it.id);
39
40 match it.node {
41 hir::ForeignItemKind::Fn(..) => {}
42 _ => {
43 struct_span_err!(tcx.sess, it.span, E0622,
44 "intrinsic must be a function")
45 .span_label(it.span, "expected a function")
46 .emit();
47 return;
48 }
49 }
50
51 let i_n_tps = tcx.generics_of(def_id).own_counts().types;
52 if i_n_tps != n_tps {
53 let span = match it.node {
54 hir::ForeignItemKind::Fn(_, _, ref generics) => generics.span,
55 _ => bug!()
56 };
57
58 struct_span_err!(tcx.sess, span, E0094,
59 "intrinsic has wrong number of type \
60 parameters: found {}, expected {}",
61 i_n_tps, n_tps)
62 .span_label(span, format!("expected {} type parameter", n_tps))
63 .emit();
64 return;
65 }
66
67 let fty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
68 inputs.into_iter(),
69 output,
70 false,
71 safety,
72 abi
73 )));
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);
76 }
77
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");
87
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)),
91 param(0),
92 param(0)],
93 tcx.intern_tup(&[param(0), tcx.types.bool])),
94 "load" => (1, vec![tcx.mk_imm_ptr(param(0))],
95 param(0)),
96 "store" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)],
97 tcx.mk_unit()),
98
99 "xchg" | "xadd" | "xsub" | "and" | "nand" | "or" | "xor" | "max" |
100 "min" | "umax" | "umin" => {
101 (1, vec![tcx.mk_mut_ptr(param(0)), param(0)],
102 param(0))
103 }
104 "fence" | "singlethreadfence" => {
105 (0, Vec::new(), tcx.mk_unit())
106 }
107 op => {
108 struct_span_err!(tcx.sess, it.span, E0092,
109 "unrecognized atomic operation function: `{}`", op)
110 .span_label(it.span, "unrecognized atomic operation")
111 .emit();
112 return;
113 }
114 };
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)
118 } else {
119 let unsafety = match &name[..] {
120 "size_of" | "min_align_of" | "needs_drop" => hir::Unsafety::Normal,
121 _ => hir::Unsafety::Unsafe,
122 };
123 let (n_tps, inputs, output) = match &name[..] {
124 "breakpoint" => (0, Vec::new(), tcx.mk_unit()),
125 "size_of" |
126 "pref_align_of" | "min_align_of" => (1, Vec::new(), tcx.types.usize),
127 "size_of_val" | "min_align_of_val" => {
128 (1, vec![
129 tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::INNERMOST,
130 ty::BrAnon(0))),
131 param(0))
132 ], tcx.types.usize)
133 }
134 "rustc_peek" => (1, vec![param(0)], param(0)),
135 "init" => (1, Vec::new(), param(0)),
136 "uninit" => (1, Vec::new(), param(0)),
137 "transmute" => (2, vec![ param(0) ], param(1)),
138 "move_val_init" => {
139 (1,
140 vec![
141 tcx.mk_mut_ptr(param(0)),
142 param(0)
143 ],
144 tcx.mk_unit())
145 }
146 "prefetch_read_data" | "prefetch_write_data" |
147 "prefetch_read_instruction" | "prefetch_write_instruction" => {
148 (1, vec![tcx.mk_ptr(ty::TypeAndMut {
149 ty: param(0),
150 mutbl: hir::MutImmutable
151 }), tcx.types.i32],
152 tcx.mk_unit())
153 }
154 "drop_in_place" => {
155 (1, vec![tcx.mk_mut_ptr(param(0))], tcx.mk_unit())
156 }
157 "needs_drop" => (1, Vec::new(), tcx.types.bool),
158
159 "type_name" => (1, Vec::new(), tcx.mk_static_str()),
160 "type_id" => (1, Vec::new(), tcx.types.u64),
161 "offset" | "arith_offset" => {
162 (1,
163 vec![
164 tcx.mk_ptr(ty::TypeAndMut {
165 ty: param(0),
166 mutbl: hir::MutImmutable
167 }),
168 tcx.types.isize
169 ],
170 tcx.mk_ptr(ty::TypeAndMut {
171 ty: param(0),
172 mutbl: hir::MutImmutable
173 }))
174 }
175 "copy" | "copy_nonoverlapping" => {
176 (1,
177 vec![
178 tcx.mk_ptr(ty::TypeAndMut {
179 ty: param(0),
180 mutbl: hir::MutImmutable
181 }),
182 tcx.mk_ptr(ty::TypeAndMut {
183 ty: param(0),
184 mutbl: hir::MutMutable
185 }),
186 tcx.types.usize,
187 ],
188 tcx.mk_unit())
189 }
190 "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => {
191 (1,
192 vec![
193 tcx.mk_ptr(ty::TypeAndMut {
194 ty: param(0),
195 mutbl: hir::MutMutable
196 }),
197 tcx.mk_ptr(ty::TypeAndMut {
198 ty: param(0),
199 mutbl: hir::MutImmutable
200 }),
201 tcx.types.usize,
202 ],
203 tcx.mk_unit())
204 }
205 "write_bytes" | "volatile_set_memory" => {
206 (1,
207 vec![
208 tcx.mk_ptr(ty::TypeAndMut {
209 ty: param(0),
210 mutbl: hir::MutMutable
211 }),
212 tcx.types.u8,
213 tcx.types.usize,
214 ],
215 tcx.mk_unit())
216 }
217 "sqrtf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
218 "sqrtf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
219 "powif32" => {
220 (0,
221 vec![ tcx.types.f32, tcx.types.i32 ],
222 tcx.types.f32)
223 }
224 "powif64" => {
225 (0,
226 vec![ tcx.types.f64, tcx.types.i32 ],
227 tcx.types.f64)
228 }
229 "sinf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
230 "sinf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
231 "cosf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
232 "cosf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
233 "powf32" => {
234 (0,
235 vec![ tcx.types.f32, tcx.types.f32 ],
236 tcx.types.f32)
237 }
238 "powf64" => {
239 (0,
240 vec![ tcx.types.f64, tcx.types.f64 ],
241 tcx.types.f64)
242 }
243 "expf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
244 "expf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
245 "exp2f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
246 "exp2f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
247 "logf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
248 "logf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
249 "log10f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
250 "log10f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
251 "log2f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
252 "log2f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
253 "fmaf32" => {
254 (0,
255 vec![ tcx.types.f32, tcx.types.f32, tcx.types.f32 ],
256 tcx.types.f32)
257 }
258 "fmaf64" => {
259 (0,
260 vec![ tcx.types.f64, tcx.types.f64, tcx.types.f64 ],
261 tcx.types.f64)
262 }
263 "fabsf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
264 "fabsf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
265 "copysignf32" => (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32),
266 "copysignf64" => (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64),
267 "floorf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
268 "floorf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
269 "ceilf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
270 "ceilf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
271 "truncf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
272 "truncf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
273 "rintf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
274 "rintf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
275 "nearbyintf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
276 "nearbyintf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
277 "roundf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
278 "roundf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
279
280 "volatile_load" | "unaligned_volatile_load" =>
281 (1, vec![ tcx.mk_imm_ptr(param(0)) ], param(0)),
282 "volatile_store" | "unaligned_volatile_store" =>
283 (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_unit()),
284
285 "ctpop" | "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" |
286 "bswap" | "bitreverse" =>
287 (1, vec![param(0)], param(0)),
288
289 "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" =>
290 (1, vec![param(0), param(0)],
291 tcx.intern_tup(&[param(0), tcx.types.bool])),
292
293 "unchecked_div" | "unchecked_rem" | "exact_div" =>
294 (1, vec![param(0), param(0)], param(0)),
295 "unchecked_shl" | "unchecked_shr" =>
296 (1, vec![param(0), param(0)], param(0)),
297
298 "overflowing_add" | "overflowing_sub" | "overflowing_mul" =>
299 (1, vec![param(0), param(0)], param(0)),
300 "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" =>
301 (1, vec![param(0), param(0)], param(0)),
302
303 "assume" => (0, vec![tcx.types.bool], tcx.mk_unit()),
304 "likely" => (0, vec![tcx.types.bool], tcx.types.bool),
305 "unlikely" => (0, vec![tcx.types.bool], tcx.types.bool),
306
307 "discriminant_value" => (1, vec![
308 tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::INNERMOST,
309 ty::BrAnon(0))),
310 param(0))], tcx.types.u64),
311
312 "try" => {
313 let mut_u8 = tcx.mk_mut_ptr(tcx.types.u8);
314 let fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
315 iter::once(mut_u8),
316 tcx.mk_unit(),
317 false,
318 hir::Unsafety::Normal,
319 Abi::Rust,
320 ));
321 (0, vec![tcx.mk_fn_ptr(fn_ty), mut_u8, mut_u8], tcx.types.i32)
322 }
323
324 "nontemporal_store" => {
325 (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_unit())
326 }
327
328 ref other => {
329 struct_span_err!(tcx.sess, it.span, E0093,
330 "unrecognized intrinsic function: `{}`",
331 *other)
332 .span_label(it.span, "unrecognized intrinsic")
333 .emit();
334 return;
335 }
336 };
337 (n_tps, inputs, output, unsafety)
338 };
339 equate_intrinsic_type(tcx, it, n_tps, Abi::RustIntrinsic, unsafety, inputs, output)
340 }
341
342 /// Type-check `extern "platform-intrinsic" { ... }` functions.
343 pub fn check_platform_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
344 it: &hir::ForeignItem) {
345 let param = |n| {
346 let name = Symbol::intern(&format!("P{}", n)).as_interned_str();
347 tcx.mk_ty_param(n, name)
348 };
349
350 let def_id = tcx.hir.local_def_id(it.id);
351 let i_n_tps = tcx.generics_of(def_id).own_counts().types;
352 let name = it.name.as_str();
353
354 let (n_tps, inputs, output) = match &*name {
355 "simd_eq" | "simd_ne" | "simd_lt" | "simd_le" | "simd_gt" | "simd_ge" => {
356 (2, vec![param(0), param(0)], param(1))
357 }
358 "simd_add" | "simd_sub" | "simd_mul" | "simd_rem" |
359 "simd_div" | "simd_shl" | "simd_shr" |
360 "simd_and" | "simd_or" | "simd_xor" |
361 "simd_fmin" | "simd_fmax" | "simd_fpow" => {
362 (1, vec![param(0), param(0)], param(0))
363 }
364 "simd_fsqrt" | "simd_fsin" | "simd_fcos" | "simd_fexp" | "simd_fexp2" |
365 "simd_flog2" | "simd_flog10" | "simd_flog" |
366 "simd_fabs" | "simd_floor" | "simd_ceil" => {
367 (1, vec![param(0)], param(0))
368 }
369 "simd_fpowi" => {
370 (1, vec![param(0), tcx.types.i32], param(0))
371 }
372 "simd_fma" => {
373 (1, vec![param(0), param(0), param(0)], param(0))
374 }
375 "simd_gather" => {
376 (3, vec![param(0), param(1), param(2)], param(0))
377 }
378 "simd_scatter" => {
379 (3, vec![param(0), param(1), param(2)], tcx.mk_unit())
380 }
381 "simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)),
382 "simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)),
383 "simd_cast" => (2, vec![param(0)], param(1)),
384 "simd_select" => (2, vec![param(0), param(1), param(1)], param(1)),
385 "simd_reduce_all" | "simd_reduce_any" => (1, vec![param(0)], tcx.types.bool),
386 "simd_reduce_add_ordered" | "simd_reduce_mul_ordered"
387 => (2, vec![param(0), param(1)], param(1)),
388 "simd_reduce_add_unordered" | "simd_reduce_mul_unordered" |
389 "simd_reduce_and" | "simd_reduce_or" | "simd_reduce_xor" |
390 "simd_reduce_min" | "simd_reduce_max" |
391 "simd_reduce_min_nanless" | "simd_reduce_max_nanless"
392 => (2, vec![param(0)], param(1)),
393 name if name.starts_with("simd_shuffle") => {
394 match name["simd_shuffle".len()..].parse() {
395 Ok(n) => {
396 let params = vec![param(0), param(0),
397 tcx.mk_array(tcx.types.u32, n)];
398 (2, params, param(1))
399 }
400 Err(_) => {
401 span_err!(tcx.sess, it.span, E0439,
402 "invalid `simd_shuffle`, needs length: `{}`", name);
403 return
404 }
405 }
406 }
407 _ => {
408 match intrinsics::Intrinsic::find(&name) {
409 Some(intr) => {
410 // this function is a platform specific intrinsic
411 if i_n_tps != 0 {
412 span_err!(tcx.sess, it.span, E0440,
413 "platform-specific intrinsic has wrong number of type \
414 parameters: found {}, expected 0",
415 i_n_tps);
416 return
417 }
418
419 let mut structural_to_nomimal = FxHashMap::default();
420
421 let sig = tcx.fn_sig(def_id);
422 let sig = sig.no_late_bound_regions().unwrap();
423 if intr.inputs.len() != sig.inputs().len() {
424 span_err!(tcx.sess, it.span, E0444,
425 "platform-specific intrinsic has invalid number of \
426 arguments: found {}, expected {}",
427 sig.inputs().len(), intr.inputs.len());
428 return
429 }
430 let input_pairs = intr.inputs.iter().zip(sig.inputs());
431 for (i, (expected_arg, arg)) in input_pairs.enumerate() {
432 match_intrinsic_type_to_type(tcx, &format!("argument {}", i + 1), it.span,
433 &mut structural_to_nomimal, expected_arg, arg);
434 }
435 match_intrinsic_type_to_type(tcx, "return value", it.span,
436 &mut structural_to_nomimal,
437 &intr.output, sig.output());
438 return
439 }
440 None => {
441 span_err!(tcx.sess, it.span, E0441,
442 "unrecognized platform-specific intrinsic function: `{}`", name);
443 return;
444 }
445 }
446 }
447 };
448
449 equate_intrinsic_type(tcx, it, n_tps, Abi::PlatformIntrinsic, hir::Unsafety::Unsafe,
450 inputs, output)
451 }
452
453 // walk the expected type and the actual type in lock step, checking they're
454 // the same, in a kinda-structural way, i.e. `Vector`s have to be simd structs with
455 // exactly the right element type
456 fn match_intrinsic_type_to_type<'a, 'tcx>(
457 tcx: TyCtxt<'a, 'tcx, 'tcx>,
458 position: &str,
459 span: Span,
460 structural_to_nominal: &mut FxHashMap<&'a intrinsics::Type, Ty<'tcx>>,
461 expected: &'a intrinsics::Type, t: Ty<'tcx>)
462 {
463 use intrinsics::Type::*;
464
465 let simple_error = |real: &str, expected: &str| {
466 span_err!(tcx.sess, span, E0442,
467 "intrinsic {} has wrong type: found {}, expected {}",
468 position, real, expected)
469 };
470
471 match *expected {
472 Void => match t.sty {
473 ty::Tuple(ref v) if v.is_empty() => {},
474 _ => simple_error(&format!("`{}`", t), "()"),
475 },
476 // (The width we pass to LLVM doesn't concern the type checker.)
477 Integer(signed, bits, _llvm_width) => match (signed, bits, &t.sty) {
478 (true, 8, &ty::Int(ast::IntTy::I8)) |
479 (false, 8, &ty::Uint(ast::UintTy::U8)) |
480 (true, 16, &ty::Int(ast::IntTy::I16)) |
481 (false, 16, &ty::Uint(ast::UintTy::U16)) |
482 (true, 32, &ty::Int(ast::IntTy::I32)) |
483 (false, 32, &ty::Uint(ast::UintTy::U32)) |
484 (true, 64, &ty::Int(ast::IntTy::I64)) |
485 (false, 64, &ty::Uint(ast::UintTy::U64)) |
486 (true, 128, &ty::Int(ast::IntTy::I128)) |
487 (false, 128, &ty::Uint(ast::UintTy::U128)) => {},
488 _ => simple_error(&format!("`{}`", t),
489 &format!("`{}{n}`",
490 if signed {"i"} else {"u"},
491 n = bits)),
492 },
493 Float(bits) => match (bits, &t.sty) {
494 (32, &ty::Float(ast::FloatTy::F32)) |
495 (64, &ty::Float(ast::FloatTy::F64)) => {},
496 _ => simple_error(&format!("`{}`", t),
497 &format!("`f{n}`", n = bits)),
498 },
499 Pointer(ref inner_expected, ref _llvm_type, const_) => {
500 match t.sty {
501 ty::RawPtr(ty::TypeAndMut { ty, mutbl }) => {
502 if (mutbl == hir::MutImmutable) != const_ {
503 simple_error(&format!("`{}`", t),
504 if const_ {"const pointer"} else {"mut pointer"})
505 }
506 match_intrinsic_type_to_type(tcx, position, span, structural_to_nominal,
507 inner_expected, ty)
508 }
509 _ => simple_error(&format!("`{}`", t), "raw pointer"),
510 }
511 }
512 Vector(ref inner_expected, ref _llvm_type, len) => {
513 if !t.is_simd() {
514 simple_error(&format!("non-simd type `{}`", t), "simd type");
515 return;
516 }
517 let t_len = t.simd_size(tcx);
518 if len as usize != t_len {
519 simple_error(&format!("vector with length {}", t_len),
520 &format!("length {}", len));
521 return;
522 }
523 let t_ty = t.simd_type(tcx);
524 {
525 // check that a given structural type always has the same an intrinsic definition
526 let previous = structural_to_nominal.entry(expected).or_insert(t);
527 if *previous != t {
528 // this gets its own error code because it is non-trivial
529 span_err!(tcx.sess, span, E0443,
530 "intrinsic {} has wrong type: found `{}`, expected `{}` which \
531 was used for this vector type previously in this signature",
532 position,
533 t,
534 *previous);
535 return;
536 }
537 }
538 match_intrinsic_type_to_type(tcx,
539 position,
540 span,
541 structural_to_nominal,
542 inner_expected,
543 t_ty)
544 }
545 Aggregate(_flatten, ref expected_contents) => {
546 match t.sty {
547 ty::Tuple(contents) => {
548 if contents.len() != expected_contents.len() {
549 simple_error(&format!("tuple with length {}", contents.len()),
550 &format!("tuple with length {}", expected_contents.len()));
551 return
552 }
553 for (e, c) in expected_contents.iter().zip(contents) {
554 match_intrinsic_type_to_type(tcx, position, span, structural_to_nominal,
555 e, c)
556 }
557 }
558 _ => simple_error(&format!("`{}`", t),
559 "tuple"),
560 }
561 }
562 }
563 }