Skip to main content

rustc_codegen_llvm/
asm.rs

1use std::assert_matches;
2use std::fmt::Write;
3
4use rustc_abi::{BackendRepr, Endian, Float, Integer, Primitive, Scalar, Size};
5use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
6use rustc_codegen_ssa::mir::operand::OperandValue;
7use rustc_codegen_ssa::traits::*;
8use rustc_data_structures::fx::FxHashMap;
9use rustc_middle::mir::interpret::{PointerArithmetic, Scalar as ConstScalar};
10use rustc_middle::ty::Instance;
11use rustc_middle::ty::layout::TyAndLayout;
12use rustc_session::Session;
13use rustc_session::config::Lto;
14use rustc_span::{Pos, Span, Symbol, bug, span_bug, sym};
15use rustc_target::asm::*;
16use rustc_target::spec::HasTargetSpec;
17use smallvec::SmallVec;
18use tracing::debug;
19
20use crate::builder::Builder;
21use crate::common::Funclet;
22use crate::context::CodegenCx;
23use crate::llvm::{self, ToLlvmBool, Type, Value};
24use crate::type_of::LayoutLlvmExt;
25use crate::{attributes, llvm_util};
26
27impl<'ll, 'tcx> AsmBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
28    fn codegen_inline_asm(
29        &mut self,
30        template: &[InlineAsmTemplatePiece],
31        operands: &[InlineAsmOperandRef<'tcx, Self>],
32        options: InlineAsmOptions,
33        line_spans: &[Span],
34        instance: Instance<'_>,
35        dest: Option<Self::BasicBlock>,
36        catch_funclet: Option<(Self::BasicBlock, Option<&Self::Funclet>)>,
37    ) {
38        let asm_arch = self.tcx.sess.asm_arch.unwrap();
39
40        // Collect the types of output operands
41        let mut constraints = ::alloc::vec::Vec::new()vec![];
42        let mut clobbers = ::alloc::vec::Vec::new()vec![];
43        let mut output_types = ::alloc::vec::Vec::new()vec![];
44        let mut op_idx = FxHashMap::default();
45        let mut clobbered_x87 = false;
46        for (idx, op) in operands.iter().enumerate() {
47            match *op {
48                InlineAsmOperandRef::Out { reg, late, place } => {
49                    let is_target_supported = |reg_class: InlineAsmRegClass| {
50                        for &(_, feature) in reg_class.supported_types(asm_arch, true).as_ref() {
51                            if let Some(feature) = feature {
52                                if self
53                                    .tcx
54                                    .asm_target_features(instance.def_id())
55                                    .contains(&feature)
56                                {
57                                    return true;
58                                }
59                            } else {
60                                // Register class is unconditionally supported
61                                return true;
62                            }
63                        }
64                        false
65                    };
66
67                    let mut layout = None;
68                    let ty = if let Some(ref place) = place {
69                        layout = Some(&place.layout);
70                        llvm_fixup_output_type(self.cx, reg.reg_class(), &place.layout, instance)
71                    } else if #[allow(non_exhaustive_omitted_patterns)] match reg.reg_class() {
    InlineAsmRegClass::X86(X86InlineAsmRegClass::mmx_reg |
        X86InlineAsmRegClass::x87_reg) => true,
    _ => false,
}matches!(
72                        reg.reg_class(),
73                        InlineAsmRegClass::X86(
74                            X86InlineAsmRegClass::mmx_reg | X86InlineAsmRegClass::x87_reg
75                        )
76                    ) {
77                        // Special handling for x87/mmx registers: we always
78                        // clobber the whole set if one register is marked as
79                        // clobbered. This is due to the way LLVM handles the
80                        // FP stack in inline assembly.
81                        if !clobbered_x87 {
82                            clobbered_x87 = true;
83                            clobbers.push("~{st}".to_string());
84                            for i in 1..=7 {
85                                clobbers.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("~{{st({0})}}", i))
    })format!("~{{st({})}}", i));
86                            }
87                        }
88                        continue;
89                    } else if !is_target_supported(reg.reg_class())
90                        || reg.reg_class().is_clobber_only(asm_arch, true)
91                    {
92                        // We turn discarded outputs into clobber constraints
93                        // if the target feature needed by the register class is
94                        // disabled. This is necessary otherwise LLVM will try
95                        // to actually allocate a register for the dummy output.
96                        {
    match reg {
        InlineAsmRegOrRegClass::Reg(_) => {}
        ref left_val => {
            ::core::panicking::assert_matches_failed(left_val,
                "InlineAsmRegOrRegClass::Reg(_)",
                ::core::option::Option::None);
        }
    }
};assert_matches!(reg, InlineAsmRegOrRegClass::Reg(_));
97                        clobbers.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("~{0}", reg_to_llvm(reg, None)))
    })format!("~{}", reg_to_llvm(reg, None)));
98                        continue;
99                    } else {
100                        // If the output is discarded, we don't really care what
101                        // type is used. We're just using this to tell LLVM to
102                        // reserve the register.
103                        dummy_output_type(self.cx, reg.reg_class())
104                    };
105                    output_types.push(ty);
106                    op_idx.insert(idx, constraints.len());
107                    let prefix = if late { "=" } else { "=&" };
108                    constraints.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", prefix,
                reg_to_llvm(reg, layout)))
    })format!("{}{}", prefix, reg_to_llvm(reg, layout)));
109                }
110                InlineAsmOperandRef::InOut { reg, late, in_value, out_place } => {
111                    let layout = if let Some(ref out_place) = out_place {
112                        &out_place.layout
113                    } else {
114                        // LLVM required tied operands to have the same type,
115                        // so we just use the type of the input.
116                        &in_value.layout
117                    };
118                    let ty = llvm_fixup_output_type(self.cx, reg.reg_class(), layout, instance);
119                    output_types.push(ty);
120                    op_idx.insert(idx, constraints.len());
121                    let prefix = if late { "=" } else { "=&" };
122                    constraints.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}{1}", prefix,
                reg_to_llvm(reg, Some(layout))))
    })format!("{}{}", prefix, reg_to_llvm(reg, Some(layout))));
123                }
124                _ => {}
125            }
126        }
127
128        // Collect input operands
129        let mut inputs = ::alloc::vec::Vec::new()vec![];
130        for (idx, op) in operands.iter().enumerate() {
131            match *op {
132                InlineAsmOperandRef::In { reg, value } => {
133                    let llval = llvm_fixup_input(
134                        self,
135                        value.immediate(),
136                        reg.reg_class(),
137                        &value.layout,
138                        instance,
139                    );
140                    inputs.push(llval);
141                    op_idx.insert(idx, constraints.len());
142                    constraints.push(reg_to_llvm(reg, Some(&value.layout)));
143                }
144                InlineAsmOperandRef::InOut { reg, late, in_value, out_place: _ } => {
145                    let value = llvm_fixup_input(
146                        self,
147                        in_value.immediate(),
148                        reg.reg_class(),
149                        &in_value.layout,
150                        instance,
151                    );
152                    inputs.push(value);
153
154                    // In the case of fixed registers, we have the choice of
155                    // either using a tied operand or duplicating the constraint.
156                    // We prefer the latter because it matches the behavior of
157                    // Clang.
158                    if late && #[allow(non_exhaustive_omitted_patterns)] match reg {
    InlineAsmRegOrRegClass::Reg(_) => true,
    _ => false,
}matches!(reg, InlineAsmRegOrRegClass::Reg(_)) {
159                        constraints.push(reg_to_llvm(reg, Some(&in_value.layout)));
160                    } else {
161                        constraints.push(::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{0}", op_idx[&idx]))
    })format!("{}", op_idx[&idx]));
162                    }
163                }
164                InlineAsmOperandRef::Const { value, ty: _ } => match value {
165                    ConstScalar::Int(_) => (),
166                    ConstScalar::Ptr(ptr, _) => {
167                        let (prov, _) = ptr.prov_and_relative_offset();
168                        let global_alloc = self.tcx.global_alloc(prov.alloc_id());
169                        let value = self.cx.alloc_to_backend(global_alloc, false, None).unwrap();
170                        inputs.push(value);
171                        op_idx.insert(idx, constraints.len());
172                        constraints.push("s".to_string());
173                    }
174                },
175                InlineAsmOperandRef::SymThreadLocalStatic { def_id } => {
176                    inputs.push(self.cx.get_static(def_id));
177                    op_idx.insert(idx, constraints.len());
178                    constraints.push("s".to_string());
179                }
180                _ => {}
181            }
182        }
183
184        // Build the template string
185        let mut labels = ::alloc::vec::Vec::new()vec![];
186        let mut template_str = String::new();
187        for piece in template {
188            match *piece {
189                InlineAsmTemplatePiece::String(ref s) => {
190                    if s.contains('$') {
191                        for c in s.chars() {
192                            if c == '$' {
193                                template_str.push_str("$$");
194                            } else {
195                                template_str.push(c);
196                            }
197                        }
198                    } else {
199                        template_str.push_str(s)
200                    }
201                }
202                InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span } => {
203                    match operands[operand_idx] {
204                        InlineAsmOperandRef::In { reg, .. }
205                        | InlineAsmOperandRef::Out { reg, .. }
206                        | InlineAsmOperandRef::InOut { reg, .. } => {
207                            let modifier = modifier_to_llvm(asm_arch, reg.reg_class(), modifier);
208                            if let Some(modifier) = modifier {
209                                template_str.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("${{{0}:{1}}}",
                op_idx[&operand_idx], modifier))
    })format!(
210                                    "${{{}:{}}}",
211                                    op_idx[&operand_idx], modifier
212                                ));
213                            } else {
214                                template_str.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("${{{0}}}", op_idx[&operand_idx]))
    })format!("${{{}}}", op_idx[&operand_idx]));
215                            }
216                        }
217                        InlineAsmOperandRef::Const { value, ty } => {
218                            match value {
219                                ConstScalar::Int(int) => {
220                                    // Const operands get injected directly into the template
221                                    let string = rustc_codegen_ssa::common::asm_const_to_str(
222                                        self.tcx,
223                                        span,
224                                        int,
225                                        self.layout_of(ty),
226                                    );
227                                    template_str.push_str(&string);
228                                }
229                                ConstScalar::Ptr(ptr, _) => {
230                                    let (_, offset) = ptr.prov_and_relative_offset();
231
232                                    // Only emit the raw symbol name
233                                    template_str
234                                        .push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("${{{0}:c}}", op_idx[&operand_idx]))
    })format!("${{{}:c}}", op_idx[&operand_idx]));
