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(|| ::rustc_span::macros::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/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/asm.rs:554",
                        "rustc_codegen_llvm::asm", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/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/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/asm.rs:559",
                        "rustc_codegen_llvm::asm", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/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/db8f076d2619ce2585b0380dda06e8da25a40da4/compiler/rustc_codegen_llvm/src/asm.rs:564",
                        "rustc_codegen_llvm::asm", ::tracing::Level::DEBUG,
                        ::tracing_core::__macro_support::Option::Some("/rustc-dev/db8f076d2619ce2585b0380dda06e8da25a40da4/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
756                if class == 'x'
757                    && reg == InlineAsmReg::AArch64(AArch64InlineAsmReg::x30)
758                    && llvm_util::get_version() < (23, 0, 0)
759                {
760                    // FIXME(llvm): LLVM <23 does not recognize `x30` as a register name.
761                    // This workaround can be removed when support for LLVM 22 is dropped.
762                    "{lr}".to_string()
763                } else {
764                    ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}{1}}}", class, idx))
    })format!("{{{}{}}}", class, idx)
765                }
766            } else if let Some(idx) = a64_vreg_index(reg) {
767                let class = match layout {
768                    Some(layout)
769                        if #[allow(non_exhaustive_omitted_patterns)] match layout.backend_repr {
    BackendRepr::SimdScalableVector { .. } => true,
    _ => false,
}matches!(
770                            layout.backend_repr,
771                            BackendRepr::SimdScalableVector { .. }
772                        ) =>
773                    {
774                        'z'
775                    }
776                    Some(layout) => match layout.size.bytes() {
777                        16 => 'q',
778                        8 => 'd',
779                        4 => 's',
780                        2 => 'h',
781                        1 => 'd', // We fixup i8 to i8x8
782                        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
783                    },
784                    // We use i64x2 as the type for discarded outputs
785                    None => 'q',
786                };
787                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}{1}}}", class, idx))
    })format!("{{{}{}}}", class, idx)
788            } else if let Some(idx) = hexagon_reg_pair_index(reg) {
789                // LLVM uses `dN` for Hexagon double registers, not the `rN+1:N` asm syntax.
790                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{d{0}}}", idx))
    })format!("{{d{}}}", idx)
791            } else if let Some(idx) = hexagon_vreg_pair_index(reg) {
792                // LLVM uses `wN` for Hexagon HVX vector pair registers.
793                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{w{0}}}", idx))
    })format!("{{w{}}}", idx)
794            } else if reg == InlineAsmReg::Arm(ArmInlineAsmReg::r14) {
795                // FIXME(llvm): LLVM <23 does not recognize `r14` as a register name
796                // in inline assembly.
797                // We can make this branch fallthrough again for LLVM 23+ when https://github.com/llvm/llvm-project/pull/225746 gets released.
798                "{lr}".to_string()
799            } else if let InlineAsmReg::Sparc(reg) = reg
800                && let Some(num) = reg.dreg_number()
801            {
802                // LLVM numbers d registers sequentially (d0 => d0, d2 => d1, d4 => d2 etc.)
803                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{d{0}}}", num / 2))
    })format!("{{d{}}}", num / 2)
804            } else if let InlineAsmReg::Sparc(reg) = reg
805                && let Some(num) = reg.qreg_number()
806            {
807                // LLVM numbers q registers sequentially (q0 => q0, q4 => q1, q8 => q2 etc.)
808                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{q{0}}}", num / 4))
    })format!("{{q{}}}", num / 4)
