]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_typeck/src/check/intrinsicck.rs
Add 'compiler/rustc_smir/' from commit '9abcb5c7b574cf316eb23d3f469187bb86ba3019'
[rust.git] / compiler / rustc_typeck / src / check / intrinsicck.rs
1 use rustc_ast::InlineAsmTemplatePiece;
2 use rustc_data_structures::stable_set::FxHashSet;
3 use rustc_errors::struct_span_err;
4 use rustc_hir as hir;
5 use rustc_index::vec::Idx;
6 use rustc_middle::ty::layout::{LayoutError, SizeSkeleton};
7 use rustc_middle::ty::{self, Article, FloatTy, InferTy, IntTy, Ty, TyCtxt, TypeFoldable, UintTy};
8 use rustc_session::lint;
9 use rustc_span::{Span, Symbol, DUMMY_SP};
10 use rustc_target::abi::{Pointer, VariantIdx};
11 use rustc_target::asm::{InlineAsmReg, InlineAsmRegClass, InlineAsmRegOrRegClass, InlineAsmType};
12 use rustc_trait_selection::infer::InferCtxtExt;
13
14 use super::FnCtxt;
15
16 /// If the type is `Option<T>`, it will return `T`, otherwise
17 /// the type itself. Works on most `Option`-like types.
18 fn unpack_option_like<'tcx>(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>) -> Ty<'tcx> {
19     let ty::Adt(def, substs) = *ty.kind() else { return ty };
20
21     if def.variants().len() == 2 && !def.repr().c() && def.repr().int.is_none() {
22         let data_idx;
23
24         let one = VariantIdx::new(1);
25         let zero = VariantIdx::new(0);
26
27         if def.variant(zero).fields.is_empty() {
28             data_idx = one;
29         } else if def.variant(one).fields.is_empty() {
30             data_idx = zero;
31         } else {
32             return ty;
33         }
34
35         if def.variant(data_idx).fields.len() == 1 {
36             return def.variant(data_idx).fields[0].ty(tcx, substs);
37         }
38     }
39
40     ty
41 }
42
43 impl<'a, 'tcx> FnCtxt<'a, 'tcx> {
44     pub fn check_transmute(&self, span: Span, from: Ty<'tcx>, to: Ty<'tcx>) {
45         let convert = |ty: Ty<'tcx>| {
46             let ty = self.resolve_vars_if_possible(ty);
47             let ty = self.tcx.normalize_erasing_regions(self.param_env, ty);
48             (SizeSkeleton::compute(ty, self.tcx, self.param_env), ty)
49         };
50         let (sk_from, from) = convert(from);
51         let (sk_to, to) = convert(to);
52
53         // Check for same size using the skeletons.
54         if let (Ok(sk_from), Ok(sk_to)) = (sk_from, sk_to) {
55             if sk_from.same_size(sk_to) {
56                 return;
57             }
58
59             // Special-case transmuting from `typeof(function)` and
60             // `Option<typeof(function)>` to present a clearer error.
61             let from = unpack_option_like(self.tcx, from);
62             if let (&ty::FnDef(..), SizeSkeleton::Known(size_to)) = (from.kind(), sk_to) && size_to == Pointer.size(&self.tcx) {
63                 struct_span_err!(self.tcx.sess, span, E0591, "can't transmute zero-sized type")
64                     .note(&format!("source type: {from}"))
65                     .note(&format!("target type: {to}"))
66                     .help("cast with `as` to a pointer instead")
67                     .emit();
68                 return;
69             }
70         }
71
72         // Try to display a sensible error with as much information as possible.
73         let skeleton_string = |ty: Ty<'tcx>, sk| match sk {
74             Ok(SizeSkeleton::Known(size)) => format!("{} bits", size.bits()),
75             Ok(SizeSkeleton::Pointer { tail, .. }) => format!("pointer to `{tail}`"),
76             Err(LayoutError::Unknown(bad)) => {
77                 if bad == ty {
78                     "this type does not have a fixed size".to_owned()
79                 } else {
80                     format!("size can vary because of {bad}")
81                 }
82             }
83             Err(err) => err.to_string(),
84         };
85
86         let mut err = struct_span_err!(
87             self.tcx.sess,
88             span,
89             E0512,
90             "cannot transmute between types of different sizes, \
91                                         or dependently-sized types"
92         );
93         if from == to {
94             err.note(&format!("`{from}` does not have a fixed size"));
95         } else {
96             err.note(&format!("source type: `{}` ({})", from, skeleton_string(from, sk_from)))
97                 .note(&format!("target type: `{}` ({})", to, skeleton_string(to, sk_to)));
98         }
99         err.emit();
100     }
101
102     fn is_thin_ptr_ty(&self, ty: Ty<'tcx>) -> bool {
103         if ty.is_sized(self.tcx.at(DUMMY_SP), self.param_env) {
104             return true;
105         }
106         if let ty::Foreign(..) = ty.kind() {
107             return true;
108         }
109         false
110     }
111
112     fn check_asm_operand_type(
113         &self,
114         idx: usize,
115         reg: InlineAsmRegOrRegClass,
116         expr: &hir::Expr<'tcx>,
117         template: &[InlineAsmTemplatePiece],
118         is_input: bool,
119         tied_input: Option<(&hir::Expr<'tcx>, Option<InlineAsmType>)>,
120         target_features: &FxHashSet<Symbol>,
121     ) -> Option<InlineAsmType> {
122         // Check the type against the allowed types for inline asm.
123         let ty = self.typeck_results.borrow().expr_ty_adjusted(expr);
124         let ty = self.resolve_vars_if_possible(ty);
125         let asm_ty_isize = match self.tcx.sess.target.pointer_width {
126             16 => InlineAsmType::I16,
127             32 => InlineAsmType::I32,
128             64 => InlineAsmType::I64,
129             _ => unreachable!(),
130         };
131         let asm_ty = match *ty.kind() {
132             // `!` is allowed for input but not for output (issue #87802)
133             ty::Never if is_input => return None,
134             ty::Error(_) => return None,
135             ty::Int(IntTy::I8) | ty::Uint(UintTy::U8) => Some(InlineAsmType::I8),
136             ty::Int(IntTy::I16) | ty::Uint(UintTy::U16) => Some(InlineAsmType::I16),
137             // Somewhat of a hack: fallback in the presence of errors does not actually
138             // fall back to i32, but to ty::Error. For integer inference variables this
139             // means that they don't get any fallback and stay as `{integer}`.
140             // Since compilation can't succeed anyway, it's fine to use this to avoid printing
141             // "cannot use value of type `{integer}`", even though that would absolutely
142             // work due due i32 fallback if the current function had no other errors.
143             ty::Infer(InferTy::IntVar(_)) => {
144                 assert!(self.is_tainted_by_errors());
145                 Some(InlineAsmType::I32)
146             }
147             ty::Int(IntTy::I32) | ty::Uint(UintTy::U32) => Some(InlineAsmType::I32),
148             ty::Int(IntTy::I64) | ty::Uint(UintTy::U64) => Some(InlineAsmType::I64),
149             ty::Int(IntTy::I128) | ty::Uint(UintTy::U128) => Some(InlineAsmType::I128),
150             ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => Some(asm_ty_isize),
151             ty::Infer(InferTy::FloatVar(_)) => {
152                 assert!(self.is_tainted_by_errors());
153                 Some(InlineAsmType::F32)
154             }
155             ty::Float(FloatTy::F32) => Some(InlineAsmType::F32),
156             ty::Float(FloatTy::F64) => Some(InlineAsmType::F64),
157             ty::FnPtr(_) => Some(asm_ty_isize),
158             ty::RawPtr(ty::TypeAndMut { ty, mutbl: _ }) if self.is_thin_ptr_ty(ty) => {
159                 Some(asm_ty_isize)
160             }
161             ty::Adt(adt, substs) if adt.repr().simd() => {
162                 let fields = &adt.non_enum_variant().fields;
163                 let elem_ty = fields[0].ty(self.tcx, substs);
164                 match elem_ty.kind() {
165                     ty::Never | ty::Error(_) => return None,
166                     ty::Int(IntTy::I8) | ty::Uint(UintTy::U8) => {
167                         Some(InlineAsmType::VecI8(fields.len() as u64))
168                     }
169                     ty::Int(IntTy::I16) | ty::Uint(UintTy::U16) => {
170                         Some(InlineAsmType::VecI16(fields.len() as u64))
171                     }
172                     ty::Int(IntTy::I32) | ty::Uint(UintTy::U32) => {
173                         Some(InlineAsmType::VecI32(fields.len() as u64))
174                     }
175                     ty::Int(IntTy::I64) | ty::Uint(UintTy::U64) => {
176                         Some(InlineAsmType::VecI64(fields.len() as u64))
177                     }
178                     ty::Int(IntTy::I128) | ty::Uint(UintTy::U128) => {
179                         Some(InlineAsmType::VecI128(fields.len() as u64))
180                     }
181                     ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => {
182                         Some(match self.tcx.sess.target.pointer_width {
183                             16 => InlineAsmType::VecI16(fields.len() as u64),
184                             32 => InlineAsmType::VecI32(fields.len() as u64),
185                             64 => InlineAsmType::VecI64(fields.len() as u64),
186                             _ => unreachable!(),
187                         })
188                     }
189                     ty::Float(FloatTy::F32) => Some(InlineAsmType::VecF32(fields.len() as u64)),
190                     ty::Float(FloatTy::F64) => Some(InlineAsmType::VecF64(fields.len() as u64)),
191                     _ => None,
192                 }
193             }
194             _ => None,
195         };
196         let Some(asm_ty) = asm_ty else {
197             let msg = &format!("cannot use value of type `{ty}` for inline assembly");
198             let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
199             err.note(
200                 "only integers, floats, SIMD vectors, pointers and function pointers \
201                  can be used as arguments for inline assembly",
202             );
203             err.emit();
204             return None;
205         };
206
207         if ty.has_infer_types_or_consts() {
208             assert!(self.is_tainted_by_errors());
209             return None;
210         }
211
212         // Check that the type implements Copy. The only case where this can
213         // possibly fail is for SIMD types which don't #[derive(Copy)].
214         if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, DUMMY_SP) {
215             let msg = "arguments for inline assembly must be copyable";
216             let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
217             err.note(&format!("`{ty}` does not implement the Copy trait"));
218             err.emit();
219         }
220
221         // Ideally we wouldn't need to do this, but LLVM's register allocator
222         // really doesn't like it when tied operands have different types.
223         //
224         // This is purely an LLVM limitation, but we have to live with it since
225         // there is no way to hide this with implicit conversions.
226         //
227         // For the purposes of this check we only look at the `InlineAsmType`,
228         // which means that pointers and integers are treated as identical (modulo
229         // size).
230         if let Some((in_expr, Some(in_asm_ty))) = tied_input {
231             if in_asm_ty != asm_ty {
232                 let msg = "incompatible types for asm inout argument";
233                 let mut err = self.tcx.sess.struct_span_err(vec![in_expr.span, expr.span], msg);
234
235                 let in_expr_ty = self.typeck_results.borrow().expr_ty_adjusted(in_expr);
236                 let in_expr_ty = self.resolve_vars_if_possible(in_expr_ty);
237                 err.span_label(in_expr.span, &format!("type `{in_expr_ty}`"));
238                 err.span_label(expr.span, &format!("type `{ty}`"));
239                 err.note(
240                     "asm inout arguments must have the same type, \
241                     unless they are both pointers or integers of the same size",
242                 );
243                 err.emit();
244             }
245
246             // All of the later checks have already been done on the input, so
247             // let's not emit errors and warnings twice.
248             return Some(asm_ty);
249         }
250
251         // Check the type against the list of types supported by the selected
252         // register class.
253         let asm_arch = self.tcx.sess.asm_arch.unwrap();
254         let reg_class = reg.reg_class();
255         let supported_tys = reg_class.supported_types(asm_arch);
256         let Some((_, feature)) = supported_tys.iter().find(|&&(t, _)| t == asm_ty) else {
257             let msg = &format!("type `{ty}` cannot be used with this register class");
258             let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
259             let supported_tys: Vec<_> =
260                 supported_tys.iter().map(|(t, _)| t.to_string()).collect();
261             err.note(&format!(
262                 "register class `{}` supports these types: {}",
263                 reg_class.name(),
264                 supported_tys.join(", "),
265             ));
266             if let Some(suggest) = reg_class.suggest_class(asm_arch, asm_ty) {
267                 err.help(&format!(
268                     "consider using the `{}` register class instead",
269                     suggest.name()
270                 ));
271             }
272             err.emit();
273             return Some(asm_ty);
274         };
275
276         // Check whether the selected type requires a target feature. Note that
277         // this is different from the feature check we did earlier. While the
278         // previous check checked that this register class is usable at all
279         // with the currently enabled features, some types may only be usable
280         // with a register class when a certain feature is enabled. We check
281         // this here since it depends on the results of typeck.
282         //
283         // Also note that this check isn't run when the operand type is never
284         // (!). In that case we still need the earlier check to verify that the
285         // register class is usable at all.
286         if let Some(feature) = feature {
287             if !target_features.contains(&feature) {
288                 let msg = &format!("`{}` target feature is not enabled", feature);
289                 let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
290                 err.note(&format!(
291                     "this is required to use type `{}` with register class `{}`",
292                     ty,
293                     reg_class.name(),
294                 ));
295                 err.emit();
296                 return Some(asm_ty);
297             }
298         }
299
300         // Check whether a modifier is suggested for using this type.
301         if let Some((suggested_modifier, suggested_result)) =
302             reg_class.suggest_modifier(asm_arch, asm_ty)
303         {
304             // Search for any use of this operand without a modifier and emit
305             // the suggestion for them.
306             let mut spans = vec![];
307             for piece in template {
308                 if let &InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span } = piece
309                 {
310                     if operand_idx == idx && modifier.is_none() {
311                         spans.push(span);
312                     }
313                 }
314             }
315             if !spans.is_empty() {
316                 let (default_modifier, default_result) =
317                     reg_class.default_modifier(asm_arch).unwrap();
318                 self.tcx.struct_span_lint_hir(
319                     lint::builtin::ASM_SUB_REGISTER,
320                     expr.hir_id,
321                     spans,
322                     |lint| {
323                         let msg = "formatting may not be suitable for sub-register argument";
324                         let mut err = lint.build(msg);
325                         err.span_label(expr.span, "for this argument");
326                         err.help(&format!(
327                             "use the `{suggested_modifier}` modifier to have the register formatted as `{suggested_result}`",
328                         ));
329                         err.help(&format!(
330                             "or use the `{default_modifier}` modifier to keep the default formatting of `{default_result}`",
331                         ));
332                         err.emit();
333                     },
334                 );
335             }
336         }
337
338         Some(asm_ty)
339     }
340
341     pub fn check_asm(&self, asm: &hir::InlineAsm<'tcx>, enclosing_id: hir::HirId) {
342         let hir = self.tcx.hir();
343         let enclosing_def_id = hir.local_def_id(enclosing_id).to_def_id();
344         let target_features = self.tcx.asm_target_features(enclosing_def_id);
345         let Some(asm_arch) = self.tcx.sess.asm_arch else {
346             self.tcx.sess.delay_span_bug(DUMMY_SP, "target architecture does not support asm");
347             return;
348         };
349         for (idx, (op, op_sp)) in asm.operands.iter().enumerate() {
350             // Validate register classes against currently enabled target
351             // features. We check that at least one type is available for
352             // the enabled features.
353             //
354             // We ignore target feature requirements for clobbers: if the
355             // feature is disabled then the compiler doesn't care what we
356             // do with the registers.
357             //
358             // Note that this is only possible for explicit register
359             // operands, which cannot be used in the asm string.
360             if let Some(reg) = op.reg() {
361                 // Some explicit registers cannot be used depending on the
362                 // target. Reject those here.
363                 if let InlineAsmRegOrRegClass::Reg(reg) = reg {
364                     if let InlineAsmReg::Err = reg {
365                         // `validate` will panic on `Err`, as an error must
366                         // already have been reported.
367                         continue;
368                     }
369                     if let Err(msg) = reg.validate(
370                         asm_arch,
371                         self.tcx.sess.relocation_model(),
372                         &target_features,
373                         &self.tcx.sess.target,
374                         op.is_clobber(),
375                     ) {
376                         let msg = format!("cannot use register `{}`: {}", reg.name(), msg);
377                         self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
378                         continue;
379                     }
380                 }
381
382                 if !op.is_clobber() {
383                     let mut missing_required_features = vec![];
384                     let reg_class = reg.reg_class();
385                     if let InlineAsmRegClass::Err = reg_class {
386                         continue;
387                     }
388                     for &(_, feature) in reg_class.supported_types(asm_arch) {
389                         match feature {
390                             Some(feature) => {
391                                 if target_features.contains(&feature) {
392                                     missing_required_features.clear();
393                                     break;
394                                 } else {
395                                     missing_required_features.push(feature);
396                                 }
397                             }
398                             None => {
399                                 missing_required_features.clear();
400                                 break;
401                             }
402                         }
403                     }
404
405                     // We are sorting primitive strs here and can use unstable sort here
406                     missing_required_features.sort_unstable();
407                     missing_required_features.dedup();
408                     match &missing_required_features[..] {
409                         [] => {}
410                         [feature] => {
411                             let msg = format!(
412                                 "register class `{}` requires the `{}` target feature",
413                                 reg_class.name(),
414                                 feature
415                             );
416                             self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
417                             // register isn't enabled, don't do more checks
418                             continue;
419                         }
420                         features => {
421                             let msg = format!(
422                                 "register class `{}` requires at least one of the following target features: {}",
423                                 reg_class.name(),
424                                 features
425                                     .iter()
426                                     .map(|f| f.as_str())
427                                     .intersperse(", ")
428                                     .collect::<String>(),
429                             );
430                             self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
431                             // register isn't enabled, don't do more checks
432                             continue;
433                         }
434                     }
435                 }
436             }
437
438             match *op {
439                 hir::InlineAsmOperand::In { reg, ref expr } => {
440                     self.check_asm_operand_type(
441                         idx,
442                         reg,
443                         expr,
444                         asm.template,
445                         true,
446                         None,
447                         &target_features,
448                     );
449                 }
450                 hir::InlineAsmOperand::Out { reg, late: _, ref expr } => {
451                     if let Some(expr) = expr {
452                         self.check_asm_operand_type(
453                             idx,
454                             reg,
455                             expr,
456                             asm.template,
457                             false,
458                             None,
459                             &target_features,
460                         );
461                     }
462                 }
463                 hir::InlineAsmOperand::InOut { reg, late: _, ref expr } => {
464                     self.check_asm_operand_type(
465                         idx,
466                         reg,
467                         expr,
468                         asm.template,
469                         false,
470                         None,
471                         &target_features,
472                     );
473                 }
474                 hir::InlineAsmOperand::SplitInOut { reg, late: _, ref in_expr, ref out_expr } => {
475                     let in_ty = self.check_asm_operand_type(
476                         idx,
477                         reg,
478                         in_expr,
479                         asm.template,
480                         true,
481                         None,
482                         &target_features,
483                     );
484                     if let Some(out_expr) = out_expr {
485                         self.check_asm_operand_type(
486                             idx,
487                             reg,
488                             out_expr,
489                             asm.template,
490                             false,
491                             Some((in_expr, in_ty)),
492                             &target_features,
493                         );
494                     }
495                 }
496                 // No special checking is needed for these:
497                 // - Typeck has checked that Const operands are integers.
498                 // - AST lowering guarantees that SymStatic points to a static.
499                 hir::InlineAsmOperand::Const { .. } | hir::InlineAsmOperand::SymStatic { .. } => {}
500                 // Check that sym actually points to a function. Later passes
501                 // depend on this.
502                 hir::InlineAsmOperand::SymFn { anon_const } => {
503                     let ty = self.tcx.typeck_body(anon_const.body).node_type(anon_const.hir_id);
504                     match ty.kind() {
505                         ty::Never | ty::Error(_) => {}
506                         ty::FnDef(..) => {}
507                         _ => {
508                             let mut err =
509                                 self.tcx.sess.struct_span_err(*op_sp, "invalid `sym` operand");
510                             err.span_label(
511                                 self.tcx.hir().span(anon_const.body.hir_id),
512                                 &format!("is {} `{}`", ty.kind().article(), ty),
513                             );
514                             err.help("`sym` operands must refer to either a function or a static");
515                             err.emit();
516                         }
517                     };
518                 }
519             }
520         }
521     }
522 }