235
236                                    if offset != Size::ZERO {
237                                        let offset =
238                                            self.sign_extend_to_target_isize(offset.bytes());
239                                        template_str.write_fmt(format_args!("{0:+}", offset))write!(template_str, "{offset:+}").unwrap();
240                                    }
241                                }
242                            }
243                        }
244                        InlineAsmOperandRef::SymThreadLocalStatic { .. } => {
245                            // Only emit the raw symbol name
246                            template_str.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("${{{0}:c}}", op_idx[&operand_idx]))
    })format!("${{{}:c}}", op_idx[&operand_idx]));
247                        }
248                        InlineAsmOperandRef::Label { label } => {
249                            template_str.push_str(&::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("${{{0}:l}}", constraints.len()))
    })format!("${{{}:l}}", constraints.len()));
250                            constraints.push("!i".to_owned());
251                            labels.push(label);
252                        }
253                    }
254                }
255            }
256        }
257
258        constraints.append(&mut clobbers);
259        if !options.contains(InlineAsmOptions::PRESERVES_FLAGS) {
260            match asm_arch {
261                InlineAsmArch::AArch64 | InlineAsmArch::Arm64EC | InlineAsmArch::Arm => {
262                    constraints.push("~{cc}".to_string());
263                }
264                InlineAsmArch::Amdgpu => {}
265                InlineAsmArch::X86 | InlineAsmArch::X86_64 => {
266                    constraints.extend_from_slice(&[
267                        "~{dirflag}".to_string(),
268                        "~{fpsr}".to_string(),
269                        "~{flags}".to_string(),
270                    ]);
271                }
272                InlineAsmArch::RiscV32 | InlineAsmArch::RiscV64 => {
273                    constraints.extend_from_slice(&[
274                        "~{fflags}".to_string(),
275                        "~{vtype}".to_string(),
276                        "~{vl}".to_string(),
277                        "~{vxsat}".to_string(),
278                        "~{vxrm}".to_string(),
279                    ]);
280                }
281                InlineAsmArch::Avr => {
282                    constraints.push("~{sreg}".to_string());
283                }
284                InlineAsmArch::Nvptx64 => {}
285                InlineAsmArch::PowerPC | InlineAsmArch::PowerPC64 => {}
286                InlineAsmArch::Hexagon => {}
287                InlineAsmArch::LoongArch32 | InlineAsmArch::LoongArch64 => {
288                    constraints.extend_from_slice(&[
289                        "~{$fcc0}".to_string(),
290                        "~{$fcc1}".to_string(),
291                        "~{$fcc2}".to_string(),
292                        "~{$fcc3}".to_string(),
293                        "~{$fcc4}".to_string(),
294                        "~{$fcc5}".to_string(),
295                        "~{$fcc6}".to_string(),
296                        "~{$fcc7}".to_string(),
297                    ]);
298                }
299                InlineAsmArch::Mips | InlineAsmArch::Mips64 => {}
300                InlineAsmArch::S390x => {
301                    constraints.push("~{cc}".to_string());
302                }
303                InlineAsmArch::Sparc | InlineAsmArch::Sparc64 => {
304                    // In LLVM, ~{icc} represents icc and xcc in 64-bit code.
305                    // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/Sparc/SparcRegisterInfo.td#L64
306                    constraints.push("~{icc}".to_string());
307                    constraints.push("~{fcc0}".to_string());
308                    constraints.push("~{fcc1}".to_string());
309                    constraints.push("~{fcc2}".to_string());
310                    constraints.push("~{fcc3}".to_string());
311                }
312                InlineAsmArch::SpirV => {}
313                InlineAsmArch::Wasm32 | InlineAsmArch::Wasm64 => {}
314                InlineAsmArch::Xtensa => {}
315                InlineAsmArch::Bpf => {}
316                InlineAsmArch::Msp430 => {
317                    constraints.push("~{sr}".to_string());
318                }
319                InlineAsmArch::M68k => {
320                    constraints.push("~{ccr}".to_string());
321                }
322                InlineAsmArch::CSKY => {
323                    constraints.push("~{psr}".to_string());
324                }
325            }
326        }
327        if !options.contains(InlineAsmOptions::NOMEM) {
328            // This is actually ignored by LLVM, but it's probably best to keep
329            // it just in case. LLVM instead uses the ReadOnly/ReadNone
330            // attributes on the call instruction to optimize.
331            constraints.push("~{memory}".to_string());
332        }
333        let volatile = !options.contains(InlineAsmOptions::PURE);
334        let alignstack = !options.contains(InlineAsmOptions::NOSTACK);
335        let output_type = match &output_types[..] {
336            [] => self.type_void(),
337            [ty] => ty,
338            tys => self.type_struct(tys, false),
339        };
340        let dialect = match asm_arch {
341            InlineAsmArch::X86 | InlineAsmArch::X86_64
342                if !options.contains(InlineAsmOptions::ATT_SYNTAX) =>
343            {
344                llvm::AsmDialect::Intel
345            }
346            _ => llvm::AsmDialect::Att,
347        };
348        let result = inline_asm_call(
349            self,
350            &template_str,
351            &constraints.join(","),
352            &inputs,
353            output_type,
354            &labels,
355            volatile,
356            alignstack,
357            dialect,
358            line_spans,
359            options.contains(InlineAsmOptions::MAY_UNWIND),
360            dest,
361            catch_funclet,
362        )
363        .unwrap_or_else(|| bug_impl(Some(line_spans[0]),
    format_args!("LLVM asm constraint validation failed"), Location::caller())span_bug!(line_spans[0], "LLVM asm constraint validation failed"));
