]> git.lizzy.rs Git - rust.git/blob - src/librustc_typeck/check/intrinsic.rs
Rollup merge of #61409 - varkor:condition-trait-param-ice, r=oli-obk
[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         => hir::Unsafety::Normal,
75         _ => hir::Unsafety::Unsafe,
76     }
77 }
78
79 /// Remember to add all intrinsics here, in librustc_codegen_llvm/intrinsic.rs,
80 /// and in libcore/intrinsics.rs
81 pub fn check_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
82                                       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             "copysignf32"  => (0, vec![ tcx.types.f32, tcx.types.f32 ], tcx.types.f32),
276             "copysignf64"  => (0, vec![ tcx.types.f64, tcx.types.f64 ], tcx.types.f64),
277             "floorf32"     => (0, vec![ tcx.types.f32 ], tcx.types.f32),
278             "floorf64"     => (0, vec![ tcx.types.f64 ], tcx.types.f64),
279             "ceilf32"      => (0, vec![ tcx.types.f32 ], tcx.types.f32),
280             "ceilf64"      => (0, vec![ tcx.types.f64 ], tcx.types.f64),
281             "truncf32"     => (0, vec![ tcx.types.f32 ], tcx.types.f32),
282             "truncf64"     => (0, vec![ tcx.types.f64 ], tcx.types.f64),
283             "rintf32"      => (0, vec![ tcx.types.f32 ], tcx.types.f32),
284             "rintf64"      => (0, vec![ tcx.types.f64 ], tcx.types.f64),
285             "nearbyintf32" => (0, vec![ tcx.types.f32 ], tcx.types.f32),
286             "nearbyintf64" => (0, vec![ tcx.types.f64 ], tcx.types.f64),
287             "roundf32"     => (0, vec![ tcx.types.f32 ], tcx.types.f32),
288             "roundf64"     => (0, vec![ tcx.types.f64 ], tcx.types.f64),
289
290             "volatile_load" | "unaligned_volatile_load" =>
291                 (1, vec![ tcx.mk_imm_ptr(param(0)) ], param(0)),
292             "volatile_store" | "unaligned_volatile_store" =>
293                 (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_unit()),
294
295             "ctpop" | "ctlz" | "ctlz_nonzero" | "cttz" | "cttz_nonzero" |
296             "bswap" | "bitreverse" =>
297                 (1, vec![param(0)], param(0)),
298
299             "add_with_overflow" | "sub_with_overflow"  | "mul_with_overflow" =>
300                 (1, vec![param(0), param(0)],
301                 tcx.intern_tup(&[param(0), tcx.types.bool])),
302
303             "unchecked_div" | "unchecked_rem" | "exact_div" =>
304                 (1, vec![param(0), param(0)], param(0)),
305             "unchecked_shl" | "unchecked_shr" |
306             "rotate_left" | "rotate_right" =>
307                 (1, vec![param(0), param(0)], param(0)),
308             "unchecked_add" | "unchecked_sub" | "unchecked_mul" =>
309                 (1, vec![param(0), param(0)], param(0)),
310             "overflowing_add" | "overflowing_sub" | "overflowing_mul" =>
311                 (1, vec![param(0), param(0)], param(0)),
312             "saturating_add" | "saturating_sub" =>
313                 (1, vec![param(0), param(0)], param(0)),
314             "fadd_fast" | "fsub_fast" | "fmul_fast" | "fdiv_fast" | "frem_fast" =>
315                 (1, vec![param(0), param(0)], param(0)),
316
317             "assume" => (0, vec![tcx.types.bool], tcx.mk_unit()),
318             "likely" => (0, vec![tcx.types.bool], tcx.types.bool),
319             "unlikely" => (0, vec![tcx.types.bool], tcx.types.bool),
320
321             "discriminant_value" => (1, vec![
322                     tcx.mk_imm_ref(tcx.mk_region(ty::ReLateBound(ty::INNERMOST,
323                                                                  ty::BrAnon(0))),
324                                    param(0))], tcx.types.u64),
325
326             "try" => {
327                 let mut_u8 = tcx.mk_mut_ptr(tcx.types.u8);
328                 let fn_ty = ty::Binder::bind(tcx.mk_fn_sig(
329                     iter::once(mut_u8),
330                     tcx.mk_unit(),
331                     false,
332                     hir::Unsafety::Normal,
333                     Abi::Rust,
334                 ));
335                 (0, vec![tcx.mk_fn_ptr(fn_ty), mut_u8, mut_u8], tcx.types.i32)
336             }
337
338             "va_start" | "va_end" => {
339                 match mk_va_list_ty() {
340                     Some(va_list_ty) => (0, vec![va_list_ty], tcx.mk_unit()),
341                     None => bug!("`va_list` language item needed for C-variadic intrinsics")
342                 }
343             }
344
345             "va_copy" => {
346                 match tcx.lang_items().va_list() {
347                     Some(did) => {
348                         let region = tcx.mk_region(ty::ReLateBound(ty::INNERMOST, ty::BrAnon(0)));
349                         let env_region = ty::ReLateBound(ty::INNERMOST, ty::BrEnv);
350                         let va_list_ty = tcx.type_of(did).subst(tcx, &[region.into()]);
351                         let ret_ty = match va_list_ty.sty {
352                             ty::Adt(def, _) if def.is_struct() => {
353                                 let fields = &def.non_enum_variant().fields;
354                                 match tcx.type_of(fields[0].did).subst(tcx, &[region.into()]).sty {
355                                     ty::Ref(_, element_ty, _) => match element_ty.sty {
356                                         ty::Adt(..) => element_ty,
357                                         _ => va_list_ty
358                                     }
359                                     _ => bug!("va_list structure is invalid")
360                                 }
361                             }
362                             _ => {
363                                 bug!("va_list structure is invalid")
364                             }
365                         };
366                         (0, vec![tcx.mk_imm_ref(tcx.mk_region(env_region), va_list_ty)], ret_ty)
367                     }
368                     None => bug!("`va_list` language item needed for C-variadic intrinsics")
369                 }
370             }
371
372             "va_arg" => {
373                 match mk_va_list_ty() {
374                     Some(va_list_ty) => (1, vec![va_list_ty], param(0)),
375                     None => bug!("`va_list` language item needed for C-variadic intrinsics")
376                 }
377             }
378
379             "nontemporal_store" => {
380                 (1, vec![ tcx.mk_mut_ptr(param(0)), param(0) ], tcx.mk_unit())
381             }
382
383             ref other => {
384                 struct_span_err!(tcx.sess, it.span, E0093,
385                                  "unrecognized intrinsic function: `{}`",
386                                  *other)
387                                  .span_label(it.span, "unrecognized intrinsic")
388                                  .emit();
389                 return;
390             }
391         };
392         (n_tps, inputs, output, unsafety)
393     };
394     equate_intrinsic_type(tcx, it, n_tps, Abi::RustIntrinsic, unsafety, inputs, output)
395 }
396
397 /// Type-check `extern "platform-intrinsic" { ... }` functions.
398 pub fn check_platform_intrinsic_type<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
399                                                it: &hir::ForeignItem) {
400     let param = |n| {
401         let name = InternedString::intern(&format!("P{}", n));
402         tcx.mk_ty_param(n, name)
403     };
404
405     let name = it.ident.as_str();
406
407     let (n_tps, inputs, output) = match &*name {
408         "simd_eq" | "simd_ne" | "simd_lt" | "simd_le" | "simd_gt" | "simd_ge" => {
409             (2, vec![param(0), param(0)], param(1))
410         }
411         "simd_add" | "simd_sub" | "simd_mul" | "simd_rem" |
412         "simd_div" | "simd_shl" | "simd_shr" |
413         "simd_and" | "simd_or" | "simd_xor" |
414         "simd_fmin" | "simd_fmax" | "simd_fpow" |
415         "simd_saturating_add" | "simd_saturating_sub" => {
416             (1, vec![param(0), param(0)], param(0))
417         }
418         "simd_fsqrt" | "simd_fsin" | "simd_fcos" | "simd_fexp" | "simd_fexp2" |
419         "simd_flog2" | "simd_flog10" | "simd_flog" |
420         "simd_fabs" | "simd_floor" | "simd_ceil" => {
421             (1, vec![param(0)], param(0))
422         }
423         "simd_fpowi" => {
424             (1, vec![param(0), tcx.types.i32], param(0))
425         }
426         "simd_fma" => {
427             (1, vec![param(0), param(0), param(0)], param(0))
428         }
429         "simd_gather" => {
430             (3, vec![param(0), param(1), param(2)], param(0))
431         }
432         "simd_scatter" => {
433             (3, vec![param(0), param(1), param(2)], tcx.mk_unit())
434         }
435         "simd_insert" => (2, vec![param(0), tcx.types.u32, param(1)], param(0)),
436         "simd_extract" => (2, vec![param(0), tcx.types.u32], param(1)),
437         "simd_cast" => (2, vec![param(0)], param(1)),
438         "simd_bitmask" => (2, vec![param(0)], param(1)),
439         "simd_select" |
440         "simd_select_bitmask" => (2, vec![param(0), param(1), param(1)], param(1)),
441         "simd_reduce_all" | "simd_reduce_any" => (1, vec![param(0)], tcx.types.bool),
442         "simd_reduce_add_ordered" | "simd_reduce_mul_ordered"
443             => (2, vec![param(0), param(1)], param(1)),
444         "simd_reduce_add_unordered" | "simd_reduce_mul_unordered" |
445         "simd_reduce_and" | "simd_reduce_or"  | "simd_reduce_xor" |
446         "simd_reduce_min" | "simd_reduce_max" |
447         "simd_reduce_min_nanless" | "simd_reduce_max_nanless"
448             => (2, vec![param(0)], param(1)),
449         name if name.starts_with("simd_shuffle") => {
450             match name["simd_shuffle".len()..].parse() {
451                 Ok(n) => {
452                     let params = vec![param(0), param(0),
453                                       tcx.mk_array(tcx.types.u32, n)];
454                     (2, params, param(1))
455                 }
456                 Err(_) => {
457                     span_err!(tcx.sess, it.span, E0439,
458                               "invalid `simd_shuffle`, needs length: `{}`", name);
459                     return
460                 }
461             }
462         }
463         _ => {
464             let msg = format!("unrecognized platform-specific intrinsic function: `{}`", name);
465             tcx.sess.span_err(it.span, &msg);
466             return;
467         }
468     };
469
470     equate_intrinsic_type(tcx, it, n_tps, Abi::PlatformIntrinsic, hir::Unsafety::Unsafe,
471                           inputs, output)
472 }