Skip to main content

rustc_hir_typeck/
inline_asm.rs

1use rustc_abi::FieldIdx;
2use rustc_ast::InlineAsmTemplatePiece;
3use rustc_data_structures::fx::FxIndexSet;
4use rustc_errors::{Diag, DiagCtxtHandle, Diagnostic, Level};
5use rustc_hir as hir;
6use rustc_hir::attrs::lang_items::LangItem;
7use rustc_hir::def_id::DefId;
8use rustc_lint_defs::builtin::ASM_SUB_REGISTER;
9use rustc_middle::ty::{
10    self, Article, FloatTy, IntTy, Ty, TyCtxt, TypeVisitableExt, UintTy, Unnormalized,
11};
12use rustc_span::def_id::LocalDefId;
13use rustc_span::{ErrorGuaranteed, Span, Symbol, bug, sym};
14use rustc_target::asm::{
15    InlineAsmReg, InlineAsmRegClass, InlineAsmRegOrRegClass, InlineAsmSize, InlineAsmType,
16    ModifierInfo,
17};
18use rustc_trait_selection::infer::InferCtxtExt;
19
20use crate::FnCtxt;
21use crate::diagnostics::{AsmConstPtrUnstable, RegisterTypeUnstable};
22
23pub(crate) struct InlineAsmCtxt<'a, 'tcx> {
24    target_features: &'tcx FxIndexSet<Symbol>,
25    fcx: &'a FnCtxt<'a, 'tcx>,
26}
27
28enum NonAsmTypeReason<'tcx> {
29    UnevaluatedSIMDArrayLength(DefId, ty::Const<'tcx>),
30    Invalid(Ty<'tcx>),
31    InvalidElement(DefId, Ty<'tcx>),
32    NotSizedPtr(Ty<'tcx>),
33    EmptySIMDArray(Ty<'tcx>),
34    Tainted(ErrorGuaranteed),
35}
36
37impl<'a, 'tcx> InlineAsmCtxt<'a, 'tcx> {
38    pub(crate) fn new(fcx: &'a FnCtxt<'a, 'tcx>, def_id: LocalDefId) -> Self {
39        InlineAsmCtxt { target_features: fcx.tcx.asm_target_features(def_id), fcx }
40    }
41
42    fn tcx(&self) -> TyCtxt<'tcx> {
43        self.fcx.tcx
44    }
45
46    fn expr_ty(&self, expr: &hir::Expr<'tcx>) -> Ty<'tcx> {
47        let ty = self.fcx.typeck_results.borrow().expr_ty_adjusted(expr);
48        let ty = self.fcx.deeply_resolve_ignoring_regions_with_obligations(ty);
49        if ty.has_non_region_infer() {
50            Ty::new_misc_error(self.tcx())
51        } else {
52            self.tcx().erase_and_anonymize_regions(ty)
53        }
54    }
55
56    // FIXME(compiler-errors): This could use `<$ty as Pointee>::Metadata == ()`
57    fn is_thin_ptr_ty(&self, ty: Ty<'tcx>) -> bool {
58        // Type still may have region variables, but `Sized` does not depend
59        // on those, so just erase them before querying.
60        if self.fcx.type_is_sized_modulo_regions(self.fcx.param_env, ty) {
61            return true;
62        }
63        if let ty::Foreign(..) =
64            self.fcx.deeply_resolve_ignoring_regions_with_obligations(ty).kind()
65        {
66            return true;
67        }
68        false
69    }
70
71    fn get_asm_ty(
72        &self,
73        span: Span,
74        ty: Ty<'tcx>,
75    ) -> Result<InlineAsmType, NonAsmTypeReason<'tcx>> {
76        let asm_ty_isize = match self.tcx().sess.target.pointer_width {
77            16 => InlineAsmType::I16,
78            32 => InlineAsmType::I32,
79            64 => InlineAsmType::I64,
80            width => bug_impl(None, format_args!("unsupported pointer width: {0}", width),
    Location::caller())bug!("unsupported pointer width: {width}"),
81        };
82
83        match *ty.kind() {
84            ty::Int(IntTy::I8) | ty::Uint(UintTy::U8) => Ok(InlineAsmType::I8),
85            ty::Int(IntTy::I16) | ty::Uint(UintTy::U16) => Ok(InlineAsmType::I16),
86            ty::Int(IntTy::I32) | ty::Uint(UintTy::U32) => Ok(InlineAsmType::I32),
87            ty::Int(IntTy::I64) | ty::Uint(UintTy::U64) => Ok(InlineAsmType::I64),
88            ty::Int(IntTy::I128) | ty::Uint(UintTy::U128) => Ok(InlineAsmType::I128),
89            ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => Ok(asm_ty_isize),
90            ty::Float(FloatTy::F16) => Ok(InlineAsmType::F16),
91            ty::Float(FloatTy::F32) => Ok(InlineAsmType::F32),
92            ty::Float(FloatTy::F64) => Ok(InlineAsmType::F64),
93            ty::Float(FloatTy::F128) => Ok(InlineAsmType::F128),
94            ty::FnPtr(..) => Ok(asm_ty_isize),
95            ty::RawPtr(elem_ty, _) => {
96                if self.is_thin_ptr_ty(elem_ty) {
97                    Ok(asm_ty_isize)
98                } else {
99                    Err(NonAsmTypeReason::NotSizedPtr(ty))
100                }
101            }
102            ty::Adt(adt, args) if adt.repr().simd() => {
103                if !adt.is_struct() {
104                    let guar = self.fcx.dcx().span_delayed_bug(
105                        span,
106                        ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("repr(simd) should only be used on structs, got {0}",
                adt.descr()))
    })format!("repr(simd) should only be used on structs, got {}", adt.descr()),
107                    );
108                    return Err(NonAsmTypeReason::Tainted(guar));
109                }
110
111                let fields = &adt.non_enum_variant().fields;
112                if fields.is_empty() {
113                    return Err(NonAsmTypeReason::EmptySIMDArray(ty));
114                }
115                let field = &fields[FieldIdx::ZERO];
116                let elem_ty = field.ty(self.tcx(), args).skip_norm_wip();
117
118                let (size, ty) = match *elem_ty.kind() {
119                    ty::Array(ty, len) => {
120                        // FIXME: `try_structurally_resolve_const` doesn't eval consts
121                        // in the old solver.
122                        let len = if self.fcx.next_trait_solver() {
123                            self.fcx.try_structurally_resolve_const(span, len)
124                        } else {
125                            self.fcx.tcx.normalize_erasing_regions(
126                                self.fcx.typing_env(self.fcx.param_env),
127                                Unnormalized::new_wip(len),
128                            )
129                        };
130                        let Some(len) = len.try_to_target_usize(self.tcx()) else {
131                            return Err(NonAsmTypeReason::UnevaluatedSIMDArrayLength(
132                                field.did, len,
133                            ));
134                        };
135                        (len, ty)
136                    }
137                    _ => (fields.len() as u64, elem_ty),
138                };
139
140                match ty.kind() {
141                    ty::Int(IntTy::I8) | ty::Uint(UintTy::U8) => Ok(InlineAsmType::VecI8(size)),
142                    ty::Int(IntTy::I16) | ty::Uint(UintTy::U16) => Ok(InlineAsmType::VecI16(size)),
143                    ty::Int(IntTy::I32) | ty::Uint(UintTy::U32) => Ok(InlineAsmType::VecI32(size)),
144                    ty::Int(IntTy::I64) | ty::Uint(UintTy::U64) => Ok(InlineAsmType::VecI64(size)),
145                    ty::Int(IntTy::I128) | ty::Uint(UintTy::U128) => {
146                        Ok(InlineAsmType::VecI128(size))
147                    }
148                    ty::Int(IntTy::Isize) | ty::Uint(UintTy::Usize) => {
149                        Ok(match self.tcx().sess.target.pointer_width {
150                            16 => InlineAsmType::VecI16(size),
151                            32 => InlineAsmType::VecI32(size),
152                            64 => InlineAsmType::VecI64(size),
153                            width => bug_impl(None, format_args!("unsupported pointer width: {0}", width),
    Location::caller())bug!("unsupported pointer width: {width}"),
154                        })
155                    }
156                    ty::Float(FloatTy::F16) => Ok(InlineAsmType::VecF16(size)),
157                    ty::Float(FloatTy::F32) => Ok(InlineAsmType::VecF32(size)),
158                    ty::Float(FloatTy::F64) => Ok(InlineAsmType::VecF64(size)),
159                    ty::Float(FloatTy::F128) => Ok(InlineAsmType::VecF128(size)),
160                    _ => Err(NonAsmTypeReason::InvalidElement(field.did, ty)),
161                }
162            }
163            ty::Adt(adt, _args) if adt.repr().scalable() => {
164                let (_element_count, elem_ty, _number_of_vectors) =
165                    ty.scalable_vector_parts(self.tcx()).unwrap();
166
167                match elem_ty.kind() {
168                    ty::Int(IntTy::I8) | ty::Uint(UintTy::U8) => Ok(InlineAsmType::SveVecI8),
169                    ty::Int(IntTy::I16) | ty::Uint(UintTy::U16) => Ok(InlineAsmType::SveVecI16),
170                    ty::Int(IntTy::I32) | ty::Uint(UintTy::U32) => Ok(InlineAsmType::SveVecI32),
171                    ty::Int(IntTy::I64) | ty::Uint(UintTy::U64) => Ok(InlineAsmType::SveVecI64),
172                    ty::Int(IntTy::I128) | ty::Uint(UintTy::U128) => Ok(InlineAsmType::SveVecI128),
173                    ty::Float(FloatTy::F16) => Ok(InlineAsmType::SveVecF16),
174                    ty::Float(FloatTy::F32) => Ok(InlineAsmType::SveVecF32),
175                    ty::Float(FloatTy::F64) => Ok(InlineAsmType::SveVecF64),
176                    ty::Float(FloatTy::F128) => Ok(InlineAsmType::SveVecF128),
177                    ty::Bool => Ok(InlineAsmType::SveVecBool),
178                    _ => {
179                        let fields = &adt.non_enum_variant().fields;
180                        let field = &fields[FieldIdx::ZERO];
181                        Err(NonAsmTypeReason::InvalidElement(field.did, ty))
182                    }
183                }
184            }
185            ty::Infer(_) => bug_impl(None, format_args!("unexpected infer ty in asm operand"),
    Location::caller())bug!("unexpected infer ty in asm operand"),
186            _ => Err(NonAsmTypeReason::Invalid(ty)),
187        }
188    }
189
190    fn check_asm_operand_type(
191        &self,
192        idx: usize,
193        reg: InlineAsmRegOrRegClass,
194        expr: &'tcx hir::Expr<'tcx>,
195        template: &[InlineAsmTemplatePiece],
196        is_input: bool,
197        tied_input: Option<(&'tcx hir::Expr<'tcx>, Option<InlineAsmType>)>,
198    ) -> Option<InlineAsmType> {
199        struct FormattingSubRegisterArg<'a> {
200            expr_span: Span,
201            idx: usize,
202            suggested_modifier: char,
203            suggested_result: &'a str,
204            suggested_size: InlineAsmSize,
205            default_modifier: char,
206            default_result: &'a str,
207            default_size: InlineAsmSize,
208        }
209
210        impl<'a, 'b> Diagnostic<'a, ()> for FormattingSubRegisterArg<'b> {
211            fn into_diag(self, dcx: DiagCtxtHandle<'a>, level: Level) -> Diag<'a, ()> {
212                let Self {
213                    expr_span,
214                    idx,
215                    suggested_modifier,
216                    suggested_result,
217                    suggested_size,
218                    default_modifier,
219                    default_result,
220                    default_size,
221                } = self;
222
223                fn format_size(size: InlineAsmSize) -> String {
224                    match size {
225                        InlineAsmSize::FixedBytes(size) => ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}-byte values", size))
    })format!("{size}-byte values"),
226                        InlineAsmSize::Scalable => "scalable values".to_string(),
227                    }
228                }
229                Diag::new(dcx, level, "formatting may not be suitable for sub-register argument")
230                    .with_span_label(expr_span, "for this argument")
231                    .with_help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use `{{{1}:{2}}}` to have the register formatted as `{3}` (for {0})",
                format_size(suggested_size), idx, suggested_modifier,
                suggested_result))
    })format!(
232                        "use `{{{idx}:{suggested_modifier}}}` to have the register formatted as \
233                        `{suggested_result}` (for {})",
234                        format_size(suggested_size)
235                    ))
236                    .with_help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("or use `{{{1}:{2}}}` to keep the default formatting of `{3}` (for {0})",
                format_size(default_size), idx, default_modifier,
                default_result))
    })format!(
237                        "or use `{{{idx}:{default_modifier}}}` to keep the default formatting of \
238                        `{default_result}` (for {})",
239                        format_size(default_size)
240                    ))
241            }
242        }
243
244        let ty = self.expr_ty(expr);
245        if ty.has_non_region_infer() {
246            bug_impl(None,
    format_args!("inference variable in asm operand ty: {0:?} {1:?}", expr,
        ty), Location::caller());bug!("inference variable in asm operand ty: {:?} {:?}", expr, ty);
247        }
248
249        let asm_ty = match *ty.kind() {
250            // `!` is allowed for input but not for output (issue #87802)
251            ty::Never if is_input => return None,
252            _ if ty.references_error() => return None,
253            ty::Adt(adt, args) if self.tcx().is_lang_item(adt.did(), LangItem::MaybeUninit) => {
254                let ty = args.type_at(0);
255                self.get_asm_ty(expr.span, ty)
256            }
257            _ => self.get_asm_ty(expr.span, ty),
258        };
259        let asm_ty = match asm_ty {
260            Ok(asm_ty) => asm_ty,
261            Err(reason) => {
262                match reason {
263                    NonAsmTypeReason::UnevaluatedSIMDArrayLength(did, len) => {
264                        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot evaluate SIMD vector length `{0}`",
                len))
    })format!("cannot evaluate SIMD vector length `{len}`");
