]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/asm.rs
Fix font color for help button in ayu and dark themes
[rust.git] / src / librustc_codegen_llvm / 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::span_bug;
16 use rustc_middle::ty::layout::TyAndLayout;
17 use rustc_span::{Pos, Span};
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.target.arch[..] {
64             "x86" | "x86_64" => vec!["~{dirflag}", "~{fpsr}", "~{flags}"],
65             "mips" | "mips64" => vec!["~{$1}"],
66             _ => Vec::new(),
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 output_types = vec![];
129         let mut op_idx = FxHashMap::default();
130         for (idx, op) in operands.iter().enumerate() {
131             match *op {
132                 InlineAsmOperandRef::Out { reg, late, place } => {
133                     let mut layout = None;
134                     let ty = if let Some(ref place) = place {
135                         layout = Some(&place.layout);
136                         llvm_fixup_output_type(self.cx, reg.reg_class(), &place.layout)
137                     } else {
138                         // If the output is discarded, we don't really care what
139                         // type is used. We're just using this to tell LLVM to
140                         // reserve the register.
141                         dummy_output_type(self.cx, reg.reg_class())
142                     };
143                     output_types.push(ty);
144                     op_idx.insert(idx, constraints.len());
145                     let prefix = if late { "=" } else { "=&" };
146                     constraints.push(format!("{}{}", prefix, reg_to_llvm(reg, layout)));
147                 }
148                 InlineAsmOperandRef::InOut { reg, late, in_value, out_place } => {
149                     let layout = if let Some(ref out_place) = out_place {
150                         &out_place.layout
151                     } else {
152                         // LLVM required tied operands to have the same type,
153                         // so we just use the type of the input.
154                         &in_value.layout
155                     };
156                     let ty = llvm_fixup_output_type(self.cx, reg.reg_class(), layout);
157                     output_types.push(ty);
158                     op_idx.insert(idx, constraints.len());
159                     let prefix = if late { "=" } else { "=&" };
160                     constraints.push(format!("{}{}", prefix, reg_to_llvm(reg, Some(layout))));
161                 }
162                 _ => {}
163             }
164         }
165
166         // Collect input operands
167         let mut inputs = vec![];
168         for (idx, op) in operands.iter().enumerate() {
169             match *op {
170                 InlineAsmOperandRef::In { reg, value } => {
171                     let llval =
172                         llvm_fixup_input(self, value.immediate(), reg.reg_class(), &value.layout);
173                     inputs.push(llval);
174                     op_idx.insert(idx, constraints.len());
175                     constraints.push(reg_to_llvm(reg, Some(&value.layout)));
176                 }
177                 InlineAsmOperandRef::InOut { reg, late: _, in_value, out_place: _ } => {
178                     let value = llvm_fixup_input(
179                         self,
180                         in_value.immediate(),
181                         reg.reg_class(),
182                         &in_value.layout,
183                     );
184                     inputs.push(value);
185                     constraints.push(format!("{}", op_idx[&idx]));
186                 }
187                 InlineAsmOperandRef::SymFn { instance } => {
188                     inputs.push(self.cx.get_fn(instance));
189                     op_idx.insert(idx, constraints.len());
190                     constraints.push("s".to_string());
191                 }
192                 InlineAsmOperandRef::SymStatic { def_id } => {
193                     inputs.push(self.cx.get_static(def_id));
194                     op_idx.insert(idx, constraints.len());
195                     constraints.push("s".to_string());
196                 }
197                 _ => {}
198             }
199         }
200
201         // Build the template string
202         let mut template_str = String::new();
203         for piece in template {
204             match *piece {
205                 InlineAsmTemplatePiece::String(ref s) => {
206                     if s.contains('$') {
207                         for c in s.chars() {
208                             if c == '$' {
209                                 template_str.push_str("$$");
210                             } else {
211                                 template_str.push(c);
212                             }
213                         }
214                     } else {
215                         template_str.push_str(s)
216                     }
217                 }
218                 InlineAsmTemplatePiece::Placeholder { operand_idx, modifier, span: _ } => {
219                     match operands[operand_idx] {
220                         InlineAsmOperandRef::In { reg, .. }
221                         | InlineAsmOperandRef::Out { reg, .. }
222                         | InlineAsmOperandRef::InOut { reg, .. } => {
223                             let modifier = modifier_to_llvm(asm_arch, reg.reg_class(), modifier);
224                             if let Some(modifier) = modifier {
225                                 template_str.push_str(&format!(
226                                     "${{{}:{}}}",
227                                     op_idx[&operand_idx], modifier
228                                 ));
229                             } else {
230                                 template_str.push_str(&format!("${{{}}}", op_idx[&operand_idx]));
231                             }
232                         }
233                         InlineAsmOperandRef::Const { ref string } => {
234                             // Const operands get injected directly into the template
235                             template_str.push_str(string);
236                         }
237                         InlineAsmOperandRef::SymFn { .. }
238                         | InlineAsmOperandRef::SymStatic { .. } => {
239                             // Only emit the raw symbol name
240                             template_str.push_str(&format!("${{{}:c}}", op_idx[&operand_idx]));
241                         }
242                     }
243                 }
244             }
245         }
246
247         if !options.contains(InlineAsmOptions::PRESERVES_FLAGS) {
248             match asm_arch {
249                 InlineAsmArch::AArch64 | InlineAsmArch::Arm => {
250                     constraints.push("~{cc}".to_string());
251                 }
252                 InlineAsmArch::X86 | InlineAsmArch::X86_64 => {
253                     constraints.extend_from_slice(&[
254                         "~{dirflag}".to_string(),
255                         "~{fpsr}".to_string(),
256                         "~{flags}".to_string(),
257                     ]);
258                 }
259                 InlineAsmArch::RiscV32 | InlineAsmArch::RiscV64 => {}
260                 InlineAsmArch::Nvptx64 => {}
261                 InlineAsmArch::Hexagon => {}
262             }
263         }
264         if !options.contains(InlineAsmOptions::NOMEM) {
265             // This is actually ignored by LLVM, but it's probably best to keep
266             // it just in case. LLVM instead uses the ReadOnly/ReadNone
267             // attributes on the call instruction to optimize.
268             constraints.push("~{memory}".to_string());
269         }
270         let volatile = !options.contains(InlineAsmOptions::PURE);
271         let alignstack = !options.contains(InlineAsmOptions::NOSTACK);
272         let output_type = match &output_types[..] {
273             [] => self.type_void(),
274             [ty] => ty,
275             tys => self.type_struct(&tys, false),
276         };
277         let dialect = match asm_arch {
278             InlineAsmArch::X86 | InlineAsmArch::X86_64
279                 if !options.contains(InlineAsmOptions::ATT_SYNTAX) =>
280             {
281                 LlvmAsmDialect::Intel
282             }
283             _ => LlvmAsmDialect::Att,
284         };
285         let result = inline_asm_call(
286             self,
287             &template_str,
288             &constraints.join(","),
289             &inputs,
290             output_type,
291             volatile,
292             alignstack,
293             dialect,
294             line_spans,
295         )
296         .unwrap_or_else(|| span_bug!(line_spans[0], "LLVM asm constraint validation failed"));
297
298         if options.contains(InlineAsmOptions::PURE) {
299             if options.contains(InlineAsmOptions::NOMEM) {
300                 llvm::Attribute::ReadNone.apply_callsite(llvm::AttributePlace::Function, result);
301             } else if options.contains(InlineAsmOptions::READONLY) {
302                 llvm::Attribute::ReadOnly.apply_callsite(llvm::AttributePlace::Function, result);
303             }
304         } else {
305             if options.contains(InlineAsmOptions::NOMEM) {
306                 llvm::Attribute::InaccessibleMemOnly
307                     .apply_callsite(llvm::AttributePlace::Function, result);
308             } else {
309                 // LLVM doesn't have an attribute to represent ReadOnly + SideEffect
310             }
311         }
312
313         // Write results to outputs
314         for (idx, op) in operands.iter().enumerate() {
315             if let InlineAsmOperandRef::Out { reg, place: Some(place), .. }
316             | InlineAsmOperandRef::InOut { reg, out_place: Some(place), .. } = *op
317             {
318                 let value = if output_types.len() == 1 {
319                     result
320                 } else {
321                     self.extract_value(result, op_idx[&idx] as u64)
322                 };
323                 let value = llvm_fixup_output(self, value, reg.reg_class(), &place.layout);
324                 OperandValue::Immediate(value).store(self, place);
325             }
326         }
327     }
328 }
329
330 impl AsmMethods for CodegenCx<'ll, 'tcx> {
331     fn codegen_global_asm(&self, ga: &hir::GlobalAsm) {
332         let asm = ga.asm.as_str();
333         unsafe {
334             llvm::LLVMRustAppendModuleInlineAsm(self.llmod, asm.as_ptr().cast(), asm.len());
335         }
336     }
337 }
338
339 fn inline_asm_call(
340     bx: &mut Builder<'a, 'll, 'tcx>,
341     asm: &str,
342     cons: &str,
343     inputs: &[&'ll Value],
344     output: &'ll llvm::Type,
345     volatile: bool,
346     alignstack: bool,
347     dia: LlvmAsmDialect,
348     line_spans: &[Span],
349 ) -> Option<&'ll Value> {
350     let volatile = if volatile { llvm::True } else { llvm::False };
351     let alignstack = if alignstack { llvm::True } else { llvm::False };
352
353     let argtys = inputs
354         .iter()
355         .map(|v| {
356             debug!("Asm Input Type: {:?}", *v);
357             bx.cx.val_ty(*v)
358         })
359         .collect::<Vec<_>>();
360
361     debug!("Asm Output Type: {:?}", output);
362     let fty = bx.cx.type_func(&argtys[..], output);
363     unsafe {
364         // Ask LLVM to verify that the constraints are well-formed.
365         let constraints_ok = llvm::LLVMRustInlineAsmVerify(fty, cons.as_ptr().cast(), cons.len());
366         debug!("constraint verification result: {:?}", constraints_ok);
367         if constraints_ok {
368             let v = llvm::LLVMRustInlineAsm(
369                 fty,
370                 asm.as_ptr().cast(),
371                 asm.len(),
372                 cons.as_ptr().cast(),
373                 cons.len(),
374                 volatile,
375                 alignstack,
376                 llvm::AsmDialect::from_generic(dia),
377             );
378             let call = bx.call(v, inputs, None);
379
380             // Store mark in a metadata node so we can map LLVM errors
381             // back to source locations.  See #17552.
382             let key = "srcloc";
383             let kind = llvm::LLVMGetMDKindIDInContext(
384                 bx.llcx,
385                 key.as_ptr() as *const c_char,
386                 key.len() as c_uint,
387             );
388
389             // srcloc contains one integer for each line of assembly code.
390             // Unfortunately this isn't enough to encode a full span so instead
391             // we just encode the start position of each line.
392             // FIXME: Figure out a way to pass the entire line spans.
393             let mut srcloc = vec![];
394             if dia == LlvmAsmDialect::Intel && line_spans.len() > 1 {
395                 // LLVM inserts an extra line to add the ".intel_syntax", so add
396                 // a dummy srcloc entry for it.
397                 //
398                 // Don't do this if we only have 1 line span since that may be
399                 // due to the asm template string coming from a macro. LLVM will
400                 // default to the first srcloc for lines that don't have an
401                 // associated srcloc.
402                 srcloc.push(bx.const_i32(0));
403             }
404             srcloc.extend(line_spans.iter().map(|span| bx.const_i32(span.lo().to_u32() as i32)));
405             let md = llvm::LLVMMDNodeInContext(bx.llcx, srcloc.as_ptr(), srcloc.len() as u32);
406             llvm::LLVMSetMetadata(call, kind, md);
407
408             Some(call)
409         } else {
410             // LLVM has detected an issue with our constraints, bail out
411             None
412         }
413     }
414 }
415
416 /// If the register is an xmm/ymm/zmm register then return its index.
417 fn xmm_reg_index(reg: InlineAsmReg) -> Option<u32> {
418     match reg {
419         InlineAsmReg::X86(reg)
420             if reg as u32 >= X86InlineAsmReg::xmm0 as u32
421                 && reg as u32 <= X86InlineAsmReg::xmm15 as u32 =>
422         {
423             Some(reg as u32 - X86InlineAsmReg::xmm0 as u32)
424         }
425         InlineAsmReg::X86(reg)
426             if reg as u32 >= X86InlineAsmReg::ymm0 as u32
427                 && reg as u32 <= X86InlineAsmReg::ymm15 as u32 =>
428         {
429             Some(reg as u32 - X86InlineAsmReg::ymm0 as u32)
430         }
431         InlineAsmReg::X86(reg)
432             if reg as u32 >= X86InlineAsmReg::zmm0 as u32
433                 && reg as u32 <= X86InlineAsmReg::zmm31 as u32 =>
434         {
435             Some(reg as u32 - X86InlineAsmReg::zmm0 as u32)
436         }
437         _ => None,
438     }
439 }
440
441 /// If the register is an AArch64 vector register then return its index.
442 fn a64_vreg_index(reg: InlineAsmReg) -> Option<u32> {
443     match reg {
444         InlineAsmReg::AArch64(reg)
445             if reg as u32 >= AArch64InlineAsmReg::v0 as u32
446                 && reg as u32 <= AArch64InlineAsmReg::v31 as u32 =>
447         {
448             Some(reg as u32 - AArch64InlineAsmReg::v0 as u32)
449         }
450         _ => None,
451     }
452 }
453
454 /// Converts a register class to an LLVM constraint code.
455 fn reg_to_llvm(reg: InlineAsmRegOrRegClass, layout: Option<&TyAndLayout<'tcx>>) -> String {
456     match reg {
457         // For vector registers LLVM wants the register name to match the type size.
458         InlineAsmRegOrRegClass::Reg(reg) => {
459             if let Some(idx) = xmm_reg_index(reg) {
460                 let class = if let Some(layout) = layout {
461                     match layout.size.bytes() {
462                         64 => 'z',
463                         32 => 'y',
464                         _ => 'x',
465                     }
466                 } else {
467                     // We use f32 as the type for discarded outputs
468                     'x'
469                 };
470                 format!("{{{}mm{}}}", class, idx)
471             } else if let Some(idx) = a64_vreg_index(reg) {
472                 let class = if let Some(layout) = layout {
473                     match layout.size.bytes() {
474                         16 => 'q',
475                         8 => 'd',
476                         4 => 's',
477                         2 => 'h',
478                         1 => 'd', // We fixup i8 to i8x8
479                         _ => unreachable!(),
480                     }
481                 } else {
482                     // We use i32 as the type for discarded outputs
483                     's'
484                 };
485                 format!("{{{}{}}}", class, idx)
486             } else {
487                 format!("{{{}}}", reg.name())
488             }
489         }
490         InlineAsmRegOrRegClass::RegClass(reg) => match reg {
491             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => "r",
492             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg) => "w",
493             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => "x",
494             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg) => "r",
495             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => "l",
496             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
497             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
498             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8) => "t",
499             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16)
500             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8)
501             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => "x",
502             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
503             | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg) => "w",
504             InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => "r",
505             InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => "h",
506             InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => "r",
507             InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => "l",
508             InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => "r",
509             InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => "f",
510             InlineAsmRegClass::X86(X86InlineAsmRegClass::reg) => "r",
511             InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => "Q",
512             InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => "q",
513             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg)
514             | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg) => "x",
515             InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => "v",
516             InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => "^Yk",
517         }
518         .to_string(),
519     }
520 }
521
522 /// Converts a modifier into LLVM's equivalent modifier.
523 fn modifier_to_llvm(
524     arch: InlineAsmArch,
525     reg: InlineAsmRegClass,
526     modifier: Option<char>,
527 ) -> Option<char> {
528     match reg {
529         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => modifier,
530         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg)
531         | InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
532             if modifier == Some('v') { None } else { modifier }
533         }
534         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg)
535         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => None,
536         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
537         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) => None,
538         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
539         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
540         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) => Some('P'),
541         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg)
542         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8)
543         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => {
544             if modifier.is_none() {
545                 Some('q')
546             } else {
547                 modifier
548             }
549         }
550         InlineAsmRegClass::Hexagon(_) => None,
551         InlineAsmRegClass::Nvptx(_) => None,
552         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg)
553         | InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => None,
554         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg)
555         | InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => match modifier {
556             None if arch == InlineAsmArch::X86_64 => Some('q'),
557             None => Some('k'),
558             Some('l') => Some('b'),
559             Some('h') => Some('h'),
560             Some('x') => Some('w'),
561             Some('e') => Some('k'),
562             Some('r') => Some('q'),
563             _ => unreachable!(),
564         },
565         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => None,
566         InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::xmm_reg)
567         | InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::ymm_reg)
568         | InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::zmm_reg) => match (reg, modifier) {
569             (X86InlineAsmRegClass::xmm_reg, None) => Some('x'),
570             (X86InlineAsmRegClass::ymm_reg, None) => Some('t'),
571             (X86InlineAsmRegClass::zmm_reg, None) => Some('g'),
572             (_, Some('x')) => Some('x'),
573             (_, Some('y')) => Some('t'),
574             (_, Some('z')) => Some('g'),
575             _ => unreachable!(),
576         },
577         InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => None,
578     }
579 }
580
581 /// Type to use for outputs that are discarded. It doesn't really matter what
582 /// the type is, as long as it is valid for the constraint code.
583 fn dummy_output_type(cx: &CodegenCx<'ll, 'tcx>, reg: InlineAsmRegClass) -> &'ll Type {
584     match reg {
585         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => cx.type_i32(),
586         InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg)
587         | InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
588             cx.type_vector(cx.type_i64(), 2)
589         }
590         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg)
591         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => cx.type_i32(),
592         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
593         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) => cx.type_f32(),
594         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
595         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
596         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) => cx.type_f64(),
597         InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg)
598         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8)
599         | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => {
600             cx.type_vector(cx.type_i64(), 2)
601         }
602         InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => cx.type_i32(),
603         InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => cx.type_i16(),
604         InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => cx.type_i32(),
605         InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => cx.type_i64(),
606         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => cx.type_i32(),
607         InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => cx.type_f32(),
608         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg)
609         | InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => cx.type_i32(),
610         InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => cx.type_i8(),
611         InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg)
612         | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg)
613         | InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => cx.type_f32(),
614         InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => cx.type_i16(),
615     }
616 }
617
618 /// Helper function to get the LLVM type for a Scalar. Pointers are returned as
619 /// the equivalent integer type.
620 fn llvm_asm_scalar_type(cx: &CodegenCx<'ll, 'tcx>, scalar: &Scalar) -> &'ll Type {
621     match scalar.value {
622         Primitive::Int(Integer::I8, _) => cx.type_i8(),
623         Primitive::Int(Integer::I16, _) => cx.type_i16(),
624         Primitive::Int(Integer::I32, _) => cx.type_i32(),
625         Primitive::Int(Integer::I64, _) => cx.type_i64(),
626         Primitive::F32 => cx.type_f32(),
627         Primitive::F64 => cx.type_f64(),
628         Primitive::Pointer => cx.type_isize(),
629         _ => unreachable!(),
630     }
631 }
632
633 /// Fix up an input value to work around LLVM bugs.
634 fn llvm_fixup_input(
635     bx: &mut Builder<'a, 'll, 'tcx>,
636     mut value: &'ll Value,
637     reg: InlineAsmRegClass,
638     layout: &TyAndLayout<'tcx>,
639 ) -> &'ll Value {
640     match (reg, &layout.abi) {
641         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
642             if let Primitive::Int(Integer::I8, _) = s.value {
643                 let vec_ty = bx.cx.type_vector(bx.cx.type_i8(), 8);
644                 bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
645             } else {
646                 value
647             }
648         }
649         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
650             let elem_ty = llvm_asm_scalar_type(bx.cx, s);
651             let count = 16 / layout.size.bytes();
652             let vec_ty = bx.cx.type_vector(elem_ty, count);
653             if let Primitive::Pointer = s.value {
654                 value = bx.ptrtoint(value, bx.cx.type_isize());
655             }
656             bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
657         }
658         (
659             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
660             Abi::Vector { element, count },
661         ) if layout.size.bytes() == 8 => {
662             let elem_ty = llvm_asm_scalar_type(bx.cx, element);
663             let vec_ty = bx.cx.type_vector(elem_ty, *count);
664             let indices: Vec<_> = (0..count * 2).map(|x| bx.const_i32(x as i32)).collect();
665             bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
666         }
667         (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
668             if s.value == Primitive::F64 =>
669         {
670             bx.bitcast(value, bx.cx.type_i64())
671         }
672         (
673             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
674             Abi::Vector { .. },
675         ) if layout.size.bytes() == 64 => bx.bitcast(value, bx.cx.type_vector(bx.cx.type_f64(), 8)),
676         (
677             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
678             Abi::Scalar(s),
679         ) => {
680             if let Primitive::Int(Integer::I32, _) = s.value {
681                 bx.bitcast(value, bx.cx.type_f32())
682             } else {
683                 value
684             }
685         }
686         (
687             InlineAsmRegClass::Arm(
688                 ArmInlineAsmRegClass::dreg
689                 | ArmInlineAsmRegClass::dreg_low8
690                 | ArmInlineAsmRegClass::dreg_low16,
691             ),
692             Abi::Scalar(s),
693         ) => {
694             if let Primitive::Int(Integer::I64, _) = s.value {
695                 bx.bitcast(value, bx.cx.type_f64())
696             } else {
697                 value
698             }
699         }
700         _ => value,
701     }
702 }
703
704 /// Fix up an output value to work around LLVM bugs.
705 fn llvm_fixup_output(
706     bx: &mut Builder<'a, 'll, 'tcx>,
707     mut value: &'ll Value,
708     reg: InlineAsmRegClass,
709     layout: &TyAndLayout<'tcx>,
710 ) -> &'ll Value {
711     match (reg, &layout.abi) {
712         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
713             if let Primitive::Int(Integer::I8, _) = s.value {
714                 bx.extract_element(value, bx.const_i32(0))
715             } else {
716                 value
717             }
718         }
719         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
720             value = bx.extract_element(value, bx.const_i32(0));
721             if let Primitive::Pointer = s.value {
722                 value = bx.inttoptr(value, layout.llvm_type(bx.cx));
723             }
724             value
725         }
726         (
727             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
728             Abi::Vector { element, count },
729         ) if layout.size.bytes() == 8 => {
730             let elem_ty = llvm_asm_scalar_type(bx.cx, element);
731             let vec_ty = bx.cx.type_vector(elem_ty, *count * 2);
732             let indices: Vec<_> = (0..*count).map(|x| bx.const_i32(x as i32)).collect();
733             bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
734         }
735         (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
736             if s.value == Primitive::F64 =>
737         {
738             bx.bitcast(value, bx.cx.type_f64())
739         }
740         (
741             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
742             Abi::Vector { .. },
743         ) if layout.size.bytes() == 64 => bx.bitcast(value, layout.llvm_type(bx.cx)),
744         (
745             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
746             Abi::Scalar(s),
747         ) => {
748             if let Primitive::Int(Integer::I32, _) = s.value {
749                 bx.bitcast(value, bx.cx.type_i32())
750             } else {
751                 value
752             }
753         }
754         (
755             InlineAsmRegClass::Arm(
756                 ArmInlineAsmRegClass::dreg
757                 | ArmInlineAsmRegClass::dreg_low8
758                 | ArmInlineAsmRegClass::dreg_low16,
759             ),
760             Abi::Scalar(s),
761         ) => {
762             if let Primitive::Int(Integer::I64, _) = s.value {
763                 bx.bitcast(value, bx.cx.type_i64())
764             } else {
765                 value
766             }
767         }
768         _ => value,
769     }
770 }
771
772 /// Output type to use for llvm_fixup_output.
773 fn llvm_fixup_output_type(
774     cx: &CodegenCx<'ll, 'tcx>,
775     reg: InlineAsmRegClass,
776     layout: &TyAndLayout<'tcx>,
777 ) -> &'ll Type {
778     match (reg, &layout.abi) {
779         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
780             if let Primitive::Int(Integer::I8, _) = s.value {
781                 cx.type_vector(cx.type_i8(), 8)
782             } else {
783                 layout.llvm_type(cx)
784             }
785         }
786         (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
787             let elem_ty = llvm_asm_scalar_type(cx, s);
788             let count = 16 / layout.size.bytes();
789             cx.type_vector(elem_ty, count)
790         }
791         (
792             InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
793             Abi::Vector { element, count },
794         ) if layout.size.bytes() == 8 => {
795             let elem_ty = llvm_asm_scalar_type(cx, element);
796             cx.type_vector(elem_ty, count * 2)
797         }
798         (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
799             if s.value == Primitive::F64 =>
800         {
801             cx.type_i64()
802         }
803         (
804             InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
805             Abi::Vector { .. },
806         ) if layout.size.bytes() == 64 => cx.type_vector(cx.type_f64(), 8),
807         (
808             InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
809             Abi::Scalar(s),
810         ) => {
811             if let Primitive::Int(Integer::I32, _) = s.value {
812                 cx.type_f32()
813             } else {
814                 layout.llvm_type(cx)
815             }
816         }
817         (
818             InlineAsmRegClass::Arm(
819                 ArmInlineAsmRegClass::dreg
820                 | ArmInlineAsmRegClass::dreg_low8
821                 | ArmInlineAsmRegClass::dreg_low16,
822             ),
823             Abi::Scalar(s),
824         ) => {
825             if let Primitive::Int(Integer::I64, _) = s.value {
826                 cx.type_f64()
827             } else {
828                 layout.llvm_type(cx)
829             }
830         }
831         _ => layout.llvm_type(cx),
832     }
833 }