364
365        let mut attrs = SmallVec::<[_; 2]>::new();
366        if options.contains(InlineAsmOptions::PURE) {
367            if options.contains(InlineAsmOptions::NOMEM) {
368                attrs.push(llvm::MemoryEffects::None.create_attr(self.cx.llcx));
369            } else if options.contains(InlineAsmOptions::READONLY) {
370                attrs.push(llvm::MemoryEffects::ReadOnly.create_attr(self.cx.llcx));
371            }
372            attrs.push(llvm::AttributeKind::WillReturn.create_attr(self.cx.llcx));
373        } else if options.contains(InlineAsmOptions::NOMEM) {
374            attrs.push(llvm::MemoryEffects::InaccessibleMemOnly.create_attr(self.cx.llcx));
375        } else if options.contains(InlineAsmOptions::READONLY) {
376            attrs.push(llvm::MemoryEffects::ReadOnlyNotPure.create_attr(self.cx.llcx));
377        }
378        attributes::apply_to_callsite(result, llvm::AttributePlace::Function, &{ attrs });
379
380        // Write results to outputs. We need to do this for all possible control flow.
381        //
382        // Note that `dest` maybe populated with unreachable_block when asm goto with outputs
383        // is used (because we need to codegen callbr which always needs a destination), so
384        // here we use the NORETURN option to determine if `dest` should be used.
385        for block in (if options.contains(InlineAsmOptions::NORETURN) { None } else { Some(dest) })
386            .into_iter()
387            .chain(labels.iter().copied().map(Some))
388        {
389            if let Some(block) = block {
390                self.switch_to_block(block);
391            }
392
393            for (idx, op) in operands.iter().enumerate() {
394                if let InlineAsmOperandRef::Out { reg, place: Some(place), .. }
395                | InlineAsmOperandRef::InOut { reg, out_place: Some(place), .. } = *op
396                {
397                    let value = if output_types.len() == 1 {
398                        result
399                    } else {
400                        self.extract_value(result, op_idx[&idx] as u64)
401                    };
402                    let value =
403                        llvm_fixup_output(self, value, reg.reg_class(), &place.layout, instance);
404                    OperandValue::Immediate(value).store(self, place);
405                }
406            }
407        }
408    }
409}
410
411impl<'tcx> AsmCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> {
412    fn codegen_global_asm(
413        &mut self,
414        template: &[InlineAsmTemplatePiece],
415        operands: &[GlobalAsmOperandRef<'tcx>],
416        options: InlineAsmOptions,
417        _line_spans: &[Span],
418        extra_rust_target_features: &[String],
419    ) {
420        let asm_arch = self.tcx.sess.asm_arch.unwrap();
421
422        // Build the template string
423        let mut template_str = String::new();
424
425        // On X86 platforms there are two assembly syntaxes. Rust uses intel by default,
426        // but AT&T can be specified explicitly.
427        if #[allow(non_exhaustive_omitted_patterns)] match asm_arch {
    InlineAsmArch::X86 | InlineAsmArch::X86_64 => true,
    _ => false,
}matches!(asm_arch, InlineAsmArch::X86 | InlineAsmArch::X86_64) {
428            if options.contains(InlineAsmOptions::ATT_SYNTAX) {
429                template_str.push_str(".att_syntax\n")
430            } else {
431                template_str.push_str(".intel_syntax\n")
432            }
433        }
434
435        for piece in template {
436            match *piece {
437                InlineAsmTemplatePiece::String(ref s) => template_str.push_str(s),
438                InlineAsmTemplatePiece::Placeholder { operand_idx, modifier: _, span } => {
439                    use rustc_codegen_ssa::back::symbol_export::escape_symbol_name;
440                    match operands[operand_idx] {
441                        GlobalAsmOperandRef::Const { value, ty } => {
442                            match value {
443                                ConstScalar::Int(int) => {
444                                    // Const operands get injected directly into the
445                                    // template. Note that we don't need to escape $
446                                    // here unlike normal inline assembly.
447                                    let string = rustc_codegen_ssa::common::asm_const_to_str(
448                                        self.tcx,
449                                        span,
450                                        int,
451                                        self.layout_of(ty),
452                                    );
453                                    template_str.push_str(&string);
454                                }
455
456                                ConstScalar::Ptr(ptr, _) => {
457                                    let (prov, offset) = ptr.prov_and_relative_offset();
458                                    let global_alloc = self.tcx.global_alloc(prov.alloc_id());
459                                    let llval =
460                                        self.alloc_to_backend(global_alloc, true, None).unwrap();
461
462                                    self.add_compiler_used_global(llval);
463                                    let symbol = llvm::build_string(|s| unsafe {
464                                        llvm::LLVMRustGetMangledName(llval, s);
465                                    })
466                                    .expect("symbol is not valid UTF-8");
467                                    template_str
468                                        .push_str(&escape_symbol_name(self.tcx, &symbol, span));
469
470                                    if offset != Size::ZERO {
471                                        let offset =
472                                            self.sign_extend_to_target_isize(offset.bytes());
473                                        template_str.write_fmt(format_args!("{0:+}", offset))write!(template_str, "{offset:+}").unwrap();
474                                    }
475                                }
476                            }
477                        }
478                        GlobalAsmOperandRef::SymThreadLocalStatic { def_id } => {
479                            let llval = self
480                                .renamed_statics
481                                .borrow()
482                                .get(&def_id)
483                                .copied()
484                                .unwrap_or_else(|| self.get_static(def_id));
485                            self.add_compiler_used_global(llval);
486                            let symbol = llvm::build_string(|s| unsafe {
487                                llvm::LLVMRustGetMangledName(llval, s);
488                            })
489                            .expect("symbol is not valid UTF-8");
490                            template_str.push_str(&escape_symbol_name(self.tcx, &symbol, span));
491                        }
492                    }
493                }
494            }
495        }
496
497        // Just to play it safe, if intel was used, reset the assembly syntax to att.
498        if #[allow(non_exhaustive_omitted_patterns)] match asm_arch {
    InlineAsmArch::X86 | InlineAsmArch::X86_64 => true,
    _ => false,
}matches!(asm_arch, InlineAsmArch::X86 | InlineAsmArch::X86_64)
499            && !options.contains(InlineAsmOptions::ATT_SYNTAX)
500        {
501            template_str.push_str("\n.att_syntax\n");
502        }
503
504        // Globally-enabled features that are already in the backend format.
505        let global_features = self.tcx.sess.global_backend_features.iter().map(String::as_str);
506
507        // Features enabled on a particular instance, in the rust format.
508        // These need to be translated to the LLVM format.
509        let function_features: Vec<_> = extra_rust_target_features
510            .iter()
511            .flat_map(|feat| llvm_util::to_llvm_features(&self.tcx.sess.target, feat))
512            .flat_map(|feat| feat.into_iter().map(|f| ::alloc::__export::must_use({ ::alloc::fmt::format(format_args!("+{0}", f)) })format!("+{f}")))
513            .collect();
514
515        let function_features = function_features.iter().map(String::as_str);
516        let target_features =
517            global_features.chain(function_features).intersperse(",").collect::<String>();
518
519        llvm::append_module_inline_asm(
520            self.llmod,
521            template_str.as_bytes(),
522            &target_features,
523            llvm_util::target_cpu(self.tcx.sess),
524        );
525    }
526
527    fn mangled_name(&self, instance: Instance<'tcx>) -> String {
528        let llval = self.get_fn(instance);
529        llvm::build_string(|s| unsafe {
530            llvm::LLVMRustGetMangledName(llval, s);
531        })
532        .expect("symbol is not valid UTF-8")
533    }
534}
535
536pub(crate) fn inline_asm_call<'ll>(
537    bx: &mut Builder<'_, 'll, '_>,
538    asm: &str,
539    cons: &str,
540    inputs: &[&'ll Value],
541    output: &'ll llvm::Type,
542    labels: &[&'ll llvm::BasicBlock],
543    volatile: bool,
544    alignstack: bool,
545    dia: llvm::AsmDialect,
546    line_spans: &[Span],
547    unwind: bool,
548    dest: Option<&'ll llvm::BasicBlock>,
549    catch_funclet: Option<(&'ll llvm::BasicBlock, Option<&Funclet<'ll>>)>,
550) -> Option<&'ll Value> {
551    let argtys = inputs
552        .iter()
553        .map(|v| {
554            {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/asm.rs:554",
                        "rustc_codegen_llvm::asm", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/asm.rs"),
                        ::tracing_core::__macro_support::Option::Some(554u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::asm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Asm Input Type: {0:?}",
                                                    *v) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Asm Input Type: {:?}", *v);
555            bx.cx.val_ty(*v)
556        })
557        .collect::<Vec<_>>();
558
559    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/asm.rs:559",
                        "rustc_codegen_llvm::asm", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/asm.rs"),
                        ::tracing_core::__macro_support::Option::Some(559u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::asm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("Asm Output Type: {0:?}",
                                                    output) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("Asm Output Type: {:?}", output);
560    let fty = bx.cx.type_func(&argtys, output);
561
562    // Ask LLVM to verify that the constraints are well-formed.
563    let constraints_ok = unsafe { llvm::LLVMRustInlineAsmVerify(fty, cons.as_ptr(), cons.len()) };
564    {
    use ::tracing::__macro_support::Callsite as _;
    static __CALLSITE: ::tracing::callsite::DefaultCallsite =
        {
            static META: ::tracing::Metadata<'static> =
                {
                    ::tracing_core::metadata::Metadata::new("event /rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/asm.rs:564",
                        "rustc_codegen_llvm::asm", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/923c95cdf5ba65cea505aa2ea829f578e1506ed8/compiler/rustc_codegen_llvm/src/asm.rs"),
                        ::tracing_core::__macro_support::Option::Some(564u32),
                        ::tracing_core::__macro_support::Option::Some("rustc_codegen_llvm::asm"),
                        ::tracing_core::field::FieldSet::new(&["message"],
                            ::tracing_core::callsite::Identifier(&__CALLSITE)),
                        ::tracing::metadata::Kind::EVENT)
                };
            ::tracing::callsite::DefaultCallsite::new(&META)
        };
    let enabled =
        ::tracing::Level::DEBUG <= ::tracing::level_filters::STATIC_MAX_LEVEL
                &&
                ::tracing::Level::DEBUG <=
                    ::tracing::level_filters::LevelFilter::current() &&
            {
                let interest = __CALLSITE.interest();
                !interest.is_never() &&
                    ::tracing::__macro_support::__is_enabled(__CALLSITE.metadata(),
                        interest)
            };
    if enabled {
        (|value_set: ::tracing::field::ValueSet|
                    {
                        let meta = __CALLSITE.metadata();
                        ::tracing::Event::dispatch(meta, &value_set);
                        ;
                    })({
                #[allow(unused_imports)]
                use ::tracing::field::{debug, display, Value};
                __CALLSITE.metadata().fields().value_set_all(&[(::tracing::__macro_support::Option::Some(&format_args!("constraint verification result: {0:?}",
                                                    constraints_ok) as &dyn ::tracing::field::Value))])
            });
    } else { ; }
};debug!("constraint verification result: {:?}", constraints_ok);
565    if !constraints_ok {
566        // LLVM has detected an issue with our constraints, so bail out.
567        return None;
568    }
569
570    let v = unsafe {
571        llvm::LLVMGetInlineAsm(
572            fty,
573            asm.as_ptr(),
574            asm.len(),
575            cons.as_ptr(),
576            cons.len(),
577            volatile.to_llvm_bool(),
578            alignstack.to_llvm_bool(),
579            dia,
580            unwind.to_llvm_bool(),
581        )
582    };
583
584    let call = if !labels.is_empty() {
585        if !catch_funclet.is_none() {
    ::core::panicking::panic("assertion failed: catch_funclet.is_none()")
};assert!(catch_funclet.is_none());
586        bx.callbr(fty, None, None, v, inputs, dest.unwrap(), labels, None, None)
587    } else if let Some((catch, funclet)) = catch_funclet {
588        bx.invoke(
589            fty,
590            None,
591            None,
592            v,
593            ReturnSlot::Direct,
594            inputs,
595            dest.unwrap(),
596            catch,
597            funclet,
598            None,
599        )
600    } else {
601        bx.call(fty, None, None, v, ReturnSlot::Direct, inputs, None, None)
602    };
603
604    // Store mark in a metadata node so we can map LLVM errors
605    // back to source locations. See #17552.
606    let key = "srcloc";
607    let kind = bx.get_md_kind_id(key);
608
609    if allow_raw_span_inline_asm_srcloc(bx.tcx.sess, bx.bitcode_needed) {
610        // `srcloc` contains one 64-bit integer for each line of assembly code,
611        // where the lower 32 bits hold the lo byte position and the upper 32 bits
612        // hold the hi byte position.
613        let mut srcloc = ::alloc::vec::Vec::new()vec![];
614        if dia == llvm::AsmDialect::Intel && line_spans.len() > 1 {
615            // LLVM inserts an extra line to add the ".intel_syntax", so add
616            // a dummy srcloc entry for it.
617            //
618            // Don't do this if we only have 1 line span since that may be
619            // due to the asm template string coming from a macro. LLVM will
620            // default to the first srcloc for lines that don't have an
621            // associated srcloc.
622            srcloc.push(llvm::LLVMValueAsMetadata(bx.const_u64(0)));
623        }
624        srcloc.extend(line_spans.iter().map(|span| {
625            llvm::LLVMValueAsMetadata(
626                bx.const_u64(u64::from(span.lo().to_u32()) | (u64::from(span.hi().to_u32()) << 32)),
627            )
628        }));
629        bx.cx.set_metadata_node(call, kind, &srcloc);
630    }
631
632    Some(call)
633}
634
635/// Whenever inline assembly bitcode is built, its `srcloc` contains the raw span numbers
636/// as location cookies. This is problematic since that is nondeterministic when using
637/// the parallel frontend. Even without parallelism, the cookies are meaningless in another
638/// rustc session.
639///
640/// Discussion about replacing the cookies with something stable: rust-lang/rust#150451
641fn allow_raw_span_inline_asm_srcloc(sess: &Session, bitcode_needed: bool) -> bool {
642    // even for Lto::ThinLocal, where the bitcode isn't serialized into files, the changes in
643    // raw span positions would reflect in the LTO module hashes, which could lead to
644    // nondeterminism
645    sess.lto() == Lto::No && !bitcode_needed
646}
647
648/// If the register is an xmm/ymm/zmm register then return its index.
649fn xmm_reg_index(reg: InlineAsmReg) -> Option<u32> {
650    use X86InlineAsmReg::*;
651    match reg {
652        InlineAsmReg::X86(reg) if reg as u32 >= xmm0 as u32 && reg as u32 <= xmm15 as u32 => {
653            Some(reg as u32 - xmm0 as u32)
654        }
655        InlineAsmReg::X86(reg) if reg as u32 >= ymm0 as u32 && reg as u32 <= ymm15 as u32 => {
656            Some(reg as u32 - ymm0 as u32)
657        }
658        InlineAsmReg::X86(reg) if reg as u32 >= zmm0 as u32 && reg as u32 <= zmm31 as u32 => {
659            Some(reg as u32 - zmm0 as u32)
660        }
661        _ => None,
662    }
663}
664
665/// If the register is an AArch64 integer register then return its index.
666fn a64_reg_index(reg: InlineAsmReg) -> Option<u32> {
667    match reg {
668        InlineAsmReg::AArch64(r) => r.reg_index(),
669        _ => None,
670    }
671}
672
673/// If the register is an AArch64 vector register then return its index.
674fn a64_vreg_index(reg: InlineAsmReg) -> Option<u32> {
675    match reg {
676        InlineAsmReg::AArch64(reg) => reg.vreg_index(),
677        _ => None,
678    }
679}
680
681/// If the register is a Hexagon register pair then return its LLVM double register index.
682/// LLVM uses `d0`, `d1`, ... for Hexagon double registers in inline asm constraints,
683/// not the assembly-printed `r1:0`, `r3:2`, ... format.
684fn hexagon_reg_pair_index(reg: InlineAsmReg) -> Option<u32> {
685    match reg {
686        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r1_0) => Some(0),
687        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r3_2) => Some(1),
688        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r5_4) => Some(2),
689        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r7_6) => Some(3),
690        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r9_8) => Some(4),
691        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r11_10) => Some(5),
692        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r13_12) => Some(6),
693        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r15_14) => Some(7),
694        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r17_16) => Some(8),
695        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r21_20) => Some(10),
696        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r23_22) => Some(11),
697        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r25_24) => Some(12),
698        InlineAsmReg::Hexagon(HexagonInlineAsmReg::r27_26) => Some(13),
699        _ => None,
700    }
701}
702
703/// If the register is a Hexagon HVX vector pair then return its LLVM W-register index.
704/// LLVM uses `w0`, `w1`, ... for Hexagon vector pair registers in inline asm constraints.
705fn hexagon_vreg_pair_index(reg: InlineAsmReg) -> Option<u32> {
706    match reg {
707        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v1_0) => Some(0),
708        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v3_2) => Some(1),
709        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v5_4) => Some(2),
710        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v7_6) => Some(3),
711        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v9_8) => Some(4),
712        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v11_10) => Some(5),
713        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v13_12) => Some(6),
714        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v15_14) => Some(7),
715        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v17_16) => Some(8),
716        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v19_18) => Some(9),
717        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v21_20) => Some(10),
718        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v23_22) => Some(11),
719        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v25_24) => Some(12),
720        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v27_26) => Some(13),
721        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v29_28) => Some(14),
722        InlineAsmReg::Hexagon(HexagonInlineAsmReg::v31_30) => Some(15),
723        _ => None,
724    }
725}
726
727/// Converts a register class to an LLVM constraint code.
728fn reg_to_llvm(reg: InlineAsmRegOrRegClass, layout: Option<&TyAndLayout<'_>>) -> String {
729    use InlineAsmRegClass::*;
730    match reg {
731        // For vector registers LLVM wants the register name to match the type size.
732        InlineAsmRegOrRegClass::Reg(reg) => {
733            if let Some(idx) = xmm_reg_index(reg) {
734                let class = if let Some(layout) = layout {
735                    match layout.size.bytes() {
736                        64 => 'z',
737                        32 => 'y',
738                        _ => 'x',
739                    }
740                } else {
741                    // We use f32 as the type for discarded outputs
742                    'x'
743                };
744                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}mm{1}}}", class, idx))
    })format!("{{{}mm{}}}", class, idx)