265                        self.fcx
266                            .dcx()
267                            .struct_span_err(self.tcx().def_span(did), msg)
268                            .with_span_note(
269                                expr.span,
270                                "SIMD vector length needs to be known statically for use in `asm!`",
271                            )
272                            .emit();
273                    }
274                    NonAsmTypeReason::Invalid(ty) => {
275                        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot use value of type `{0}` for inline assembly",
                ty))
    })format!("cannot use value of type `{ty}` for inline assembly");
276                        self.fcx.dcx().struct_span_err(expr.span, msg).with_note(
277                            "only integers, floats, SIMD vectors, scalable vectors, pointers and function \
278                            pointers can be used as arguments for inline assembly",
279                        ).emit();
280                    }
281                    NonAsmTypeReason::NotSizedPtr(ty) => {
282                        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot use value of unsized pointer type `{0}` for inline assembly",
                ty))
    })format!(
283                            "cannot use value of unsized pointer type `{ty}` for inline assembly"
284                        );
285                        self.fcx
286                            .dcx()
287                            .struct_span_err(expr.span, msg)
288                            .with_note("only sized pointers can be used in inline assembly")
289                            .emit();
290                    }
291                    NonAsmTypeReason::InvalidElement(did, ty) => {
292                        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot use SIMD vector with element type `{0}` for inline assembly",
                ty))
    })format!(
293                            "cannot use SIMD vector with element type `{ty}` for inline assembly"
294                        );
295                        self.fcx.dcx()
296                        .struct_span_err(self.tcx().def_span(did), msg).with_span_note(
297                            expr.span,
298                            "only integers, floats, SIMD vectors, pointers and function pointers \
299                            can be used as arguments for inline assembly",
300                        ).emit();
301                    }
302                    NonAsmTypeReason::EmptySIMDArray(ty) => {
303                        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("use of empty SIMD vector `{0}`",
                ty))
    })format!("use of empty SIMD vector `{ty}`");
