]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_hir_analysis/src/check/intrinsicck.rs
Auto merge of #107843 - bjorn3:sync_cg_clif-2023-02-09, r=bjorn3
[rust.git] / compiler / rustc_hir_analysis / src / check / intrinsicck.rs
1 use rustc_ast::InlineAsmTemplatePiece;
2 use rustc_data_structures::fx::FxHashSet;
3 use rustc_hir as hir;
4 use rustc_middle::ty::{self, Article, FloatTy, IntTy, Ty, TyCtxt, TypeVisitable, UintTy};
5 use rustc_session::lint;
6 use rustc_span::def_id::LocalDefId;
7 use rustc_span::{Symbol, DUMMY_SP};
8 use rustc_target::asm::{InlineAsmReg, InlineAsmRegClass, InlineAsmRegOrRegClass, InlineAsmType};
9
10 pub struct InlineAsmCtxt<'a, 'tcx> {
11     tcx: TyCtxt<'tcx>,
12     param_env: ty::ParamEnv<'tcx>,
13     get_operand_ty: Box<dyn Fn(&'tcx hir::Expr<'tcx>) -> Ty<'tcx> + 'a>,
14 }
15
16 impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
17     pub fn new_global_asm(tcx: TyCtxt<'tcx>) -> Self {
18         InlineAsmCtxt {
19             tcx,
20             param_env: ty::ParamEnv::empty(),
21             get_operand_ty: Box::new(|e| bug!("asm operand in global asm: {e:?}")),
22         }
23     }
24
25     pub fn new_in_fn(
26         tcx: TyCtxt<'tcx>,
27         param_env: ty::ParamEnv<'tcx>,
28         get_operand_ty: impl Fn(&'tcx hir::Expr<'tcx>) -> Ty<'tcx> + 'a,
29     ) -> Self {
30         InlineAsmCtxt { tcx, param_env, get_operand_ty: Box::new(get_operand_ty) }
31     }
32
33     // FIXME(compiler-errors): This could use `<$ty as Pointee>::Metadata == ()`
34     fn is_thin_ptr_ty(&self, ty: Ty<'tcx>) -> bool {
35         // Type still may have region variables, but `Sized` does not depend
36         // on those, so just erase them before querying.
37         if ty.is_sized(self.tcx, self.param_env) {
38             return true;
39         }
40         if let ty::Foreign(..) = ty.kind() {
41             return true;
42         }
43         false
44     }
45
46     fn check_asm_operand_type(
47         &self,
48         idx: usize,
49         reg: InlineAsmRegOrRegClass,
50         expr: &'tcx hir::Expr<'tcx>,
51         template: &[InlineAsmTemplatePiece],
52         is_input: bool,
53         tied_input: Option<(&'tcx hir::Expr<'tcx>, Option<InlineAsmType>)>,
54         target_features: &FxHashSet<Symbol>,
55     ) -> Option<InlineAsmType> {
56         let ty = (self.get_operand_ty)(expr);
57         if ty.has_non_region_infer() {
58             bug!("inference variable in asm operand ty: {:?} {:?}", expr, ty);
59         }
60         let asm_ty_isize = match self.tcx.sess.target.pointer_width {
61             16 => InlineAsmType::I16,
62             32 => InlineAsmType::I32,
63             64 => InlineAsmType::I64,
64             _ => unreachable!(),
65         };
66
67         let asm_ty = match *ty.kind() {
68             // `!` is allowed for input but not for output (issue #87802)
69             ty::Never if is_input => return None,
70             ty::Error(_) => return None,
71             ty::Int(IntTy::I8) | ty::Uint(UintTy::U8) => Some(InlineAsmType::I8),
72             ty::Int(IntTy::I16) | ty::Uint(UintTy::U16) => Some(InlineAsmType::I16),
73             ty::Int(IntTy::I32) | ty::Uint(UintTy::U32) => Some(InlineAsmType::I32),
74             ty::Int(IntTy::I64) | ty::Uint(UintTy::U64) => Some(InlineAsmType::I64),
75             ty::Int(IntTy::I128) | ty::Uint(UintTy::U128) => Some(InlineAsmType::I128),
76             ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => Some(asm_ty_isize),
77             ty::Float(FloatTy::F32) => Some(InlineAsmType::F32),
78             ty::Float(FloatTy::F64) => Some(InlineAsmType::F64),
79             ty::FnPtr(_) => Some(asm_ty_isize),
80             ty::RawPtr(ty::TypeAndMut { ty, mutbl: _ }) if self.is_thin_ptr_ty(ty) => {
81                 Some(asm_ty_isize)
82             }
83             ty::Adt(adt, substs) if adt.repr().simd() => {
84                 let fields = &adt.non_enum_variant().fields;
85                 let elem_ty = fields[0].ty(self.tcx, substs);
86                 match elem_ty.kind() {
87                     ty::Never | ty::Error(_) => return None,
88                     ty::Int(IntTy::I8) | ty::Uint(UintTy::U8) => {
89                         Some(InlineAsmType::VecI8(fields.len() as u64))
90                     }
91                     ty::Int(IntTy::I16) | ty::Uint(UintTy::U16) => {
92                         Some(InlineAsmType::VecI16(fields.len() as u64))
93                     }
94                     ty::Int(IntTy::I32) | ty::Uint(UintTy::U32) => {
95                         Some(InlineAsmType::VecI32(fields.len() as u64))
96                     }
97                     ty::Int(IntTy::I64) | ty::Uint(UintTy::U64) => {
98                         Some(InlineAsmType::VecI64(fields.len() as u64))
99                     }
100                     ty::Int(IntTy::I128) | ty::Uint(UintTy::U128) => {
101                         Some(InlineAsmType::VecI128(fields.len() as u64))
102                     }
103                     ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => {
104                         Some(match self.tcx.sess.target.pointer_width {
105                             16 => InlineAsmType::VecI16(fields.len() as u64),
106                             32 => InlineAsmType::VecI32(fields.len() as u64),
107                             64 => InlineAsmType::VecI64(fields.len() as u64),
108                             _ => unreachable!(),
109                         })
110                     }
111                     ty::Float(FloatTy::F32) => Some(InlineAsmType::VecF32(fields.len() as u64)),
112                     ty::Float(FloatTy::F64) => Some(InlineAsmType::VecF64(fields.len() as u64)),
113                     _ => None,
114                 }
115             }
116             ty::Infer(_) => unreachable!(),
117             _ => None,
118         };
119         let Some(asm_ty) = asm_ty else {
120             let msg = &format!("cannot use value of type `{ty}` for inline assembly");
121             let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
122             err.note(
123                 "only integers, floats, SIMD vectors, pointers and function pointers \
124                  can be used as arguments for inline assembly",
125             );
126             err.emit();
127             return None;
128         };
129
130         // Check that the type implements Copy. The only case where this can
131         // possibly fail is for SIMD types which don't #[derive(Copy)].
132         if !ty.is_copy_modulo_regions(self.tcx, self.param_env) {
133             let msg = "arguments for inline assembly must be copyable";
134             let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
135             err.note(&format!("`{ty}` does not implement the Copy trait"));
136             err.emit();
137         }
138
139         // Ideally we wouldn't need to do this, but LLVM's register allocator
140         // really doesn't like it when tied operands have different types.
141         //
142         // This is purely an LLVM limitation, but we have to live with it since
143         // there is no way to hide this with implicit conversions.
144         //
145         // For the purposes of this check we only look at the `InlineAsmType`,
146         // which means that pointers and integers are treated as identical (modulo
147         // size).
148         if let Some((in_expr, Some(in_asm_ty))) = tied_input {
149             if in_asm_ty != asm_ty {
150                 let msg = "incompatible types for asm inout argument";
151                 let mut err = self.tcx.sess.struct_span_err(vec![in_expr.span, expr.span], msg);
152
153                 let in_expr_ty = (self.get_operand_ty)(in_expr);
154                 err.span_label(in_expr.span, &format!("type `{in_expr_ty}`"));
155                 err.span_label(expr.span, &format!("type `{ty}`"));
156                 err.note(
157                     "asm inout arguments must have the same type, \
158                     unless they are both pointers or integers of the same size",
159                 );
160                 err.emit();
161             }
162
163             // All of the later checks have already been done on the input, so
164             // let's not emit errors and warnings twice.
165             return Some(asm_ty);
166         }
167
168         // Check the type against the list of types supported by the selected
169         // register class.
170         let asm_arch = self.tcx.sess.asm_arch.unwrap();
171         let reg_class = reg.reg_class();
172         let supported_tys = reg_class.supported_types(asm_arch);
173         let Some((_, feature)) = supported_tys.iter().find(|&&(t, _)| t == asm_ty) else {
174             let msg = &format!("type `{ty}` cannot be used with this register class");
175             let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
176             let supported_tys: Vec<_> =
177                 supported_tys.iter().map(|(t, _)| t.to_string()).collect();
178             err.note(&format!(
179                 "register class `{}` supports these types: {}",
180                 reg_class.name(),
181                 supported_tys.join(", "),
182             ));
183             if let Some(suggest) = reg_class.suggest_class(asm_arch, asm_ty) {
184                 err.help(&format!(
185                     "consider using the `{}` register class instead",
186                     suggest.name()
187                 ));
188             }
189             err.emit();
190             return Some(asm_ty);
191         };
192
193         // Check whether the selected type requires a target feature. Note that
194         // this is different from the feature check we did earlier. While the
195         // previous check checked that this register class is usable at all
196         // with the currently enabled features, some types may only be usable
197         // with a register class when a certain feature is enabled. We check
198         // this here since it depends on the results of typeck.
199         //
200         // Also note that this check isn't run when the operand type is never
201         // (!). In that case we still need the earlier check to verify that the
202         // register class is usable at all.
203         if let Some(feature) = feature {
204             if !target_features.contains(&feature) {
205                 let msg = &format!("`{}` target feature is not enabled", feature);
206                 let mut err = self.tcx.sess.struct_span_err(expr.span, msg);
207                 err.note(&format!(
208                     "this is required to use type `{}` with register class `{}`",
209                     ty,
210                     reg_class.name(),
211                 ));
212                 err.emit();
213                 return Some(asm_ty);
214             }
215         }
216
217         // Check whether a modifier is suggested for using this type.
218         if let Some((suggested_modifier, suggested_result)) =
219             reg_class.suggest_modifier(asm_arch, asm_ty)
220         {
221             // Search for any use of this operand without a modifier and emit
222             // the suggestion for them.
223             let mut spans = vec![];
224             for piece in template {
225                 if let &InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span } = piece
226                 {
227                     if operand_idx == idx && modifier.is_none() {
228                         spans.push(span);
229                     }
230                 }
231             }
232             if !spans.is_empty() {
233                 let (default_modifier, default_result) =
234                     reg_class.default_modifier(asm_arch).unwrap();
235                 self.tcx.struct_span_lint_hir(
236                     lint::builtin::ASM_SUB_REGISTER,
237                     expr.hir_id,
238                     spans,
239                     "formatting may not be suitable for sub-register argument",
240                     |lint| {
241                         lint.span_label(expr.span, "for this argument");
242                         lint.help(&format!(
243                             "use `{{{idx}:{suggested_modifier}}}` to have the register formatted as `{suggested_result}`",
244                         ));
245                         lint.help(&format!(
246                             "or use `{{{idx}:{default_modifier}}}` to keep the default formatting of `{default_result}`",
247                         ));
248                         lint
249                     },
250                 );
251             }
252         }
253
254         Some(asm_ty)
255     }
256
257     pub fn check_asm(&self, asm: &hir::InlineAsm<'tcx>, enclosing_id: LocalDefId) {
258         let target_features = self.tcx.asm_target_features(enclosing_id.to_def_id());
259         let Some(asm_arch) = self.tcx.sess.asm_arch else {
260             self.tcx.sess.delay_span_bug(DUMMY_SP, "target architecture does not support asm");
261             return;
262         };
263         for (idx, (op, op_sp)) in asm.operands.iter().enumerate() {
264             // Validate register classes against currently enabled target
265             // features. We check that at least one type is available for
266             // the enabled features.
267             //
268             // We ignore target feature requirements for clobbers: if the
269             // feature is disabled then the compiler doesn't care what we
270             // do with the registers.
271             //
272             // Note that this is only possible for explicit register
273             // operands, which cannot be used in the asm string.
274             if let Some(reg) = op.reg() {
275                 // Some explicit registers cannot be used depending on the
276                 // target. Reject those here.
277                 if let InlineAsmRegOrRegClass::Reg(reg) = reg {
278                     if let InlineAsmReg::Err = reg {
279                         // `validate` will panic on `Err`, as an error must
280                         // already have been reported.
281                         continue;
282                     }
283                     if let Err(msg) = reg.validate(
284                         asm_arch,
285                         self.tcx.sess.relocation_model(),
286                         &target_features,
287                         &self.tcx.sess.target,
288                         op.is_clobber(),
289                     ) {
290                         let msg = format!("cannot use register `{}`: {}", reg.name(), msg);
291                         self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
292                         continue;
293                     }
294                 }
295
296                 if !op.is_clobber() {
297                     let mut missing_required_features = vec![];
298                     let reg_class = reg.reg_class();
299                     if let InlineAsmRegClass::Err = reg_class {
300                         continue;
301                     }
302                     for &(_, feature) in reg_class.supported_types(asm_arch) {
303                         match feature {
304                             Some(feature) => {
305                                 if target_features.contains(&feature) {
306                                     missing_required_features.clear();
307                                     break;
308                                 } else {
309                                     missing_required_features.push(feature);
310                                 }
311                             }
312                             None => {
313                                 missing_required_features.clear();
314                                 break;
315                             }
316                         }
317                     }
318
319                     // We are sorting primitive strs here and can use unstable sort here
320                     missing_required_features.sort_unstable();
321                     missing_required_features.dedup();
322                     match &missing_required_features[..] {
323                         [] => {}
324                         [feature] => {
325                             let msg = format!(
326                                 "register class `{}` requires the `{}` target feature",
327                                 reg_class.name(),
328                                 feature
329                             );
330                             self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
331                             // register isn't enabled, don't do more checks
332                             continue;
333                         }
334                         features => {
335                             let msg = format!(
336                                 "register class `{}` requires at least one of the following target features: {}",
337                                 reg_class.name(),
338                                 features
339                                     .iter()
340                                     .map(|f| f.as_str())
341                                     .intersperse(", ")
342                                     .collect::<String>(),
343                             );
344                             self.tcx.sess.struct_span_err(*op_sp, &msg).emit();
345                             // register isn't enabled, don't do more checks
346                             continue;
347                         }
348                     }
349                 }
350             }
351
352             match *op {
353                 hir::InlineAsmOperand::In { reg, expr } => {
354                     self.check_asm_operand_type(
355                         idx,
356                         reg,
357                         expr,
358                         asm.template,
359                         true,
360                         None,
361                         &target_features,
362                     );
363                 }
364                 hir::InlineAsmOperand::Out { reg, late: _, expr } => {
365                     if let Some(expr) = expr {
366                         self.check_asm_operand_type(
367                             idx,
368                             reg,
369                             expr,
370                             asm.template,
371                             false,
372                             None,
373                             &target_features,
374                         );
375                     }
376                 }
377                 hir::InlineAsmOperand::InOut { reg, late: _, expr } => {
378                     self.check_asm_operand_type(
379                         idx,
380                         reg,
381                         expr,
382                         asm.template,
383                         false,
384                         None,
385                         &target_features,
386                     );
387                 }
388                 hir::InlineAsmOperand::SplitInOut { reg, late: _, in_expr, out_expr } => {
389                     let in_ty = self.check_asm_operand_type(
390                         idx,
391                         reg,
392                         in_expr,
393                         asm.template,
394                         true,
395                         None,
396                         &target_features,
397                     );
398                     if let Some(out_expr) = out_expr {
399                         self.check_asm_operand_type(
400                             idx,
401                             reg,
402                             out_expr,
403                             asm.template,
404                             false,
405                             Some((in_expr, in_ty)),
406                             &target_features,
407                         );
408                     }
409                 }
410                 // No special checking is needed for these:
411                 // - Typeck has checked that Const operands are integers.
412                 // - AST lowering guarantees that SymStatic points to a static.
413                 hir::InlineAsmOperand::Const { .. } | hir::InlineAsmOperand::SymStatic { .. } => {}
414                 // Check that sym actually points to a function. Later passes
415                 // depend on this.
416                 hir::InlineAsmOperand::SymFn { anon_const } => {
417                     let ty = self.tcx.typeck_body(anon_const.body).node_type(anon_const.hir_id);
418                     match ty.kind() {
419                         ty::Never | ty::Error(_) => {}
420                         ty::FnDef(..) => {}
421                         _ => {
422                             let mut err =
423                                 self.tcx.sess.struct_span_err(*op_sp, "invalid `sym` operand");
424                             err.span_label(
425                                 self.tcx.hir().span(anon_const.body.hir_id),
426                                 &format!("is {} `{}`", ty.kind().article(), ty),
427                             );
428                             err.help("`sym` operands must refer to either a function or a static");
429                             err.emit();
430                         }
431                     };
432                 }
433             }
434         }
435     }
436 }