]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/intrinsic.rs
Rollup merge of #63872 - marmistrz:readdir, r=jonas-schievink
[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>,
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(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         "wrapping_add" | "wrapping_sub" | "wrapping_mul" |
71         "saturating_add" | "saturating_sub" |
72         "rotate_left" | "rotate_right" |
73         "ctpop" | "ctlz" | "cttz" | "bswap" | "bitreverse" |
74         "minnumf32" | "minnumf64" | "maxnumf32" | "maxnumf64" | "type_name"
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: TyCtxt<'_>, 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 = |mutbl| {
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_ref(tcx.mk_region(env_region), ty::TypeAndMut {
92                 ty: va_list_ty,
93                 mutbl
94             }), va_list_ty)
95         })
96     };
97
98     let (n_tps, inputs, output, unsafety) = if name.starts_with("atomic_") {
99         let split : Vec<&str> = name.split('_').collect();
100         assert!(split.len() >= 2, "Atomic intrinsic in an incorrect format");
101
102         //We only care about the operation here
103         let (n_tps, inputs, output) = match split[1] {
104             "cxchg" | "cxchgweak" => (1, vec![tcx.mk_mut_ptr(param(0)),
105                                               param(0),
106                                               param(0)],
107                                       tcx.intern_tup(&[param(0), tcx.types.bool])),
108             "load" => (1, vec![tcx.mk_imm_ptr(param(0))],
109                        param(0)),
110             "store" => (1, vec![tcx.mk_mut_ptr(param(0)), param(0)],
111                         tcx.mk_unit()),
112
113             "xchg" | "xadd" | "xsub" | "and"  | "nand" | "or" | "xor" | "max" |
114             "min"  | "umax" | "umin" => {
115                 (1, vec![tcx.mk_mut_ptr(param(0)), param(0)],
116                  param(0))
117             }
118             "fence" | "singlethreadfence" => {
119                 (0, Vec::new(), tcx.mk_unit())
120             }
121             op => {
122                 struct_span_err!(tcx.sess, it.span, E0092,
123                       "unrecognized atomic operation function: `{}`", op)
124                   .span_label(it.span, "unrecognized atomic operation")
125                   .emit();
126                 return;
127             }
128         };
129         (n_tps, inputs, output, hir::Unsafety::Unsafe)
130     } else if &name[..] == "abort" || &name[..] == "unreachable" {
131         (0, Vec::new(), tcx.types.never, hir::Unsafety::Unsafe)
132     } else {
133         let unsafety = intrisic_operation_unsafety(&name[..]);
134         let (n_tps, inputs, output) = match &name[..] {
135             "breakpoint" => (0, Vec::new(), tcx.mk_unit()),
136             "size_of" |
137             "pref_align_of" | "min_align_of" => (1, Vec::new(), tcx.types.usize),
138             "size_of_val" |  "min_align_of_val" => {
139                 (1, vec![
140                     tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::INNERMOST,
141                                                                  ty::BrAnon(0))),
142                                    param(0))
143                  ], tcx.types.usize)
144             }
145             "rustc_peek" => (1, vec![param(0)], param(0)),
146             "panic_if_uninhabited" => (1, Vec::new(), tcx.mk_unit()),
147             "init" => (1, Vec::new(), param(0)),
148             "uninit" => (1, Vec::new(), param(0)),
149             "forget" => (1, vec![param(0)], tcx.mk_unit()),
150             "transmute" => (2, vec![ param(0) ], param(1)),
151             "move_val_init" => {
152                 (1,
153                  vec![
154                     tcx.mk_mut_ptr(param(0)),
155                     param(0)
156                   ],
157                tcx.mk_unit())
158             }
159             "prefetch_read_data" | "prefetch_write_data" |
160             "prefetch_read_instruction" | "prefetch_write_instruction" => {
161                 (1, vec![tcx.mk_ptr(ty::TypeAndMut {
162                           ty: param(0),
163                           mutbl: hir::MutImmutable
164                          }), tcx.types.i32],
165                     tcx.mk_unit())
166             }
167             "drop_in_place" => {
168                 (1, vec![tcx.mk_mut_ptr(param(0))], tcx.mk_unit())
169             }
170             "needs_drop" => (1, Vec::new(), tcx.types.bool),
171
172             "type_name" => (1, Vec::new(), tcx.mk_static_str()),
173             "type_id" => (1, Vec::new(), tcx.types.u64),
174             "offset" | "arith_offset" => {
175               (1,
176                vec![
177                   tcx.mk_ptr(ty::TypeAndMut {
178                       ty: param(0),
179                       mutbl: hir::MutImmutable
180                   }),
181                   tcx.types.isize
182                ],
183                tcx.mk_ptr(ty::TypeAndMut {
184                    ty: param(0),
185                    mutbl: hir::MutImmutable
186                }))
187             }
188             "copy" | "copy_nonoverlapping" => {
189               (1,
190                vec![
191                   tcx.mk_ptr(ty::TypeAndMut {
192                       ty: param(0),
193                       mutbl: hir::MutImmutable
194                   }),
195                   tcx.mk_ptr(ty::TypeAndMut {
196                       ty: param(0),
197                       mutbl: hir::MutMutable
198                   }),
199                   tcx.types.usize,
200                ],
201                tcx.mk_unit())
202             }
203             "volatile_copy_memory" | "volatile_copy_nonoverlapping_memory" => {
204               (1,
205                vec![
206                   tcx.mk_ptr(ty::TypeAndMut {
207                       ty: param(0),
208                       mutbl: hir::MutMutable
209                   }),
210                   tcx.mk_ptr(ty::TypeAndMut {
211                       ty: param(0),
212                       mutbl: hir::MutImmutable
213                   }),
214                   tcx.types.usize,
215                ],
216                tcx.mk_unit())
217             }
218             "write_bytes" | "volatile_set_memory" => {
219               (1,
220                vec![
221                   tcx.mk_ptr(ty::TypeAndMut {
222                       ty: param(0),
223                       mutbl: hir::MutMutable
224                   }),
225                   tcx.types.u8,
226                   tcx.types.usize,
227                ],
228                tcx.mk_unit())
229             }
230             "sqrtf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
231             "sqrtf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
232             "powif32" => {
233                (0,
234                 vec![ tcx.types.f32, tcx.types.i32 ],
235                 tcx.types.f32)
236             }
237             "powif64" => {
238                (0,
239                 vec![ tcx.types.f64, tcx.types.i32 ],
240                 tcx.types.f64)
241             }
242             "sinf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
243             "sinf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
244             "cosf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
245             "cosf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
246             "powf32" => {
247                (0,
248                 vec![ tcx.types.f32, tcx.types.f32 ],
249                 tcx.types.f32)
250             }
251             "powf64" => {
252                (0,
253                 vec![ tcx.types.f64, tcx.types.f64 ],
254                 tcx.types.f64)
255             }
256             "expf32"   => (0, vec![ tcx.types.f32 ], tcx.types.f32),
257             "expf64"   => (0, vec![ tcx.types.f64 ], tcx.types.f64),
258             "exp2f32"  => (0, vec![ tcx.types.f32 ], tcx.types.f32),
259             "exp2f64"  => (0, vec![ tcx.types.f64 ], tcx.types.f64),
260             "logf32"   => (0, vec![ tcx.types.f32 ], tcx.types.f32),
261             "logf64"   => (0, vec![ tcx.types.f64 ], tcx.types.f64),
262             "log10f32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
263             "log10f64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
264             "log2f32"  => (0, vec![ tcx.types.f32 ], tcx.types.f32),
265             "log2f64"  => (0, vec![ tcx.types.f64 ], tcx.types.f64),
266             "fmaf32" => {
267                 (0,
268                  vec![ tcx.types.f32, tcx.types.f32, tcx.types.f32 ],
269                  tcx.types.f32)
270             }
271             "fmaf64" => {
272                 (0,
273                  vec![ tcx.types.f64, tcx.types.f64, tcx.types.f64 ],
274                  tcx.types.f64)
275             }
276             "fabsf32"      => (0, vec![ tcx.types.f32 ], tcx.types.f32),
277             "fabsf64"      => (0, vec![ tcx.types.f64 ], tcx.types.f64),
278             "minnumf32"    => (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32),
279             "minnumf64"    => (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64),
280             "maxnumf32"    => (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32),
281             "maxnumf64"    => (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64),
282             "copysignf32"  => (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32),
283             "copysignf64"  => (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64),
284             "floorf32"     => (0, vec![ tcx.types.f32 ], tcx.types.f32),
285             "floorf64"     => (0, vec![ tcx.types.f64 ], tcx.types.f64),
286             "ceilf32"      => (0, vec![ tcx.types.f32 ], tcx.types.f32),
287             "ceilf64"      => (0, vec![ tcx.types.f64 ], tcx.types.f64),
288             "truncf32"     => (0, vec![ tcx.types.f32 ], tcx.types.f32),
289             "truncf64"     => (0, vec![ tcx.types.f64 ], tcx.types.f64),
290             "rintf32"      => (0, vec![ tcx.types.f32 ], tcx.types.f32),
291             "rintf64"      => (0, vec![ tcx.types.f64 ], tcx.types.f64),
292             "nearbyintf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
293             "nearbyintf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
294             "roundf32"     => (0, vec![ tcx.types.f32 ], tcx.types.f32),
295             "roundf64"     => (0, vec![ tcx.types.f64 ], tcx.types.f64),
296
297             "volatile_load" | "unaligned_volatile_load" =>
298                 (1, vec![ tcx.mk_imm_ptr(param(0)) ], param(0)),
299             "volatile_store" | "unaligned_volatile_store" =>
300                 (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_unit()),
301
302             "ctpop" | "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" |
303             "bswap" | "bitreverse" =>
304                 (1, vec![param(0)], param(0)),
305
306             "add_with_overflow" | "sub_with_overflow"  | "mul_with_overflow" =>
307                 (1, vec![param(0), param(0)],
308                 tcx.intern_tup(&[param(0), tcx.types.bool])),
309
310             "unchecked_div" | "unchecked_rem" | "exact_div" =>
311                 (1, vec![param(0), param(0)], param(0)),
312             "unchecked_shl" | "unchecked_shr" |
313             "rotate_left" | "rotate_right" =>
314                 (1, vec![param(0), param(0)], param(0)),
315             "unchecked_add" | "unchecked_sub" | "unchecked_mul" =>
316                 (1, vec![param(0), param(0)], param(0)),
317             "wrapping_add" | "wrapping_sub" | "wrapping_mul" =>
318                 (1, vec![param(0), param(0)], param(0)),
319             "saturating_add" | "saturating_sub" =>
320                 (1, vec![param(0), param(0)], param(0)),
321             "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" =>
322                 (1, vec![param(0), param(0)], param(0)),
323
324             "assume" => (0, vec![tcx.types.bool], tcx.mk_unit()),
325             "likely" => (0, vec![tcx.types.bool], tcx.types.bool),
326             "unlikely" => (0, vec![tcx.types.bool], tcx.types.bool),
327
328             "discriminant_value" => (1, vec![
329                     tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::INNERMOST,
330                                                                  ty::BrAnon(0))),
331                                    param(0))], tcx.types.u64),
332
333             "try" => {
334                 let mut_u8 = tcx.mk_mut_ptr(tcx.types.u8);
335                 let fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
336                     iter::once(mut_u8),
337                     tcx.mk_unit(),
338                     false,
339                     hir::Unsafety::Normal,
340                     Abi::Rust,
341                 ));
342                 (0, vec![tcx.mk_fn_ptr(fn_ty), mut_u8, mut_u8], tcx.types.i32)
343             }
344
345             "va_start" | "va_end" => {
346                 match mk_va_list_ty(hir::MutMutable) {
347                     Some((va_list_ref_ty, _)) => (0, vec![va_list_ref_ty], tcx.mk_unit()),
348                     None => bug!("`va_list` language item needed for C-variadic intrinsics")
349                 }
350             }
351
352             "va_copy" => {
353                 match mk_va_list_ty(hir::MutImmutable) {
354                     Some((va_list_ref_ty, va_list_ty)) => {
355                         let va_list_ptr_ty = tcx.mk_mut_ptr(va_list_ty);
356                         (0, vec![va_list_ptr_ty, va_list_ref_ty], tcx.mk_unit())
357                     }
358                     None => bug!("`va_list` language item needed for C-variadic intrinsics")
359                 }
360             }
361
362             "va_arg" => {
363                 match mk_va_list_ty(hir::MutMutable) {
364                     Some((va_list_ref_ty, _)) => (1, vec![va_list_ref_ty], param(0)),
365                     None => bug!("`va_list` language item needed for C-variadic intrinsics")
366                 }
367             }
368
369             "nontemporal_store" => {
370                 (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_unit())
371             }
372
373             ref other => {
374                 struct_span_err!(tcx.sess, it.span, E0093,
375                                  "unrecognized intrinsic function: `{}`",
376                                  *other)
377                                  .span_label(it.span, "unrecognized intrinsic")
378                                  .emit();
379                 return;
380             }
381         };
382         (n_tps, inputs, output, unsafety)
383     };
384     equate_intrinsic_type(tcx, it, n_tps, Abi::RustIntrinsic, unsafety, inputs, output)
385 }
386
387 /// Type-check `extern "platform-intrinsic" { ... }` functions.
388 pub fn check_platform_intrinsic_type(tcx: TyCtxt<'_>, it: &hir::ForeignItem) {
389     let param = |n| {
390         let name = InternedString::intern(&format!("P{}", n));
391         tcx.mk_ty_param(n, name)
392     };
393
394     let name = it.ident.as_str();
395
396     let (n_tps, inputs, output) = match &*name {
397         "simd_eq" | "simd_ne" | "simd_lt" | "simd_le" | "simd_gt" | "simd_ge" => {
398             (2, vec![param(0), param(0)], param(1))
399         }
400         "simd_add" | "simd_sub" | "simd_mul" | "simd_rem" |
401         "simd_div" | "simd_shl" | "simd_shr" |
402         "simd_and" | "simd_or" | "simd_xor" |
403         "simd_fmin" | "simd_fmax" | "simd_fpow" |
404         "simd_saturating_add" | "simd_saturating_sub" => {
405             (1, vec![param(0), param(0)], param(0))
406         }
407         "simd_fsqrt" | "simd_fsin" | "simd_fcos" | "simd_fexp" | "simd_fexp2" |
408         "simd_flog2" | "simd_flog10" | "simd_flog" |
409         "simd_fabs" | "simd_floor" | "simd_ceil" => {
410             (1, vec![param(0)], param(0))
411         }
412         "simd_fpowi" => {
413             (1, vec![param(0), tcx.types.i32], param(0))
414         }
415         "simd_fma" => {
416             (1, vec![param(0), param(0), param(0)], param(0))
417         }
418         "simd_gather" => {
419             (3, vec![param(0), param(1), param(2)], param(0))
420         }
421         "simd_scatter" => {
422             (3, vec![param(0), param(1), param(2)], tcx.mk_unit())
423         }
424         "simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)),
425         "simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)),
426         "simd_cast" => (2, vec![param(0)], param(1)),
427         "simd_bitmask" => (2, vec![param(0)], param(1)),
428         "simd_select" |
429         "simd_select_bitmask" => (2, vec![param(0), param(1), param(1)], param(1)),
430         "simd_reduce_all" | "simd_reduce_any" => (1, vec![param(0)], tcx.types.bool),
431         "simd_reduce_add_ordered" | "simd_reduce_mul_ordered"
432             => (2, vec![param(0), param(1)], param(1)),
433         "simd_reduce_add_unordered" | "simd_reduce_mul_unordered" |
434         "simd_reduce_and" | "simd_reduce_or"  | "simd_reduce_xor" |
435         "simd_reduce_min" | "simd_reduce_max" |
436         "simd_reduce_min_nanless" | "simd_reduce_max_nanless"
437             => (2, vec![param(0)], param(1)),
438         name if name.starts_with("simd_shuffle") => {
439             match name["simd_shuffle".len()..].parse() {
440                 Ok(n) => {
441                     let params = vec![param(0), param(0),
442                                       tcx.mk_array(tcx.types.u32, n)];
443                     (2, params, param(1))
444                 }
445                 Err(_) => {
446                     span_err!(tcx.sess, it.span, E0439,
447                               "invalid `simd_shuffle`, needs length: `{}`", name);
448                     return
449                 }
450             }
451         }
452         _ => {
453             let msg = format!("unrecognized platform-specific intrinsic function: `{}`", name);
454             tcx.sess.span_err(it.span, &msg);
455             return;
456         }
457     };
458
459     equate_intrinsic_type(tcx, it, n_tps, Abi::PlatformIntrinsic, hir::Unsafety::Unsafe,
460                           inputs, output)
461 }