]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_codegen_llvm/src/asm.rs
bd2751790aa63679a9918b0d5ac0bb5d01e4d8e9
[rust.git] / compiler / rustc_codegen_llvm / src / asm.rs
1 use crate::builder::Builder;
2 use crate::context::CodegenCx;
3 use crate::llvm;
4 use crate::type_::Type;
5 use crate::type_of::LayoutLlvmExt;
6 use crate::value::Value;
7
8 use rustc_ast::LlvmAsmDialect;
9 use rustc_ast::{InlineAsmOptions, InlineAsmTemplatePiece};
10 use rustc_codegen_ssa::mir::operand::OperandValue;
11 use rustc_codegen_ssa::mir::place::PlaceRef;
12 use rustc_codegen_ssa::traits::*;
13 use rustc_data_structures::fx::FxHashMap;
14 use rustc_hir as hir;
15 use rustc_middle::ty::layout::TyAndLayout;
16 use rustc_middle::{bug, span_bug};
17 use rustc_span::{Pos, Span, Symbol};
18 use rustc_target::abi::*;
19 use rustc_target::asm::*;
20
21 use libc::{c_char, c_uint};
22 use tracing::debug;
23
24 impl AsmBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
25     fn codegen_llvm_inline_asm(
26         &mut self,
27         ia: &hir::LlvmInlineAsmInner,
28         outputs: Vec<PlaceRef<'tcx, &'ll Value>>,
29         mut inputs: Vec<&'ll Value>,
30         span: Span,
31     ) -> bool {
32         let mut ext_constraints = vec![];
33         let mut output_types = vec![];
34
35         // Prepare the output operands
36         let mut indirect_outputs = vec![];
37         for (i, (out, &place)) in ia.outputs.iter().zip(&outputs).enumerate() {
38             if out.is_rw {
39                 let operand = self.load_operand(place);
40                 if let OperandValue::Immediate(_) = operand.val {
41                     inputs.push(operand.immediate());
42                 }
43                 ext_constraints.push(i.to_string());
44             }
45             if out.is_indirect {
46                 let operand = self.load_operand(place);
47                 if let OperandValue::Immediate(_) = operand.val {
48                     indirect_outputs.push(operand.immediate());
49                 }
50             } else {
51                 output_types.push(place.layout.llvm_type(self.cx));
52             }
53         }
54         if !indirect_outputs.is_empty() {
55             indirect_outputs.extend_from_slice(&inputs);
56             inputs = indirect_outputs;
57         }
58
59         let clobbers = ia.clobbers.iter().map(|s| format!("~{{{}}}", &s));
60
61         // Default per-arch clobbers
62         // Basically what clang does
63         let arch_clobbers = match &self.sess().target.arch[..] {
64             "x86" | "x86_64" => &["~{dirflag}", "~{fpsr}", "~{flags}"][..],
65             "mips" | "mips64" => &["~{$1}"],
66             _ => &[],
67         };
68
69         let all_constraints = ia
70             .outputs
71             .iter()
72             .map(|out| out.constraint.to_string())
73             .chain(ia.inputs.iter().map(|s| s.to_string()))
74             .chain(ext_constraints)
75             .chain(clobbers)
76             .chain(arch_clobbers.iter().map(|s| (*s).to_string()))
77             .collect::<Vec<String>>()
78             .join(",");
79
80         debug!("Asm Constraints: {}", &all_constraints);
81
82         // Depending on how many outputs we have, the return type is different
83         let num_outputs = output_types.len();
84         let output_type = match num_outputs {
85             0 => self.type_void(),
86             1 => output_types[0],
87             _ => self.type_struct(&output_types, false),
88         };
89
90         let asm = ia.asm.as_str();
91         let r = inline_asm_call(
92             self,
93             &asm,
94             &all_constraints,
95             &inputs,
96             output_type,
97             ia.volatile,
98             ia.alignstack,
99             ia.dialect,
100             &[span],
101         );
102         if r.is_none() {
103             return false;
104         }
105         let r = r.unwrap();
106
107         // Again, based on how many outputs we have
108         let outputs = ia.outputs.iter().zip(&outputs).filter(|&(ref o, _)| !o.is_indirect);
109         for (i, (_, &place)) in outputs.enumerate() {
110             let v = if num_outputs == 1 { r } else { self.extract_value(r, i as u64) };
111             OperandValue::Immediate(v).store(self, place);
112         }
113
114         true
115     }
116
117     fn codegen_inline_asm(
118         &mut self,
119         template: &[InlineAsmTemplatePiece],
120         operands: &[InlineAsmOperandRef<'tcx, Self>],
121         options: InlineAsmOptions,
122         line_spans: &[Span],
123     ) {
124         let asm_arch = self.tcx.sess.asm_arch.unwrap();
125
126         // Collect the types of output operands
127         let mut constraints = vec![];
128         let mut clobbers = vec![];
129         let mut output_types = vec![];
130         let mut op_idx = FxHashMap::default();
131         let mut clobbered_x87 = false;
132         for (idx, op) in operands.iter().enumerate() {
133             match *op {
134                 InlineAsmOperandRef::Out { reg, late, place } => {
135                     let is_target_supported = |reg_class: InlineAsmRegClass| {
136                         for &(_, feature) in reg_class.supported_types(asm_arch) {
137                             if let Some(feature) = feature {
138                                 if self.tcx.sess.target_features.contains(&Symbol::intern(feature))
139                                 {
140                                     return true;
141                                 }
142                             } else {
143                                 // Register class is unconditionally supported
144                                 return true;
145                             }
146                         }
147                         false
148                     };
149
150                     let mut layout = None;
151                     let ty = if let Some(ref place) = place {
152                         layout = Some(&place.layout);
153                         llvm_fixup_output_type(self.cx, reg.reg_class(), &place.layout)
154                     } else if matches!(
155                         reg.reg_class(),
156                         InlineAsmRegClass::X86(
157                             X86InlineAsmRegClass::mmx_reg | X86InlineAsmRegClass::x87_reg
158                         )
159                     ) {
160                         // Special handling for x87/mmx registers: we always
161                         // clobber the whole set if one register is marked as
162                         // clobbered. This is due to the way LLVM handles the
163                         // FP stack in inline assembly.
164                         if !clobbered_x87 {
165                             clobbered_x87 = true;
166                             clobbers.push("~{st}".to_string());
167                             for i in 1..=7 {
168                                 clobbers.push(format!("~{{st({})}}", i));
169                             }
170                         }
171                         continue;
172                     } else if !is_target_supported(reg.reg_class())
173                         || reg.reg_class().is_clobber_only(asm_arch)
174                     {
175                         // We turn discarded outputs into clobber constraints
176                         // if the target feature needed by the register class is
177                         // disabled. This is necessary otherwise LLVM will try
178                         // to actually allocate a register for the dummy output.
179                         assert!(matches!(reg, InlineAsmRegOrRegClass::Reg(_)));
180                         clobbers.push(format!("~{}", reg_to_llvm(reg, None)));
181                         continue;
182                     } else {
183                         // If the output is discarded, we don't really care what
184                         // type is used. We're just using this to tell LLVM to
185                         // reserve the register.
186                         dummy_output_type(self.cx, reg.reg_class())
187                     };
188                     output_types.push(ty);
189                     op_idx.insert(idx, constraints.len());
190                     let prefix = if late { "=" } else { "=&" };
191                     constraints.push(format!("{}{}", prefix, reg_to_llvm(reg, layout)));
192                 }
193                 InlineAsmOperandRef::InOut { reg, late, in_value, out_place } => {
194                     let layout = if let Some(ref out_place) = out_place {
195                         &out_place.layout
196                     } else {
197                         // LLVM required tied operands to have the same type,
198                         // so we just use the type of the input.
199                         &in_value.layout
200                     };
201                     let ty = llvm_fixup_output_type(self.cx, reg.reg_class(), layout);
202                     output_types.push(ty);
203                     op_idx.insert(idx, constraints.len());
204                     let prefix = if late { "=" } else { "=&" };
205                     constraints.push(format!("{}{}", prefix, reg_to_llvm(reg, Some(layout))));
206                 }
207                 _ => {}
208             }
209         }
210
211         // Collect input operands
212         let mut inputs = vec![];
213         for (idx, op) in operands.iter().enumerate() {
214             match *op {
215                 InlineAsmOperandRef::In { reg, value } => {
216                     let llval =
217                         llvm_fixup_input(self, value.immediate(), reg.reg_class(), &value.layout);
218                     inputs.push(llval);
219                     op_idx.insert(idx, constraints.len());
220                     constraints.push(reg_to_llvm(reg, Some(&value.layout)));
221                 }
222                 InlineAsmOperandRef::InOut { reg, late: _, in_value, out_place: _ } => {
223                     let value = llvm_fixup_input(
224                         self,
225                         in_value.immediate(),
226                         reg.reg_class(),
227                         &in_value.layout,
228                     );
229                     inputs.push(value);
230                     constraints.push(format!("{}", op_idx[&idx]));
231                 }
232                 InlineAsmOperandRef::SymFn { instance } => {
233                     inputs.push(self.cx.get_fn(instance));
234                     op_idx.insert(idx, constraints.len());
235                     constraints.push("s".to_string());
236                 }
237                 InlineAsmOperandRef::SymStatic { def_id } => {
238                     inputs.push(self.cx.get_static(def_id));
239                     op_idx.insert(idx, constraints.len());
240                     constraints.push("s".to_string());
241                 }
242                 _ => {}
243             }
244         }
245
246         // Build the template string
247         let mut template_str = String::new();
248         for piece in template {
249             match *piece {
250                 InlineAsmTemplatePiece::String(ref s) => {
251                     if s.contains('$') {
252                         for c in s.chars() {
253                             if c == '$' {
254                                 template_str.push_str("$$");
255                             } else {
256                                 template_str.push(c);
257                             }
258                         }
259                     } else {
260                         template_str.push_str(s)
261                     }
262                 }
263                 InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span: _ } => {
264                     match operands[operand_idx] {
265                         InlineAsmOperandRef::In { reg, .. }
266                         | InlineAsmOperandRef::Out { reg, .. }
267                         | InlineAsmOperandRef::InOut { reg, .. } => {
268                             let modifier = modifier_to_llvm(asm_arch, reg.reg_class(), modifier);
269                             if let Some(modifier) = modifier {
270                                 template_str.push_str(&format!(
271                                     "${{{}:{}}}",
272                                     op_idx[&operand_idx], modifier
273                                 ));
274                             } else {
275                                 template_str.push_str(&format!("${{{}}}", op_idx[&operand_idx]));
276                             }
277                         }
278                         InlineAsmOperandRef::Const { ref string } => {
279                             // Const operands get injected directly into the template
280                             template_str.push_str(string);
281                         }
282                         InlineAsmOperandRef::SymFn { .. }
283                         | InlineAsmOperandRef::SymStatic { .. } => {
284                             // Only emit the raw symbol name
285                             template_str.push_str(&format!("${{{}:c}}", op_idx[&operand_idx]));
286                         }
287                     }
288                 }
289             }
290         }
291
292         constraints.append(&mut clobbers);
293         if !options.contains(InlineAsmOptions::PRESERVES_FLAGS) {
294             match asm_arch {
295                 InlineAsmArch::AArch64 | InlineAsmArch::Arm => {
296                     constraints.push("~{cc}".to_string());
297                 }
298                 InlineAsmArch::X86 | InlineAsmArch::X86_64 => {
299                     constraints.extend_from_slice(&[
300                         "~{dirflag}".to_string(),
301                         "~{fpsr}".to_string(),
302                         "~{flags}".to_string(),
303                     ]);
304                 }
305                 InlineAsmArch::RiscV32 | InlineAsmArch::RiscV64 => {}
306                 InlineAsmArch::Nvptx64 => {}
307                 InlineAsmArch::PowerPC | InlineAsmArch::PowerPC64 => {}
308                 InlineAsmArch::Hexagon => {}
309                 InlineAsmArch::Mips | InlineAsmArch::Mips64 => {}
310                 InlineAsmArch::SpirV => {}
311                 InlineAsmArch::Wasm32 => {}
312             }
313         }
314         if !options.contains(InlineAsmOptions::NOMEM) {
315             // This is actually ignored by LLVM, but it's probably best to keep
316             // it just in case. LLVM instead uses the ReadOnly/ReadNone
317             // attributes on the call instruction to optimize.
318             constraints.push("~{memory}".to_string());
319         }
320         let volatile = !options.contains(InlineAsmOptions::PURE);
321         let alignstack = !options.contains(InlineAsmOptions::NOSTACK);
322         let output_type = match &output_types[..] {
323             [] => self.type_void(),
324             [ty] => ty,
325             tys => self.type_struct(&tys, false),
326         };
327         let dialect = match asm_arch {
328             InlineAsmArch::X86 | InlineAsmArch::X86_64
329                 if !options.contains(InlineAsmOptions::ATT_SYNTAX) =>
330             {
331                 LlvmAsmDialect::Intel
332             }
333             _ => LlvmAsmDialect::Att,
334         };
335         let result = inline_asm_call(
336             self,
337             &template_str,
338             &constraints.join(","),
339             &inputs,
340             output_type,
341             volatile,
342             alignstack,
343             dialect,
344             line_spans,
345         )
346         .unwrap_or_else(|| span_bug!(line_spans[0], "LLVM asm constraint validation failed"));
347
348         if options.contains(InlineAsmOptions::PURE) {
349             if options.contains(InlineAsmOptions::NOMEM) {
350                 llvm::Attribute::ReadNone.apply_callsite(llvm::AttributePlace::Function, result);
351             } else if options.contains(InlineAsmOptions::READONLY) {
352                 llvm::Attribute::ReadOnly.apply_callsite(llvm::AttributePlace::Function, result);
353             }
354             llvm::Attribute::WillReturn.apply_callsite(llvm::AttributePlace::Function, result);
355         } else if options.contains(InlineAsmOptions::NOMEM) {
356             llvm::Attribute::InaccessibleMemOnly
357                 .apply_callsite(llvm::AttributePlace::Function, result);
358         } else {
359             // LLVM doesn't have an attribute to represent ReadOnly + SideEffect
360         }
361
362         // Write results to outputs
363         for (idx, op) in operands.iter().enumerate() {
364             if let InlineAsmOperandRef::Out { reg, place: Some(place), .. }
365             | InlineAsmOperandRef::InOut { reg, out_place: Some(place), .. } = *op
366             {
367                 let value = if output_types.len() == 1 {
368                     result
369                 } else {
370                     self.extract_value(result, op_idx[&idx] as u64)
371                 };
372                 let value = llvm_fixup_output(self, value, reg.reg_class(), &place.layout);
373                 OperandValue::Immediate(value).store(self, place);
374             }
375         }
376     }
377 }
378
379 impl AsmMethods for CodegenCx<'ll, 'tcx> {
380     fn codegen_global_asm(
381         &self,
382         template: &[InlineAsmTemplatePiece],
383         operands: &[GlobalAsmOperandRef],
384         options: InlineAsmOptions,
385         _line_spans: &[Span],
386     ) {
387         let asm_arch = self.tcx.sess.asm_arch.unwrap();
388
389         // Default to Intel syntax on x86
390         let intel_syntax = matches!(asm_arch, InlineAsmArch::X86 | InlineAsmArch::X86_64)
391             && !options.contains(InlineAsmOptions::ATT_SYNTAX);
392
393         // Build the template string
394         let mut template_str = String::new();
395         if intel_syntax {
396             template_str.push_str(".intel_syntax\n");
397         }
398         for piece in template {
399             match *piece {
400                 InlineAsmTemplatePiece::String(ref s) => template_str.push_str(s),
401                 InlineAsmTemplatePiece::Placeholder { operand_idx, modifier: _, span: _ } => {
402                     match operands[operand_idx] {
403                         GlobalAsmOperandRef::Const { ref string } => {
404                             // Const operands get injected directly into the
405                             // template. Note that we don't need to escape $
406                             // here unlike normal inline assembly.
407                             template_str.push_str(string);
408                         }
409                     }
410                 }
411             }
412         }
413         if intel_syntax {
414             template_str.push_str("\n.att_syntax\n");
415         }
416
417         unsafe {
418             llvm::LLVMRustAppendModuleInlineAsm(
419                 self.llmod,
420                 template_str.as_ptr().cast(),
421                 template_str.len(),
422             );
423         }
424     }
425 }
426
427 fn inline_asm_call(
428     bx: &mut Builder<'a, 'll, 'tcx>,
429     asm: &str,
430     cons: &str,
431     inputs: &[&'ll Value],
432     output: &'ll llvm::Type,
433     volatile: bool,
434     alignstack: bool,
435     dia: LlvmAsmDialect,
436     line_spans: &[Span],
437 ) -> Option<&'ll Value> {
438     let volatile = if volatile { llvm::True } else { llvm::False };
439     let alignstack = if alignstack { llvm::True } else { llvm::False };
440
441     let argtys = inputs
442         .iter()
443         .map(|v| {
444             debug!("Asm Input Type: {:?}", *v);
445             bx.cx.val_ty(*v)
446         })
447         .collect::<Vec<_>>();
448
449     debug!("Asm Output Type: {:?}", output);
450     let fty = bx.cx.type_func(&argtys[..], output);
451     unsafe {
452         // Ask LLVM to verify that the constraints are well-formed.
453         let constraints_ok = llvm::LLVMRustInlineAsmVerify(fty, cons.as_ptr().cast(), cons.len());
454         debug!("constraint verification result: {:?}", constraints_ok);
455         if constraints_ok {
456             let v = llvm::LLVMRustInlineAsm(
457                 fty,
458                 asm.as_ptr().cast(),
459                 asm.len(),
460                 cons.as_ptr().cast(),
461                 cons.len(),
462                 volatile,
463                 alignstack,
464                 llvm::AsmDialect::from_generic(dia),
465             );
466             let call = bx.call(v, inputs, None);
467
468             // Store mark in a metadata node so we can map LLVM errors
469             // back to source locations.  See #17552.
470             let key = "srcloc";
471             let kind = llvm::LLVMGetMDKindIDInContext(
472                 bx.llcx,
473                 key.as_ptr() as *const c_char,
474                 key.len() as c_uint,
475             );
476
477             // srcloc contains one integer for each line of assembly code.
478             // Unfortunately this isn't enough to encode a full span so instead
479             // we just encode the start position of each line.
480             // FIXME: Figure out a way to pass the entire line spans.
481             let mut srcloc = vec![];
482             if dia == LlvmAsmDialect::Intel && line_spans.len() > 1 {
483                 // LLVM inserts an extra line to add the ".intel_syntax", so add
484                 // a dummy srcloc entry for it.
485                 //
486                 // Don't do this if we only have 1 line span since that may be
487                 // due to the asm template string coming from a macro. LLVM will
488                 // default to the first srcloc for lines that don't have an
489                 // associated srcloc.
490                 srcloc.push(bx.const_i32(0));
491             }
492             srcloc.extend(line_spans.iter().map(|span| bx.const_i32(span.lo().to_u32() as i32)));
493             let md = llvm::LLVMMDNodeInContext(bx.llcx, srcloc.as_ptr(), srcloc.len() as u32);
494             llvm::LLVMSetMetadata(call, kind, md);
495
496             Some(call)
497         } else {
498             // LLVM has detected an issue with our constraints, bail out
499             None
500         }
501     }
502 }
503
504 /// If the register is an xmm/ymm/zmm register then return its index.
505 fn xmm_reg_index(reg: InlineAsmReg) -> Option<u32> {
506     match reg {
507         InlineAsmReg::X86(reg)
508             if reg as u32 >= X86InlineAsmReg::xmm0 as u32
509                 && reg as u32 <= X86InlineAsmReg::xmm15 as u32 =>
510         {
511             Some(reg as u32 - X86InlineAsmReg::xmm0 as u32)
512         }
513         InlineAsmReg::X86(reg)
514             if reg as u32 >= X86InlineAsmReg::ymm0 as u32
515                 && reg as u32 <= X86InlineAsmReg::ymm15 as u32 =>
516         {
517             Some(reg as u32 - X86InlineAsmReg::ymm0 as u32)
518         }
519         InlineAsmReg::X86(reg)
520             if reg as u32 >= X86InlineAsmReg::zmm0 as u32
521                 && reg as u32 <= X86InlineAsmReg::zmm31 as u32 =>
522         {
523             Some(reg as u32 - X86InlineAsmReg::zmm0 as u32)
524         }
525         _ => None,
526     }
527 }
528
529 /// If the register is an AArch64 vector register then return its index.
530 fn a64_vreg_index(reg: InlineAsmReg) -> Option<u32> {
531     match reg {
532         InlineAsmReg::AArch64(reg)
533             if reg as u32 >= AArch64InlineAsmReg::v0 as u32
534                 && reg as u32 <= AArch64InlineAsmReg::v31 as u32 =>
535         {
536             Some(reg as u32 - AArch64InlineAsmReg::v0 as u32)
537         }
538         _ => None,
539     }
540 }
541
542 /// Converts a register class to an LLVM constraint code.
543 fn reg_to_llvm(reg: InlineAsmRegOrRegClass, layout: Option<&TyAndLayout<'tcx>>) -> String {
544     match reg {
545         // For vector registers LLVM wants the register name to match the type size.
546         InlineAsmRegOrRegClass::Reg(reg) => {
547             if let Some(idx) = xmm_reg_index(reg) {
548                 let class = if let Some(layout) = layout {
549                     match layout.size.bytes() {
550                         64 => 'z',
551                         32 => 'y',
552                         _ => 'x',
553                     }
554                 } else {
555                     // We use f32 as the type for discarded outputs
556                     'x'
557                 };
558                 format!("{{{}mm{}}}", class, idx)
559             } else if let Some(idx) = a64_vreg_index(reg) {
560                 let class = if let Some(layout) = layout {
561                     match layout.size.bytes() {
562                         16 => 'q',
563                         8 => 'd',
564                         4 => 's',
565                         2 => 'h',
566                         1 => 'd', // We fixup i8 to i8x8
567                         _ => unreachable!(),
568                     }
569                 } else {
570                     // We use i64x2 as the type for discarded outputs
571                     'q'
572                 };
573                 format!("{{{}{}}}", class, idx)
574             } else if reg == InlineAsmReg::AArch64(AArch64InlineAsmReg::x30) {
575                 // LLVM doesn't recognize x30
576                 "{lr}".to_string()
577             } else if reg == InlineAsmReg::Arm(ArmInlineAsmReg::r14) {
578                 // LLVM doesn't recognize r14
579                 "{lr}".to_string()
580             } else {
581                 format!("{{{}}}", reg.name())
582             }
583         }
584         InlineAsmRegOrRegClass::RegClass(reg) => match reg {
585             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => "r",
586             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg) => "w",
587             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => "x",
588             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::preg) => {
589                 unreachable!("clobber-only")
590             }
591             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg) => "r",
592             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => "l",
593             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
594             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
595             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8) => "t",
596             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16)
597             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8)
598             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => "x",
599             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
600             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg) => "w",
601             InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => "r",
602             InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg) => "r",
603             InlineAsmRegClass::Mips(MipsInlineAsmRegClass::freg) => "f",
604             InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => "h",
605             InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => "r",
606             InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => "l",
607             InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg) => "r",
608             InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => "b",
609             InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::freg) => "f",
610             InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => "r",
611             InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => "f",
612             InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::vreg) => {
613                 unreachable!("clobber-only")
614             }
615             InlineAsmRegClass::X86(X86InlineAsmRegClass::reg) => "r",
616             InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => "Q",
617             InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => "q",
618             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg)
619             | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg) => "x",
620             InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => "v",
621             InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => "^Yk",
622             InlineAsmRegClass::X86(
623                 X86InlineAsmRegClass::x87_reg | X86InlineAsmRegClass::mmx_reg,
624             ) => unreachable!("clobber-only"),
625             InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => "r",
626             InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => {
627                 bug!("LLVM backend does not support SPIR-V")
628             }
629             InlineAsmRegClass::Err => unreachable!(),
630         }
631         .to_string(),
632     }
633 }
634
635 /// Converts a modifier into LLVM's equivalent modifier.
636 fn modifier_to_llvm(
637     arch: InlineAsmArch,
638     reg: InlineAsmRegClass,
639     modifier: Option<char>,
640 ) -> Option<char> {
641     match reg {
642         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => modifier,
643         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg)
644         | InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
645             if modifier == Some('v') { None } else { modifier }
646         }
647         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::preg) => {
648             unreachable!("clobber-only")
649         }
650         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg)
651         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => None,
652         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
653         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) => None,
654         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
655         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
656         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) => Some('P'),
657         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg)
658         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8)
659         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => {
660             if modifier.is_none() {
661                 Some('q')
662             } else {
663                 modifier
664             }
665         }
666         InlineAsmRegClass::Hexagon(_) => None,
667         InlineAsmRegClass::Mips(_) => None,
668         InlineAsmRegClass::Nvptx(_) => None,
669         InlineAsmRegClass::PowerPC(_) => None,
670         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg)
671         | InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => None,
672         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::vreg) => {
673             unreachable!("clobber-only")
674         }
675         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg)
676         | InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => match modifier {
677             None if arch == InlineAsmArch::X86_64 => Some('q'),
678             None => Some('k'),
679             Some('l') => Some('b'),
680             Some('h') => Some('h'),
681             Some('x') => Some('w'),
682             Some('e') => Some('k'),
683             Some('r') => Some('q'),
684             _ => unreachable!(),
685         },
686         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => None,
687         InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::xmm_reg)
688         | InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::ymm_reg)
689         | InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::zmm_reg) => match (reg, modifier) {
690             (X86InlineAsmRegClass::xmm_reg, None) => Some('x'),
691             (X86InlineAsmRegClass::ymm_reg, None) => Some('t'),
692             (X86InlineAsmRegClass::zmm_reg, None) => Some('g'),
693             (_, Some('x')) => Some('x'),
694             (_, Some('y')) => Some('t'),
695             (_, Some('z')) => Some('g'),
696             _ => unreachable!(),
697         },
698         InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => None,
699         InlineAsmRegClass::X86(X86InlineAsmRegClass::x87_reg | X86InlineAsmRegClass::mmx_reg) => {
700             unreachable!("clobber-only")
701         }
702         InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => None,
703         InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => {
704             bug!("LLVM backend does not support SPIR-V")
705         }
706         InlineAsmRegClass::Err => unreachable!(),
707     }
708 }
709
710 /// Type to use for outputs that are discarded. It doesn't really matter what
711 /// the type is, as long as it is valid for the constraint code.
712 fn dummy_output_type(cx: &CodegenCx<'ll, 'tcx>, reg: InlineAsmRegClass) -> &'ll Type {
713     match reg {
714         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => cx.type_i32(),
715         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg)
716         | InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
717             cx.type_vector(cx.type_i64(), 2)
718         }
719         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::preg) => {
720             unreachable!("clobber-only")
721         }
722         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg)
723         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => cx.type_i32(),
724         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
725         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) => cx.type_f32(),
726         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
727         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
728         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) => cx.type_f64(),
729         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg)
730         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8)
731         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => {
732             cx.type_vector(cx.type_i64(), 2)
733         }
734         InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => cx.type_i32(),
735         InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg) => cx.type_i32(),
736         InlineAsmRegClass::Mips(MipsInlineAsmRegClass::freg) => cx.type_f32(),
737         InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => cx.type_i16(),
738         InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => cx.type_i32(),
739         InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => cx.type_i64(),
740         InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg) => cx.type_i32(),
741         InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => cx.type_i32(),
742         InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::freg) => cx.type_f64(),
743         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => cx.type_i32(),
744         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => cx.type_f32(),
745         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::vreg) => {
746             unreachable!("clobber-only")
747         }
748         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg)
749         | InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => cx.type_i32(),
750         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => cx.type_i8(),
751         InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg)
752         | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg)
753         | InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => cx.type_f32(),
754         InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => cx.type_i16(),
755         InlineAsmRegClass::X86(X86InlineAsmRegClass::x87_reg | X86InlineAsmRegClass::mmx_reg) => {
756             unreachable!("clobber-only")
757         }
758         InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => cx.type_i32(),
759         InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => {
760             bug!("LLVM backend does not support SPIR-V")
761         }
762         InlineAsmRegClass::Err => unreachable!(),
763     }
764 }
765
766 /// Helper function to get the LLVM type for a Scalar. Pointers are returned as
767 /// the equivalent integer type.
768 fn llvm_asm_scalar_type(cx: &CodegenCx<'ll, 'tcx>, scalar: &Scalar) -> &'ll Type {
769     match scalar.value {
770         Primitive::Int(Integer::I8, _) => cx.type_i8(),
771         Primitive::Int(Integer::I16, _) => cx.type_i16(),
772         Primitive::Int(Integer::I32, _) => cx.type_i32(),
773         Primitive::Int(Integer::I64, _) => cx.type_i64(),
774         Primitive::F32 => cx.type_f32(),
775         Primitive::F64 => cx.type_f64(),
776         Primitive::Pointer => cx.type_isize(),
777         _ => unreachable!(),
778     }
779 }
780
781 /// Fix up an input value to work around LLVM bugs.
782 fn llvm_fixup_input(
783     bx: &mut Builder<'a, 'll, 'tcx>,
784     mut value: &'ll Value,
785     reg: InlineAsmRegClass,
786     layout: &TyAndLayout<'tcx>,
787 ) -> &'ll Value {
788     match (reg, &layout.abi) {
789         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
790             if let Primitive::Int(Integer::I8, _) = s.value {
791                 let vec_ty = bx.cx.type_vector(bx.cx.type_i8(), 8);
792                 bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
793             } else {
794                 value
795             }
796         }
797         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
798             let elem_ty = llvm_asm_scalar_type(bx.cx, s);
799             let count = 16 / layout.size.bytes();
800             let vec_ty = bx.cx.type_vector(elem_ty, count);
801             if let Primitive::Pointer = s.value {
802                 value = bx.ptrtoint(value, bx.cx.type_isize());
803             }
804             bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
805         }
806         (
807             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
808             Abi::Vector { element, count },
809         ) if layout.size.bytes() == 8 => {
810             let elem_ty = llvm_asm_scalar_type(bx.cx, element);
811             let vec_ty = bx.cx.type_vector(elem_ty, *count);
812             let indices: Vec<_> = (0..count * 2).map(|x| bx.const_i32(x as i32)).collect();
813             bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
814         }
815         (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
816             if s.value == Primitive::F64 =>
817         {
818             bx.bitcast(value, bx.cx.type_i64())
819         }
820         (
821             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
822             Abi::Vector { .. },
823         ) if layout.size.bytes() == 64 => bx.bitcast(value, bx.cx.type_vector(bx.cx.type_f64(), 8)),
824         (
825             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
826             Abi::Scalar(s),
827         ) => {
828             if let Primitive::Int(Integer::I32, _) = s.value {
829                 bx.bitcast(value, bx.cx.type_f32())
830             } else {
831                 value
832             }
833         }
834         (
835             InlineAsmRegClass::Arm(
836                 ArmInlineAsmRegClass::dreg
837                 | ArmInlineAsmRegClass::dreg_low8
838                 | ArmInlineAsmRegClass::dreg_low16,
839             ),
840             Abi::Scalar(s),
841         ) => {
842             if let Primitive::Int(Integer::I64, _) = s.value {
843                 bx.bitcast(value, bx.cx.type_f64())
844             } else {
845                 value
846             }
847         }
848         (InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg), Abi::Scalar(s)) => match s.value {
849             // MIPS only supports register-length arithmetics.
850             Primitive::Int(Integer::I8 | Integer::I16, _) => bx.zext(value, bx.cx.type_i32()),
851             Primitive::F32 => bx.bitcast(value, bx.cx.type_i32()),
852             Primitive::F64 => bx.bitcast(value, bx.cx.type_i64()),
853             _ => value,
854         },
855         _ => value,
856     }
857 }
858
859 /// Fix up an output value to work around LLVM bugs.
860 fn llvm_fixup_output(
861     bx: &mut Builder<'a, 'll, 'tcx>,
862     mut value: &'ll Value,
863     reg: InlineAsmRegClass,
864     layout: &TyAndLayout<'tcx>,
865 ) -> &'ll Value {
866     match (reg, &layout.abi) {
867         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
868             if let Primitive::Int(Integer::I8, _) = s.value {
869                 bx.extract_element(value, bx.const_i32(0))
870             } else {
871                 value
872             }
873         }
874         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
875             value = bx.extract_element(value, bx.const_i32(0));
876             if let Primitive::Pointer = s.value {
877                 value = bx.inttoptr(value, layout.llvm_type(bx.cx));
878             }
879             value
880         }
881         (
882             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
883             Abi::Vector { element, count },
884         ) if layout.size.bytes() == 8 => {
885             let elem_ty = llvm_asm_scalar_type(bx.cx, element);
886             let vec_ty = bx.cx.type_vector(elem_ty, *count * 2);
887             let indices: Vec<_> = (0..*count).map(|x| bx.const_i32(x as i32)).collect();
888             bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
889         }
890         (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
891             if s.value == Primitive::F64 =>
892         {
893             bx.bitcast(value, bx.cx.type_f64())
894         }
895         (
896             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
897             Abi::Vector { .. },
898         ) if layout.size.bytes() == 64 => bx.bitcast(value, layout.llvm_type(bx.cx)),
899         (
900             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
901             Abi::Scalar(s),
902         ) => {
903             if let Primitive::Int(Integer::I32, _) = s.value {
904                 bx.bitcast(value, bx.cx.type_i32())
905             } else {
906                 value
907             }
908         }
909         (
910             InlineAsmRegClass::Arm(
911                 ArmInlineAsmRegClass::dreg
912                 | ArmInlineAsmRegClass::dreg_low8
913                 | ArmInlineAsmRegClass::dreg_low16,
914             ),
915             Abi::Scalar(s),
916         ) => {
917             if let Primitive::Int(Integer::I64, _) = s.value {
918                 bx.bitcast(value, bx.cx.type_i64())
919             } else {
920                 value
921             }
922         }
923         (InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg), Abi::Scalar(s)) => match s.value {
924             // MIPS only supports register-length arithmetics.
925             Primitive::Int(Integer::I8, _) => bx.trunc(value, bx.cx.type_i8()),
926             Primitive::Int(Integer::I16, _) => bx.trunc(value, bx.cx.type_i16()),
927             Primitive::F32 => bx.bitcast(value, bx.cx.type_f32()),
928             Primitive::F64 => bx.bitcast(value, bx.cx.type_f64()),
929             _ => value,
930         },
931         _ => value,
932     }
933 }
934
935 /// Output type to use for llvm_fixup_output.
936 fn llvm_fixup_output_type(
937     cx: &CodegenCx<'ll, 'tcx>,
938     reg: InlineAsmRegClass,
939     layout: &TyAndLayout<'tcx>,
940 ) -> &'ll Type {
941     match (reg, &layout.abi) {
942         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
943             if let Primitive::Int(Integer::I8, _) = s.value {
944                 cx.type_vector(cx.type_i8(), 8)
945             } else {
946                 layout.llvm_type(cx)
947             }
948         }
949         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
950             let elem_ty = llvm_asm_scalar_type(cx, s);
951             let count = 16 / layout.size.bytes();
952             cx.type_vector(elem_ty, count)
953         }
954         (
955             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
956             Abi::Vector { element, count },
957         ) if layout.size.bytes() == 8 => {
958             let elem_ty = llvm_asm_scalar_type(cx, element);
959             cx.type_vector(elem_ty, count * 2)
960         }
961         (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
962             if s.value == Primitive::F64 =>
963         {
964             cx.type_i64()
965         }
966         (
967             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
968             Abi::Vector { .. },
969         ) if layout.size.bytes() == 64 => cx.type_vector(cx.type_f64(), 8),
970         (
971             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
972             Abi::Scalar(s),
973         ) => {
974             if let Primitive::Int(Integer::I32, _) = s.value {
975                 cx.type_f32()
976             } else {
977                 layout.llvm_type(cx)
978             }
979         }
980         (
981             InlineAsmRegClass::Arm(
982                 ArmInlineAsmRegClass::dreg
983                 | ArmInlineAsmRegClass::dreg_low8
984                 | ArmInlineAsmRegClass::dreg_low16,
985             ),
986             Abi::Scalar(s),
987         ) => {
988             if let Primitive::Int(Integer::I64, _) = s.value {
989                 cx.type_f64()
990             } else {
991                 layout.llvm_type(cx)
992             }
993         }
994         (InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg), Abi::Scalar(s)) => match s.value {
995             // MIPS only supports register-length arithmetics.
996             Primitive::Int(Integer::I8 | Integer::I16, _) => cx.type_i32(),
997             Primitive::F32 => cx.type_i32(),
998             Primitive::F64 => cx.type_i64(),
999             _ => layout.llvm_type(cx),
1000         },
1001         _ => layout.llvm_type(cx),
1002     }
1003 }