745            } else if let Some(idx) = a64_reg_index(reg) {
746                let class = if let Some(layout) = layout {
747                    match layout.size.bytes() {
748                        8 => 'x',
749                        _ => 'w',
750                    }
751                } else {
752                    // We use i32 as the type for discarded outputs
753                    'w'
754                };
755                if class == 'x' && reg == InlineAsmReg::AArch64(AArch64InlineAsmReg::x30) {
756                    // LLVM doesn't recognize x30. use lr instead.
757                    "{lr}".to_string()
758                } else {
759                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}{1}}}", class, idx))
    })format!("{{{}{}}}", class, idx)
760                }
761            } else if let Some(idx) = a64_vreg_index(reg) {
762                let class = match layout {
763                    Some(layout)
764                        if #[allow(non_exhaustive_omitted_patterns)] match layout.backend_repr {
    BackendRepr::SimdScalableVector { .. } => true,
    _ => false,
}matches!(
765                            layout.backend_repr,
766                            BackendRepr::SimdScalableVector { .. }
767                        ) =>
768                    {
769                        'z'
770                    }
771                    Some(layout) => match layout.size.bytes() {
772                        16 => 'q',
773                        8 => 'd',
774                        4 => 's',
775                        2 => 'h',
776                        1 => 'd', // We fixup i8 to i8x8
777                        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
778                    },
779                    // We use i64x2 as the type for discarded outputs
780                    None => 'q',
781                };
782                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}{1}}}", class, idx))
    })format!("{{{}{}}}", class, idx)
783            } else if let Some(idx) = hexagon_reg_pair_index(reg) {
784                // LLVM uses `dN` for Hexagon double registers, not the `rN+1:N` asm syntax.
785                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{d{0}}}", idx))
    })format!("{{d{}}}", idx)
786            } else if let Some(idx) = hexagon_vreg_pair_index(reg) {
787                // LLVM uses `wN` for Hexagon HVX vector pair registers.
788                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{w{0}}}", idx))
    })format!("{{w{}}}", idx)
789            } else if reg == InlineAsmReg::Arm(ArmInlineAsmReg::r14) {
790                // LLVM doesn't recognize r14
791                "{lr}".to_string()
792            } else if let InlineAsmReg::Sparc(reg) = reg
793                && let Some(num) = reg.dreg_number()
794            {
795                // LLVM numbers d registers sequentially (d0 => d0, d2 => d1, d4 => d2 etc.)
796                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{d{0}}}", num / 2))
    })format!("{{d{}}}", num / 2)
797            } else if let InlineAsmReg::Sparc(reg) = reg
798                && let Some(num) = reg.qreg_number()
799            {
800                // LLVM numbers q registers sequentially (q0 => q0, q4 => q1, q8 => q2 etc.)
801                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{q{0}}}", num / 4))
    })format!("{{q{}}}", num / 4)
802            } else {
803                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}}}", reg.name()))
    })format!("{{{}}}", reg.name())
