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