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