]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/intrinsic.rs
0b800fe8247c70b9f345ff240c1477060766a307
[rust.git] / src / librustc_typeck / check / intrinsic.rs
1 //! Type-checking for the rust-intrinsic and platform-intrinsic
2 //! intrinsics that the compiler exposes.
3
4 use rustc::traits::{ObligationCause, ObligationCauseCode};
5 use rustc::ty::{self, TyCtxt, Ty};
6 use rustc::ty::subst::Subst;
7 use crate::require_same_types;
8
9 use rustc_target::spec::abi::Abi;
10 use syntax::symbol::InternedString;
11
12 use rustc::hir;
13
14 use std::iter;
15
16 fn equate_intrinsic_type<'tcx>(
17     tcx: TyCtxt<'tcx, 'tcx>,
18     it: &hir::ForeignItem,
19     n_tps: usize,
20     abi: Abi,
21     safety: hir::Unsafety,
22     inputs: Vec<Ty<'tcx>>,
23     output: Ty<'tcx>,
24 ) {
25     let def_id = tcx.hir().local_def_id_from_hir_id(it.hir_id);
26
27     match it.node {
28         hir::ForeignItemKind::Fn(..) => {}
29         _ => {
30             struct_span_err!(tcx.sess, it.span, E0622,
31                              "intrinsic must be a function")
32                 .span_label(it.span, "expected a function")
33                 .emit();
34             return;
35         }
36     }
37
38     let i_n_tps = tcx.generics_of(def_id).own_counts().types;
39     if i_n_tps != n_tps {
40         let span = match it.node {
41             hir::ForeignItemKind::Fn(_, _, ref generics) => generics.span,
42             _ => bug!()
43         };
44
45         struct_span_err!(tcx.sess, span, E0094,
46                         "intrinsic has wrong number of type \
47                          parameters: found {}, expected {}",
48                         i_n_tps, n_tps)
49             .span_label(span, format!("expected {} type parameter", n_tps))
50             .emit();
51         return;
52     }
53
54     let fty = tcx.mk_fn_ptr(ty::Binder::bind(tcx.mk_fn_sig(
55         inputs.into_iter(),
56         output,
57         false,
58         safety,
59         abi
60     )));
61     let cause = ObligationCause::new(it.span, it.hir_id, ObligationCauseCode::IntrinsicType);
62     require_same_types(tcx, &cause, tcx.mk_fn_ptr(tcx.fn_sig(def_id)), fty);
63 }
64
65 /// Returns `true` if the given intrinsic is unsafe to call or not.
66 pub fn intrisic_operation_unsafety(intrinsic: &str) -> hir::Unsafety {
67     match intrinsic {
68         "size_of" | "min_align_of" | "needs_drop" |
69         "add_with_overflow" | "sub_with_overflow" | "mul_with_overflow" |
70         "overflowing_add" | "overflowing_sub" | "overflowing_mul" |
71         "saturating_add" | "saturating_sub" |
72         "rotate_left" | "rotate_right" |
73         "ctpop" | "ctlz" | "cttz" | "bswap" | "bitreverse" |
74         "minnumf32" | "minnumf64" | "maxnumf32" | "maxnumf64"
75         => hir::Unsafety::Normal,
76         _ => hir::Unsafety::Unsafe,
77     }
78 }
79
80 /// Remember to add all intrinsics here, in librustc_codegen_llvm/intrinsic.rs,
81 /// and in libcore/intrinsics.rs
82 pub fn check_intrinsic_type<'tcx>(tcx: TyCtxt<'tcx, 'tcx>, it: &hir::ForeignItem) {
83     let param = |n| tcx.mk_ty_param(n, InternedString::intern(&format!("P{}", n)));
84     let name = it.ident.as_str();
85
86     let mk_va_list_ty = || {
87         tcx.lang_items().va_list().map(|did| {
88             let region = tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(0)));
89             let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
90             let va_list_ty = tcx.type_of(did).subst(tcx, &[region.into()]);
91             tcx.mk_mut_ref(tcx.mk_region(env_region), va_list_ty)
92         })
93     };
94
95     let (n_tps, inputs, output, unsafety) = if name.starts_with("atomic_") {
96         let split : Vec<&str> = name.split('_').collect();
97         assert!(split.len() >= 2, "Atomic intrinsic in an incorrect format");
98
99         //We only care about the operation here
100         let (n_tps, inputs, output) = match split[1] {
101             "cxchg" | "cxchgweak" => (1, vec![tcx.mk_mut_ptr(param(0)),
102                                               param(0),
103                                               param(0)],
104                                       tcx.intern_tup(&[param(0), tcx.types.bool])),
105             "load" => (1, vec![tcx.mk_imm_ptr(param(0))],
106                        param(0)),
107             "store" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)],
108                         tcx.mk_unit()),
109
110             "xchg" | "xadd" | "xsub" | "and"  | "nand" | "or" | "xor" | "max" |
111             "min"  | "umax" | "umin" => {
112                 (1, vec![tcx.mk_mut_ptr(param(0)), param(0)],
113                  param(0))
114             }
115             "fence" | "singlethreadfence" => {
116                 (0, Vec::new(), tcx.mk_unit())
117             }
118             op => {
119                 struct_span_err!(tcx.sess, it.span, E0092,
120                       "unrecognized atomic operation function: `{}`", op)
121                   .span_label(it.span, "unrecognized atomic operation")
122                   .emit();
123                 return;
124             }
125         };
126         (n_tps, inputs, output, hir::Unsafety::Unsafe)
127     } else if &name[..] == "abort" || &name[..] == "unreachable" {
128         (0, Vec::new(), tcx.types.never, hir::Unsafety::Unsafe)
129     } else {
130         let unsafety = intrisic_operation_unsafety(&name[..]);
131         let (n_tps, inputs, output) = match &name[..] {
132             "breakpoint" => (0, Vec::new(), tcx.mk_unit()),
133             "size_of" |
134             "pref_align_of" | "min_align_of" => (1, Vec::new(), tcx.types.usize),
135             "size_of_val" |  "min_align_of_val" => {
136                 (1, vec![
137                     tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::INNERMOST,
138                                                                  ty::BrAnon(0))),
139                                    param(0))
140                  ], tcx.types.usize)
141             }
142             "rustc_peek" => (1, vec![param(0)], param(0)),
143             "panic_if_uninhabited" => (1, Vec::new(), tcx.mk_unit()),
144             "init" => (1, Vec::new(), param(0)),
145             "uninit" => (1, Vec::new(), param(0)),
146             "forget" => (1, vec![param(0)], tcx.mk_unit()),
147             "transmute" => (2, vec![ param(0) ], param(1)),
148             "move_val_init" => {
149                 (1,
150                  vec![
151                     tcx.mk_mut_ptr(param(0)),
152                     param(0)
153                   ],
154                tcx.mk_unit())
155             }
156             "prefetch_read_data" | "prefetch_write_data" |
157             "prefetch_read_instruction" | "prefetch_write_instruction" => {
158                 (1, vec![tcx.mk_ptr(ty::TypeAndMut {
159                           ty: param(0),
160                           mutbl: hir::MutImmutable
161                          }), tcx.types.i32],
162                     tcx.mk_unit())
163             }
164             "drop_in_place" => {
165                 (1, vec![tcx.mk_mut_ptr(param(0))], tcx.mk_unit())
166             }
167             "needs_drop" => (1, Vec::new(), tcx.types.bool),
168
169             "type_name" => (1, Vec::new(), tcx.mk_static_str()),
170             "type_id" => (1, Vec::new(), tcx.types.u64),
171             "offset" | "arith_offset" => {
172               (1,
173                vec![
174                   tcx.mk_ptr(ty::TypeAndMut {
175                       ty: param(0),
176                       mutbl: hir::MutImmutable
177                   }),
178                   tcx.types.isize
179                ],
180                tcx.mk_ptr(ty::TypeAndMut {
181                    ty: param(0),
182                    mutbl: hir::MutImmutable
183                }))
184             }
185             "copy" | "copy_nonoverlapping" => {
186               (1,
187                vec![
188                   tcx.mk_ptr(ty::TypeAndMut {
189                       ty: param(0),
190                       mutbl: hir::MutImmutable
191                   }),
192                   tcx.mk_ptr(ty::TypeAndMut {
193                       ty: param(0),
194                       mutbl: hir::MutMutable
195                   }),
196                   tcx.types.usize,
197                ],
198                tcx.mk_unit())
199             }
200             "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => {
201               (1,
202                vec![
203                   tcx.mk_ptr(ty::TypeAndMut {
204                       ty: param(0),
205                       mutbl: hir::MutMutable
206                   }),
207                   tcx.mk_ptr(ty::TypeAndMut {
208                       ty: param(0),
209                       mutbl: hir::MutImmutable
210                   }),
211                   tcx.types.usize,
212                ],
213                tcx.mk_unit())
214             }
215             "write_bytes" | "volatile_set_memory" => {
216               (1,
217                vec![
218                   tcx.mk_ptr(ty::TypeAndMut {
219                       ty: param(0),
220                       mutbl: hir::MutMutable
221                   }),
222                   tcx.types.u8,
223                   tcx.types.usize,
224                ],
225                tcx.mk_unit())
226             }
227             "sqrtf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
228             "sqrtf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
229             "powif32" => {
230                (0,
231                 vec![ tcx.types.f32, tcx.types.i32 ],
232                 tcx.types.f32)
233             }
234             "powif64" => {
235                (0,
236                 vec![ tcx.types.f64, tcx.types.i32 ],
237                 tcx.types.f64)
238             }
239             "sinf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
240             "sinf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
241             "cosf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
242             "cosf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
243             "powf32" => {
244                (0,
245                 vec![ tcx.types.f32, tcx.types.f32 ],
246                 tcx.types.f32)
247             }
248             "powf64" => {
249                (0,
250                 vec![ tcx.types.f64, tcx.types.f64 ],
251                 tcx.types.f64)
252             }
253             "expf32"   => (0, vec![ tcx.types.f32 ], tcx.types.f32),
254             "expf64"   => (0, vec![ tcx.types.f64 ], tcx.types.f64),
255             "exp2f32"  => (0, vec![ tcx.types.f32 ], tcx.types.f32),
256             "exp2f64"  => (0, vec![ tcx.types.f64 ], tcx.types.f64),
257             "logf32"   => (0, vec![ tcx.types.f32 ], tcx.types.f32),
258             "logf64"   => (0, vec![ tcx.types.f64 ], tcx.types.f64),
259             "log10f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
260             "log10f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
261             "log2f32"  => (0, vec![ tcx.types.f32 ], tcx.types.f32),
262             "log2f64"  => (0, vec![ tcx.types.f64 ], tcx.types.f64),
263             "fmaf32" => {
264                 (0,
265                  vec![ tcx.types.f32, tcx.types.f32, tcx.types.f32 ],
266                  tcx.types.f32)
267             }
268             "fmaf64" => {
269                 (0,
270                  vec![ tcx.types.f64, tcx.types.f64, tcx.types.f64 ],
271                  tcx.types.f64)
272             }
273             "fabsf32"      => (0, vec![ tcx.types.f32 ], tcx.types.f32),
274             "fabsf64"      => (0, vec![ tcx.types.f64 ], tcx.types.f64),
275             "minnumf32"    => (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32),
276             "minnumf64"    => (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64),
277             "maxnumf32"    => (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32),
278             "maxnumf64"    => (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64),
279             "copysignf32"  => (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32),
280             "copysignf64"  => (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64),
281             "floorf32"     => (0, vec![ tcx.types.f32 ], tcx.types.f32),
282             "floorf64"     => (0, vec![ tcx.types.f64 ], tcx.types.f64),
283             "ceilf32"      => (0, vec![ tcx.types.f32 ], tcx.types.f32),
284             "ceilf64"      => (0, vec![ tcx.types.f64 ], tcx.types.f64),
285             "truncf32"     => (0, vec![ tcx.types.f32 ], tcx.types.f32),
286             "truncf64"     => (0, vec![ tcx.types.f64 ], tcx.types.f64),
287             "rintf32"      => (0, vec![ tcx.types.f32 ], tcx.types.f32),
288             "rintf64"      => (0, vec![ tcx.types.f64 ], tcx.types.f64),
289             "nearbyintf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
290             "nearbyintf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
291             "roundf32"     => (0, vec![ tcx.types.f32 ], tcx.types.f32),
292             "roundf64"     => (0, vec![ tcx.types.f64 ], tcx.types.f64),
293
294             "volatile_load" | "unaligned_volatile_load" =>
295                 (1, vec![ tcx.mk_imm_ptr(param(0)) ], param(0)),
296             "volatile_store" | "unaligned_volatile_store" =>
297                 (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_unit()),
298
299             "ctpop" | "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" |
300             "bswap" | "bitreverse" =>
301                 (1, vec![param(0)], param(0)),
302
303             "add_with_overflow" | "sub_with_overflow"  | "mul_with_overflow" =>
304                 (1, vec![param(0), param(0)],
305                 tcx.intern_tup(&[param(0), tcx.types.bool])),
306
307             "unchecked_div" | "unchecked_rem" | "exact_div" =>
308                 (1, vec![param(0), param(0)], param(0)),
309             "unchecked_shl" | "unchecked_shr" |
310             "rotate_left" | "rotate_right" =>
311                 (1, vec![param(0), param(0)], param(0)),
312             "unchecked_add" | "unchecked_sub" | "unchecked_mul" =>
313                 (1, vec![param(0), param(0)], param(0)),
314             "overflowing_add" | "overflowing_sub" | "overflowing_mul" =>
315                 (1, vec![param(0), param(0)], param(0)),
316             "saturating_add" | "saturating_sub" =>
317                 (1, vec![param(0), param(0)], param(0)),
318             "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" =>
319                 (1, vec![param(0), param(0)], param(0)),
320
321             "assume" => (0, vec![tcx.types.bool], tcx.mk_unit()),
322             "likely" => (0, vec![tcx.types.bool], tcx.types.bool),
323             "unlikely" => (0, vec![tcx.types.bool], tcx.types.bool),
324
325             "discriminant_value" => (1, vec![
326                     tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::INNERMOST,
327                                                                  ty::BrAnon(0))),
328                                    param(0))], tcx.types.u64),
329
330             "try" => {
331                 let mut_u8 = tcx.mk_mut_ptr(tcx.types.u8);
332                 let fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
333                     iter::once(mut_u8),
334                     tcx.mk_unit(),
335                     false,
336                     hir::Unsafety::Normal,
337                     Abi::Rust,
338                 ));
339                 (0, vec![tcx.mk_fn_ptr(fn_ty), mut_u8, mut_u8], tcx.types.i32)
340             }
341
342             "va_start" | "va_end" => {
343                 match mk_va_list_ty() {
344                     Some(va_list_ty) => (0, vec![va_list_ty], tcx.mk_unit()),
345                     None => bug!("`va_list` language item needed for C-variadic intrinsics")
346                 }
347             }
348
349             "va_copy" => {
350                 match tcx.lang_items().va_list() {
351                     Some(did) => {
352                         let region = tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(0)));
353                         let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
354                         let va_list_ty = tcx.type_of(did).subst(tcx, &[region.into()]);
355                         let ret_ty = match va_list_ty.sty {
356                             ty::Adt(def, _) if def.is_struct() => {
357                                 let fields = &def.non_enum_variant().fields;
358                                 match tcx.type_of(fields[0].did).subst(tcx, &[region.into()]).sty {
359                                     ty::Ref(_, element_ty, _) => match element_ty.sty {
360                                         ty::Adt(..) => element_ty,
361                                         _ => va_list_ty
362                                     }
363                                     _ => bug!("va_list structure is invalid")
364                                 }
365                             }
366                             _ => {
367                                 bug!("va_list structure is invalid")
368                             }
369                         };
370                         (0, vec![tcx.mk_imm_ref(tcx.mk_region(env_region), va_list_ty)], ret_ty)
371                     }
372                     None => bug!("`va_list` language item needed for C-variadic intrinsics")
373                 }
374             }
375
376             "va_arg" => {
377                 match mk_va_list_ty() {
378                     Some(va_list_ty) => (1, vec![va_list_ty], param(0)),
379                     None => bug!("`va_list` language item needed for C-variadic intrinsics")
380                 }
381             }
382
383             "nontemporal_store" => {
384                 (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_unit())
385             }
386
387             ref other => {
388                 struct_span_err!(tcx.sess, it.span, E0093,
389                                  "unrecognized intrinsic function: `{}`",
390                                  *other)
391                                  .span_label(it.span, "unrecognized intrinsic")
392                                  .emit();
393                 return;
394             }
395         };
396         (n_tps, inputs, output, unsafety)
397     };
398     equate_intrinsic_type(tcx, it, n_tps, Abi::RustIntrinsic, unsafety, inputs, output)
399 }
400
401 /// Type-check `extern "platform-intrinsic" { ... }` functions.
402 pub fn check_platform_intrinsic_type<'tcx>(tcx: TyCtxt<'tcx, 'tcx>, it: &hir::ForeignItem) {
403     let param = |n| {
404         let name = InternedString::intern(&format!("P{}", n));
405         tcx.mk_ty_param(n, name)
406     };
407
408     let name = it.ident.as_str();
409
410     let (n_tps, inputs, output) = match &*name {
411         "simd_eq" | "simd_ne" | "simd_lt" | "simd_le" | "simd_gt" | "simd_ge" => {
412             (2, vec![param(0), param(0)], param(1))
413         }
414         "simd_add" | "simd_sub" | "simd_mul" | "simd_rem" |
415         "simd_div" | "simd_shl" | "simd_shr" |
416         "simd_and" | "simd_or" | "simd_xor" |
417         "simd_fmin" | "simd_fmax" | "simd_fpow" |
418         "simd_saturating_add" | "simd_saturating_sub" => {
419             (1, vec![param(0), param(0)], param(0))
420         }
421         "simd_fsqrt" | "simd_fsin" | "simd_fcos" | "simd_fexp" | "simd_fexp2" |
422         "simd_flog2" | "simd_flog10" | "simd_flog" |
423         "simd_fabs" | "simd_floor" | "simd_ceil" => {
424             (1, vec![param(0)], param(0))
425         }
426         "simd_fpowi" => {
427             (1, vec![param(0), tcx.types.i32], param(0))
428         }
429         "simd_fma" => {
430             (1, vec![param(0), param(0), param(0)], param(0))
431         }
432         "simd_gather" => {
433             (3, vec![param(0), param(1), param(2)], param(0))
434         }
435         "simd_scatter" => {
436             (3, vec![param(0), param(1), param(2)], tcx.mk_unit())
437         }
438         "simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)),
439         "simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)),
440         "simd_cast" => (2, vec![param(0)], param(1)),
441         "simd_bitmask" => (2, vec![param(0)], param(1)),
442         "simd_select" |
443         "simd_select_bitmask" => (2, vec![param(0), param(1), param(1)], param(1)),
444         "simd_reduce_all" | "simd_reduce_any" => (1, vec![param(0)], tcx.types.bool),
445         "simd_reduce_add_ordered" | "simd_reduce_mul_ordered"
446             => (2, vec![param(0), param(1)], param(1)),
447         "simd_reduce_add_unordered" | "simd_reduce_mul_unordered" |
448         "simd_reduce_and" | "simd_reduce_or"  | "simd_reduce_xor" |
449         "simd_reduce_min" | "simd_reduce_max" |
450         "simd_reduce_min_nanless" | "simd_reduce_max_nanless"
451             => (2, vec![param(0)], param(1)),
452         name if name.starts_with("simd_shuffle") => {
453             match name["simd_shuffle".len()..].parse() {
454                 Ok(n) => {
455                     let params = vec![param(0), param(0),
456                                       tcx.mk_array(tcx.types.u32, n)];
457                     (2, params, param(1))
458                 }
459                 Err(_) => {
460                     span_err!(tcx.sess, it.span, E0439,
461                               "invalid `simd_shuffle`, needs length: `{}`", name);
462                     return
463                 }
464             }
465         }
466         _ => {
467             let msg = format!("unrecognized platform-specific intrinsic function: `{}`", name);
468             tcx.sess.span_err(it.span, &msg);
469             return;
470         }
471     };
472
473     equate_intrinsic_type(tcx, it, n_tps, Abi::PlatformIntrinsic, hir::Unsafety::Unsafe,
474                           inputs, output)
475 }