809            } else {
810                ::alloc::__export::must_use({
        ::alloc::fmt::format(format_args!("{{{0}}}", reg.name()))
    })format!("{{{}}}", reg.name())
811            }
812        }
813        // The constraints can be retrieved from
814        // https://llvm.org/docs/LangRef.html#supported-constraint-code-list
815        InlineAsmRegOrRegClass::RegClass(reg) => match reg {
816            AArch64(AArch64InlineAsmRegClass::reg) => "r",
817            AArch64(AArch64InlineAsmRegClass::vreg) => "w",
818            AArch64(AArch64InlineAsmRegClass::vreg_low16) => "x",
819            // Although the above link suggests its just 'Upa', llvm's own tests seem to suggest its
820            // '@3Upa'. (see "src/llvm-project/clang/test/CodeGen/AArch64/sve-inline-asm-datatypes.c" line 139)
821            AArch64(AArch64InlineAsmRegClass::preg) => "@3Upa",
822            AArch64(AArch64InlineAsmRegClass::ffr) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
823            Arm(ArmInlineAsmRegClass::reg) => "r",
824            Arm(ArmInlineAsmRegClass::sreg)
825            | Arm(ArmInlineAsmRegClass::dreg_low16)
826            | Arm(ArmInlineAsmRegClass::qreg_low8) => "t",
827            Arm(ArmInlineAsmRegClass::sreg_low16)
828            | Arm(ArmInlineAsmRegClass::dreg_low8)
829            | Arm(ArmInlineAsmRegClass::qreg_low4) => "x",
830            Arm(ArmInlineAsmRegClass::dreg) | Arm(ArmInlineAsmRegClass::qreg) => "w",
831            Amdgpu(AmdgpuInlineAsmRegClass::Sgpr(_)) => "s",
832            Amdgpu(AmdgpuInlineAsmRegClass::Vgpr(_)) => "v",
833            Hexagon(HexagonInlineAsmRegClass::reg) => "r",
834            Hexagon(HexagonInlineAsmRegClass::reg_pair) => "r",
835            Hexagon(HexagonInlineAsmRegClass::preg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
836            Hexagon(HexagonInlineAsmRegClass::vreg) => "v",
837            Hexagon(HexagonInlineAsmRegClass::vreg_pair) => "v",
838            Hexagon(HexagonInlineAsmRegClass::qreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
839            LoongArch(LoongArchInlineAsmRegClass::reg) => "r",
840            LoongArch(LoongArchInlineAsmRegClass::freg)
841            | LoongArch(LoongArchInlineAsmRegClass::vreg)
842            | LoongArch(LoongArchInlineAsmRegClass::xreg) => "f",
843            Mips(MipsInlineAsmRegClass::reg) => "r",
844            Mips(MipsInlineAsmRegClass::freg | MipsInlineAsmRegClass::wreg) => "f",
845            Nvptx(NvptxInlineAsmRegClass::reg16) => "h",
846            Nvptx(NvptxInlineAsmRegClass::reg32) => "r",
847            Nvptx(NvptxInlineAsmRegClass::reg64) => "l",
848            PowerPC(PowerPCInlineAsmRegClass::reg) => "r",
849            PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => "b",
850            PowerPC(PowerPCInlineAsmRegClass::freg) => "f",
851            PowerPC(PowerPCInlineAsmRegClass::vreg) => "v",
852            PowerPC(PowerPCInlineAsmRegClass::vsreg) => "^wa",
853            PowerPC(
854                PowerPCInlineAsmRegClass::cr
855                | PowerPCInlineAsmRegClass::ctr
856                | PowerPCInlineAsmRegClass::lr
857                | PowerPCInlineAsmRegClass::xer
858                | PowerPCInlineAsmRegClass::spe_acc,
859            ) => {
860                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
861            }
862            RiscV(RiscVInlineAsmRegClass::reg) => "r",
863            RiscV(RiscVInlineAsmRegClass::freg) => "f",
864            RiscV(RiscVInlineAsmRegClass::vreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
865            X86(X86InlineAsmRegClass::reg) => "r",
866            X86(X86InlineAsmRegClass::reg_abcd) => "Q",
867            X86(X86InlineAsmRegClass::reg_byte) => "q",
868            X86(X86InlineAsmRegClass::xmm_reg) | X86(X86InlineAsmRegClass::ymm_reg) => "x",
869            X86(X86InlineAsmRegClass::zmm_reg) => "v",
870            X86(X86InlineAsmRegClass::kreg) => "^Yk",
871            X86(
872                X86InlineAsmRegClass::x87_reg
873                | X86InlineAsmRegClass::mmx_reg
874                | X86InlineAsmRegClass::kreg0
875                | X86InlineAsmRegClass::tmm_reg,
876            ) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
877            Xtensa(XtensaInlineAsmRegClass::freg) => "f",
878            Xtensa(XtensaInlineAsmRegClass::reg) => "r",
879            Xtensa(XtensaInlineAsmRegClass::sreg | XtensaInlineAsmRegClass::breg) => {
880                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
881            }
882            Wasm(WasmInlineAsmRegClass::local) => "r",
883            Bpf(BpfInlineAsmRegClass::reg) => "r",
884            Bpf(BpfInlineAsmRegClass::wreg) => "w",
885            Avr(AvrInlineAsmRegClass::reg) => "r",
886            Avr(AvrInlineAsmRegClass::reg_upper) => "d",
887            Avr(AvrInlineAsmRegClass::reg_pair) => "r",
888            Avr(AvrInlineAsmRegClass::reg_iw) => "w",
889            Avr(AvrInlineAsmRegClass::reg_ptr) => "e",
890            S390x(S390xInlineAsmRegClass::reg) => "r",
891            S390x(S390xInlineAsmRegClass::reg_addr) => "a",
892            S390x(S390xInlineAsmRegClass::freg) => "f",
893            S390x(S390xInlineAsmRegClass::vreg) => "v",
894            S390x(S390xInlineAsmRegClass::areg) => {
895                {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
896            }
897            Sparc(SparcInlineAsmRegClass::reg) => "r",
898            Sparc(SparcInlineAsmRegClass::freg) => "f",
899            Sparc(SparcInlineAsmRegClass::dreg | SparcInlineAsmRegClass::qreg) => "e",
900            Sparc(SparcInlineAsmRegClass::yreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
901            Msp430(Msp430InlineAsmRegClass::reg) => "r",
902            M68k(M68kInlineAsmRegClass::reg) => "r",
903            M68k(M68kInlineAsmRegClass::reg_addr) => "a",
904            M68k(M68kInlineAsmRegClass::reg_data) => "d",
905            CSKY(CSKYInlineAsmRegClass::reg) => "r",
906            CSKY(CSKYInlineAsmRegClass::freg) => "f",
907            SpirV(SpirVInlineAsmRegClass::reg) => ::rustc_span::macros::bug_impl(None,
    format_args!("LLVM backend does not support SPIR-V"), Location::caller())bug!("LLVM backend does not support SPIR-V"),
908            Err => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
909        }
910        .to_string(),
911    }
912}
913
914/// Converts a modifier into LLVM's equivalent modifier.
915fn modifier_to_llvm(
916    arch: InlineAsmArch,
917    reg: InlineAsmRegClass,
918    modifier: Option<char>,
919) -> Option<char> {
920    use InlineAsmRegClass::*;
921    // The modifiers can be retrieved from
922    // https://llvm.org/docs/LangRef.html#asm-template-argument-modifiers
923    match reg {
924        AArch64(AArch64InlineAsmRegClass::reg) => modifier,
925        AArch64(AArch64InlineAsmRegClass::vreg) | AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
926            if modifier == Some('v') {
927                None
928            } else {
929                modifier
930            }
931        }
932        AArch64(AArch64InlineAsmRegClass::preg | AArch64InlineAsmRegClass::ffr) => None,
933        Arm(ArmInlineAsmRegClass::reg) => None,
934        Arm(ArmInlineAsmRegClass::sreg) | Arm(ArmInlineAsmRegClass::sreg_low16) => None,
935        Arm(ArmInlineAsmRegClass::dreg)
936        | Arm(ArmInlineAsmRegClass::dreg_low16)
937        | Arm(ArmInlineAsmRegClass::dreg_low8) => Some('P'),
938        Arm(ArmInlineAsmRegClass::qreg)
939        | Arm(ArmInlineAsmRegClass::qreg_low8)
940        | Arm(ArmInlineAsmRegClass::qreg_low4) => {
941            if modifier.is_none() {
942                Some('q')
943            } else {
944                modifier
945            }
946        }
947        Amdgpu(_) => None,
948        Hexagon(_) => None,
949        LoongArch(LoongArchInlineAsmRegClass::reg) => None,
950        LoongArch(LoongArchInlineAsmRegClass::freg) => modifier,
951        LoongArch(LoongArchInlineAsmRegClass::vreg) => {
952            if modifier.is_none() {
953                Some('w')
954            } else {
955                modifier
956            }
957        }
958        LoongArch(LoongArchInlineAsmRegClass::xreg) => {
959            if modifier.is_none() {
960                Some('u')
961            } else {
962                modifier
963            }
964        }
965        Mips(MipsInlineAsmRegClass::reg) => None,
966        Mips(MipsInlineAsmRegClass::freg) => modifier,
967        Mips(MipsInlineAsmRegClass::wreg) => Some('w'),
968        Nvptx(_) => None,
969        PowerPC(PowerPCInlineAsmRegClass::vsreg) => {
970            // The documentation for the 'x' modifier is missing for llvm, and the gcc
971            // documentation is simply "use this for any vsx argument". It is needed
972            // to ensure the correct vsx register number is used.
973            if modifier.is_none() { Some('x') } else { modifier }
974        }
975        PowerPC(_) => None,
976        RiscV(RiscVInlineAsmRegClass::reg) | RiscV(RiscVInlineAsmRegClass::freg) => None,
977        RiscV(RiscVInlineAsmRegClass::vreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
978        X86(X86InlineAsmRegClass::reg) | X86(X86InlineAsmRegClass::reg_abcd) => match modifier {
979            None if arch == InlineAsmArch::X86_64 => Some('q'),
980            None => Some('k'),
981            Some('l') => Some('b'),
982            Some('h') => Some('h'),
983            Some('x') => Some('w'),
984            Some('e') => Some('k'),
985            Some('r') => Some('q'),
986            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
987        },
988        X86(X86InlineAsmRegClass::reg_byte) => None,
989        X86(reg @ X86InlineAsmRegClass::xmm_reg)
990        | X86(reg @ X86InlineAsmRegClass::ymm_reg)
991        | X86(reg @ X86InlineAsmRegClass::zmm_reg) => match (reg, modifier) {
992            (X86InlineAsmRegClass::xmm_reg, None) => Some('x'),
993            (X86InlineAsmRegClass::ymm_reg, None) => Some('t'),
994            (X86InlineAsmRegClass::zmm_reg, None) => Some('g'),
995            (_, Some('x')) => Some('x'),
996            (_, Some('y')) => Some('t'),
997            (_, Some('z')) => Some('g'),
998            _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
999        },
1000        X86(X86InlineAsmRegClass::kreg) => None,
1001        X86(
1002            X86InlineAsmRegClass::x87_reg
1003            | X86InlineAsmRegClass::mmx_reg
1004            | X86InlineAsmRegClass::kreg0
1005            | X86InlineAsmRegClass::tmm_reg,
1006        ) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
1007        Xtensa(_) => None,
1008        Wasm(WasmInlineAsmRegClass::local) => None,
1009        Bpf(_) => None,
1010        Avr(AvrInlineAsmRegClass::reg_pair)
1011        | Avr(AvrInlineAsmRegClass::reg_iw)
1012        | Avr(AvrInlineAsmRegClass::reg_ptr) => match modifier {
1013            Some('h') => Some('B'),
1014            Some('l') => Some('A'),
1015            _ => None,
1016        },
1017        Avr(_) => None,
1018        S390x(_) => None,
1019        Sparc(_) => None,
1020        Msp430(_) => None,
1021        SpirV(SpirVInlineAsmRegClass::reg) => ::rustc_span::macros::bug_impl(None,
    format_args!("LLVM backend does not support SPIR-V"), Location::caller())bug!("LLVM backend does not support SPIR-V"),
1022        M68k(_) => None,
1023        CSKY(_) => None,
1024        Err => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1025    }
1026}
1027
1028/// Type to use for outputs that are discarded. It doesn't really matter what
1029/// the type is, as long as it is valid for the constraint code.
1030fn dummy_output_type<'ll>(cx: &CodegenCx<'ll, '_>, reg: InlineAsmRegClass) -> &'ll Type {
1031    use InlineAsmRegClass::*;
1032    match reg {
1033        AArch64(AArch64InlineAsmRegClass::reg) => cx.type_i32(),
1034        AArch64(AArch64InlineAsmRegClass::vreg) | AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
1035            cx.type_vector(cx.type_i64(), 2)
1036        }
1037        AArch64(AArch64InlineAsmRegClass::preg) => cx.type_scalable_vector(cx.type_i1(), 16),
1038        AArch64(AArch64InlineAsmRegClass::ffr) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
1039        Arm(ArmInlineAsmRegClass::reg) => cx.type_i32(),
1040        Arm(ArmInlineAsmRegClass::sreg) | Arm(ArmInlineAsmRegClass::sreg_low16) => cx.type_f32(),
1041        Arm(ArmInlineAsmRegClass::dreg)
1042        | Arm(ArmInlineAsmRegClass::dreg_low16)
1043        | Arm(ArmInlineAsmRegClass::dreg_low8) => cx.type_f64(),
1044        Arm(ArmInlineAsmRegClass::qreg)
1045        | Arm(ArmInlineAsmRegClass::qreg_low8)
1046        | Arm(ArmInlineAsmRegClass::qreg_low4) => cx.type_vector(cx.type_i64(), 2),
1047        Amdgpu(_) => cx.type_i32(),
1048        Hexagon(HexagonInlineAsmRegClass::reg) => cx.type_i32(),
1049        Hexagon(HexagonInlineAsmRegClass::reg_pair) => cx.type_i64(),
1050        Hexagon(HexagonInlineAsmRegClass::preg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
1051        Hexagon(HexagonInlineAsmRegClass::vreg) => {
1052            // HVX vector register size depends on the HVX mode.
1053            // LLVM's "v" constraint requires the exact vector width.
1054            if cx.tcx.sess.internal_target_features.contains(&sym::hvx_length128b) {
1055                cx.type_vector(cx.type_i32(), 32) // 1024-bit for 128B mode
1056            } else {
1057                cx.type_vector(cx.type_i32(), 16) // 512-bit for 64B mode
1058            }
1059        }
1060        Hexagon(HexagonInlineAsmRegClass::vreg_pair) => {
1061            if cx.tcx.sess.internal_target_features.contains(&sym::hvx_length128b) {
1062                cx.type_vector(cx.type_i32(), 64) // 2048-bit for 128B mode
1063            } else {
1064                cx.type_vector(cx.type_i32(), 32) // 1024-bit for 64B mode
1065            }
1066        }
1067        Hexagon(HexagonInlineAsmRegClass::qreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
1068        LoongArch(LoongArchInlineAsmRegClass::reg) => cx.type_i32(),
1069        LoongArch(LoongArchInlineAsmRegClass::freg) => cx.type_f32(),
1070        LoongArch(LoongArchInlineAsmRegClass::vreg) => cx.type_vector(cx.type_i32(), 4),
1071        LoongArch(LoongArchInlineAsmRegClass::xreg) => cx.type_vector(cx.type_i32(), 8),
1072        Mips(MipsInlineAsmRegClass::reg) => cx.type_i32(),
1073        Mips(MipsInlineAsmRegClass::freg) => cx.type_f32(),
1074        Mips(MipsInlineAsmRegClass::wreg) => cx.type_vector(cx.type_i32(), 4),
1075        Nvptx(NvptxInlineAsmRegClass::reg16) => cx.type_i16(),
1076        Nvptx(NvptxInlineAsmRegClass::reg32) => cx.type_i32(),
1077        Nvptx(NvptxInlineAsmRegClass::reg64) => cx.type_i64(),
1078        PowerPC(PowerPCInlineAsmRegClass::reg) => cx.type_i32(),
1079        PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => cx.type_i32(),
1080        PowerPC(PowerPCInlineAsmRegClass::freg) => cx.type_f64(),
1081        PowerPC(PowerPCInlineAsmRegClass::vreg) => cx.type_vector(cx.type_i32(), 4),
1082        PowerPC(PowerPCInlineAsmRegClass::vsreg) => cx.type_vector(cx.type_i32(), 4),
1083        PowerPC(
1084            PowerPCInlineAsmRegClass::cr
1085            | PowerPCInlineAsmRegClass::ctr
1086            | PowerPCInlineAsmRegClass::lr
1087            | PowerPCInlineAsmRegClass::xer
1088            | PowerPCInlineAsmRegClass::spe_acc,
1089        ) => {
1090            {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
1091        }
1092        RiscV(RiscVInlineAsmRegClass::reg) => cx.type_i32(),
1093        RiscV(RiscVInlineAsmRegClass::freg) => cx.type_f32(),
1094        RiscV(RiscVInlineAsmRegClass::vreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
1095        X86(X86InlineAsmRegClass::reg) | X86(X86InlineAsmRegClass::reg_abcd) => cx.type_i32(),
1096        X86(X86InlineAsmRegClass::reg_byte) => cx.type_i8(),
1097        X86(X86InlineAsmRegClass::xmm_reg)
1098        | X86(X86InlineAsmRegClass::ymm_reg)
1099        | X86(X86InlineAsmRegClass::zmm_reg) => cx.type_f32(),
1100        X86(X86InlineAsmRegClass::kreg) => cx.type_i16(),
1101        X86(
1102            X86InlineAsmRegClass::x87_reg
1103            | X86InlineAsmRegClass::mmx_reg
1104            | X86InlineAsmRegClass::kreg0
1105            | X86InlineAsmRegClass::tmm_reg,
1106        ) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
1107        Xtensa(XtensaInlineAsmRegClass::reg) => cx.type_i32(),
1108        Xtensa(XtensaInlineAsmRegClass::freg) => cx.type_f32(),
1109        Xtensa(XtensaInlineAsmRegClass::sreg | XtensaInlineAsmRegClass::breg) => {
1110            {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
1111        }
1112        Wasm(WasmInlineAsmRegClass::local) => cx.type_i32(),
1113        Bpf(BpfInlineAsmRegClass::reg) => cx.type_i64(),
1114        Bpf(BpfInlineAsmRegClass::wreg) => cx.type_i32(),
1115        Avr(AvrInlineAsmRegClass::reg) => cx.type_i8(),
1116        Avr(AvrInlineAsmRegClass::reg_upper) => cx.type_i8(),
1117        Avr(AvrInlineAsmRegClass::reg_pair) => cx.type_i16(),
1118        Avr(AvrInlineAsmRegClass::reg_iw) => cx.type_i16(),
1119        Avr(AvrInlineAsmRegClass::reg_ptr) => cx.type_i16(),
1120        S390x(S390xInlineAsmRegClass::reg | S390xInlineAsmRegClass::reg_addr) => cx.type_i32(),
1121        S390x(S390xInlineAsmRegClass::freg) => cx.type_f64(),
1122        S390x(S390xInlineAsmRegClass::vreg) => cx.type_vector(cx.type_i64(), 2),
1123        S390x(S390xInlineAsmRegClass::areg) => {
1124            {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only")
1125        }
1126        Sparc(SparcInlineAsmRegClass::reg) => cx.type_i32(),
1127        Sparc(SparcInlineAsmRegClass::freg) => cx.type_f32(),
1128        Sparc(SparcInlineAsmRegClass::dreg) => cx.type_f64(),
1129        Sparc(SparcInlineAsmRegClass::qreg) => cx.type_f128(),
1130        Sparc(SparcInlineAsmRegClass::yreg) => {
    ::core::panicking::panic_fmt(format_args!("internal error: entered unreachable code: {0}",
            format_args!("clobber-only")));
}unreachable!("clobber-only"),
1131        Msp430(Msp430InlineAsmRegClass::reg) => cx.type_i16(),
1132        M68k(M68kInlineAsmRegClass::reg) => cx.type_i32(),
1133        M68k(M68kInlineAsmRegClass::reg_addr) => cx.type_i32(),
1134        M68k(M68kInlineAsmRegClass::reg_data) => cx.type_i32(),
1135        CSKY(CSKYInlineAsmRegClass::reg) => cx.type_i32(),
1136        CSKY(CSKYInlineAsmRegClass::freg) => cx.type_f32(),
1137        SpirV(SpirVInlineAsmRegClass::reg) => ::rustc_span::macros::bug_impl(None,
    format_args!("LLVM backend does not support SPIR-V"), Location::caller())bug!("LLVM backend does not support SPIR-V"),
1138        Err => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1139    }
1140}
1141
1142/// Helper function to get the LLVM type for a Scalar. Pointers are returned as
1143/// the equivalent integer type.
1144fn llvm_asm_scalar_type<'ll>(cx: &CodegenCx<'ll, '_>, scalar: Scalar) -> &'ll Type {
1145    let dl = &cx.tcx.data_layout;
1146    match scalar.primitive() {
1147        Primitive::Int(Integer::I8, _) => cx.type_i8(),
1148        Primitive::Int(Integer::I16, _) => cx.type_i16(),
1149        Primitive::Int(Integer::I32, _) => cx.type_i32(),
1150        Primitive::Int(Integer::I64, _) => cx.type_i64(),
1151        Primitive::Float(Float::F16) => cx.type_f16(),
1152        Primitive::Float(Float::F32) => cx.type_f32(),
1153        Primitive::Float(Float::F64) => cx.type_f64(),
1154        Primitive::Float(Float::F128) => cx.type_f128(),
1155        // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
1156        Primitive::Pointer(_) => cx.type_from_integer(dl.ptr_sized_integer()),
1157        _ => ::core::panicking::panic("internal error: entered unreachable code")unreachable!(),
1158    }
1159}
1160
1161fn any_target_feature_enabled(
1162    cx: &CodegenCx<'_, '_>,
1163    instance: Instance<'_>,
1164    features: &[Symbol],
1165) -> bool {
1166    let enabled = cx.tcx.asm_target_features(instance.def_id());
1167    features.iter().any(|feat| enabled.contains(feat))
1168}
1169
1170/// Fix up an input value to work around LLVM bugs.
1171fn llvm_fixup_input<'ll, 'tcx>(
1172    bx: &mut Builder<'_, 'll, 'tcx>,
1173    mut value: &'ll Value,
1174    reg: InlineAsmRegClass,
1175    layout: &TyAndLayout<'tcx>,
1176    instance: Instance<'_>,
1177) -> &'ll Value {
1178    use InlineAsmRegClass::*;
1179    let dl = &bx.tcx.data_layout;
1180    match (reg, layout.backend_repr) {
1181        (AArch64(AArch64InlineAsmRegClass::vreg), BackendRepr::Scalar(s)) => {
1182            if let Primitive::Int(Integer::I8, _) = s.primitive() {
1183                let vec_ty = bx.cx.type_vector(bx.cx.type_i8(), 8);
1184                bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
1185            } else {
1186                value
1187            }
1188        }
1189        (AArch64(AArch64InlineAsmRegClass::vreg_low16), BackendRepr::Scalar(s))
1190            if s.primitive() != Primitive::Float(Float::F128) =>
1191        {
1192            let elem_ty = llvm_asm_scalar_type(bx.cx, s);
1193            let count = 16 / layout.size.bytes();
1194            let vec_ty = bx.cx.type_vector(elem_ty, count);
1195            // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
1196            if let Primitive::Pointer(_) = s.primitive() {
1197                let t = bx.type_from_integer(dl.ptr_sized_integer());
1198                value = bx.ptrtoint(value, t);
1199            }
1200            bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
1201        }
1202        (
1203            AArch64(AArch64InlineAsmRegClass::vreg_low16),
1204            BackendRepr::SimdVector { element, count },
1205        ) if layout.size.bytes() == 8 => {
1206            let elem_ty = llvm_asm_scalar_type(bx.cx, element);
1207            let count = count.as_u32();
1208            let vec_ty = bx.cx.type_vector(elem_ty, u64::from(count));
1209            let indices: Vec<_> = (0..count * 2).map(|x| bx.const_u32(x)).collect();
1210            bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
1211        }
1212        (X86(X86InlineAsmRegClass::reg_abcd), BackendRepr::Scalar(s))
1213            if s.primitive() == Primitive::Float(Float::F64) =>
1214        {
1215            bx.bitcast(value, bx.cx.type_i64())
1216        }
1217        (
1218            X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
1219            BackendRepr::SimdVector { .. },
1220        ) if layout.size.bytes() == 64 => bx.bitcast(value, bx.cx.type_vector(bx.cx.type_f64(), 8)),
1221        (
1222            X86(
1223                X86InlineAsmRegClass::xmm_reg
1224                | X86InlineAsmRegClass::ymm_reg
1225                | X86InlineAsmRegClass::zmm_reg,
1226            ),
1227            BackendRepr::Scalar(s),
1228        ) if bx.sess().asm_arch == Some(InlineAsmArch::X86)
1229            && s.primitive() == Primitive::Float(Float::F128) =>
1230        {
1231            bx.bitcast(value, bx.type_vector(bx.type_i32(), 4))
1232        }
1233        (
1234            X86(
1235                X86InlineAsmRegClass::xmm_reg
1236                | X86InlineAsmRegClass::ymm_reg
1237                | X86InlineAsmRegClass::zmm_reg,
1238            ),
1239            BackendRepr::Scalar(s),
1240        ) if s.primitive() == Primitive::Float(Float::F16) => {
1241            let value = bx.insert_element(
1242                bx.const_undef(bx.type_vector(bx.type_f16(), 8)),
1243                value,
1244                bx.const_usize(0),
1245            );
1246            bx.bitcast(value, bx.type_vector(bx.type_i16(), 8))
1247        }
1248        (
1249            X86(
1250                X86InlineAsmRegClass::xmm_reg
1251                | X86InlineAsmRegClass::ymm_reg
1252                | X86InlineAsmRegClass::zmm_reg,
1253            ),
1254            BackendRepr::SimdVector { element, count },
1255        ) if let count = count.as_u64()
1256            && let 8 | 16 = count
1257            && element.primitive() == Primitive::Float(Float::F16) =>
1258        {
1259            bx.bitcast(value, bx.type_vector(bx.type_i16(), count))
1260        }
1261        (
1262            Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
1263            BackendRepr::Scalar(s),
1264        ) => {
1265            if let Primitive::Int(Integer::I32, _) = s.primitive() {
1266                bx.bitcast(value, bx.cx.type_f32())
1267            } else {
1268                value
1269            }
1270        }
1271        (
1272            Arm(
1273                ArmInlineAsmRegClass::dreg
1274                | ArmInlineAsmRegClass::dreg_low8
1275                | ArmInlineAsmRegClass::dreg_low16,
1276            ),
1277            BackendRepr::Scalar(s),
1278        ) => {
1279            if let Primitive::Int(Integer::I64, _) = s.primitive() {
1280                bx.bitcast(value, bx.cx.type_f64())
1281            } else {
1282                value
1283            }
1284        }
1285        (
1286            Arm(
1287                ArmInlineAsmRegClass::dreg
1288                | ArmInlineAsmRegClass::dreg_low8
1289                | ArmInlineAsmRegClass::dreg_low16
1290                | ArmInlineAsmRegClass::qreg
1291                | ArmInlineAsmRegClass::qreg_low4
1292                | ArmInlineAsmRegClass::qreg_low8,
1293            ),
1294            BackendRepr::SimdVector { element, count },
1295        ) if let count = count.as_u64()
1296            && let 4 | 8 = count
1297            && element.primitive() == Primitive::Float(Float::F16) =>
1298        {
1299            bx.bitcast(value, bx.type_vector(bx.type_i16(), count))
1300        }
1301        (LoongArch(LoongArchInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1302            if s.primitive() == Primitive::Float(Float::F16) =>
1303        {
1304            // The LoongArch psABI only requires the upper bits to be widened to
1305            // GRLEN, leaving them undefined. We NaN-box instead (set all upper
1306            // bits to 1), matching LLVM's own codegen, to avoid an `f16` value
1307            // being mistaken for a valid `f32` value.
1308            let value = bx.bitcast(value, bx.type_i16());
1309            let value = bx.zext(value, bx.type_i32());
1310            let value = bx.or(value, bx.const_u32(0xFFFF_0000));
1311            bx.bitcast(value, bx.type_f32())
1312        }
1313        (Mips(MipsInlineAsmRegClass::reg), BackendRepr::Scalar(s)) => {
1314            match s.primitive() {
1315                // MIPS only supports register-length arithmetics.
1316                Primitive::Int(Integer::I8 | Integer::I16, _) => bx.zext(value, bx.type_i32()),
1317                Primitive::Float(Float::F16) => {
1318                    let value = bx.bitcast(value, bx.type_i16());
1319                    bx.zext(value, bx.type_i32())
1320                }
1321                Primitive::Float(Float::F32) => bx.bitcast(value, bx.type_i32()),
1322                Primitive::Float(Float::F64) => bx.bitcast(value, bx.type_i64()),
1323                _ => value,
1324            }
1325        }
1326        (
1327            Mips(MipsInlineAsmRegClass::freg | MipsInlineAsmRegClass::wreg),
1328            BackendRepr::Scalar(s),
1329        ) if s.primitive() == Primitive::Float(Float::F16) => {
1330            let value = bx.bitcast(value, bx.type_i16());
1331            let value = bx.zext(value, bx.type_i32());
1332            bx.bitcast(value, bx.type_f32())
1333        }
1334        (RiscV(RiscVInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1335            if s.primitive() == Primitive::Float(Float::F16)
1336                && !any_target_feature_enabled(bx, instance, &[sym::zfhmin, sym::zfh]) =>
1337        {
1338            // Smaller floats are always "NaN-boxed" inside larger floats on RISC-V.
1339            let value = bx.bitcast(value, bx.type_i16());
1340            let value = bx.zext(value, bx.type_i32());
1341            let value = bx.or(value, bx.const_u32(0xFFFF_0000));
1342            bx.bitcast(value, bx.type_f32())
1343        }
1344        (
1345            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1346            BackendRepr::Scalar(s),
1347        ) if let Primitive::Float(float @ (Float::F16 | Float::F32 | Float::F64)) =
1348            s.primitive() =>
1349        {
1350            let num_lanes = 16 / float.size().bytes();
1351            // `f16` is located in the rightmost halfword of doubleword 0 per section 7.3.2.5 of
1352            // "Power Instruction Set Architecture", version 3.1C.
1353            let offset = if float == Float::F16 { 3 } else { 0 };
1354            bx.insert_element(
1355                bx.const_undef(bx.type_vector(bx.type_from_float(float), num_lanes)),
1356                value,
1357                bx.const_usize(match bx.target_spec().endian {
1358                    Endian::Little => num_lanes - 1 - offset,
1359                    Endian::Big => offset,
1360                }),
1361            )
1362        }
1363        (
1364            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1365            BackendRepr::Scalar(s),
1366        ) if s.primitive() == Primitive::Float(Float::F128) => {
1367            bx.bitcast(value, bx.type_vector(bx.type_f64(), 2))
1368        }
1369        _ => value,
1370    }
1371}
1372
1373/// Fix up an output value to work around LLVM bugs.
1374fn llvm_fixup_output<'ll, 'tcx>(
1375    bx: &mut Builder<'_, 'll, 'tcx>,
1376    mut value: &'ll Value,
1377    reg: InlineAsmRegClass,
1378    layout: &TyAndLayout<'tcx>,
1379    instance: Instance<'_>,
1380) -> &'ll Value {
1381    use InlineAsmRegClass::*;
1382    match (reg, layout.backend_repr) {
1383        (AArch64(AArch64InlineAsmRegClass::vreg), BackendRepr::Scalar(s)) => {
1384            if let Primitive::Int(Integer::I8, _) = s.primitive() {
1385                bx.extract_element(value, bx.const_i32(0))
1386            } else {
1387                value
1388            }
1389        }
1390        (AArch64(AArch64InlineAsmRegClass::vreg_low16), BackendRepr::Scalar(s))
1391            if s.primitive() != Primitive::Float(Float::F128) =>
1392        {
1393            value = bx.extract_element(value, bx.const_i32(0));
1394            if let Primitive::Pointer(_) = s.primitive() {
1395                value = bx.inttoptr(value, layout.llvm_type(bx.cx));
1396            }
1397            value
1398        }
1399        (
1400            AArch64(AArch64InlineAsmRegClass::vreg_low16),
1401            BackendRepr::SimdVector { element, count },
1402        ) if layout.size.bytes() == 8 => {
1403            let elem_ty = llvm_asm_scalar_type(bx.cx, element);
1404            let count = count.as_u64();
1405            let vec_ty = bx.cx.type_vector(elem_ty, count * 2);
1406            let indices: Vec<_> = (0..count).map(|x| bx.const_i32(x as i32)).collect();
1407            bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
1408        }
1409        (X86(X86InlineAsmRegClass::reg_abcd), BackendRepr::Scalar(s))
1410            if s.primitive() == Primitive::Float(Float::F64) =>
1411        {
1412            bx.bitcast(value, bx.cx.type_f64())
1413        }
1414        (
1415            X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
1416            BackendRepr::SimdVector { .. },
1417        ) if layout.size.bytes() == 64 => bx.bitcast(value, layout.llvm_type(bx.cx)),
1418        (
1419            X86(
1420                X86InlineAsmRegClass::xmm_reg
1421                | X86InlineAsmRegClass::ymm_reg
1422                | X86InlineAsmRegClass::zmm_reg,
1423            ),
1424            BackendRepr::Scalar(s),
1425        ) if bx.sess().asm_arch == Some(InlineAsmArch::X86)
1426            && s.primitive() == Primitive::Float(Float::F128) =>
1427        {
1428            bx.bitcast(value, bx.type_f128())
1429        }
1430        (
1431            X86(
1432                X86InlineAsmRegClass::xmm_reg
1433                | X86InlineAsmRegClass::ymm_reg
1434                | X86InlineAsmRegClass::zmm_reg,
1435            ),
1436            BackendRepr::Scalar(s),
1437        ) if s.primitive() == Primitive::Float(Float::F16) => {
1438            let value = bx.bitcast(value, bx.type_vector(bx.type_f16(), 8));
1439            bx.extract_element(value, bx.const_usize(0))
1440        }
1441        (
1442            X86(
1443                X86InlineAsmRegClass::xmm_reg
1444                | X86InlineAsmRegClass::ymm_reg
1445                | X86InlineAsmRegClass::zmm_reg,
1446            ),
1447            BackendRepr::SimdVector { element, count },
1448        ) if let count = count.as_u64()
1449            && let 8 | 16 = count
1450            && element.primitive() == Primitive::Float(Float::F16) =>
1451        {
1452            bx.bitcast(value, bx.type_vector(bx.type_f16(), count))
1453        }
1454        (
1455            Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
1456            BackendRepr::Scalar(s),
1457        ) => {
1458            if let Primitive::Int(Integer::I32, _) = s.primitive() {
1459                bx.bitcast(value, bx.cx.type_i32())
1460            } else {
1461                value
1462            }
1463        }
1464        (
1465            Arm(
1466                ArmInlineAsmRegClass::dreg
1467                | ArmInlineAsmRegClass::dreg_low8
1468                | ArmInlineAsmRegClass::dreg_low16,
1469            ),
1470            BackendRepr::Scalar(s),
1471        ) => {
1472            if let Primitive::Int(Integer::I64, _) = s.primitive() {
1473                bx.bitcast(value, bx.cx.type_i64())
1474            } else {
1475                value
1476            }
1477        }
1478        (
1479            Arm(
1480                ArmInlineAsmRegClass::dreg
1481                | ArmInlineAsmRegClass::dreg_low8
1482                | ArmInlineAsmRegClass::dreg_low16
1483                | ArmInlineAsmRegClass::qreg
1484                | ArmInlineAsmRegClass::qreg_low4
1485                | ArmInlineAsmRegClass::qreg_low8,
1486            ),
1487            BackendRepr::SimdVector { element, count },
1488        ) if let count = count.as_u64()
1489            && let 4 | 8 = count
1490            && element.primitive() == Primitive::Float(Float::F16) =>
1491        {
1492            bx.bitcast(value, bx.type_vector(bx.type_f16(), count))
1493        }
1494        (LoongArch(LoongArchInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1495            if s.primitive() == Primitive::Float(Float::F16) =>
1496        {
1497            let value = bx.bitcast(value, bx.type_i32());
1498            let value = bx.trunc(value, bx.type_i16());
1499            bx.bitcast(value, bx.type_f16())
1500        }
1501        (Mips(MipsInlineAsmRegClass::reg), BackendRepr::Scalar(s)) => {
1502            match s.primitive() {
1503                // MIPS only supports register-length arithmetics.
1504                Primitive::Int(Integer::I8, _) => bx.trunc(value, bx.type_i8()),
1505                Primitive::Int(Integer::I16, _) => bx.trunc(value, bx.type_i16()),
1506                Primitive::Float(Float::F16) => {
1507                    let value = bx.trunc(value, bx.type_i16());
1508                    bx.bitcast(value, bx.type_f16())
1509                }
1510                Primitive::Float(Float::F32) => bx.bitcast(value, bx.type_f32()),
1511                Primitive::Float(Float::F64) => bx.bitcast(value, bx.type_f64()),
1512                _ => value,
1513            }
1514        }
1515        (
1516            Mips(MipsInlineAsmRegClass::freg | MipsInlineAsmRegClass::wreg),
1517            BackendRepr::Scalar(s),
1518        ) if s.primitive() == Primitive::Float(Float::F16) => {
1519            let value = bx.bitcast(value, bx.type_i32());
1520            let value = bx.trunc(value, bx.type_i16());
1521            bx.bitcast(value, bx.type_f16())
1522        }
1523        (RiscV(RiscVInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1524            if s.primitive() == Primitive::Float(Float::F16)
1525                && !any_target_feature_enabled(bx, instance, &[sym::zfhmin, sym::zfh]) =>
1526        {
1527            let value = bx.bitcast(value, bx.type_i32());
1528            let value = bx.trunc(value, bx.type_i16());
1529            bx.bitcast(value, bx.type_f16())
1530        }
1531        (
1532            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1533            BackendRepr::Scalar(s),
1534        ) if let Primitive::Float(float @ (Float::F16 | Float::F32 | Float::F64)) =
1535            s.primitive() =>
1536        {
1537            let num_lanes = 16 / float.size().bytes();
1538            // `f16` is located in the rightmost halfword of doubleword 0 per section 7.3.2.5 of
1539            // "Power Instruction Set Architecture", version 3.1C.
1540            let offset = if float == Float::F16 { 3 } else { 0 };
1541            bx.extract_element(
1542                value,
1543                bx.const_usize(match bx.target_spec().endian {
1544                    Endian::Little => num_lanes - 1 - offset,
1545                    Endian::Big => offset,
1546                }),
1547            )
1548        }
1549        (
1550            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1551            BackendRepr::Scalar(s),
1552        ) if s.primitive() == Primitive::Float(Float::F128) => bx.bitcast(value, bx.type_f128()),
1553        _ => value,
1554    }
1555}
1556
1557/// Output type to use for llvm_fixup_output.
1558fn llvm_fixup_output_type<'ll, 'tcx>(
1559    cx: &CodegenCx<'ll, 'tcx>,
1560    reg: InlineAsmRegClass,
1561    layout: &TyAndLayout<'tcx>,
1562    instance: Instance<'_>,
1563) -> &'ll Type {
1564    use InlineAsmRegClass::*;
1565    match (reg, layout.backend_repr) {
1566        (AArch64(AArch64InlineAsmRegClass::vreg), BackendRepr::Scalar(s)) => {
1567            if let Primitive::Int(Integer::I8, _) = s.primitive() {
1568                cx.type_vector(cx.type_i8(), 8)
1569            } else {
1570                layout.llvm_type(cx)
1571            }
1572        }
1573        (AArch64(AArch64InlineAsmRegClass::vreg_low16), BackendRepr::Scalar(s))
1574            if s.primitive() != Primitive::Float(Float::F128) =>
1575        {
1576            let elem_ty = llvm_asm_scalar_type(cx, s);
1577            let count = 16 / layout.size.bytes();
1578            cx.type_vector(elem_ty, count)
1579        }
1580        (
1581            AArch64(AArch64InlineAsmRegClass::vreg_low16),
1582            BackendRepr::SimdVector { element, count },
1583        ) if layout.size.bytes() == 8 => {
1584            let elem_ty = llvm_asm_scalar_type(cx, element);
1585            cx.type_vector(elem_ty, count.as_u64() * 2)
1586        }
1587        (X86(X86InlineAsmRegClass::reg_abcd), BackendRepr::Scalar(s))
1588            if s.primitive() == Primitive::Float(Float::F64) =>
1589        {
1590            cx.type_i64()
1591        }
1592        (
1593            X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
1594            BackendRepr::SimdVector { .. },
1595        ) if layout.size.bytes() == 64 => cx.type_vector(cx.type_f64(), 8),
1596        (
1597            X86(
1598                X86InlineAsmRegClass::xmm_reg
1599                | X86InlineAsmRegClass::ymm_reg
1600                | X86InlineAsmRegClass::zmm_reg,
1601            ),
1602            BackendRepr::Scalar(s),
1603        ) if cx.sess().asm_arch == Some(InlineAsmArch::X86)
1604            && s.primitive() == Primitive::Float(Float::F128) =>
1605        {
1606            cx.type_vector(cx.type_i32(), 4)
1607        }
1608        (
1609            X86(
1610                X86InlineAsmRegClass::xmm_reg
1611                | X86InlineAsmRegClass::ymm_reg
1612                | X86InlineAsmRegClass::zmm_reg,
1613            ),
1614            BackendRepr::Scalar(s),
1615        ) if s.primitive() == Primitive::Float(Float::F16) => cx.type_vector(cx.type_i16(), 8),
1616        (
1617            X86(
1618                X86InlineAsmRegClass::xmm_reg
1619                | X86InlineAsmRegClass::ymm_reg
1620                | X86InlineAsmRegClass::zmm_reg,
1621            ),
1622            BackendRepr::SimdVector { element, count },
1623        ) if let count = count.as_u64()
1624            && let 8 | 16 = count
1625            && element.primitive() == Primitive::Float(Float::F16) =>
1626        {
1627            cx.type_vector(cx.type_i16(), count)
1628        }
1629        (
1630            Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
1631            BackendRepr::Scalar(s),
1632        ) => {
1633            if let Primitive::Int(Integer::I32, _) = s.primitive() {
1634                cx.type_f32()
1635            } else {
1636                layout.llvm_type(cx)
1637            }
1638        }
1639        (
1640            Arm(
1641                ArmInlineAsmRegClass::dreg
1642                | ArmInlineAsmRegClass::dreg_low8
1643                | ArmInlineAsmRegClass::dreg_low16,
1644            ),
1645            BackendRepr::Scalar(s),
1646        ) => {
1647            if let Primitive::Int(Integer::I64, _) = s.primitive() {
1648                cx.type_f64()
1649            } else {
1650                layout.llvm_type(cx)
1651            }
1652        }
1653        (
1654            Arm(
1655                ArmInlineAsmRegClass::dreg
1656                | ArmInlineAsmRegClass::dreg_low8
1657                | ArmInlineAsmRegClass::dreg_low16
1658                | ArmInlineAsmRegClass::qreg
1659                | ArmInlineAsmRegClass::qreg_low4
1660                | ArmInlineAsmRegClass::qreg_low8,
1661            ),
1662            BackendRepr::SimdVector { element, count },
1663        ) if let count = count.as_u64()
1664            && let 4 | 8 = count
1665            && element.primitive() == Primitive::Float(Float::F16) =>
1666        {
1667            cx.type_vector(cx.type_i16(), count)
1668        }
1669        (LoongArch(LoongArchInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1670            if s.primitive() == Primitive::Float(Float::F16) =>
1671        {
1672            cx.type_f32()
1673        }
1674        (Mips(MipsInlineAsmRegClass::reg), BackendRepr::Scalar(s)) => {
1675            match s.primitive() {
1676                // MIPS only supports register-length arithmetics.
1677                Primitive::Int(Integer::I8 | Integer::I16, _) => cx.type_i32(),
1678                Primitive::Float(Float::F16 | Float::F32) => cx.type_i32(),
1679                Primitive::Float(Float::F64) => cx.type_i64(),
1680                _ => layout.llvm_type(cx),
1681            }
1682        }
1683
1684        (
1685            Mips(MipsInlineAsmRegClass::freg | MipsInlineAsmRegClass::wreg),
1686            BackendRepr::Scalar(s),
1687        ) if s.primitive() == Primitive::Float(Float::F16) => cx.type_f32(),
1688        (RiscV(RiscVInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1689            if s.primitive() == Primitive::Float(Float::F16)
1690                && !any_target_feature_enabled(cx, instance, &[sym::zfhmin, sym::zfh]) =>
1691        {
1692            cx.type_f32()
1693        }
1694        (
1695            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1696            BackendRepr::Scalar(s),
1697        ) if let Primitive::Float(float @ (Float::F16 | Float::F32 | Float::F64)) =
1698            s.primitive() =>
1699        {
1700            cx.type_vector(cx.type_from_float(float), 16 / float.size().bytes())
1701        }
1702        (
1703            PowerPC(PowerPCInlineAsmRegClass::vreg | PowerPCInlineAsmRegClass::vsreg),
1704            BackendRepr::Scalar(s),
1705        ) if s.primitive() == Primitive::Float(Float::F128) => cx.type_vector(cx.type_f64(), 2),
1706        _ => layout.llvm_type(cx),
1707    }
1708}