rustc_codegen_llvm/
asm.rs

1use std::assert_matches::assert_matches;
2
3use rustc_abi::{BackendRepr, Float, Integer, Primitive, Scalar};
4use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
5use rustc_codegen_ssa::mir::operand::OperandValue;
6use rustc_codegen_ssa::traits::*;
7use rustc_data_structures::fx::FxHashMap;
8use rustc_middle::ty::Instance;
9use rustc_middle::ty::layout::TyAndLayout;
10use rustc_middle::{bug, span_bug};
11use rustc_span::{Pos, Span, Symbol, sym};
12use rustc_target::asm::*;
13use smallvec::SmallVec;
14use tracing::debug;
15
16use crate::attributes;
17use crate::builder::Builder;
18use crate::common::Funclet;
19use crate::context::CodegenCx;
20use crate::llvm::{self, ToLlvmBool, Type, Value};
21use crate::type_of::LayoutLlvmExt;
22
23impl<'ll, 'tcx> AsmBuilderMethods<'tcx> for Builder<'_, 'll, 'tcx> {
24    fn codegen_inline_asm(
25        &mut self,
26        template: &[InlineAsmTemplatePiece],
27        operands: &[InlineAsmOperandRef<'tcx, Self>],
28        options: InlineAsmOptions,
29        line_spans: &[Span],
30        instance: Instance<'_>,
31        dest: Option<Self::BasicBlock>,
32        catch_funclet: Option<(Self::BasicBlock, Option<&Self::Funclet>)>,
33    ) {
34        let asm_arch = self.tcx.sess.asm_arch.unwrap();
35
36        // Collect the types of output operands
37        let mut constraints = vec![];
38        let mut clobbers = vec![];
39        let mut output_types = vec![];
40        let mut op_idx = FxHashMap::default();
41        let mut clobbered_x87 = false;
42        for (idx, op) in operands.iter().enumerate() {
43            match *op {
44                InlineAsmOperandRef::Out { reg, late, place } => {
45                    let is_target_supported = |reg_class: InlineAsmRegClass| {
46                        for &(_, feature) in reg_class.supported_types(asm_arch, true) {
47                            if let Some(feature) = feature {
48                                if self
49                                    .tcx
50                                    .asm_target_features(instance.def_id())
51                                    .contains(&feature)
52                                {
53                                    return true;
54                                }
55                            } else {
56                                // Register class is unconditionally supported
57                                return true;
58                            }
59                        }
60                        false
61                    };
62
63                    let mut layout = None;
64                    let ty = if let Some(ref place) = place {
65                        layout = Some(&place.layout);
66                        llvm_fixup_output_type(self.cx, reg.reg_class(), &place.layout, instance)
67                    } else if matches!(
68                        reg.reg_class(),
69                        InlineAsmRegClass::X86(
70                            X86InlineAsmRegClass::mmx_reg | X86InlineAsmRegClass::x87_reg
71                        )
72                    ) {
73                        // Special handling for x87/mmx registers: we always
74                        // clobber the whole set if one register is marked as
75                        // clobbered. This is due to the way LLVM handles the
76                        // FP stack in inline assembly.
77                        if !clobbered_x87 {
78                            clobbered_x87 = true;
79                            clobbers.push("~{st}".to_string());
80                            for i in 1..=7 {
81                                clobbers.push(format!("~{{st({})}}", i));
82                            }
83                        }
84                        continue;
85                    } else if !is_target_supported(reg.reg_class())
86                        || reg.reg_class().is_clobber_only(asm_arch, true)
87                    {
88                        // We turn discarded outputs into clobber constraints
89                        // if the target feature needed by the register class is
90                        // disabled. This is necessary otherwise LLVM will try
91                        // to actually allocate a register for the dummy output.
92                        assert_matches!(reg, InlineAsmRegOrRegClass::Reg(_));
93                        clobbers.push(format!("~{}", reg_to_llvm(reg, None)));
94                        continue;
95                    } else {
96                        // If the output is discarded, we don't really care what
97                        // type is used. We're just using this to tell LLVM to
98                        // reserve the register.
99                        dummy_output_type(self.cx, reg.reg_class())
100                    };
101                    output_types.push(ty);
102                    op_idx.insert(idx, constraints.len());
103                    let prefix = if late { "=" } else { "=&" };
104                    constraints.push(format!("{}{}", prefix, reg_to_llvm(reg, layout)));
105                }
106                InlineAsmOperandRef::InOut { reg, late, in_value, out_place } => {
107                    let layout = if let Some(ref out_place) = out_place {
108                        &out_place.layout
109                    } else {
110                        // LLVM required tied operands to have the same type,
111                        // so we just use the type of the input.
112                        &in_value.layout
113                    };
114                    let ty = llvm_fixup_output_type(self.cx, reg.reg_class(), layout, instance);
115                    output_types.push(ty);
116                    op_idx.insert(idx, constraints.len());
117                    let prefix = if late { "=" } else { "=&" };
118                    constraints.push(format!("{}{}", prefix, reg_to_llvm(reg, Some(layout))));
119                }
120                _ => {}
121            }
122        }
123
124        // Collect input operands
125        let mut inputs = vec![];
126        for (idx, op) in operands.iter().enumerate() {
127            match *op {
128                InlineAsmOperandRef::In { reg, value } => {
129                    let llval = llvm_fixup_input(
130                        self,
131                        value.immediate(),
132                        reg.reg_class(),
133                        &value.layout,
134                        instance,
135                    );
136                    inputs.push(llval);
137                    op_idx.insert(idx, constraints.len());
138                    constraints.push(reg_to_llvm(reg, Some(&value.layout)));
139                }
140                InlineAsmOperandRef::InOut { reg, late, in_value, out_place: _ } => {
141                    let value = llvm_fixup_input(
142                        self,
143                        in_value.immediate(),
144                        reg.reg_class(),
145                        &in_value.layout,
146                        instance,
147                    );
148                    inputs.push(value);
149
150                    // In the case of fixed registers, we have the choice of
151                    // either using a tied operand or duplicating the constraint.
152                    // We prefer the latter because it matches the behavior of
153                    // Clang.
154                    if late && matches!(reg, InlineAsmRegOrRegClass::Reg(_)) {
155                        constraints.push(reg_to_llvm(reg, Some(&in_value.layout)));
156                    } else {
157                        constraints.push(format!("{}", op_idx[&idx]));
158                    }
159                }
160                InlineAsmOperandRef::SymFn { instance } => {
161                    inputs.push(self.cx.get_fn(instance));
162                    op_idx.insert(idx, constraints.len());
163                    constraints.push("s".to_string());
164                }
165                InlineAsmOperandRef::SymStatic { def_id } => {
166                    inputs.push(self.cx.get_static(def_id));
167                    op_idx.insert(idx, constraints.len());
168                    constraints.push("s".to_string());
169                }
170                _ => {}
171            }
172        }
173
174        // Build the template string
175        let mut labels = vec![];
176        let mut template_str = String::new();
177        for piece in template {
178            match *piece {
179                InlineAsmTemplatePiece::String(ref s) => {
180                    if s.contains('$') {
181                        for c in s.chars() {
182                            if c == '$' {
183                                template_str.push_str("$$");
184                            } else {
185                                template_str.push(c);
186                            }
187                        }
188                    } else {
189                        template_str.push_str(s)
190                    }
191                }
192                InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span: _ } => {
193                    match operands[operand_idx] {
194                        InlineAsmOperandRef::In { reg, .. }
195                        | InlineAsmOperandRef::Out { reg, .. }
196                        | InlineAsmOperandRef::InOut { reg, .. } => {
197                            let modifier = modifier_to_llvm(asm_arch, reg.reg_class(), modifier);
198                            if let Some(modifier) = modifier {
199                                template_str.push_str(&format!(
200                                    "${{{}:{}}}",
201                                    op_idx[&operand_idx], modifier
202                                ));
203                            } else {
204                                template_str.push_str(&format!("${{{}}}", op_idx[&operand_idx]));
205                            }
206                        }
207                        InlineAsmOperandRef::Const { ref string } => {
208                            // Const operands get injected directly into the template
209                            template_str.push_str(string);
210                        }
211                        InlineAsmOperandRef::SymFn { .. }
212                        | InlineAsmOperandRef::SymStatic { .. } => {
213                            // Only emit the raw symbol name
214                            template_str.push_str(&format!("${{{}:c}}", op_idx[&operand_idx]));
215                        }
216                        InlineAsmOperandRef::Label { label } => {
217                            template_str.push_str(&format!("${{{}:l}}", constraints.len()));
218                            constraints.push("!i".to_owned());
219                            labels.push(label);
220                        }
221                    }
222                }
223            }
224        }
225
226        constraints.append(&mut clobbers);
227        if !options.contains(InlineAsmOptions::PRESERVES_FLAGS) {
228            match asm_arch {
229                InlineAsmArch::AArch64 | InlineAsmArch::Arm64EC | InlineAsmArch::Arm => {
230                    constraints.push("~{cc}".to_string());
231                }
232                InlineAsmArch::X86 | InlineAsmArch::X86_64 => {
233                    constraints.extend_from_slice(&[
234                        "~{dirflag}".to_string(),
235                        "~{fpsr}".to_string(),
236                        "~{flags}".to_string(),
237                    ]);
238                }
239                InlineAsmArch::RiscV32 | InlineAsmArch::RiscV64 => {
240                    constraints.extend_from_slice(&[
241                        "~{fflags}".to_string(),
242                        "~{vtype}".to_string(),
243                        "~{vl}".to_string(),
244                        "~{vxsat}".to_string(),
245                        "~{vxrm}".to_string(),
246                    ]);
247                }
248                InlineAsmArch::Avr => {
249                    constraints.push("~{sreg}".to_string());
250                }
251                InlineAsmArch::Nvptx64 => {}
252                InlineAsmArch::PowerPC | InlineAsmArch::PowerPC64 => {}
253                InlineAsmArch::Hexagon => {}
254                InlineAsmArch::LoongArch32 | InlineAsmArch::LoongArch64 => {
255                    constraints.extend_from_slice(&[
256                        "~{$fcc0}".to_string(),
257                        "~{$fcc1}".to_string(),
258                        "~{$fcc2}".to_string(),
259                        "~{$fcc3}".to_string(),
260                        "~{$fcc4}".to_string(),
261                        "~{$fcc5}".to_string(),
262                        "~{$fcc6}".to_string(),
263                        "~{$fcc7}".to_string(),
264                    ]);
265                }
266                InlineAsmArch::Mips | InlineAsmArch::Mips64 => {}
267                InlineAsmArch::S390x => {
268                    constraints.push("~{cc}".to_string());
269                }
270                InlineAsmArch::Sparc | InlineAsmArch::Sparc64 => {
271                    // In LLVM, ~{icc} represents icc and xcc in 64-bit code.
272                    // https://github.com/llvm/llvm-project/blob/llvmorg-19.1.0/llvm/lib/Target/Sparc/SparcRegisterInfo.td#L64
273                    constraints.push("~{icc}".to_string());
274                    constraints.push("~{fcc0}".to_string());
275                    constraints.push("~{fcc1}".to_string());
276                    constraints.push("~{fcc2}".to_string());
277                    constraints.push("~{fcc3}".to_string());
278                }
279                InlineAsmArch::SpirV => {}
280                InlineAsmArch::Wasm32 | InlineAsmArch::Wasm64 => {}
281                InlineAsmArch::Bpf => {}
282                InlineAsmArch::Msp430 => {
283                    constraints.push("~{sr}".to_string());
284                }
285                InlineAsmArch::M68k => {
286                    constraints.push("~{ccr}".to_string());
287                }
288                InlineAsmArch::CSKY => {
289                    constraints.push("~{psr}".to_string());
290                }
291            }
292        }
293        if !options.contains(InlineAsmOptions::NOMEM) {
294            // This is actually ignored by LLVM, but it's probably best to keep
295            // it just in case. LLVM instead uses the ReadOnly/ReadNone
296            // attributes on the call instruction to optimize.
297            constraints.push("~{memory}".to_string());
298        }
299        let volatile = !options.contains(InlineAsmOptions::PURE);
300        let alignstack = !options.contains(InlineAsmOptions::NOSTACK);
301        let output_type = match &output_types[..] {
302            [] => self.type_void(),
303            [ty] => ty,
304            tys => self.type_struct(tys, false),
305        };
306        let dialect = match asm_arch {
307            InlineAsmArch::X86 | InlineAsmArch::X86_64
308                if !options.contains(InlineAsmOptions::ATT_SYNTAX) =>
309            {
310                llvm::AsmDialect::Intel
311            }
312            _ => llvm::AsmDialect::Att,
313        };
314        let result = inline_asm_call(
315            self,
316            &template_str,
317            &constraints.join(","),
318            &inputs,
319            output_type,
320            &labels,
321            volatile,
322            alignstack,
323            dialect,
324            line_spans,
325            options.contains(InlineAsmOptions::MAY_UNWIND),
326            dest,
327            catch_funclet,
328        )
329        .unwrap_or_else(|| span_bug!(line_spans[0], "LLVM asm constraint validation failed"));
330
331        let mut attrs = SmallVec::<[_; 2]>::new();
332        if options.contains(InlineAsmOptions::PURE) {
333            if options.contains(InlineAsmOptions::NOMEM) {
334                attrs.push(llvm::MemoryEffects::None.create_attr(self.cx.llcx));
335            } else if options.contains(InlineAsmOptions::READONLY) {
336                attrs.push(llvm::MemoryEffects::ReadOnly.create_attr(self.cx.llcx));
337            }
338            attrs.push(llvm::AttributeKind::WillReturn.create_attr(self.cx.llcx));
339        } else if options.contains(InlineAsmOptions::NOMEM) {
340            attrs.push(llvm::MemoryEffects::InaccessibleMemOnly.create_attr(self.cx.llcx));
341        } else if options.contains(InlineAsmOptions::READONLY) {
342            attrs.push(llvm::MemoryEffects::ReadOnlyNotPure.create_attr(self.cx.llcx));
343        }
344        attributes::apply_to_callsite(result, llvm::AttributePlace::Function, &{ attrs });
345
346        // Write results to outputs. We need to do this for all possible control flow.
347        //
348        // Note that `dest` maybe populated with unreachable_block when asm goto with outputs
349        // is used (because we need to codegen callbr which always needs a destination), so
350        // here we use the NORETURN option to determine if `dest` should be used.
351        for block in (if options.contains(InlineAsmOptions::NORETURN) { None } else { Some(dest) })
352            .into_iter()
353            .chain(labels.iter().copied().map(Some))
354        {
355            if let Some(block) = block {
356                self.switch_to_block(block);
357            }
358
359            for (idx, op) in operands.iter().enumerate() {
360                if let InlineAsmOperandRef::Out { reg, place: Some(place), .. }
361                | InlineAsmOperandRef::InOut { reg, out_place: Some(place), .. } = *op
362                {
363                    let value = if output_types.len() == 1 {
364                        result
365                    } else {
366                        self.extract_value(result, op_idx[&idx] as u64)
367                    };
368                    let value =
369                        llvm_fixup_output(self, value, reg.reg_class(), &place.layout, instance);
370                    OperandValue::Immediate(value).store(self, place);
371                }
372            }
373        }
374    }
375}
376
377impl<'tcx> AsmCodegenMethods<'tcx> for CodegenCx<'_, 'tcx> {
378    fn codegen_global_asm(
379        &mut self,
380        template: &[InlineAsmTemplatePiece],
381        operands: &[GlobalAsmOperandRef<'tcx>],
382        options: InlineAsmOptions,
383        _line_spans: &[Span],
384    ) {
385        let asm_arch = self.tcx.sess.asm_arch.unwrap();
386
387        // Build the template string
388        let mut template_str = String::new();
389
390        // On X86 platforms there are two assembly syntaxes. Rust uses intel by default,
391        // but AT&T can be specified explicitly.
392        if matches!(asm_arch, InlineAsmArch::X86 | InlineAsmArch::X86_64) {
393            if options.contains(InlineAsmOptions::ATT_SYNTAX) {
394                template_str.push_str(".att_syntax\n")
395            } else {
396                template_str.push_str(".intel_syntax\n")
397            }
398        }
399
400        for piece in template {
401            match *piece {
402                InlineAsmTemplatePiece::String(ref s) => template_str.push_str(s),
403                InlineAsmTemplatePiece::Placeholder { operand_idx, modifier: _, span: _ } => {
404                    match operands[operand_idx] {
405                        GlobalAsmOperandRef::Const { ref string } => {
406                            // Const operands get injected directly into the
407                            // template. Note that we don't need to escape $
408                            // here unlike normal inline assembly.
409                            template_str.push_str(string);
410                        }
411                        GlobalAsmOperandRef::SymFn { instance } => {
412                            let llval = self.get_fn(instance);
413                            self.add_compiler_used_global(llval);
414                            let symbol = llvm::build_string(|s| unsafe {
415                                llvm::LLVMRustGetMangledName(llval, s);
416                            })
417                            .expect("symbol is not valid UTF-8");
418                            template_str.push_str(&symbol);
419                        }
420                        GlobalAsmOperandRef::SymStatic { def_id } => {
421                            let llval = self
422                                .renamed_statics
423                                .borrow()
424                                .get(&def_id)
425                                .copied()
426                                .unwrap_or_else(|| self.get_static(def_id));
427                            self.add_compiler_used_global(llval);
428                            let symbol = llvm::build_string(|s| unsafe {
429                                llvm::LLVMRustGetMangledName(llval, s);
430                            })
431                            .expect("symbol is not valid UTF-8");
432                            template_str.push_str(&symbol);
433                        }
434                    }
435                }
436            }
437        }
438
439        // Just to play it safe, if intel was used, reset the assembly syntax to att.
440        if matches!(asm_arch, InlineAsmArch::X86 | InlineAsmArch::X86_64)
441            && !options.contains(InlineAsmOptions::ATT_SYNTAX)
442        {
443            template_str.push_str("\n.att_syntax\n");
444        }
445
446        llvm::append_module_inline_asm(self.llmod, template_str.as_bytes());
447    }
448
449    fn mangled_name(&self, instance: Instance<'tcx>) -> String {
450        let llval = self.get_fn(instance);
451        llvm::build_string(|s| unsafe {
452            llvm::LLVMRustGetMangledName(llval, s);
453        })
454        .expect("symbol is not valid UTF-8")
455    }
456}
457
458pub(crate) fn inline_asm_call<'ll>(
459    bx: &mut Builder<'_, 'll, '_>,
460    asm: &str,
461    cons: &str,
462    inputs: &[&'ll Value],
463    output: &'ll llvm::Type,
464    labels: &[&'ll llvm::BasicBlock],
465    volatile: bool,
466    alignstack: bool,
467    dia: llvm::AsmDialect,
468    line_spans: &[Span],
469    unwind: bool,
470    dest: Option<&'ll llvm::BasicBlock>,
471    catch_funclet: Option<(&'ll llvm::BasicBlock, Option<&Funclet<'ll>>)>,
472) -> Option<&'ll Value> {
473    let argtys = inputs
474        .iter()
475        .map(|v| {
476            debug!("Asm Input Type: {:?}", *v);
477            bx.cx.val_ty(*v)
478        })
479        .collect::<Vec<_>>();
480
481    debug!("Asm Output Type: {:?}", output);
482    let fty = bx.cx.type_func(&argtys, output);
483
484    // Ask LLVM to verify that the constraints are well-formed.
485    let constraints_ok = unsafe { llvm::LLVMRustInlineAsmVerify(fty, cons.as_ptr(), cons.len()) };
486    debug!("constraint verification result: {:?}", constraints_ok);
487    if !constraints_ok {
488        // LLVM has detected an issue with our constraints, so bail out.
489        return None;
490    }
491
492    let v = unsafe {
493        llvm::LLVMGetInlineAsm(
494            fty,
495            asm.as_ptr(),
496            asm.len(),
497            cons.as_ptr(),
498            cons.len(),
499            volatile.to_llvm_bool(),
500            alignstack.to_llvm_bool(),
501            dia,
502            unwind.to_llvm_bool(),
503        )
504    };
505
506    let call = if !labels.is_empty() {
507        assert!(catch_funclet.is_none());
508        bx.callbr(fty, None, None, v, inputs, dest.unwrap(), labels, None, None)
509    } else if let Some((catch, funclet)) = catch_funclet {
510        bx.invoke(fty, None, None, v, inputs, dest.unwrap(), catch, funclet, None)
511    } else {
512        bx.call(fty, None, None, v, inputs, None, None)
513    };
514
515    // Store mark in a metadata node so we can map LLVM errors
516    // back to source locations. See #17552.
517    let key = "srcloc";
518    let kind = bx.get_md_kind_id(key);
519
520    // `srcloc` contains one 64-bit integer for each line of assembly code,
521    // where the lower 32 bits hold the lo byte position and the upper 32 bits
522    // hold the hi byte position.
523    let mut srcloc = vec![];
524    if dia == llvm::AsmDialect::Intel && line_spans.len() > 1 {
525        // LLVM inserts an extra line to add the ".intel_syntax", so add
526        // a dummy srcloc entry for it.
527        //
528        // Don't do this if we only have 1 line span since that may be
529        // due to the asm template string coming from a macro. LLVM will
530        // default to the first srcloc for lines that don't have an
531        // associated srcloc.
532        srcloc.push(llvm::LLVMValueAsMetadata(bx.const_u64(0)));
533    }
534    srcloc.extend(line_spans.iter().map(|span| {
535        llvm::LLVMValueAsMetadata(
536            bx.const_u64(u64::from(span.lo().to_u32()) | (u64::from(span.hi().to_u32()) << 32)),
537        )
538    }));
539    bx.cx.set_metadata_node(call, kind, &srcloc);
540
541    Some(call)
542}
543
544/// If the register is an xmm/ymm/zmm register then return its index.
545fn xmm_reg_index(reg: InlineAsmReg) -> Option<u32> {
546    use X86InlineAsmReg::*;
547    match reg {
548        InlineAsmReg::X86(reg) if reg as u32 >= xmm0 as u32 && reg as u32 <= xmm15 as u32 => {
549            Some(reg as u32 - xmm0 as u32)
550        }
551        InlineAsmReg::X86(reg) if reg as u32 >= ymm0 as u32 && reg as u32 <= ymm15 as u32 => {
552            Some(reg as u32 - ymm0 as u32)
553        }
554        InlineAsmReg::X86(reg) if reg as u32 >= zmm0 as u32 && reg as u32 <= zmm31 as u32 => {
555            Some(reg as u32 - zmm0 as u32)
556        }
557        _ => None,
558    }
559}
560
561/// If the register is an AArch64 integer register then return its index.
562fn a64_reg_index(reg: InlineAsmReg) -> Option<u32> {
563    match reg {
564        InlineAsmReg::AArch64(r) => r.reg_index(),
565        _ => None,
566    }
567}
568
569/// If the register is an AArch64 vector register then return its index.
570fn a64_vreg_index(reg: InlineAsmReg) -> Option<u32> {
571    match reg {
572        InlineAsmReg::AArch64(reg) => reg.vreg_index(),
573        _ => None,
574    }
575}
576
577/// Converts a register class to an LLVM constraint code.
578fn reg_to_llvm(reg: InlineAsmRegOrRegClass, layout: Option<&TyAndLayout<'_>>) -> String {
579    use InlineAsmRegClass::*;
580    match reg {
581        // For vector registers LLVM wants the register name to match the type size.
582        InlineAsmRegOrRegClass::Reg(reg) => {
583            if let Some(idx) = xmm_reg_index(reg) {
584                let class = if let Some(layout) = layout {
585                    match layout.size.bytes() {
586                        64 => 'z',
587                        32 => 'y',
588                        _ => 'x',
589                    }
590                } else {
591                    // We use f32 as the type for discarded outputs
592                    'x'
593                };
594                format!("{{{}mm{}}}", class, idx)
595            } else if let Some(idx) = a64_reg_index(reg) {
596                let class = if let Some(layout) = layout {
597                    match layout.size.bytes() {
598                        8 => 'x',
599                        _ => 'w',
600                    }
601                } else {
602                    // We use i32 as the type for discarded outputs
603                    'w'
604                };
605                if class == 'x' && reg == InlineAsmReg::AArch64(AArch64InlineAsmReg::x30) {
606                    // LLVM doesn't recognize x30. use lr instead.
607                    "{lr}".to_string()
608                } else {
609                    format!("{{{}{}}}", class, idx)
610                }
611            } else if let Some(idx) = a64_vreg_index(reg) {
612                let class = if let Some(layout) = layout {
613                    match layout.size.bytes() {
614                        16 => 'q',
615                        8 => 'd',
616                        4 => 's',
617                        2 => 'h',
618                        1 => 'd', // We fixup i8 to i8x8
619                        _ => unreachable!(),
620                    }
621                } else {
622                    // We use i64x2 as the type for discarded outputs
623                    'q'
624                };
625                format!("{{{}{}}}", class, idx)
626            } else if reg == InlineAsmReg::Arm(ArmInlineAsmReg::r14) {
627                // LLVM doesn't recognize r14
628                "{lr}".to_string()
629            } else {
630                format!("{{{}}}", reg.name())
631            }
632        }
633        // The constraints can be retrieved from
634        // https://llvm.org/docs/LangRef.html#supported-constraint-code-list
635        InlineAsmRegOrRegClass::RegClass(reg) => match reg {
636            AArch64(AArch64InlineAsmRegClass::reg) => "r",
637            AArch64(AArch64InlineAsmRegClass::vreg) => "w",
638            AArch64(AArch64InlineAsmRegClass::vreg_low16) => "x",
639            AArch64(AArch64InlineAsmRegClass::preg) => unreachable!("clobber-only"),
640            Arm(ArmInlineAsmRegClass::reg) => "r",
641            Arm(ArmInlineAsmRegClass::sreg)
642            | Arm(ArmInlineAsmRegClass::dreg_low16)
643            | Arm(ArmInlineAsmRegClass::qreg_low8) => "t",
644            Arm(ArmInlineAsmRegClass::sreg_low16)
645            | Arm(ArmInlineAsmRegClass::dreg_low8)
646            | Arm(ArmInlineAsmRegClass::qreg_low4) => "x",
647            Arm(ArmInlineAsmRegClass::dreg) | Arm(ArmInlineAsmRegClass::qreg) => "w",
648            Hexagon(HexagonInlineAsmRegClass::reg) => "r",
649            Hexagon(HexagonInlineAsmRegClass::preg) => unreachable!("clobber-only"),
650            LoongArch(LoongArchInlineAsmRegClass::reg) => "r",
651            LoongArch(LoongArchInlineAsmRegClass::freg) => "f",
652            Mips(MipsInlineAsmRegClass::reg) => "r",
653            Mips(MipsInlineAsmRegClass::freg) => "f",
654            Nvptx(NvptxInlineAsmRegClass::reg16) => "h",
655            Nvptx(NvptxInlineAsmRegClass::reg32) => "r",
656            Nvptx(NvptxInlineAsmRegClass::reg64) => "l",
657            PowerPC(PowerPCInlineAsmRegClass::reg) => "r",
658            PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => "b",
659            PowerPC(PowerPCInlineAsmRegClass::freg) => "f",
660            PowerPC(PowerPCInlineAsmRegClass::vreg) => "v",
661            PowerPC(
662                PowerPCInlineAsmRegClass::cr
663                | PowerPCInlineAsmRegClass::ctr
664                | PowerPCInlineAsmRegClass::lr
665                | PowerPCInlineAsmRegClass::xer,
666            ) => {
667                unreachable!("clobber-only")
668            }
669            RiscV(RiscVInlineAsmRegClass::reg) => "r",
670            RiscV(RiscVInlineAsmRegClass::freg) => "f",
671            RiscV(RiscVInlineAsmRegClass::vreg) => unreachable!("clobber-only"),
672            X86(X86InlineAsmRegClass::reg) => "r",
673            X86(X86InlineAsmRegClass::reg_abcd) => "Q",
674            X86(X86InlineAsmRegClass::reg_byte) => "q",
675            X86(X86InlineAsmRegClass::xmm_reg) | X86(X86InlineAsmRegClass::ymm_reg) => "x",
676            X86(X86InlineAsmRegClass::zmm_reg) => "v",
677            X86(X86InlineAsmRegClass::kreg) => "^Yk",
678            X86(
679                X86InlineAsmRegClass::x87_reg
680                | X86InlineAsmRegClass::mmx_reg
681                | X86InlineAsmRegClass::kreg0
682                | X86InlineAsmRegClass::tmm_reg,
683            ) => unreachable!("clobber-only"),
684            Wasm(WasmInlineAsmRegClass::local) => "r",
685            Bpf(BpfInlineAsmRegClass::reg) => "r",
686            Bpf(BpfInlineAsmRegClass::wreg) => "w",
687            Avr(AvrInlineAsmRegClass::reg) => "r",
688            Avr(AvrInlineAsmRegClass::reg_upper) => "d",
689            Avr(AvrInlineAsmRegClass::reg_pair) => "r",
690            Avr(AvrInlineAsmRegClass::reg_iw) => "w",
691            Avr(AvrInlineAsmRegClass::reg_ptr) => "e",
692            S390x(S390xInlineAsmRegClass::reg) => "r",
693            S390x(S390xInlineAsmRegClass::reg_addr) => "a",
694            S390x(S390xInlineAsmRegClass::freg) => "f",
695            S390x(S390xInlineAsmRegClass::vreg) => "v",
696            S390x(S390xInlineAsmRegClass::areg) => {
697                unreachable!("clobber-only")
698            }
699            Sparc(SparcInlineAsmRegClass::reg) => "r",
700            Sparc(SparcInlineAsmRegClass::yreg) => unreachable!("clobber-only"),
701            Msp430(Msp430InlineAsmRegClass::reg) => "r",
702            M68k(M68kInlineAsmRegClass::reg) => "r",
703            M68k(M68kInlineAsmRegClass::reg_addr) => "a",
704            M68k(M68kInlineAsmRegClass::reg_data) => "d",
705            CSKY(CSKYInlineAsmRegClass::reg) => "r",
706            CSKY(CSKYInlineAsmRegClass::freg) => "f",
707            SpirV(SpirVInlineAsmRegClass::reg) => bug!("LLVM backend does not support SPIR-V"),
708            Err => unreachable!(),
709        }
710        .to_string(),
711    }
712}
713
714/// Converts a modifier into LLVM's equivalent modifier.
715fn modifier_to_llvm(
716    arch: InlineAsmArch,
717    reg: InlineAsmRegClass,
718    modifier: Option<char>,
719) -> Option<char> {
720    use InlineAsmRegClass::*;
721    // The modifiers can be retrieved from
722    // https://llvm.org/docs/LangRef.html#asm-template-argument-modifiers
723    match reg {
724        AArch64(AArch64InlineAsmRegClass::reg) => modifier,
725        AArch64(AArch64InlineAsmRegClass::vreg) | AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
726            if modifier == Some('v') {
727                None
728            } else {
729                modifier
730            }
731        }
732        AArch64(AArch64InlineAsmRegClass::preg) => unreachable!("clobber-only"),
733        Arm(ArmInlineAsmRegClass::reg) => None,
734        Arm(ArmInlineAsmRegClass::sreg) | Arm(ArmInlineAsmRegClass::sreg_low16) => None,
735        Arm(ArmInlineAsmRegClass::dreg)
736        | Arm(ArmInlineAsmRegClass::dreg_low16)
737        | Arm(ArmInlineAsmRegClass::dreg_low8) => Some('P'),
738        Arm(ArmInlineAsmRegClass::qreg)
739        | Arm(ArmInlineAsmRegClass::qreg_low8)
740        | Arm(ArmInlineAsmRegClass::qreg_low4) => {
741            if modifier.is_none() {
742                Some('q')
743            } else {
744                modifier
745            }
746        }
747        Hexagon(_) => None,
748        LoongArch(_) => None,
749        Mips(_) => None,
750        Nvptx(_) => None,
751        PowerPC(_) => None,
752        RiscV(RiscVInlineAsmRegClass::reg) | RiscV(RiscVInlineAsmRegClass::freg) => None,
753        RiscV(RiscVInlineAsmRegClass::vreg) => unreachable!("clobber-only"),
754        X86(X86InlineAsmRegClass::reg) | X86(X86InlineAsmRegClass::reg_abcd) => match modifier {
755            None if arch == InlineAsmArch::X86_64 => Some('q'),
756            None => Some('k'),
757            Some('l') => Some('b'),
758            Some('h') => Some('h'),
759            Some('x') => Some('w'),
760            Some('e') => Some('k'),
761            Some('r') => Some('q'),
762            _ => unreachable!(),
763        },
764        X86(X86InlineAsmRegClass::reg_byte) => None,
765        X86(reg @ X86InlineAsmRegClass::xmm_reg)
766        | X86(reg @ X86InlineAsmRegClass::ymm_reg)
767        | X86(reg @ X86InlineAsmRegClass::zmm_reg) => match (reg, modifier) {
768            (X86InlineAsmRegClass::xmm_reg, None) => Some('x'),
769            (X86InlineAsmRegClass::ymm_reg, None) => Some('t'),
770            (X86InlineAsmRegClass::zmm_reg, None) => Some('g'),
771            (_, Some('x')) => Some('x'),
772            (_, Some('y')) => Some('t'),
773            (_, Some('z')) => Some('g'),
774            _ => unreachable!(),
775        },
776        X86(X86InlineAsmRegClass::kreg) => None,
777        X86(
778            X86InlineAsmRegClass::x87_reg
779            | X86InlineAsmRegClass::mmx_reg
780            | X86InlineAsmRegClass::kreg0
781            | X86InlineAsmRegClass::tmm_reg,
782        ) => unreachable!("clobber-only"),
783        Wasm(WasmInlineAsmRegClass::local) => None,
784        Bpf(_) => None,
785        Avr(AvrInlineAsmRegClass::reg_pair)
786        | Avr(AvrInlineAsmRegClass::reg_iw)
787        | Avr(AvrInlineAsmRegClass::reg_ptr) => match modifier {
788            Some('h') => Some('B'),
789            Some('l') => Some('A'),
790            _ => None,
791        },
792        Avr(_) => None,
793        S390x(_) => None,
794        Sparc(_) => None,
795        Msp430(_) => None,
796        SpirV(SpirVInlineAsmRegClass::reg) => bug!("LLVM backend does not support SPIR-V"),
797        M68k(_) => None,
798        CSKY(_) => None,
799        Err => unreachable!(),
800    }
801}
802
803/// Type to use for outputs that are discarded. It doesn't really matter what
804/// the type is, as long as it is valid for the constraint code.
805fn dummy_output_type<'ll>(cx: &CodegenCx<'ll, '_>, reg: InlineAsmRegClass) -> &'ll Type {
806    use InlineAsmRegClass::*;
807    match reg {
808        AArch64(AArch64InlineAsmRegClass::reg) => cx.type_i32(),
809        AArch64(AArch64InlineAsmRegClass::vreg) | AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
810            cx.type_vector(cx.type_i64(), 2)
811        }
812        AArch64(AArch64InlineAsmRegClass::preg) => unreachable!("clobber-only"),
813        Arm(ArmInlineAsmRegClass::reg) => cx.type_i32(),
814        Arm(ArmInlineAsmRegClass::sreg) | Arm(ArmInlineAsmRegClass::sreg_low16) => cx.type_f32(),
815        Arm(ArmInlineAsmRegClass::dreg)
816        | Arm(ArmInlineAsmRegClass::dreg_low16)
817        | Arm(ArmInlineAsmRegClass::dreg_low8) => cx.type_f64(),
818        Arm(ArmInlineAsmRegClass::qreg)
819        | Arm(ArmInlineAsmRegClass::qreg_low8)
820        | Arm(ArmInlineAsmRegClass::qreg_low4) => cx.type_vector(cx.type_i64(), 2),
821        Hexagon(HexagonInlineAsmRegClass::reg) => cx.type_i32(),
822        Hexagon(HexagonInlineAsmRegClass::preg) => unreachable!("clobber-only"),
823        LoongArch(LoongArchInlineAsmRegClass::reg) => cx.type_i32(),
824        LoongArch(LoongArchInlineAsmRegClass::freg) => cx.type_f32(),
825        Mips(MipsInlineAsmRegClass::reg) => cx.type_i32(),
826        Mips(MipsInlineAsmRegClass::freg) => cx.type_f32(),
827        Nvptx(NvptxInlineAsmRegClass::reg16) => cx.type_i16(),
828        Nvptx(NvptxInlineAsmRegClass::reg32) => cx.type_i32(),
829        Nvptx(NvptxInlineAsmRegClass::reg64) => cx.type_i64(),
830        PowerPC(PowerPCInlineAsmRegClass::reg) => cx.type_i32(),
831        PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => cx.type_i32(),
832        PowerPC(PowerPCInlineAsmRegClass::freg) => cx.type_f64(),
833        PowerPC(PowerPCInlineAsmRegClass::vreg) => cx.type_vector(cx.type_i32(), 4),
834        PowerPC(
835            PowerPCInlineAsmRegClass::cr
836            | PowerPCInlineAsmRegClass::ctr
837            | PowerPCInlineAsmRegClass::lr
838            | PowerPCInlineAsmRegClass::xer,
839        ) => {
840            unreachable!("clobber-only")
841        }
842        RiscV(RiscVInlineAsmRegClass::reg) => cx.type_i32(),
843        RiscV(RiscVInlineAsmRegClass::freg) => cx.type_f32(),
844        RiscV(RiscVInlineAsmRegClass::vreg) => unreachable!("clobber-only"),
845        X86(X86InlineAsmRegClass::reg) | X86(X86InlineAsmRegClass::reg_abcd) => cx.type_i32(),
846        X86(X86InlineAsmRegClass::reg_byte) => cx.type_i8(),
847        X86(X86InlineAsmRegClass::xmm_reg)
848        | X86(X86InlineAsmRegClass::ymm_reg)
849        | X86(X86InlineAsmRegClass::zmm_reg) => cx.type_f32(),
850        X86(X86InlineAsmRegClass::kreg) => cx.type_i16(),
851        X86(
852            X86InlineAsmRegClass::x87_reg
853            | X86InlineAsmRegClass::mmx_reg
854            | X86InlineAsmRegClass::kreg0
855            | X86InlineAsmRegClass::tmm_reg,
856        ) => unreachable!("clobber-only"),
857        Wasm(WasmInlineAsmRegClass::local) => cx.type_i32(),
858        Bpf(BpfInlineAsmRegClass::reg) => cx.type_i64(),
859        Bpf(BpfInlineAsmRegClass::wreg) => cx.type_i32(),
860        Avr(AvrInlineAsmRegClass::reg) => cx.type_i8(),
861        Avr(AvrInlineAsmRegClass::reg_upper) => cx.type_i8(),
862        Avr(AvrInlineAsmRegClass::reg_pair) => cx.type_i16(),
863        Avr(AvrInlineAsmRegClass::reg_iw) => cx.type_i16(),
864        Avr(AvrInlineAsmRegClass::reg_ptr) => cx.type_i16(),
865        S390x(S390xInlineAsmRegClass::reg | S390xInlineAsmRegClass::reg_addr) => cx.type_i32(),
866        S390x(S390xInlineAsmRegClass::freg) => cx.type_f64(),
867        S390x(S390xInlineAsmRegClass::vreg) => cx.type_vector(cx.type_i64(), 2),
868        S390x(S390xInlineAsmRegClass::areg) => {
869            unreachable!("clobber-only")
870        }
871        Sparc(SparcInlineAsmRegClass::reg) => cx.type_i32(),
872        Sparc(SparcInlineAsmRegClass::yreg) => unreachable!("clobber-only"),
873        Msp430(Msp430InlineAsmRegClass::reg) => cx.type_i16(),
874        M68k(M68kInlineAsmRegClass::reg) => cx.type_i32(),
875        M68k(M68kInlineAsmRegClass::reg_addr) => cx.type_i32(),
876        M68k(M68kInlineAsmRegClass::reg_data) => cx.type_i32(),
877        CSKY(CSKYInlineAsmRegClass::reg) => cx.type_i32(),
878        CSKY(CSKYInlineAsmRegClass::freg) => cx.type_f32(),
879        SpirV(SpirVInlineAsmRegClass::reg) => bug!("LLVM backend does not support SPIR-V"),
880        Err => unreachable!(),
881    }
882}
883
884/// Helper function to get the LLVM type for a Scalar. Pointers are returned as
885/// the equivalent integer type.
886fn llvm_asm_scalar_type<'ll>(cx: &CodegenCx<'ll, '_>, scalar: Scalar) -> &'ll Type {
887    let dl = &cx.tcx.data_layout;
888    match scalar.primitive() {
889        Primitive::Int(Integer::I8, _) => cx.type_i8(),
890        Primitive::Int(Integer::I16, _) => cx.type_i16(),
891        Primitive::Int(Integer::I32, _) => cx.type_i32(),
892        Primitive::Int(Integer::I64, _) => cx.type_i64(),
893        Primitive::Float(Float::F16) => cx.type_f16(),
894        Primitive::Float(Float::F32) => cx.type_f32(),
895        Primitive::Float(Float::F64) => cx.type_f64(),
896        Primitive::Float(Float::F128) => cx.type_f128(),
897        // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
898        Primitive::Pointer(_) => cx.type_from_integer(dl.ptr_sized_integer()),
899        _ => unreachable!(),
900    }
901}
902
903fn any_target_feature_enabled(
904    cx: &CodegenCx<'_, '_>,
905    instance: Instance<'_>,
906    features: &[Symbol],
907) -> bool {
908    let enabled = cx.tcx.asm_target_features(instance.def_id());
909    features.iter().any(|feat| enabled.contains(feat))
910}
911
912/// Fix up an input value to work around LLVM bugs.
913fn llvm_fixup_input<'ll, 'tcx>(
914    bx: &mut Builder<'_, 'll, 'tcx>,
915    mut value: &'ll Value,
916    reg: InlineAsmRegClass,
917    layout: &TyAndLayout<'tcx>,
918    instance: Instance<'_>,
919) -> &'ll Value {
920    use InlineAsmRegClass::*;
921    let dl = &bx.tcx.data_layout;
922    match (reg, layout.backend_repr) {
923        (AArch64(AArch64InlineAsmRegClass::vreg), BackendRepr::Scalar(s)) => {
924            if let Primitive::Int(Integer::I8, _) = s.primitive() {
925                let vec_ty = bx.cx.type_vector(bx.cx.type_i8(), 8);
926                bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
927            } else {
928                value
929            }
930        }
931        (AArch64(AArch64InlineAsmRegClass::vreg_low16), BackendRepr::Scalar(s))
932            if s.primitive() != Primitive::Float(Float::F128) =>
933        {
934            let elem_ty = llvm_asm_scalar_type(bx.cx, s);
935            let count = 16 / layout.size.bytes();
936            let vec_ty = bx.cx.type_vector(elem_ty, count);
937            // FIXME(erikdesjardins): handle non-default addrspace ptr sizes
938            if let Primitive::Pointer(_) = s.primitive() {
939                let t = bx.type_from_integer(dl.ptr_sized_integer());
940                value = bx.ptrtoint(value, t);
941            }
942            bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
943        }
944        (
945            AArch64(AArch64InlineAsmRegClass::vreg_low16),
946            BackendRepr::SimdVector { element, count },
947        ) if layout.size.bytes() == 8 => {
948            let elem_ty = llvm_asm_scalar_type(bx.cx, element);
949            let vec_ty = bx.cx.type_vector(elem_ty, count);
950            let indices: Vec<_> = (0..count * 2).map(|x| bx.const_i32(x as i32)).collect();
951            bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
952        }
953        (X86(X86InlineAsmRegClass::reg_abcd), BackendRepr::Scalar(s))
954            if s.primitive() == Primitive::Float(Float::F64) =>
955        {
956            bx.bitcast(value, bx.cx.type_i64())
957        }
958        (
959            X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
960            BackendRepr::SimdVector { .. },
961        ) if layout.size.bytes() == 64 => bx.bitcast(value, bx.cx.type_vector(bx.cx.type_f64(), 8)),
962        (
963            X86(
964                X86InlineAsmRegClass::xmm_reg
965                | X86InlineAsmRegClass::ymm_reg
966                | X86InlineAsmRegClass::zmm_reg,
967            ),
968            BackendRepr::Scalar(s),
969        ) if bx.sess().asm_arch == Some(InlineAsmArch::X86)
970            && s.primitive() == Primitive::Float(Float::F128) =>
971        {
972            bx.bitcast(value, bx.type_vector(bx.type_i32(), 4))
973        }
974        (
975            X86(
976                X86InlineAsmRegClass::xmm_reg
977                | X86InlineAsmRegClass::ymm_reg
978                | X86InlineAsmRegClass::zmm_reg,
979            ),
980            BackendRepr::Scalar(s),
981        ) if s.primitive() == Primitive::Float(Float::F16) => {
982            let value = bx.insert_element(
983                bx.const_undef(bx.type_vector(bx.type_f16(), 8)),
984                value,
985                bx.const_usize(0),
986            );
987            bx.bitcast(value, bx.type_vector(bx.type_i16(), 8))
988        }
989        (
990            X86(
991                X86InlineAsmRegClass::xmm_reg
992                | X86InlineAsmRegClass::ymm_reg
993                | X86InlineAsmRegClass::zmm_reg,
994            ),
995            BackendRepr::SimdVector { element, count: count @ (8 | 16) },
996        ) if element.primitive() == Primitive::Float(Float::F16) => {
997            bx.bitcast(value, bx.type_vector(bx.type_i16(), count))
998        }
999        (
1000            Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
1001            BackendRepr::Scalar(s),
1002        ) => {
1003            if let Primitive::Int(Integer::I32, _) = s.primitive() {
1004                bx.bitcast(value, bx.cx.type_f32())
1005            } else {
1006                value
1007            }
1008        }
1009        (
1010            Arm(
1011                ArmInlineAsmRegClass::dreg
1012                | ArmInlineAsmRegClass::dreg_low8
1013                | ArmInlineAsmRegClass::dreg_low16,
1014            ),
1015            BackendRepr::Scalar(s),
1016        ) => {
1017            if let Primitive::Int(Integer::I64, _) = s.primitive() {
1018                bx.bitcast(value, bx.cx.type_f64())
1019            } else {
1020                value
1021            }
1022        }
1023        (
1024            Arm(
1025                ArmInlineAsmRegClass::dreg
1026                | ArmInlineAsmRegClass::dreg_low8
1027                | ArmInlineAsmRegClass::dreg_low16
1028                | ArmInlineAsmRegClass::qreg
1029                | ArmInlineAsmRegClass::qreg_low4
1030                | ArmInlineAsmRegClass::qreg_low8,
1031            ),
1032            BackendRepr::SimdVector { element, count: count @ (4 | 8) },
1033        ) if element.primitive() == Primitive::Float(Float::F16) => {
1034            bx.bitcast(value, bx.type_vector(bx.type_i16(), count))
1035        }
1036        (LoongArch(LoongArchInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1037            if s.primitive() == Primitive::Float(Float::F16) =>
1038        {
1039            // Smaller floats are always "NaN-boxed" inside larger floats on LoongArch.
1040            let value = bx.bitcast(value, bx.type_i16());
1041            let value = bx.zext(value, bx.type_i32());
1042            let value = bx.or(value, bx.const_u32(0xFFFF_0000));
1043            bx.bitcast(value, bx.type_f32())
1044        }
1045        (Mips(MipsInlineAsmRegClass::reg), BackendRepr::Scalar(s)) => {
1046            match s.primitive() {
1047                // MIPS only supports register-length arithmetics.
1048                Primitive::Int(Integer::I8 | Integer::I16, _) => bx.zext(value, bx.cx.type_i32()),
1049                Primitive::Float(Float::F32) => bx.bitcast(value, bx.cx.type_i32()),
1050                Primitive::Float(Float::F64) => bx.bitcast(value, bx.cx.type_i64()),
1051                _ => value,
1052            }
1053        }
1054        (RiscV(RiscVInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1055            if s.primitive() == Primitive::Float(Float::F16)
1056                && !any_target_feature_enabled(bx, instance, &[sym::zfhmin, sym::zfh]) =>
1057        {
1058            // Smaller floats are always "NaN-boxed" inside larger floats on RISC-V.
1059            let value = bx.bitcast(value, bx.type_i16());
1060            let value = bx.zext(value, bx.type_i32());
1061            let value = bx.or(value, bx.const_u32(0xFFFF_0000));
1062            bx.bitcast(value, bx.type_f32())
1063        }
1064        (PowerPC(PowerPCInlineAsmRegClass::vreg), BackendRepr::Scalar(s))
1065            if s.primitive() == Primitive::Float(Float::F32) =>
1066        {
1067            let value = bx.insert_element(
1068                bx.const_undef(bx.type_vector(bx.type_f32(), 4)),
1069                value,
1070                bx.const_usize(0),
1071            );
1072            bx.bitcast(value, bx.type_vector(bx.type_f32(), 4))
1073        }
1074        (PowerPC(PowerPCInlineAsmRegClass::vreg), BackendRepr::Scalar(s))
1075            if s.primitive() == Primitive::Float(Float::F64) =>
1076        {
1077            let value = bx.insert_element(
1078                bx.const_undef(bx.type_vector(bx.type_f64(), 2)),
1079                value,
1080                bx.const_usize(0),
1081            );
1082            bx.bitcast(value, bx.type_vector(bx.type_f64(), 2))
1083        }
1084        _ => value,
1085    }
1086}
1087
1088/// Fix up an output value to work around LLVM bugs.
1089fn llvm_fixup_output<'ll, 'tcx>(
1090    bx: &mut Builder<'_, 'll, 'tcx>,
1091    mut value: &'ll Value,
1092    reg: InlineAsmRegClass,
1093    layout: &TyAndLayout<'tcx>,
1094    instance: Instance<'_>,
1095) -> &'ll Value {
1096    use InlineAsmRegClass::*;
1097    match (reg, layout.backend_repr) {
1098        (AArch64(AArch64InlineAsmRegClass::vreg), BackendRepr::Scalar(s)) => {
1099            if let Primitive::Int(Integer::I8, _) = s.primitive() {
1100                bx.extract_element(value, bx.const_i32(0))
1101            } else {
1102                value
1103            }
1104        }
1105        (AArch64(AArch64InlineAsmRegClass::vreg_low16), BackendRepr::Scalar(s))
1106            if s.primitive() != Primitive::Float(Float::F128) =>
1107        {
1108            value = bx.extract_element(value, bx.const_i32(0));
1109            if let Primitive::Pointer(_) = s.primitive() {
1110                value = bx.inttoptr(value, layout.llvm_type(bx.cx));
1111            }
1112            value
1113        }
1114        (
1115            AArch64(AArch64InlineAsmRegClass::vreg_low16),
1116            BackendRepr::SimdVector { element, count },
1117        ) if layout.size.bytes() == 8 => {
1118            let elem_ty = llvm_asm_scalar_type(bx.cx, element);
1119            let vec_ty = bx.cx.type_vector(elem_ty, count * 2);
1120            let indices: Vec<_> = (0..count).map(|x| bx.const_i32(x as i32)).collect();
1121            bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
1122        }
1123        (X86(X86InlineAsmRegClass::reg_abcd), BackendRepr::Scalar(s))
1124            if s.primitive() == Primitive::Float(Float::F64) =>
1125        {
1126            bx.bitcast(value, bx.cx.type_f64())
1127        }
1128        (
1129            X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
1130            BackendRepr::SimdVector { .. },
1131        ) if layout.size.bytes() == 64 => bx.bitcast(value, layout.llvm_type(bx.cx)),
1132        (
1133            X86(
1134                X86InlineAsmRegClass::xmm_reg
1135                | X86InlineAsmRegClass::ymm_reg
1136                | X86InlineAsmRegClass::zmm_reg,
1137            ),
1138            BackendRepr::Scalar(s),
1139        ) if bx.sess().asm_arch == Some(InlineAsmArch::X86)
1140            && s.primitive() == Primitive::Float(Float::F128) =>
1141        {
1142            bx.bitcast(value, bx.type_f128())
1143        }
1144        (
1145            X86(
1146                X86InlineAsmRegClass::xmm_reg
1147                | X86InlineAsmRegClass::ymm_reg
1148                | X86InlineAsmRegClass::zmm_reg,
1149            ),
1150            BackendRepr::Scalar(s),
1151        ) if s.primitive() == Primitive::Float(Float::F16) => {
1152            let value = bx.bitcast(value, bx.type_vector(bx.type_f16(), 8));
1153            bx.extract_element(value, bx.const_usize(0))
1154        }
1155        (
1156            X86(
1157                X86InlineAsmRegClass::xmm_reg
1158                | X86InlineAsmRegClass::ymm_reg
1159                | X86InlineAsmRegClass::zmm_reg,
1160            ),
1161            BackendRepr::SimdVector { element, count: count @ (8 | 16) },
1162        ) if element.primitive() == Primitive::Float(Float::F16) => {
1163            bx.bitcast(value, bx.type_vector(bx.type_f16(), count))
1164        }
1165        (
1166            Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
1167            BackendRepr::Scalar(s),
1168        ) => {
1169            if let Primitive::Int(Integer::I32, _) = s.primitive() {
1170                bx.bitcast(value, bx.cx.type_i32())
1171            } else {
1172                value
1173            }
1174        }
1175        (
1176            Arm(
1177                ArmInlineAsmRegClass::dreg
1178                | ArmInlineAsmRegClass::dreg_low8
1179                | ArmInlineAsmRegClass::dreg_low16,
1180            ),
1181            BackendRepr::Scalar(s),
1182        ) => {
1183            if let Primitive::Int(Integer::I64, _) = s.primitive() {
1184                bx.bitcast(value, bx.cx.type_i64())
1185            } else {
1186                value
1187            }
1188        }
1189        (
1190            Arm(
1191                ArmInlineAsmRegClass::dreg
1192                | ArmInlineAsmRegClass::dreg_low8
1193                | ArmInlineAsmRegClass::dreg_low16
1194                | ArmInlineAsmRegClass::qreg
1195                | ArmInlineAsmRegClass::qreg_low4
1196                | ArmInlineAsmRegClass::qreg_low8,
1197            ),
1198            BackendRepr::SimdVector { element, count: count @ (4 | 8) },
1199        ) if element.primitive() == Primitive::Float(Float::F16) => {
1200            bx.bitcast(value, bx.type_vector(bx.type_f16(), count))
1201        }
1202        (LoongArch(LoongArchInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1203            if s.primitive() == Primitive::Float(Float::F16) =>
1204        {
1205            let value = bx.bitcast(value, bx.type_i32());
1206            let value = bx.trunc(value, bx.type_i16());
1207            bx.bitcast(value, bx.type_f16())
1208        }
1209        (Mips(MipsInlineAsmRegClass::reg), BackendRepr::Scalar(s)) => {
1210            match s.primitive() {
1211                // MIPS only supports register-length arithmetics.
1212                Primitive::Int(Integer::I8, _) => bx.trunc(value, bx.cx.type_i8()),
1213                Primitive::Int(Integer::I16, _) => bx.trunc(value, bx.cx.type_i16()),
1214                Primitive::Float(Float::F32) => bx.bitcast(value, bx.cx.type_f32()),
1215                Primitive::Float(Float::F64) => bx.bitcast(value, bx.cx.type_f64()),
1216                _ => value,
1217            }
1218        }
1219        (RiscV(RiscVInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1220            if s.primitive() == Primitive::Float(Float::F16)
1221                && !any_target_feature_enabled(bx, instance, &[sym::zfhmin, sym::zfh]) =>
1222        {
1223            let value = bx.bitcast(value, bx.type_i32());
1224            let value = bx.trunc(value, bx.type_i16());
1225            bx.bitcast(value, bx.type_f16())
1226        }
1227        (PowerPC(PowerPCInlineAsmRegClass::vreg), BackendRepr::Scalar(s))
1228            if s.primitive() == Primitive::Float(Float::F32) =>
1229        {
1230            let value = bx.bitcast(value, bx.type_vector(bx.type_f32(), 4));
1231            bx.extract_element(value, bx.const_usize(0))
1232        }
1233        (PowerPC(PowerPCInlineAsmRegClass::vreg), BackendRepr::Scalar(s))
1234            if s.primitive() == Primitive::Float(Float::F64) =>
1235        {
1236            let value = bx.bitcast(value, bx.type_vector(bx.type_f64(), 2));
1237            bx.extract_element(value, bx.const_usize(0))
1238        }
1239        _ => value,
1240    }
1241}
1242
1243/// Output type to use for llvm_fixup_output.
1244fn llvm_fixup_output_type<'ll, 'tcx>(
1245    cx: &CodegenCx<'ll, 'tcx>,
1246    reg: InlineAsmRegClass,
1247    layout: &TyAndLayout<'tcx>,
1248    instance: Instance<'_>,
1249) -> &'ll Type {
1250    use InlineAsmRegClass::*;
1251    match (reg, layout.backend_repr) {
1252        (AArch64(AArch64InlineAsmRegClass::vreg), BackendRepr::Scalar(s)) => {
1253            if let Primitive::Int(Integer::I8, _) = s.primitive() {
1254                cx.type_vector(cx.type_i8(), 8)
1255            } else {
1256                layout.llvm_type(cx)
1257            }
1258        }
1259        (AArch64(AArch64InlineAsmRegClass::vreg_low16), BackendRepr::Scalar(s))
1260            if s.primitive() != Primitive::Float(Float::F128) =>
1261        {
1262            let elem_ty = llvm_asm_scalar_type(cx, s);
1263            let count = 16 / layout.size.bytes();
1264            cx.type_vector(elem_ty, count)
1265        }
1266        (
1267            AArch64(AArch64InlineAsmRegClass::vreg_low16),
1268            BackendRepr::SimdVector { element, count },
1269        ) if layout.size.bytes() == 8 => {
1270            let elem_ty = llvm_asm_scalar_type(cx, element);
1271            cx.type_vector(elem_ty, count * 2)
1272        }
1273        (X86(X86InlineAsmRegClass::reg_abcd), BackendRepr::Scalar(s))
1274            if s.primitive() == Primitive::Float(Float::F64) =>
1275        {
1276            cx.type_i64()
1277        }
1278        (
1279            X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
1280            BackendRepr::SimdVector { .. },
1281        ) if layout.size.bytes() == 64 => cx.type_vector(cx.type_f64(), 8),
1282        (
1283            X86(
1284                X86InlineAsmRegClass::xmm_reg
1285                | X86InlineAsmRegClass::ymm_reg
1286                | X86InlineAsmRegClass::zmm_reg,
1287            ),
1288            BackendRepr::Scalar(s),
1289        ) if cx.sess().asm_arch == Some(InlineAsmArch::X86)
1290            && s.primitive() == Primitive::Float(Float::F128) =>
1291        {
1292            cx.type_vector(cx.type_i32(), 4)
1293        }
1294        (
1295            X86(
1296                X86InlineAsmRegClass::xmm_reg
1297                | X86InlineAsmRegClass::ymm_reg
1298                | X86InlineAsmRegClass::zmm_reg,
1299            ),
1300            BackendRepr::Scalar(s),
1301        ) if s.primitive() == Primitive::Float(Float::F16) => cx.type_vector(cx.type_i16(), 8),
1302        (
1303            X86(
1304                X86InlineAsmRegClass::xmm_reg
1305                | X86InlineAsmRegClass::ymm_reg
1306                | X86InlineAsmRegClass::zmm_reg,
1307            ),
1308            BackendRepr::SimdVector { element, count: count @ (8 | 16) },
1309        ) if element.primitive() == Primitive::Float(Float::F16) => {
1310            cx.type_vector(cx.type_i16(), count)
1311        }
1312        (
1313            Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
1314            BackendRepr::Scalar(s),
1315        ) => {
1316            if let Primitive::Int(Integer::I32, _) = s.primitive() {
1317                cx.type_f32()
1318            } else {
1319                layout.llvm_type(cx)
1320            }
1321        }
1322        (
1323            Arm(
1324                ArmInlineAsmRegClass::dreg
1325                | ArmInlineAsmRegClass::dreg_low8
1326                | ArmInlineAsmRegClass::dreg_low16,
1327            ),
1328            BackendRepr::Scalar(s),
1329        ) => {
1330            if let Primitive::Int(Integer::I64, _) = s.primitive() {
1331                cx.type_f64()
1332            } else {
1333                layout.llvm_type(cx)
1334            }
1335        }
1336        (
1337            Arm(
1338                ArmInlineAsmRegClass::dreg
1339                | ArmInlineAsmRegClass::dreg_low8
1340                | ArmInlineAsmRegClass::dreg_low16
1341                | ArmInlineAsmRegClass::qreg
1342                | ArmInlineAsmRegClass::qreg_low4
1343                | ArmInlineAsmRegClass::qreg_low8,
1344            ),
1345            BackendRepr::SimdVector { element, count: count @ (4 | 8) },
1346        ) if element.primitive() == Primitive::Float(Float::F16) => {
1347            cx.type_vector(cx.type_i16(), count)
1348        }
1349        (LoongArch(LoongArchInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1350            if s.primitive() == Primitive::Float(Float::F16) =>
1351        {
1352            cx.type_f32()
1353        }
1354        (Mips(MipsInlineAsmRegClass::reg), BackendRepr::Scalar(s)) => {
1355            match s.primitive() {
1356                // MIPS only supports register-length arithmetics.
1357                Primitive::Int(Integer::I8 | Integer::I16, _) => cx.type_i32(),
1358                Primitive::Float(Float::F32) => cx.type_i32(),
1359                Primitive::Float(Float::F64) => cx.type_i64(),
1360                _ => layout.llvm_type(cx),
1361            }
1362        }
1363        (RiscV(RiscVInlineAsmRegClass::freg), BackendRepr::Scalar(s))
1364            if s.primitive() == Primitive::Float(Float::F16)
1365                && !any_target_feature_enabled(cx, instance, &[sym::zfhmin, sym::zfh]) =>
1366        {
1367            cx.type_f32()
1368        }
1369        (PowerPC(PowerPCInlineAsmRegClass::vreg), BackendRepr::Scalar(s))
1370            if s.primitive() == Primitive::Float(Float::F32) =>
1371        {
1372            cx.type_vector(cx.type_f32(), 4)
1373        }
1374        (PowerPC(PowerPCInlineAsmRegClass::vreg), BackendRepr::Scalar(s))
1375            if s.primitive() == Primitive::Float(Float::F64) =>
1376        {
1377            cx.type_vector(cx.type_f64(), 2)
1378        }
1379        _ => layout.llvm_type(cx),
1380    }
1381}