804            }
805        }
806        // The constraints can be retrieved from
807        // https://llvm.org/docs/LangRef.html#supported-constraint-code-list
808        InlineAsmRegOrRegClass::RegClass(reg) => match reg {
809            AArch64(AArch64InlineAsmRegClass::reg) => "r",
810            AArch64(AArch64InlineAsmRegClass::vreg) => "w",
811            AArch64(AArch64InlineAsmRegClass::vreg_low16) => "x",
812            // Although the above link suggests its just 'Upa', llvm's own tests seem to suggest its
813            // '@3Upa'. (see "src/llvm-project/clang/test/CodeGen/AArch64/sve-inline-asm-datatypes.c" line 139)
814            AArch64(AArch64InlineAsmRegClass::preg) => "@3Upa",
815            AArch64(AArch64InlineAsmRegClass::ffr) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
816            Arm(ArmInlineAsmRegClass::reg) => "r",
817            Arm(ArmInlineAsmRegClass::sreg)
818            | Arm(ArmInlineAsmRegClass::dreg_low16)
819            | Arm(ArmInlineAsmRegClass::qreg_low8) => "t",
820            Arm(ArmInlineAsmRegClass::sreg_low16)
821            | Arm(ArmInlineAsmRegClass::dreg_low8)
822            | Arm(ArmInlineAsmRegClass::qreg_low4) => "x",
823            Arm(ArmInlineAsmRegClass::dreg) | Arm(ArmInlineAsmRegClass::qreg) => "w",
824            Amdgpu(AmdgpuInlineAsmRegClass::Sgpr(_)) => "s",
825            Amdgpu(AmdgpuInlineAsmRegClass::Vgpr(_)) => "v",
826            Hexagon(HexagonInlineAsmRegClass::reg) => "r",
827            Hexagon(HexagonInlineAsmRegClass::reg_pair) => "r",
828            Hexagon(HexagonInlineAsmRegClass::preg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
829            Hexagon(HexagonInlineAsmRegClass::vreg) => "v",
830            Hexagon(HexagonInlineAsmRegClass::vreg_pair) => "v",
831            Hexagon(HexagonInlineAsmRegClass::qreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
832            LoongArch(LoongArchInlineAsmRegClass::reg) => "r",
833            LoongArch(LoongArchInlineAsmRegClass::freg)
834            | LoongArch(LoongArchInlineAsmRegClass::vreg)
835            | LoongArch(LoongArchInlineAsmRegClass::xreg) => "f",
836            Mips(MipsInlineAsmRegClass::reg) => "r",
837            Mips(MipsInlineAsmRegClass::freg | MipsInlineAsmRegClass::wreg) => "f",
838            Nvptx(NvptxInlineAsmRegClass::reg16) => "h",
839            Nvptx(NvptxInlineAsmRegClass::reg32) => "r",
840            Nvptx(NvptxInlineAsmRegClass::reg64) => "l",
841            PowerPC(PowerPCInlineAsmRegClass::reg) => "r",
842            PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => "b",
843            PowerPC(PowerPCInlineAsmRegClass::freg) => "f",
844            PowerPC(PowerPCInlineAsmRegClass::vreg) => "v",
845            PowerPC(PowerPCInlineAsmRegClass::vsreg) => "^wa",
846            PowerPC(
847                PowerPCInlineAsmRegClass::cr
848                | PowerPCInlineAsmRegClass::ctr
849                | PowerPCInlineAsmRegClass::lr
850                | PowerPCInlineAsmRegClass::xer
851                | PowerPCInlineAsmRegClass::spe_acc,
852            ) => {
853                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
854            }
855            RiscV(RiscVInlineAsmRegClass::reg) => "r",
856            RiscV(RiscVInlineAsmRegClass::freg) => "f",
857            RiscV(RiscVInlineAsmRegClass::vreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
858            X86(X86InlineAsmRegClass::reg) => "r",
859            X86(X86InlineAsmRegClass::reg_abcd) => "Q",
860            X86(X86InlineAsmRegClass::reg_byte) => "q",
861            X86(X86InlineAsmRegClass::xmm_reg) | X86(X86InlineAsmRegClass::ymm_reg) => "x",
862            X86(X86InlineAsmRegClass::zmm_reg) => "v",
863            X86(X86InlineAsmRegClass::kreg) => "^Yk",
864            X86(
865                X86InlineAsmRegClass::x87_reg
866                | X86InlineAsmRegClass::mmx_reg
867                | X86InlineAsmRegClass::kreg0
868                | X86InlineAsmRegClass::tmm_reg,
869            ) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
870            Xtensa(XtensaInlineAsmRegClass::freg) => "f",
871            Xtensa(XtensaInlineAsmRegClass::reg) => "r",
872            Xtensa(XtensaInlineAsmRegClass::sreg | XtensaInlineAsmRegClass::breg) => {
873                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
874            }
875            Wasm(WasmInlineAsmRegClass::local) => "r",
876            Bpf(BpfInlineAsmRegClass::reg) => "r",
877            Bpf(BpfInlineAsmRegClass::wreg) => "w",
878            Avr(AvrInlineAsmRegClass::reg) => "r",
879            Avr(AvrInlineAsmRegClass::reg_upper) => "d",
880            Avr(AvrInlineAsmRegClass::reg_pair) => "r",
881            Avr(AvrInlineAsmRegClass::reg_iw) => "w",
882            Avr(AvrInlineAsmRegClass::reg_ptr) => "e",
883            S390x(S390xInlineAsmRegClass::reg) => "r",
884            S390x(S390xInlineAsmRegClass::reg_addr) => "a",
885            S390x(S390xInlineAsmRegClass::freg) => "f",
886            S390x(S390xInlineAsmRegClass::vreg) => "v",
887            S390x(S390xInlineAsmRegClass::areg) => {
888                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
889            }
890            Sparc(SparcInlineAsmRegClass::reg) => "r",
891            Sparc(SparcInlineAsmRegClass::freg) => "f",
892            Sparc(SparcInlineAsmRegClass::dreg | SparcInlineAsmRegClass::qreg) => "e",
893            Sparc(SparcInlineAsmRegClass::yreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
894            Msp430(Msp430InlineAsmRegClass::reg) => "r",
895            M68k(M68kInlineAsmRegClass::reg) => "r",
896            M68k(M68kInlineAsmRegClass::reg_addr) => "a",
897            M68k(M68kInlineAsmRegClass::reg_data) => "d",
898            CSKY(CSKYInlineAsmRegClass::reg) => "r",
899            CSKY(CSKYInlineAsmRegClass::freg) => "f",
900            SpirV(SpirVInlineAsmRegClass::reg) => bug_impl(None, format_args!("LLVM backend does not support SPIR-V"),
    Location::caller())bug!("LLVM backend does not support SPIR-V"),
901            Err => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
902        }
903        .to_string(),
904    }
905}
906
907/// Converts a modifier into LLVM's equivalent modifier.
908fn modifier_to_llvm(
909    arch: InlineAsmArch,
910    reg: InlineAsmRegClass,
911    modifier: Option<char>,
912) -> Option<char> {
913    use InlineAsmRegClass::*;
914    // The modifiers can be retrieved from
915    // https://llvm.org/docs/LangRef.html#asm-template-argument-modifiers
916    match reg {
917        AArch64(AArch64InlineAsmRegClass::reg) => modifier,
918        AArch64(AArch64InlineAsmRegClass::vreg) | AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
919            if modifier == Some('v') {
920                None
921            } else {
922                modifier
923            }
924        }
925        AArch64(AArch64InlineAsmRegClass::preg | AArch64InlineAsmRegClass::ffr) => None,
926        Arm(ArmInlineAsmRegClass::reg) => None,
927        Arm(ArmInlineAsmRegClass::sreg) | Arm(ArmInlineAsmRegClass::sreg_low16) => None,
928        Arm(ArmInlineAsmRegClass::dreg)
929        | Arm(ArmInlineAsmRegClass::dreg_low16)
930        | Arm(ArmInlineAsmRegClass::dreg_low8) => Some('P'),
931        Arm(ArmInlineAsmRegClass::qreg)
932        | Arm(ArmInlineAsmRegClass::qreg_low8)
933        | Arm(ArmInlineAsmRegClass::qreg_low4) => {
934            if modifier.is_none() {
935                Some('q')
936            } else {
937                modifier
938            }
939        }
940        Amdgpu(_) => None,
941        Hexagon(_) => None,
942        LoongArch(LoongArchInlineAsmRegClass::reg) => None,
943        LoongArch(LoongArchInlineAsmRegClass::freg) => modifier,
944        LoongArch(LoongArchInlineAsmRegClass::vreg) => {
945            if modifier.is_none() {
946                Some('w')
947            } else {
948                modifier
949            }
950        }
951        LoongArch(LoongArchInlineAsmRegClass::xreg) => {
952            if modifier.is_none() {
953                Some('u')
954            } else {
955                modifier
956            }
957        }
958        Mips(MipsInlineAsmRegClass::reg) => None,
959        Mips(MipsInlineAsmRegClass::freg) => modifier,
960        Mips(MipsInlineAsmRegClass::wreg) => Some('w'),
961        Nvptx(_) => None,
962        PowerPC(PowerPCInlineAsmRegClass::vsreg) => {
963            // The documentation for the 'x' modifier is missing for llvm, and the gcc
964            // documentation is simply "use this for any vsx argument". It is needed
965            // to ensure the correct vsx register number is used.
966            if modifier.is_none() { Some('x') } else { modifier }
967        }
968        PowerPC(_) => None,
969        RiscV(RiscVInlineAsmRegClass::reg) | RiscV(RiscVInlineAsmRegClass::freg) => None,
970        RiscV(RiscVInlineAsmRegClass::vreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
971        X86(X86InlineAsmRegClass::reg) | X86(X86InlineAsmRegClass::reg_abcd) => match modifier {
972            None if arch == InlineAsmArch::X86_64 => Some('q'),
973            None => Some('k'),
974            Some('l') => Some('b'),
975            Some('h') => Some('h'),
976            Some('x') => Some('w'),
977            Some('e') => Some('k'),
978            Some('r') => Some('q'),
979            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
980        },
981        X86(X86InlineAsmRegClass::reg_byte) => None,
982        X86(reg @ X86InlineAsmRegClass::xmm_reg)
983        | X86(reg @ X86InlineAsmRegClass::ymm_reg)
984        | X86(reg @ X86InlineAsmRegClass::zmm_reg) => match (reg, modifier) {
985            (X86InlineAsmRegClass::xmm_reg, None) => Some('x'),
986            (X86InlineAsmRegClass::ymm_reg, None) => Some('t'),
987            (X86InlineAsmRegClass::zmm_reg, None) => Some('g'),
988            (_, Some('x')) => Some('x'),
989            (_, Some('y')) => Some('t'),
990            (_, Some('z')) => Some('g'),
991            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
992        },
993        X86(X86InlineAsmRegClass::kreg) => None,
994        X86(
995            X86InlineAsmRegClass::x87_reg
996            | X86InlineAsmRegClass::mmx_reg
997            | X86InlineAsmRegClass::kreg0
998            | X86InlineAsmRegClass::tmm_reg,
999        ) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
1000        Xtensa(_) => None,
1001        Wasm(WasmInlineAsmRegClass::local) => None,
1002        Bpf(_) => None,
1003        Avr(AvrInlineAsmRegClass::reg_pair)
1004        | Avr(AvrInlineAsmRegClass::reg_iw)
1005        | Avr(AvrInlineAsmRegClass::reg_ptr) => match modifier {
1006            Some('h') => Some('B'),
1007            Some('l') => Some('A'),
1008            _ => None,
1009        },
1010        Avr(_) => None,
1011        S390x(_) => None,
1012        Sparc(_) => None,
1013        Msp430(_) => None,
1014        SpirV(SpirVInlineAsmRegClass::reg) => bug_impl(None, format_args!("LLVM backend does not support SPIR-V"),
    Location::caller())bug!("LLVM backend does not support SPIR-V"),
1015        M68k(_) => None,
1016        CSKY(_) => None,
1017        Err => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1018    }
1019}
1020
1021/// Type to use for outputs that are discarded. It doesn't really matter what
1022/// the type is, as long as it is valid for the constraint code.
1023fn dummy_output_type<'ll>(cx: &CodegenCx<'ll, '_>, reg: InlineAsmRegClass) -> &'ll Type {
1024    use InlineAsmRegClass::*;
1025    match reg {
1026        AArch64(AArch64InlineAsmRegClass::reg) => cx.type_i32(),
1027        AArch64(AArch64InlineAsmRegClass::vreg) | AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
1028            cx.type_vector(cx.type_i64(), 2)
1029        }
1030        AArch64(AArch64InlineAsmRegClass::preg) => cx.type_scalable_vector(cx.type_i1(), 16),
1031        AArch64(AArch64InlineAsmRegClass::ffr) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
1032        Arm(ArmInlineAsmRegClass::reg) => cx.type_i32(),
1033        Arm(ArmInlineAsmRegClass::sreg) | Arm(ArmInlineAsmRegClass::sreg_low16) => cx.type_f32(),
1034        Arm(ArmInlineAsmRegClass::dreg)
1035        | Arm(ArmInlineAsmRegClass::dreg_low16)
1036        | Arm(ArmInlineAsmRegClass::dreg_low8) => cx.type_f64(),
1037        Arm(ArmInlineAsmRegClass::qreg)
1038        | Arm(ArmInlineAsmRegClass::qreg_low8)
1039        | Arm(ArmInlineAsmRegClass::qreg_low4) => cx.type_vector(cx.type_i64(), 2),
1040        Amdgpu(_) => cx.type_i32(),
1041        Hexagon(HexagonInlineAsmRegClass::reg) => cx.type_i32(),
1042        Hexagon(HexagonInlineAsmRegClass::reg_pair) => cx.type_i64(),
1043        Hexagon(HexagonInlineAsmRegClass::preg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
1044        Hexagon(HexagonInlineAsmRegClass::vreg) => {
1045            // HVX vector register size depends on the HVX mode.
1046            // LLVM's "v" constraint requires the exact vector width.
1047            if cx.tcx.sess.internal_target_features.contains(&sym::hvx_length128b) {
1048                cx.type_vector(cx.type_i32(), 32) // 1024-bit for 128B mode
1049            } else {
1050                cx.type_vector(cx.type_i32(), 16) // 512-bit for 64B mode
1051            }
1052        }
1053        Hexagon(HexagonInlineAsmRegClass::vreg_pair) => {
1054            if cx.tcx.sess.internal_target_features.contains(&sym::hvx_length128b) {
1055                cx.type_vector(cx.type_i32(), 64) // 2048-bit for 128B mode
1056            } else {
1057                cx.type_vector(cx.type_i32(), 32) // 1024-bit for 64B mode
1058            }
1059        }
1060        Hexagon(HexagonInlineAsmRegClass::qreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
1061        LoongArch(LoongArchInlineAsmRegClass::reg) => cx.type_i32(),
1062        LoongArch(LoongArchInlineAsmRegClass::freg) => cx.type_f32(),
1063        LoongArch(LoongArchInlineAsmRegClass::vreg) => cx.type_vector(cx.type_i32(), 4),
1064        LoongArch(LoongArchInlineAsmRegClass::xreg) => cx.type_vector(cx.type_i32(), 8),
1065        Mips(MipsInlineAsmRegClass::reg) => cx.type_i32(),
1066        Mips(MipsInlineAsmRegClass::freg) => cx.type_f32(),
1067        Mips(MipsInlineAsmRegClass::wreg) => cx.type_vector(cx.type_i32(), 4),
1068        Nvptx(NvptxInlineAsmRegClass::reg16) => cx.type_i16(),
1069        Nvptx(NvptxInlineAsmRegClass::reg32) => cx.type_i32(),
1070        Nvptx(NvptxInlineAsmRegClass::reg64) => cx.type_i64(),
1071        PowerPC(PowerPCInlineAsmRegClass::reg) => cx.type_i32(),
1072        PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => cx.type_i32(),
1073        PowerPC(PowerPCInlineAsmRegClass::freg) => cx.type_f64(),
1074        PowerPC(PowerPCInlineAsmRegClass::vreg) => cx.type_vector(cx.type_i32(), 4),
1075        PowerPC(PowerPCInlineAsmRegClass::vsreg) => cx.type_vector(cx.type_i32(), 4),
1076        PowerPC(
1077            PowerPCInlineAsmRegClass::cr
1078            | PowerPCInlineAsmRegClass::ctr
1079            | PowerPCInlineAsmRegClass::lr
1080            | PowerPCInlineAsmRegClass::xer
1081            | PowerPCInlineAsmRegClass::spe_acc,
1082        ) => {
1083            {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
1084        }
1085        RiscV(RiscVInlineAsmRegClass::reg) => cx.type_i32(),
1086        RiscV(RiscVInlineAsmRegClass::freg) => cx.type_f32(),
1087        RiscV(RiscVInlineAsmRegClass::vreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
1088        X86(X86InlineAsmRegClass::reg) | X86(X86InlineAsmRegClass::reg_abcd) => cx.type_i32(),
1089        X86(X86InlineAsmRegClass::reg_byte) => cx.type_i8(),
1090        X86(X86InlineAsmRegClass::xmm_reg)
1091        | X86(X86InlineAsmRegClass::ymm_reg)
1092        | X86(X86InlineAsmRegClass::zmm_reg) => cx.type_f32(),
1093        X86(X86InlineAsmRegClass::kreg) => cx.type_i16(),
1094        X86(
1095            X86InlineAsmRegClass::x87_reg
1096            | X86InlineAsmRegClass::mmx_reg
1097            | X86InlineAsmRegClass::kreg0
1098            | X86InlineAsmRegClass::tmm_reg,
1099        ) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
1100        Xtensa(XtensaInlineAsmRegClass::reg) => cx.type_i32(),
1101        Xtensa(XtensaInlineAsmRegClass::freg) => cx.type_f32(),
1102        Xtensa(XtensaInlineAsmRegClass::sreg | XtensaInlineAsmRegClass::breg) => {
1103            {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
1104        }
1105        Wasm(WasmInlineAsmRegClass::local) => cx.type_i32(),
1106        Bpf(BpfInlineAsmRegClass::reg) => cx.type_i64(),
1107        Bpf(BpfInlineAsmRegClass::wreg) => cx.type_i32(),
1108        Avr(AvrInlineAsmRegClass::reg) => cx.type_i8(),
1109        Avr(AvrInlineAsmRegClass::reg_upper) => cx.type_i8(),
1110        Avr(AvrInlineAsmRegClass::reg_pair) => cx.type_i16(),
1111        Avr(AvrInlineAsmRegClass::reg_iw) => cx.type_i16(),
1112        Avr(AvrInlineAsmRegClass::reg_ptr) => cx.type_i16(),
1113        S390x(S390xInlineAsmRegClass::reg | S390xInlineAsmRegClass::reg_addr) => cx.type_i32(),
1114        S390x(S390xInlineAsmRegClass::freg) => cx.type_f64(),
1115        S390x(S390xInlineAsmRegClass::vreg) => cx.type_vector(cx.type_i64(), 2),
1116        S390x(S390xInlineAsmRegClass::areg) => {
1117            {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
1118        }
1119        Sparc(SparcInlineAsmRegClass::reg) => cx.type_i32(),
1120        Sparc(SparcInlineAsmRegClass::freg) => cx.type_f32(),
1121        Sparc(SparcInlineAsmRegClass::dreg) => cx.type_f64(),
1122        Sparc(SparcInlineAsmRegClass::qreg) => cx.type_f128(),
1123        Sparc(SparcInlineAsmRegClass::yreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
1124        Msp430(Msp430InlineAsmRegClass::reg) => cx.type_i16(),
1125        M68k(M68kInlineAsmRegClass::reg) => cx.type_i32(),
1126        M68k(M68kInlineAsmRegClass::reg_addr) => cx.type_i32(),
1127        M68k(M68kInlineAsmRegClass::reg_data) => cx.type_i32(),
1128        CSKY(CSKYInlineAsmRegClass::reg) => cx.type_i32(),
1129        CSKY(CSKYInlineAsmRegClass::freg) => cx.type_f32(),
1130        SpirV(SpirVInlineAsmRegClass::reg) => bug_impl(None, format_args!("LLVM backend does not support SPIR-V"),
    Location::caller())bug!("LLVM backend does not support SPIR-V"),
1131        Err => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1132    }
1133}
1134
1135/// Helper function to get the LLVM type for a Scalar. Pointers are returned as
1136/// the equivalent integer type.
1137fn llvm_asm_scalar_type<'ll>(cx: &CodegenCx<'ll, '_>, scalar: Scalar) -> &'ll Type {
1138    let dl = &cx.tcx.data_layout;
1139    match scalar.primitive() {
1140        Primitive::Int(Integer::I8, _) => cx.type_i8(),
1141        Primitive::Int(Integer::I16, _) => cx.type_i16(),
1142        Primitive::Int(Integer::I32, _) => cx.type_i32(),
1143        Primitive::Int(Integer::I64, _) => cx.type_i64(),
1144        Primitive::Float(Float::F16) => cx.type_f16(),
1145        Primitive::Float(Float::F32) => cx.type_f32(),
1146        Primitive::Float(Float::F64) => cx.type_f64(),
1147        Primitive::Float(Float::F128) => cx.type_f128(),
1148        // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
1149        Primitive::Pointer(_) => cx.type_from_integer(dl.ptr_sized_integer()),
1150        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1151    }
1152}
1153
1154fn any_target_feature_enabled(
1155    cx: &CodegenCx<'_, '_>,
1156    instance: Instance<'_>,
1157    features: &[Symbol],
1158) -> bool {
1159    let enabled = cx.tcx.asm_target_features(instance.def_id());
1160    features.iter().any(|feat| enabled.contains(feat))
1161}
1162
1163/// Fix up an input value to work around LLVM bugs.
1164fn llvm_fixup_input<'ll, 'tcx>(
1165    bx: &mut Builder<'_, 'll, 'tcx>,
1166    mut value: &'ll Value,
1167    reg: InlineAsmRegClass,
1168    layout: &TyAndLayout<'tcx>,
1169    instance: Instance<'_>,
1170) -> &'ll Value {
1171    use InlineAsmRegClass::*;
1172    let dl = &bx.tcx.data_layout;
1173    match (reg, layout.backend_repr) {
1174        (AArch64(AArch64InlineAsmRegClass::vreg), BackendRepr::Scalar(s)) => {
1175            if let Primitive::Int(Integer::I8, _) = s.primitive() {
1176                let vec_ty = bx.cx.type_vector(bx.cx.type_i8(), 8);
1177                bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
1178            } else {
1179                value
1180            }
1181        }
1182        (AArch64(AArch64InlineAsmRegClass::vreg_low16), BackendRepr::Scalar(s))
1183            if s.primitive() != Primitive::Float(Float::F128) =>
1184        {
1185            let elem_ty = llvm_asm_scalar_type(bx.cx, s);
1186            let count = 16 / layout.size.bytes();
1187            let vec_ty = bx.cx.type_vector(elem_ty, count);
1188            // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
1189            if let Primitive::Pointer(_) = s.primitive() {
1190                let t = bx.type_from_integer(dl.ptr_sized_integer());
1191                value = bx.ptrtoint(value, t);
1192            }
1193            bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
1194        }
1195        (
1196            AArch64(AArch64InlineAsmRegClass::vreg_low16),
1197            BackendRepr::SimdVector { element, count },
1198        ) if layout.size.bytes() == 8 => {
1199            let elem_ty = llvm_asm_scalar_type(bx.cx, element);
1200            let count = count.as_u32();
1201            let vec_ty = bx.cx.type_vector(elem_ty, u64::from(count));
1202            let indices: Vec<_> = (0..count * 2).map(|x| bx.const_u32(x)).collect();
1203            bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
1204        }
1205        (X86(X86InlineAsmRegClass::reg_abcd), BackendRepr::Scalar(s))
1206            if s.primitive() == Primitive::Float(Float::F64) =>
1207        {
1208            bx.bitcast(value, bx.cx.type_i64())
1209        }
1210        (
1211            X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
1212            BackendRepr::SimdVector { .. },
1213        ) if layout.size.bytes() == 64 => bx.bitcast(value, bx.cx.type_vector(bx.cx.type_f64(), 8)),
1214        (
1215            X86(
1216                X86InlineAsmRegClass::xmm_reg
1217                | X86InlineAsmRegClass::ymm_reg
1218                | X86InlineAsmRegClass::zmm_reg,
1219            ),
1220            BackendRepr::Scalar(s),
1221        ) if bx.sess().asm_arch == Some(InlineAsmArch::X86)
1222            && s.primitive() == Primitive::Float(Float::F128) =>
1223        {
1224            bx.bitcast(value, bx.type_vector(bx.type_i32(), 4))
1225        }
1226        (
1227            X86(
1228                X86InlineAsmRegClass::xmm_reg
1229                | X86InlineAsmRegClass::ymm_reg
1230                | X86InlineAsmRegClass::zmm_reg,
1231            ),
1232            BackendRepr::Scalar(s),
1233        ) if s.primitive() == Primitive::Float(Float::F16) => {
1234            let value = bx.insert_element(
1235                bx.const_undef(bx.type_vector(bx.type_f16(), 8)),
1236                value,
1237                bx.const_usize(0),
1238            );
1239            bx.bitcast(value, bx.type_vector(bx.type_i16(), 8))
1240        }
1241        (
1242            X86(
1243                X86InlineAsmRegClass::xmm_reg
1244                | X86InlineAsmRegClass::ymm_reg
1245                | X86InlineAsmRegClass::zmm_reg,
1246            ),
1247            BackendRepr::SimdVector { element, count },
1248        ) if let count = count.as_u64()
1249            && let 8 | 16 = count
1250            && element.primitive() == Primitive::Float(Float::F16) =>
1251        {
1252            bx.bitcast(value, bx.type_vector(bx.type_i16(), count))
1253        }
1254        (
1255            Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
1256            BackendRepr::Scalar(s),
1257        ) => {
1258            if let Primitive::Int(Integer::I32, _) = s.primitive() {
1259                bx.bitcast(value, bx.cx.type_f32())
1260            } else {
1261                value
1262            }
1263        }
1264        (
1265            Arm(
1266                ArmInlineAsmRegClass::dreg
1267                | ArmInlineAsmRegClass::dreg_low8
1268                | ArmInlineAsmRegClass::dreg_low16,
1269            ),
1270            BackendRepr::Scalar(s),
1271        ) => {
1272            if let Primitive::Int(Integer::I64, _) = s.primitive() {
1273                bx.bitcast(value, bx.cx.type_f64())
1274            } else {
1275                value
1276            }
1277        }
1278        (
1279            Arm(
1280                ArmInlineAsmRegClass::dreg
1281                | ArmInlineAsmRegClass::dreg_low8
1282                | ArmInlineAsmRegClass::dreg_low16
1283                | ArmInlineAsmRegClass::qreg
1284                | ArmInlineAsmRegClass::qreg_low4
1285                | ArmInlineAsmRegClass::qreg_low8,
1286            ),
1287            BackendRepr::SimdVector { element, count },
1288        ) if let count = count.as_u64()
1289            && let 4 | 8 = count
1290            && element.primitive() == Primitive::Float(Float::F16) =>
1291        {
1292            bx.bitcast(value, bx.type_vector(bx.type_i16(), count))
1293        }
1294        (LoongArch(LoongArchInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1295            if s.primitive() == Primitive::Float(Float::F16) =>
1296        {
1297            // The LoongArch psABI only requires the upper bits to be widened to
1298            // GRLEN, leaving them undefined. We NaN-box instead (set all upper
1299            // bits to 1), matching LLVM's own codegen, to avoid an `f16` value
1300            // being mistaken for a valid `f32` value.
1301            let value = bx.bitcast(value, bx.type_i16());
1302            let value = bx.zext(value, bx.type_i32());
1303            let value = bx.or(value, bx.const_u32(0xFFFF_0000));
1304            bx.bitcast(value, bx.type_f32())
1305        }
1306        (Mips(MipsInlineAsmRegClass::reg), BackendRepr::Scalar(s)) => {
1307            match s.primitive() {
1308                // MIPS only supports register-length arithmetics.
1309                Primitive::Int(Integer::I8 | Integer::I16, _) => bx.zext(value, bx.type_i32()),
1310                Primitive::Float(Float::F16) => {
1311                    let value = bx.bitcast(value, bx.type_i16());
1312                    bx.zext(value, bx.type_i32())
1313                }
1314                Primitive::Float(Float::F32) => bx.bitcast(value, bx.type_i32()),
1315                Primitive::Float(Float::F64) => bx.bitcast(value, bx.type_i64()),
1316                _ => value,
1317            }
1318        }
1319        (
1320            Mips(MipsInlineAsmRegClass::freg | MipsInlineAsmRegClass::wreg),
1321            BackendRepr::Scalar(s),
1322        ) if s.primitive() == Primitive::Float(Float::F16) => {
1323            let value = bx.bitcast(value, bx.type_i16());
1324            let value = bx.zext(value, bx.type_i32());
1325            bx.bitcast(value, bx.type_f32())
1326        }
1327        (RiscV(RiscVInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1328            if s.primitive() == Primitive::Float(Float::F16)
1329                && !any_target_feature_enabled(bx, instance, &[sym::zfhmin, sym::zfh]) =>
1330        {
1331            // Smaller floats are always "NaN-boxed" inside larger floats on RISC-V.
1332            let value = bx.bitcast(value, bx.type_i16());
1333            let value = bx.zext(value, bx.type_i32());
1334            let value = bx.or(value, bx.const_u32(0xFFFF_0000));
1335            bx.bitcast(value, bx.type_f32())
1336        }
1337        (
1338            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1339            BackendRepr::Scalar(s),
1340        ) if let Primitive::Float(float @ (Float::F16 | Float::F32 | Float::F64)) =
1341            s.primitive() =>
1342        {
1343            let num_lanes = 16 / float.size().bytes();
1344            // `f16` is located in the rightmost halfword of doubleword 0 per section 7.3.2.5 of
1345            // "Power Instruction Set Architecture", version 3.1C.
1346            let offset = if float == Float::F16 { 3 } else { 0 };
1347            bx.insert_element(
1348                bx.const_undef(bx.type_vector(bx.type_from_float(float), num_lanes)),
1349                value,
1350                bx.const_usize(match bx.target_spec().endian {
1351                    Endian::Little => num_lanes - 1 - offset,
1352                    Endian::Big => offset,
1353                }),
1354            )
1355        }
1356        (
1357            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1358            BackendRepr::Scalar(s),
1359        ) if s.primitive() == Primitive::Float(Float::F128) => {
1360            bx.bitcast(value, bx.type_vector(bx.type_f64(), 2))
1361        }
1362        _ => value,
1363    }
1364}
1365
1366/// Fix up an output value to work around LLVM bugs.
1367fn llvm_fixup_output<'ll, 'tcx>(
1368    bx: &mut Builder<'_, 'll, 'tcx>,
1369    mut value: &'ll Value,
1370    reg: InlineAsmRegClass,
1371    layout: &TyAndLayout<'tcx>,
1372    instance: Instance<'_>,
1373) -> &'ll Value {
1374    use InlineAsmRegClass::*;
1375    match (reg, layout.backend_repr) {
1376        (AArch64(AArch64InlineAsmRegClass::vreg), BackendRepr::Scalar(s)) => {
1377            if let Primitive::Int(Integer::I8, _) = s.primitive() {
1378                bx.extract_element(value, bx.const_i32(0))
1379            } else {
1380                value
1381            }
1382        }
1383        (AArch64(AArch64InlineAsmRegClass::vreg_low16), BackendRepr::Scalar(s))
1384            if s.primitive() != Primitive::Float(Float::F128) =>
1385        {
1386            value = bx.extract_element(value, bx.const_i32(0));
1387            if let Primitive::Pointer(_) = s.primitive() {
1388                value = bx.inttoptr(value, layout.llvm_type(bx.cx));
1389            }
1390            value
1391        }
1392        (
1393            AArch64(AArch64InlineAsmRegClass::vreg_low16),
1394            BackendRepr::SimdVector { element, count },
1395        ) if layout.size.bytes() == 8 => {
1396            let elem_ty = llvm_asm_scalar_type(bx.cx, element);
1397            let count = count.as_u64();
1398            let vec_ty = bx.cx.type_vector(elem_ty, count * 2);
1399            let indices: Vec<_> = (0..count).map(|x| bx.const_i32(x as i32)).collect();
1400            bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
1401        }
1402        (X86(X86InlineAsmRegClass::reg_abcd), BackendRepr::Scalar(s))
1403            if s.primitive() == Primitive::Float(Float::F64) =>
1404        {
1405            bx.bitcast(value, bx.cx.type_f64())
1406        }
1407        (
1408            X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
1409            BackendRepr::SimdVector { .. },
1410        ) if layout.size.bytes() == 64 => bx.bitcast(value, layout.llvm_type(bx.cx)),
1411        (
1412            X86(
1413                X86InlineAsmRegClass::xmm_reg
1414                | X86InlineAsmRegClass::ymm_reg
1415                | X86InlineAsmRegClass::zmm_reg,
1416            ),
1417            BackendRepr::Scalar(s),
1418        ) if bx.sess().asm_arch == Some(InlineAsmArch::X86)
1419            && s.primitive() == Primitive::Float(Float::F128) =>
1420        {
1421            bx.bitcast(value, bx.type_f128())
1422        }
1423        (
1424            X86(
1425                X86InlineAsmRegClass::xmm_reg
1426                | X86InlineAsmRegClass::ymm_reg
1427                | X86InlineAsmRegClass::zmm_reg,
1428            ),
1429            BackendRepr::Scalar(s),
1430        ) if s.primitive() == Primitive::Float(Float::F16) => {
1431            let value = bx.bitcast(value, bx.type_vector(bx.type_f16(), 8));
1432            bx.extract_element(value, bx.const_usize(0))
1433        }
1434        (
1435            X86(
1436                X86InlineAsmRegClass::xmm_reg
1437                | X86InlineAsmRegClass::ymm_reg
1438                | X86InlineAsmRegClass::zmm_reg,
1439            ),
1440            BackendRepr::SimdVector { element, count },
1441        ) if let count = count.as_u64()
1442            && let 8 | 16 = count
1443            && element.primitive() == Primitive::Float(Float::F16) =>
1444        {
1445            bx.bitcast(value, bx.type_vector(bx.type_f16(), count))
1446        }
1447        (
1448            Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
1449            BackendRepr::Scalar(s),
1450        ) => {
1451            if let Primitive::Int(Integer::I32, _) = s.primitive() {
1452                bx.bitcast(value, bx.cx.type_i32())
1453            } else {
1454                value
1455            }
1456        }
1457        (
1458            Arm(
1459                ArmInlineAsmRegClass::dreg
1460                | ArmInlineAsmRegClass::dreg_low8
1461                | ArmInlineAsmRegClass::dreg_low16,
1462            ),
1463            BackendRepr::Scalar(s),
1464        ) => {
1465            if let Primitive::Int(Integer::I64, _) = s.primitive() {
1466                bx.bitcast(value, bx.cx.type_i64())
1467            } else {
1468                value
1469            }
1470        }
1471        (
1472            Arm(
1473                ArmInlineAsmRegClass::dreg
1474                | ArmInlineAsmRegClass::dreg_low8
1475                | ArmInlineAsmRegClass::dreg_low16
1476                | ArmInlineAsmRegClass::qreg
1477                | ArmInlineAsmRegClass::qreg_low4
1478                | ArmInlineAsmRegClass::qreg_low8,
1479            ),
1480            BackendRepr::SimdVector { element, count },
1481        ) if let count = count.as_u64()
1482            && let 4 | 8 = count
1483            && element.primitive() == Primitive::Float(Float::F16) =>
1484        {
1485            bx.bitcast(value, bx.type_vector(bx.type_f16(), count))
1486        }
1487        (LoongArch(LoongArchInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1488            if s.primitive() == Primitive::Float(Float::F16) =>
1489        {
1490            let value = bx.bitcast(value, bx.type_i32());
1491            let value = bx.trunc(value, bx.type_i16());
1492            bx.bitcast(value, bx.type_f16())
1493        }
1494        (Mips(MipsInlineAsmRegClass::reg), BackendRepr::Scalar(s)) => {
1495            match s.primitive() {
1496                // MIPS only supports register-length arithmetics.
1497                Primitive::Int(Integer::I8, _) => bx.trunc(value, bx.type_i8()),
1498                Primitive::Int(Integer::I16, _) => bx.trunc(value, bx.type_i16()),
1499                Primitive::Float(Float::F16) => {
1500                    let value = bx.trunc(value, bx.type_i16());
1501                    bx.bitcast(value, bx.type_f16())
1502                }
1503                Primitive::Float(Float::F32) => bx.bitcast(value, bx.type_f32()),
1504                Primitive::Float(Float::F64) => bx.bitcast(value, bx.type_f64()),
1505                _ => value,
1506            }
1507        }
1508        (
1509            Mips(MipsInlineAsmRegClass::freg | MipsInlineAsmRegClass::wreg),
1510            BackendRepr::Scalar(s),
1511        ) if s.primitive() == Primitive::Float(Float::F16) => {
1512            let value = bx.bitcast(value, bx.type_i32());
1513            let value = bx.trunc(value, bx.type_i16());
1514            bx.bitcast(value, bx.type_f16())
1515        }
1516        (RiscV(RiscVInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1517            if s.primitive() == Primitive::Float(Float::F16)
1518                && !any_target_feature_enabled(bx, instance, &[sym::zfhmin, sym::zfh]) =>
1519        {
1520            let value = bx.bitcast(value, bx.type_i32());
1521            let value = bx.trunc(value, bx.type_i16());
1522            bx.bitcast(value, bx.type_f16())
1523        }
1524        (
1525            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1526            BackendRepr::Scalar(s),
1527        ) if let Primitive::Float(float @ (Float::F16 | Float::F32 | Float::F64)) =
1528            s.primitive() =>
1529        {
1530            let num_lanes = 16 / float.size().bytes();
1531            // `f16` is located in the rightmost halfword of doubleword 0 per section 7.3.2.5 of
1532            // "Power Instruction Set Architecture", version 3.1C.
1533            let offset = if float == Float::F16 { 3 } else { 0 };
1534            bx.extract_element(
1535                value,
1536                bx.const_usize(match bx.target_spec().endian {
1537                    Endian::Little => num_lanes - 1 - offset,
1538                    Endian::Big => offset,
1539                }),
1540            )
1541        }
1542        (
1543            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1544            BackendRepr::Scalar(s),
1545        ) if s.primitive() == Primitive::Float(Float::F128) => bx.bitcast(value, bx.type_f128()),
1546        _ => value,
1547    }
1548}
1549
1550/// Output type to use for llvm_fixup_output.
1551fn llvm_fixup_output_type<'ll, 'tcx>(
1552    cx: &CodegenCx<'ll, 'tcx>,
1553    reg: InlineAsmRegClass,
1554    layout: &TyAndLayout<'tcx>,
1555    instance: Instance<'_>,
1556) -> &'ll Type {
1557    use InlineAsmRegClass::*;
1558    match (reg, layout.backend_repr) {
1559        (AArch64(AArch64InlineAsmRegClass::vreg), BackendRepr::Scalar(s)) => {
1560            if let Primitive::Int(Integer::I8, _) = s.primitive() {
1561                cx.type_vector(cx.type_i8(), 8)
1562            } else {
1563                layout.llvm_type(cx)
1564            }
1565        }
1566        (AArch64(AArch64InlineAsmRegClass::vreg_low16), BackendRepr::Scalar(s))
1567            if s.primitive() != Primitive::Float(Float::F128) =>
1568        {
1569            let elem_ty = llvm_asm_scalar_type(cx, s);
1570            let count = 16 / layout.size.bytes();
1571            cx.type_vector(elem_ty, count)
1572        }
1573        (
1574            AArch64(AArch64InlineAsmRegClass::vreg_low16),
1575            BackendRepr::SimdVector { element, count },
1576        ) if layout.size.bytes() == 8 => {
1577            let elem_ty = llvm_asm_scalar_type(cx, element);
1578            cx.type_vector(elem_ty, count.as_u64() * 2)
1579        }
1580        (X86(X86InlineAsmRegClass::reg_abcd), BackendRepr::Scalar(s))
1581            if s.primitive() == Primitive::Float(Float::F64) =>
1582        {
1583            cx.type_i64()
1584        }
1585        (
1586            X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
1587            BackendRepr::SimdVector { .. },
1588        ) if layout.size.bytes() == 64 => cx.type_vector(cx.type_f64(), 8),
1589        (
1590            X86(
1591                X86InlineAsmRegClass::xmm_reg
1592                | X86InlineAsmRegClass::ymm_reg
1593                | X86InlineAsmRegClass::zmm_reg,
1594            ),
1595            BackendRepr::Scalar(s),
1596        ) if cx.sess().asm_arch == Some(InlineAsmArch::X86)
1597            && s.primitive() == Primitive::Float(Float::F128) =>
1598        {
1599            cx.type_vector(cx.type_i32(), 4)
1600        }
1601        (
1602            X86(
1603                X86InlineAsmRegClass::xmm_reg
1604                | X86InlineAsmRegClass::ymm_reg
1605                | X86InlineAsmRegClass::zmm_reg,
1606            ),
1607            BackendRepr::Scalar(s),
1608        ) if s.primitive() == Primitive::Float(Float::F16) => cx.type_vector(cx.type_i16(), 8),
1609        (
1610            X86(
1611                X86InlineAsmRegClass::xmm_reg
1612                | X86InlineAsmRegClass::ymm_reg
1613                | X86InlineAsmRegClass::zmm_reg,
1614            ),
1615            BackendRepr::SimdVector { element, count },
1616        ) if let count = count.as_u64()
1617            && let 8 | 16 = count
1618            && element.primitive() == Primitive::Float(Float::F16) =>
1619        {
1620            cx.type_vector(cx.type_i16(), count)
1621        }
1622        (
1623            Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
1624            BackendRepr::Scalar(s),
1625        ) => {
1626            if let Primitive::Int(Integer::I32, _) = s.primitive() {
1627                cx.type_f32()
1628            } else {
1629                layout.llvm_type(cx)
1630            }
1631        }
1632        (
1633            Arm(
1634                ArmInlineAsmRegClass::dreg
1635                | ArmInlineAsmRegClass::dreg_low8
1636                | ArmInlineAsmRegClass::dreg_low16,
1637            ),
1638            BackendRepr::Scalar(s),
1639        ) => {
1640            if let Primitive::Int(Integer::I64, _) = s.primitive() {
1641                cx.type_f64()
1642            } else {
1643                layout.llvm_type(cx)
1644            }
1645        }
1646        (
1647            Arm(
1648                ArmInlineAsmRegClass::dreg
1649                | ArmInlineAsmRegClass::dreg_low8
1650                | ArmInlineAsmRegClass::dreg_low16
1651                | ArmInlineAsmRegClass::qreg
1652                | ArmInlineAsmRegClass::qreg_low4
1653                | ArmInlineAsmRegClass::qreg_low8,
1654            ),
1655            BackendRepr::SimdVector { element, count },
1656        ) if let count = count.as_u64()
1657            && let 4 | 8 = count
1658            && element.primitive() == Primitive::Float(Float::F16) =>
1659        {
1660            cx.type_vector(cx.type_i16(), count)
1661        }
1662        (LoongArch(LoongArchInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1663            if s.primitive() == Primitive::Float(Float::F16) =>
1664        {
1665            cx.type_f32()
1666        }
1667        (Mips(MipsInlineAsmRegClass::reg), BackendRepr::Scalar(s)) => {
1668            match s.primitive() {
1669                // MIPS only supports register-length arithmetics.
1670                Primitive::Int(Integer::I8 | Integer::I16, _) => cx.type_i32(),
1671                Primitive::Float(Float::F16 | Float::F32) => cx.type_i32(),
1672                Primitive::Float(Float::F64) => cx.type_i64(),
1673                _ => layout.llvm_type(cx),
1674            }
1675        }
1676
1677        (
1678            Mips(MipsInlineAsmRegClass::freg | MipsInlineAsmRegClass::wreg),
1679            BackendRepr::Scalar(s),
1680        ) if s.primitive() == Primitive::Float(Float::F16) => cx.type_f32(),
1681        (RiscV(RiscVInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1682            if s.primitive() == Primitive::Float(Float::F16)
1683                && !any_target_feature_enabled(cx, instance, &[sym::zfhmin, sym::zfh]) =>
1684        {
1685            cx.type_f32()
1686        }
1687        (
1688            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1689            BackendRepr::Scalar(s),
1690        ) if let Primitive::Float(float @ (Float::F16 | Float::F32 | Float::F64)) =
1691            s.primitive() =>
1692        {
1693            cx.type_vector(cx.type_from_float(float), 16 / float.size().bytes())
1694        }
1695        (
1696            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1697            BackendRepr::Scalar(s),
1698        ) if s.primitive() == Primitive::Float(Float::F128) => cx.type_vector(cx.type_f64(), 2),
1699        _ => layout.llvm_type(cx),
1700    }
1701}