304                        self.fcx.dcx().struct_span_err(expr.span, msg).emit();
305                    }
306                    NonAsmTypeReason::Tainted(_error_guard) => {
307                        // An error has already been reported.
308                    }
309                }
310                return None;
311            }
312        };
313
314        // Check that the type implements Copy. The only case where this can
315        // possibly fail is for SIMD types which don't #[derive(Copy)].
316        if !self.fcx.type_is_copy_modulo_regions(self.fcx.param_env, ty) {
317            let msg = "arguments for inline assembly must be copyable";
318            self.fcx
319                .dcx()
320                .struct_span_err(expr.span, msg)
321                .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` does not implement the Copy trait",
                ty))
    })format!("`{ty}` does not implement the Copy trait"))
322                .emit();
323        }
324
325        // Ideally we wouldn't need to do this, but LLVM's register allocator
326        // really doesn't like it when tied operands have different types.
327        //
328        // This is purely an LLVM limitation, but we have to live with it since
329        // there is no way to hide this with implicit conversions.
330        //
331        // For the purposes of this check we only look at the `InlineAsmType`,
332        // which means that pointers and integers are treated as identical (modulo
333        // size).
334        if let Some((in_expr, Some(in_asm_ty))) = tied_input {
335            if in_asm_ty != asm_ty {
336                let msg = "incompatible types for asm inout argument";
337                let in_expr_ty = self.expr_ty(in_expr);
338                self.fcx
339                    .dcx()
340                    .struct_span_err(::alloc::boxed::box_assume_init_into_vec_unsafe(::alloc::intrinsics::write_box_via_move(::alloc::boxed::Box::new_uninit(),
        [in_expr.span, expr.span]))vec![in_expr.span, expr.span], msg)
341                    .with_span_label(in_expr.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type `{0}`", in_expr_ty))
    })format!("type `{in_expr_ty}`"))
342                    .with_span_label(expr.span, ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type `{0}`", ty))
    })format!("type `{ty}`"))
343                    .with_note(
344                        "asm inout arguments must have the same type, \
345                        unless they are both pointers or integers of the same size",
346                    )
347                    .emit();
348            }
349
350            // All of the later checks have already been done on the input, so
351            // let's not emit errors and warnings twice.
352            return Some(asm_ty);
353        }
354
355        // Check the type against the list of types supported by the selected
356        // register class.
357        let asm_arch = self.tcx().sess.asm_arch.unwrap();
358        let allow_experimental_reg = self.tcx().features().asm_experimental_reg();
359        let reg_class = reg.reg_class();
360        let supported_tys = reg_class.supported_types(asm_arch, allow_experimental_reg);
361        let Some((_, feature)) = supported_tys.iter().find(|&&(t, _)| t == asm_ty) else {
362            let mut err = if !allow_experimental_reg
363                && reg_class.supported_types(asm_arch, true).iter().any(|&(t, _)| t == asm_ty)
364            {
365                self.tcx().sess.create_feature_err(
366                    RegisterTypeUnstable { span: expr.span, ty },
367                    sym::asm_experimental_reg,
368                )
369            } else {
370                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("type `{0}` cannot be used with this register class",
                ty))
    })format!("type `{ty}` cannot be used with this register class");
371                let mut err = self.fcx.dcx().struct_span_err(expr.span, msg);
372                let supported_tys: Vec<_> =
373                    supported_tys.iter().map(|(t, _)| t.to_string()).collect();
374                err.note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("register class `{0}` supports these types: {1}",
                reg_class.name(), supported_tys.join(", ")))
    })format!(
375                    "register class `{}` supports these types: {}",
376                    reg_class.name(),
377                    supported_tys.join(", "),
378                ));
379                err
380            };
381            if let Some(suggest) = reg_class.suggest_class(asm_arch, asm_ty) {
382                err.help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("consider using the `{0}` register class instead",
                suggest.name()))
    })format!("consider using the `{}` register class instead", suggest.name()));
383            }
384            err.emit();
385            return Some(asm_ty);
386        };
387
388        // Check whether the selected type requires a target feature. Note that
389        // this is different from the feature check we did earlier. While the
390        // previous check checked that this register class is usable at all
391        // with the currently enabled features, some types may only be usable
392        // with a register class when a certain feature is enabled. We check
393        // this here since it depends on the results of typeck.
394        //
395        // Also note that this check isn't run when the operand type is never
396        // (!). In that case we still need the earlier check to verify that the
397        // register class is usable at all.
398        if let Some(feature) = feature {
399            if !self.target_features.contains(feature) {
400                let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`{0}` target feature is not enabled",
                feature))
    })format!("`{feature}` target feature is not enabled");
401                self.fcx
402                    .dcx()
403                    .struct_span_err(expr.span, msg)
404                    .with_note(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("this is required to use type `{0}` with register class `{1}`",
                ty, reg_class.name()))
    })format!(
405                        "this is required to use type `{}` with register class `{}`",
406                        ty,
407                        reg_class.name(),
408                    ))
409                    .emit();
410                return Some(asm_ty);
411            }
412        }
413
414        // Check whether a modifier is suggested for using this type.
415        if let Some(ModifierInfo {
416            modifier: suggested_modifier,
417            result: suggested_result,
418            size: suggested_size,
419        }) = reg_class.suggest_modifier(asm_arch, asm_ty)
420        {
421            // Search for any use of this operand without a modifier and emit
422            // the suggestion for them.
423            let mut spans = ::alloc::vec::Vec::new()vec![];
424            for piece in template {
425                if let &InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span } = piece
426                {
427                    if operand_idx == idx && modifier.is_none() {
428                        spans.push(span);
429                    }
430                }
431            }
432            if !spans.is_empty() {
433                let ModifierInfo {
434                    modifier: default_modifier,
435                    result: default_result,
436                    size: default_size,
437                } = reg_class.default_modifier(asm_arch).unwrap();
438                self.tcx().emit_node_span_lint(
439                    ASM_SUB_REGISTER,
440                    expr.hir_id,
441                    spans,
442                    FormattingSubRegisterArg {
443                        expr_span: expr.span,
444                        idx,
445                        suggested_modifier,
446                        suggested_result,
447                        suggested_size,
448                        default_modifier,
449                        default_result,
450                        default_size,
451                    },
452                );
453            }
454        }
455
456        Some(asm_ty)
457    }
458
459    pub(crate) fn check_asm(&self, asm: &hir::InlineAsm<'tcx>) {
460        let Some(asm_arch) = self.tcx().sess.asm_arch else {
461            self.fcx.dcx().delayed_bug("target architecture does not support asm");
462            return;
463        };
464        let allow_experimental_reg = self.tcx().features().asm_experimental_reg();
465        for (idx, &(op, op_sp)) in asm.operands.iter().enumerate() {
466            // Validate register classes against currently enabled target
467            // features. We check that at least one type is available for
468            // the enabled features.
469            //
470            // We ignore target feature requirements for clobbers: if the
471            // feature is disabled then the compiler doesn't care what we
472            // do with the registers.
473            //
474            // Note that this is only possible for explicit register
475            // operands, which cannot be used in the asm string.
476            if let Some(reg) = op.reg() {
477                // Some explicit registers cannot be used depending on the
478                // target. Reject those here.
479                if let InlineAsmRegOrRegClass::Reg(reg) = reg {
480                    if let InlineAsmReg::Err = reg {
481                        // `validate` will panic on `Err`, as an error must
482                        // already have been reported.
483                        continue;
484                    }
485                    if let Err(msg) = reg.validate(
486                        asm_arch,
487                        self.tcx().sess.relocation_model(),
488                        self.target_features,
489                        &self.tcx().sess.target,
490                        op.is_clobber(),
491                    ) {
492                        let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("cannot use register `{0}`: {1}",
                reg.name(), msg))
    })format!("cannot use register `{}`: {}", reg.name(), msg);
493                        self.fcx.dcx().span_err(op_sp, msg);
494                        continue;
495                    }
496                }
497
498                if !op.is_clobber() {
499                    let mut missing_required_features = ::alloc::vec::Vec::new()vec![];
500                    let reg_class = reg.reg_class();
501                    if let InlineAsmRegClass::Err = reg_class {
502                        continue;
503                    }
504                    for &(_, feature) in
505                        reg_class.supported_types(asm_arch, allow_experimental_reg).as_ref()
506                    {
507                        match feature {
508                            Some(feature) => {
509                                if self.target_features.contains(&feature) {
510                                    missing_required_features.clear();
511                                    break;
512                                } else {
513                                    missing_required_features.push(feature);
514                                }
515                            }
516                            None => {
517                                missing_required_features.clear();
518                                break;
519                            }
520                        }
521                    }
522
523                    // We are sorting primitive strs here and can use unstable sort here
524                    missing_required_features.sort_unstable();
525                    missing_required_features.dedup();
526                    match &missing_required_features[..] {
527                        [] => {}
528                        [feature] => {
529                            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("register class `{0}` requires the `{1}` target feature",
                reg_class.name(), feature))
    })format!(
530                                "register class `{}` requires the `{}` target feature",
531                                reg_class.name(),
532                                feature
533                            );
534                            self.fcx.dcx().span_err(op_sp, msg);
535                            // register isn't enabled, don't do more checks
536                            continue;
537                        }
538                        features => {
539                            let msg = ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("register class `{0}` requires at least one of the following target features: {1}",
                reg_class.name(),
                features.iter().map(|f|
                                f.as_str()).intersperse(", ").collect::<String>()))
    })format!(
540                                "register class `{}` requires at least one of the following target features: {}",
541                                reg_class.name(),
542                                features
543                                    .iter()
544                                    .map(|f| f.as_str())
545                                    .intersperse(", ")
546                                    .collect::<String>(),
547                            );
548                            self.fcx.dcx().span_err(op_sp, msg);
549                            // register isn't enabled, don't do more checks
550                            continue;
551                        }
552                    }
553                }
554            }
555
556            match op {
557                hir::InlineAsmOperand::In { reg, expr } => {
558                    self.check_asm_operand_type(idx, reg, expr, asm.template, true, None);
559                }
560                hir::InlineAsmOperand::Out { reg, late: _, expr } => {
561                    if let Some(expr) = expr {
562                        self.check_asm_operand_type(idx, reg, expr, asm.template, false, None);
563                    }
564                }
565                hir::InlineAsmOperand::InOut { reg, late: _, expr } => {
566                    self.check_asm_operand_type(idx, reg, expr, asm.template, false, None);
567                }
568                hir::InlineAsmOperand::SplitInOut { reg, late: _, in_expr, out_expr } => {
569                    let in_ty =
570                        self.check_asm_operand_type(idx, reg, in_expr, asm.template, true, None);
571                    if let Some(out_expr) = out_expr {
572                        self.check_asm_operand_type(
573                            idx,
574                            reg,
575                            out_expr,
576                            asm.template,
577                            false,
578                            Some((in_expr, in_ty)),
579                        );
580                    }
581                }
582                hir::InlineAsmOperand::Const { anon_const } => {
583                    let ty = self.expr_ty(self.tcx().hir_body(anon_const.body).value);
584                    match ty.kind() {
585                        ty::Error(_) => {}
586                        _ if ty.is_integral() => {}
587                        ty::FnPtr(..) => {
588                            if !self.tcx().features().asm_const_ptr() {
589                                self.tcx()
590                                    .sess
591                                    .create_feature_err(
592                                        AsmConstPtrUnstable { span: op_sp },
593                                        sym::asm_const_ptr,
594                                    )
595                                    .emit();
596                            }
597                        }
598                        ty::RawPtr(pointee, _) | ty::Ref(_, pointee, _)
599                            if self.is_thin_ptr_ty(*pointee) =>
600                        {
601                            if !self.tcx().features().asm_const_ptr() {
602                                self.tcx()
603                                    .sess
604                                    .create_feature_err(
605                                        AsmConstPtrUnstable { span: op_sp },
606                                        sym::asm_const_ptr,
607                                    )
608                                    .emit();
609                            }
610                        }
611                        _ => {
612                            let const_possible_ty = if !self.tcx().features().asm_const_ptr() {
613                                "integer"
614                            } else {
615                                "integer or thin pointer"
616                            };
617                            self.fcx
618                                .dcx()
619                                .struct_span_err(op_sp, "invalid type for `const` operand")
620                                .with_span_label(
621                                    self.tcx().def_span(anon_const.def_id),
622                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("is {0} `{1}`", ty.kind().article(),
                ty))
    })format!("is {} `{}`", ty.kind().article(), ty),
623                                )
624                                .with_help(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("`const` operands must be of an {0} type",
                const_possible_ty))
    })format!(
625                                    "`const` operands must be of an {const_possible_ty} type"
626                                ))
627                                .emit();
628                        }
629                    }
630                }
631                // Typeck has checked that SymFn refers to a function.
632                hir::InlineAsmOperand::SymFn { expr } => {
633                    let ty = self.expr_ty(expr);
634                    match ty.kind() {
635                        ty::FnDef(..) => {}
636                        ty::Error(_) => {}
637                        _ => {
638                            self.fcx
639                                .dcx()
640                                .struct_span_err(op_sp, "invalid `sym` operand")
641                                .with_span_label(
642                                    expr.span,
643                                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("is {0} `{1}`", ty.kind().article(),
                ty))
    })format!("is {} `{}`", ty.kind().article(), ty),
644                                )
645                                .with_help(
646                                    "`sym` operands must refer to either a function or a static",
647                                )
648                                .emit();
649                        }
650                    }
651                }
652                // AST lowering guarantees that SymStatic points to a static.
653                hir::InlineAsmOperand::SymStatic { .. } => {}
654                // No special checking is needed for labels.
655                hir::InlineAsmOperand::Label { .. } => {}
656            }
657        }
658    }
659}