]> git.proxmox.com Git - rustc.git/blob - compiler/rustc_codegen_llvm/src/asm.rs
New upstream version 1.56.0~beta.4+dfsg1
[rustc.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 constraints.extend_from_slice(&[
307 "~{vtype}".to_string(),
308 "~{vl}".to_string(),
309 "~{vxsat}".to_string(),
310 "~{vxrm}".to_string(),
311 ]);
312 }
313 InlineAsmArch::Nvptx64 => {}
314 InlineAsmArch::PowerPC | InlineAsmArch::PowerPC64 => {}
315 InlineAsmArch::Hexagon => {}
316 InlineAsmArch::Mips | InlineAsmArch::Mips64 => {}
317 InlineAsmArch::S390x => {}
318 InlineAsmArch::SpirV => {}
319 InlineAsmArch::Wasm32 => {}
320 InlineAsmArch::Bpf => {}
321 }
322 }
323 if !options.contains(InlineAsmOptions::NOMEM) {
324 // This is actually ignored by LLVM, but it's probably best to keep
325 // it just in case. LLVM instead uses the ReadOnly/ReadNone
326 // attributes on the call instruction to optimize.
327 constraints.push("~{memory}".to_string());
328 }
329 let volatile = !options.contains(InlineAsmOptions::PURE);
330 let alignstack = !options.contains(InlineAsmOptions::NOSTACK);
331 let output_type = match &output_types[..] {
332 [] => self.type_void(),
333 [ty] => ty,
334 tys => self.type_struct(&tys, false),
335 };
336 let dialect = match asm_arch {
337 InlineAsmArch::X86 | InlineAsmArch::X86_64
338 if !options.contains(InlineAsmOptions::ATT_SYNTAX) =>
339 {
340 LlvmAsmDialect::Intel
341 }
342 _ => LlvmAsmDialect::Att,
343 };
344 let result = inline_asm_call(
345 self,
346 &template_str,
347 &constraints.join(","),
348 &inputs,
349 output_type,
350 volatile,
351 alignstack,
352 dialect,
353 line_spans,
354 )
355 .unwrap_or_else(|| span_bug!(line_spans[0], "LLVM asm constraint validation failed"));
356
357 if options.contains(InlineAsmOptions::PURE) {
358 if options.contains(InlineAsmOptions::NOMEM) {
359 llvm::Attribute::ReadNone.apply_callsite(llvm::AttributePlace::Function, result);
360 } else if options.contains(InlineAsmOptions::READONLY) {
361 llvm::Attribute::ReadOnly.apply_callsite(llvm::AttributePlace::Function, result);
362 }
363 llvm::Attribute::WillReturn.apply_callsite(llvm::AttributePlace::Function, result);
364 } else if options.contains(InlineAsmOptions::NOMEM) {
365 llvm::Attribute::InaccessibleMemOnly
366 .apply_callsite(llvm::AttributePlace::Function, result);
367 } else {
368 // LLVM doesn't have an attribute to represent ReadOnly + SideEffect
369 }
370
371 // Write results to outputs
372 for (idx, op) in operands.iter().enumerate() {
373 if let InlineAsmOperandRef::Out { reg, place: Some(place), .. }
374 | InlineAsmOperandRef::InOut { reg, out_place: Some(place), .. } = *op
375 {
376 let value = if output_types.len() == 1 {
377 result
378 } else {
379 self.extract_value(result, op_idx[&idx] as u64)
380 };
381 let value = llvm_fixup_output(self, value, reg.reg_class(), &place.layout);
382 OperandValue::Immediate(value).store(self, place);
383 }
384 }
385 }
386 }
387
388 impl AsmMethods for CodegenCx<'ll, 'tcx> {
389 fn codegen_global_asm(
390 &self,
391 template: &[InlineAsmTemplatePiece],
392 operands: &[GlobalAsmOperandRef],
393 options: InlineAsmOptions,
394 _line_spans: &[Span],
395 ) {
396 let asm_arch = self.tcx.sess.asm_arch.unwrap();
397
398 // Default to Intel syntax on x86
399 let intel_syntax = matches!(asm_arch, InlineAsmArch::X86 | InlineAsmArch::X86_64)
400 && !options.contains(InlineAsmOptions::ATT_SYNTAX);
401
402 // Build the template string
403 let mut template_str = String::new();
404 if intel_syntax {
405 template_str.push_str(".intel_syntax\n");
406 }
407 for piece in template {
408 match *piece {
409 InlineAsmTemplatePiece::String(ref s) => template_str.push_str(s),
410 InlineAsmTemplatePiece::Placeholder { operand_idx, modifier: _, span: _ } => {
411 match operands[operand_idx] {
412 GlobalAsmOperandRef::Const { ref string } => {
413 // Const operands get injected directly into the
414 // template. Note that we don't need to escape $
415 // here unlike normal inline assembly.
416 template_str.push_str(string);
417 }
418 }
419 }
420 }
421 }
422 if intel_syntax {
423 template_str.push_str("\n.att_syntax\n");
424 }
425
426 unsafe {
427 llvm::LLVMRustAppendModuleInlineAsm(
428 self.llmod,
429 template_str.as_ptr().cast(),
430 template_str.len(),
431 );
432 }
433 }
434 }
435
436 pub(crate) fn inline_asm_call(
437 bx: &mut Builder<'a, 'll, 'tcx>,
438 asm: &str,
439 cons: &str,
440 inputs: &[&'ll Value],
441 output: &'ll llvm::Type,
442 volatile: bool,
443 alignstack: bool,
444 dia: LlvmAsmDialect,
445 line_spans: &[Span],
446 ) -> Option<&'ll Value> {
447 let volatile = if volatile { llvm::True } else { llvm::False };
448 let alignstack = if alignstack { llvm::True } else { llvm::False };
449
450 let argtys = inputs
451 .iter()
452 .map(|v| {
453 debug!("Asm Input Type: {:?}", *v);
454 bx.cx.val_ty(*v)
455 })
456 .collect::<Vec<_>>();
457
458 debug!("Asm Output Type: {:?}", output);
459 let fty = bx.cx.type_func(&argtys[..], output);
460 unsafe {
461 // Ask LLVM to verify that the constraints are well-formed.
462 let constraints_ok = llvm::LLVMRustInlineAsmVerify(fty, cons.as_ptr().cast(), cons.len());
463 debug!("constraint verification result: {:?}", constraints_ok);
464 if constraints_ok {
465 let v = llvm::LLVMRustInlineAsm(
466 fty,
467 asm.as_ptr().cast(),
468 asm.len(),
469 cons.as_ptr().cast(),
470 cons.len(),
471 volatile,
472 alignstack,
473 llvm::AsmDialect::from_generic(dia),
474 );
475 let call = bx.call(fty, v, inputs, None);
476
477 // Store mark in a metadata node so we can map LLVM errors
478 // back to source locations. See #17552.
479 let key = "srcloc";
480 let kind = llvm::LLVMGetMDKindIDInContext(
481 bx.llcx,
482 key.as_ptr() as *const c_char,
483 key.len() as c_uint,
484 );
485
486 // srcloc contains one integer for each line of assembly code.
487 // Unfortunately this isn't enough to encode a full span so instead
488 // we just encode the start position of each line.
489 // FIXME: Figure out a way to pass the entire line spans.
490 let mut srcloc = vec![];
491 if dia == LlvmAsmDialect::Intel && line_spans.len() > 1 {
492 // LLVM inserts an extra line to add the ".intel_syntax", so add
493 // a dummy srcloc entry for it.
494 //
495 // Don't do this if we only have 1 line span since that may be
496 // due to the asm template string coming from a macro. LLVM will
497 // default to the first srcloc for lines that don't have an
498 // associated srcloc.
499 srcloc.push(bx.const_i32(0));
500 }
501 srcloc.extend(line_spans.iter().map(|span| bx.const_i32(span.lo().to_u32() as i32)));
502 let md = llvm::LLVMMDNodeInContext(bx.llcx, srcloc.as_ptr(), srcloc.len() as u32);
503 llvm::LLVMSetMetadata(call, kind, md);
504
505 Some(call)
506 } else {
507 // LLVM has detected an issue with our constraints, bail out
508 None
509 }
510 }
511 }
512
513 /// If the register is an xmm/ymm/zmm register then return its index.
514 fn xmm_reg_index(reg: InlineAsmReg) -> Option<u32> {
515 match reg {
516 InlineAsmReg::X86(reg)
517 if reg as u32 >= X86InlineAsmReg::xmm0 as u32
518 && reg as u32 <= X86InlineAsmReg::xmm15 as u32 =>
519 {
520 Some(reg as u32 - X86InlineAsmReg::xmm0 as u32)
521 }
522 InlineAsmReg::X86(reg)
523 if reg as u32 >= X86InlineAsmReg::ymm0 as u32
524 && reg as u32 <= X86InlineAsmReg::ymm15 as u32 =>
525 {
526 Some(reg as u32 - X86InlineAsmReg::ymm0 as u32)
527 }
528 InlineAsmReg::X86(reg)
529 if reg as u32 >= X86InlineAsmReg::zmm0 as u32
530 && reg as u32 <= X86InlineAsmReg::zmm31 as u32 =>
531 {
532 Some(reg as u32 - X86InlineAsmReg::zmm0 as u32)
533 }
534 _ => None,
535 }
536 }
537
538 /// If the register is an AArch64 vector register then return its index.
539 fn a64_vreg_index(reg: InlineAsmReg) -> Option<u32> {
540 match reg {
541 InlineAsmReg::AArch64(reg)
542 if reg as u32 >= AArch64InlineAsmReg::v0 as u32
543 && reg as u32 <= AArch64InlineAsmReg::v31 as u32 =>
544 {
545 Some(reg as u32 - AArch64InlineAsmReg::v0 as u32)
546 }
547 _ => None,
548 }
549 }
550
551 /// Converts a register class to an LLVM constraint code.
552 fn reg_to_llvm(reg: InlineAsmRegOrRegClass, layout: Option<&TyAndLayout<'tcx>>) -> String {
553 match reg {
554 // For vector registers LLVM wants the register name to match the type size.
555 InlineAsmRegOrRegClass::Reg(reg) => {
556 if let Some(idx) = xmm_reg_index(reg) {
557 let class = if let Some(layout) = layout {
558 match layout.size.bytes() {
559 64 => 'z',
560 32 => 'y',
561 _ => 'x',
562 }
563 } else {
564 // We use f32 as the type for discarded outputs
565 'x'
566 };
567 format!("{{{}mm{}}}", class, idx)
568 } else if let Some(idx) = a64_vreg_index(reg) {
569 let class = if let Some(layout) = layout {
570 match layout.size.bytes() {
571 16 => 'q',
572 8 => 'd',
573 4 => 's',
574 2 => 'h',
575 1 => 'd', // We fixup i8 to i8x8
576 _ => unreachable!(),
577 }
578 } else {
579 // We use i64x2 as the type for discarded outputs
580 'q'
581 };
582 format!("{{{}{}}}", class, idx)
583 } else if reg == InlineAsmReg::AArch64(AArch64InlineAsmReg::x30) {
584 // LLVM doesn't recognize x30
585 "{lr}".to_string()
586 } else if reg == InlineAsmReg::Arm(ArmInlineAsmReg::r14) {
587 // LLVM doesn't recognize r14
588 "{lr}".to_string()
589 } else {
590 format!("{{{}}}", reg.name())
591 }
592 }
593 InlineAsmRegOrRegClass::RegClass(reg) => match reg {
594 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => "r",
595 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg) => "w",
596 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => "x",
597 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::preg) => {
598 unreachable!("clobber-only")
599 }
600 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg) => "r",
601 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => "l",
602 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
603 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
604 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8) => "t",
605 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16)
606 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8)
607 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => "x",
608 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
609 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg) => "w",
610 InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => "r",
611 InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg) => "r",
612 InlineAsmRegClass::Mips(MipsInlineAsmRegClass::freg) => "f",
613 InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => "h",
614 InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => "r",
615 InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => "l",
616 InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg) => "r",
617 InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => "b",
618 InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::freg) => "f",
619 InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::cr)
620 | InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::xer) => {
621 unreachable!("clobber-only")
622 }
623 InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => "r",
624 InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => "f",
625 InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::vreg) => {
626 unreachable!("clobber-only")
627 }
628 InlineAsmRegClass::X86(X86InlineAsmRegClass::reg) => "r",
629 InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => "Q",
630 InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => "q",
631 InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg)
632 | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg) => "x",
633 InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => "v",
634 InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => "^Yk",
635 InlineAsmRegClass::X86(
636 X86InlineAsmRegClass::x87_reg | X86InlineAsmRegClass::mmx_reg,
637 ) => unreachable!("clobber-only"),
638 InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => "r",
639 InlineAsmRegClass::Bpf(BpfInlineAsmRegClass::reg) => "r",
640 InlineAsmRegClass::Bpf(BpfInlineAsmRegClass::wreg) => "w",
641 InlineAsmRegClass::S390x(S390xInlineAsmRegClass::reg) => "r",
642 InlineAsmRegClass::S390x(S390xInlineAsmRegClass::freg) => "f",
643 InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => {
644 bug!("LLVM backend does not support SPIR-V")
645 }
646 InlineAsmRegClass::Err => unreachable!(),
647 }
648 .to_string(),
649 }
650 }
651
652 /// Converts a modifier into LLVM's equivalent modifier.
653 fn modifier_to_llvm(
654 arch: InlineAsmArch,
655 reg: InlineAsmRegClass,
656 modifier: Option<char>,
657 ) -> Option<char> {
658 match reg {
659 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => modifier,
660 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg)
661 | InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
662 if modifier == Some('v') { None } else { modifier }
663 }
664 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::preg) => {
665 unreachable!("clobber-only")
666 }
667 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg)
668 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => None,
669 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
670 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) => None,
671 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
672 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
673 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) => Some('P'),
674 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg)
675 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8)
676 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => {
677 if modifier.is_none() {
678 Some('q')
679 } else {
680 modifier
681 }
682 }
683 InlineAsmRegClass::Hexagon(_) => None,
684 InlineAsmRegClass::Mips(_) => None,
685 InlineAsmRegClass::Nvptx(_) => None,
686 InlineAsmRegClass::PowerPC(_) => None,
687 InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg)
688 | InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => None,
689 InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::vreg) => {
690 unreachable!("clobber-only")
691 }
692 InlineAsmRegClass::X86(X86InlineAsmRegClass::reg)
693 | InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => match modifier {
694 None if arch == InlineAsmArch::X86_64 => Some('q'),
695 None => Some('k'),
696 Some('l') => Some('b'),
697 Some('h') => Some('h'),
698 Some('x') => Some('w'),
699 Some('e') => Some('k'),
700 Some('r') => Some('q'),
701 _ => unreachable!(),
702 },
703 InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => None,
704 InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::xmm_reg)
705 | InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::ymm_reg)
706 | InlineAsmRegClass::X86(reg @ X86InlineAsmRegClass::zmm_reg) => match (reg, modifier) {
707 (X86InlineAsmRegClass::xmm_reg, None) => Some('x'),
708 (X86InlineAsmRegClass::ymm_reg, None) => Some('t'),
709 (X86InlineAsmRegClass::zmm_reg, None) => Some('g'),
710 (_, Some('x')) => Some('x'),
711 (_, Some('y')) => Some('t'),
712 (_, Some('z')) => Some('g'),
713 _ => unreachable!(),
714 },
715 InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => None,
716 InlineAsmRegClass::X86(X86InlineAsmRegClass::x87_reg | X86InlineAsmRegClass::mmx_reg) => {
717 unreachable!("clobber-only")
718 }
719 InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => None,
720 InlineAsmRegClass::Bpf(_) => None,
721 InlineAsmRegClass::S390x(_) => None,
722 InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => {
723 bug!("LLVM backend does not support SPIR-V")
724 }
725 InlineAsmRegClass::Err => unreachable!(),
726 }
727 }
728
729 /// Type to use for outputs that are discarded. It doesn't really matter what
730 /// the type is, as long as it is valid for the constraint code.
731 fn dummy_output_type(cx: &CodegenCx<'ll, 'tcx>, reg: InlineAsmRegClass) -> &'ll Type {
732 match reg {
733 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::reg) => cx.type_i32(),
734 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg)
735 | InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16) => {
736 cx.type_vector(cx.type_i64(), 2)
737 }
738 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::preg) => {
739 unreachable!("clobber-only")
740 }
741 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg)
742 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::reg_thumb) => cx.type_i32(),
743 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg)
744 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg_low16) => cx.type_f32(),
745 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg)
746 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low16)
747 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::dreg_low8) => cx.type_f64(),
748 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg)
749 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low8)
750 | InlineAsmRegClass::Arm(ArmInlineAsmRegClass::qreg_low4) => {
751 cx.type_vector(cx.type_i64(), 2)
752 }
753 InlineAsmRegClass::Hexagon(HexagonInlineAsmRegClass::reg) => cx.type_i32(),
754 InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg) => cx.type_i32(),
755 InlineAsmRegClass::Mips(MipsInlineAsmRegClass::freg) => cx.type_f32(),
756 InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg16) => cx.type_i16(),
757 InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg32) => cx.type_i32(),
758 InlineAsmRegClass::Nvptx(NvptxInlineAsmRegClass::reg64) => cx.type_i64(),
759 InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg) => cx.type_i32(),
760 InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::reg_nonzero) => cx.type_i32(),
761 InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::freg) => cx.type_f64(),
762 InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::cr)
763 | InlineAsmRegClass::PowerPC(PowerPCInlineAsmRegClass::xer) => {
764 unreachable!("clobber-only")
765 }
766 InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::reg) => cx.type_i32(),
767 InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::freg) => cx.type_f32(),
768 InlineAsmRegClass::RiscV(RiscVInlineAsmRegClass::vreg) => {
769 unreachable!("clobber-only")
770 }
771 InlineAsmRegClass::X86(X86InlineAsmRegClass::reg)
772 | InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd) => cx.type_i32(),
773 InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_byte) => cx.type_i8(),
774 InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg)
775 | InlineAsmRegClass::X86(X86InlineAsmRegClass::ymm_reg)
776 | InlineAsmRegClass::X86(X86InlineAsmRegClass::zmm_reg) => cx.type_f32(),
777 InlineAsmRegClass::X86(X86InlineAsmRegClass::kreg) => cx.type_i16(),
778 InlineAsmRegClass::X86(X86InlineAsmRegClass::x87_reg | X86InlineAsmRegClass::mmx_reg) => {
779 unreachable!("clobber-only")
780 }
781 InlineAsmRegClass::Wasm(WasmInlineAsmRegClass::local) => cx.type_i32(),
782 InlineAsmRegClass::Bpf(BpfInlineAsmRegClass::reg) => cx.type_i64(),
783 InlineAsmRegClass::Bpf(BpfInlineAsmRegClass::wreg) => cx.type_i32(),
784 InlineAsmRegClass::S390x(S390xInlineAsmRegClass::reg) => cx.type_i32(),
785 InlineAsmRegClass::S390x(S390xInlineAsmRegClass::freg) => cx.type_f64(),
786 InlineAsmRegClass::SpirV(SpirVInlineAsmRegClass::reg) => {
787 bug!("LLVM backend does not support SPIR-V")
788 }
789 InlineAsmRegClass::Err => unreachable!(),
790 }
791 }
792
793 /// Helper function to get the LLVM type for a Scalar. Pointers are returned as
794 /// the equivalent integer type.
795 fn llvm_asm_scalar_type(cx: &CodegenCx<'ll, 'tcx>, scalar: &Scalar) -> &'ll Type {
796 match scalar.value {
797 Primitive::Int(Integer::I8, _) => cx.type_i8(),
798 Primitive::Int(Integer::I16, _) => cx.type_i16(),
799 Primitive::Int(Integer::I32, _) => cx.type_i32(),
800 Primitive::Int(Integer::I64, _) => cx.type_i64(),
801 Primitive::F32 => cx.type_f32(),
802 Primitive::F64 => cx.type_f64(),
803 Primitive::Pointer => cx.type_isize(),
804 _ => unreachable!(),
805 }
806 }
807
808 /// Fix up an input value to work around LLVM bugs.
809 fn llvm_fixup_input(
810 bx: &mut Builder<'a, 'll, 'tcx>,
811 mut value: &'ll Value,
812 reg: InlineAsmRegClass,
813 layout: &TyAndLayout<'tcx>,
814 ) -> &'ll Value {
815 match (reg, &layout.abi) {
816 (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
817 if let Primitive::Int(Integer::I8, _) = s.value {
818 let vec_ty = bx.cx.type_vector(bx.cx.type_i8(), 8);
819 bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
820 } else {
821 value
822 }
823 }
824 (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
825 let elem_ty = llvm_asm_scalar_type(bx.cx, s);
826 let count = 16 / layout.size.bytes();
827 let vec_ty = bx.cx.type_vector(elem_ty, count);
828 if let Primitive::Pointer = s.value {
829 value = bx.ptrtoint(value, bx.cx.type_isize());
830 }
831 bx.insert_element(bx.const_undef(vec_ty), value, bx.const_i32(0))
832 }
833 (
834 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
835 Abi::Vector { element, count },
836 ) if layout.size.bytes() == 8 => {
837 let elem_ty = llvm_asm_scalar_type(bx.cx, element);
838 let vec_ty = bx.cx.type_vector(elem_ty, *count);
839 let indices: Vec<_> = (0..count * 2).map(|x| bx.const_i32(x as i32)).collect();
840 bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
841 }
842 (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
843 if s.value == Primitive::F64 =>
844 {
845 bx.bitcast(value, bx.cx.type_i64())
846 }
847 (
848 InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
849 Abi::Vector { .. },
850 ) if layout.size.bytes() == 64 => bx.bitcast(value, bx.cx.type_vector(bx.cx.type_f64(), 8)),
851 (
852 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
853 Abi::Scalar(s),
854 ) => {
855 if let Primitive::Int(Integer::I32, _) = s.value {
856 bx.bitcast(value, bx.cx.type_f32())
857 } else {
858 value
859 }
860 }
861 (
862 InlineAsmRegClass::Arm(
863 ArmInlineAsmRegClass::dreg
864 | ArmInlineAsmRegClass::dreg_low8
865 | ArmInlineAsmRegClass::dreg_low16,
866 ),
867 Abi::Scalar(s),
868 ) => {
869 if let Primitive::Int(Integer::I64, _) = s.value {
870 bx.bitcast(value, bx.cx.type_f64())
871 } else {
872 value
873 }
874 }
875 (InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg), Abi::Scalar(s)) => match s.value {
876 // MIPS only supports register-length arithmetics.
877 Primitive::Int(Integer::I8 | Integer::I16, _) => bx.zext(value, bx.cx.type_i32()),
878 Primitive::F32 => bx.bitcast(value, bx.cx.type_i32()),
879 Primitive::F64 => bx.bitcast(value, bx.cx.type_i64()),
880 _ => value,
881 },
882 _ => value,
883 }
884 }
885
886 /// Fix up an output value to work around LLVM bugs.
887 fn llvm_fixup_output(
888 bx: &mut Builder<'a, 'll, 'tcx>,
889 mut value: &'ll Value,
890 reg: InlineAsmRegClass,
891 layout: &TyAndLayout<'tcx>,
892 ) -> &'ll Value {
893 match (reg, &layout.abi) {
894 (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
895 if let Primitive::Int(Integer::I8, _) = s.value {
896 bx.extract_element(value, bx.const_i32(0))
897 } else {
898 value
899 }
900 }
901 (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
902 value = bx.extract_element(value, bx.const_i32(0));
903 if let Primitive::Pointer = s.value {
904 value = bx.inttoptr(value, layout.llvm_type(bx.cx));
905 }
906 value
907 }
908 (
909 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
910 Abi::Vector { element, count },
911 ) if layout.size.bytes() == 8 => {
912 let elem_ty = llvm_asm_scalar_type(bx.cx, element);
913 let vec_ty = bx.cx.type_vector(elem_ty, *count * 2);
914 let indices: Vec<_> = (0..*count).map(|x| bx.const_i32(x as i32)).collect();
915 bx.shuffle_vector(value, bx.const_undef(vec_ty), bx.const_vector(&indices))
916 }
917 (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
918 if s.value == Primitive::F64 =>
919 {
920 bx.bitcast(value, bx.cx.type_f64())
921 }
922 (
923 InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
924 Abi::Vector { .. },
925 ) if layout.size.bytes() == 64 => bx.bitcast(value, layout.llvm_type(bx.cx)),
926 (
927 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
928 Abi::Scalar(s),
929 ) => {
930 if let Primitive::Int(Integer::I32, _) = s.value {
931 bx.bitcast(value, bx.cx.type_i32())
932 } else {
933 value
934 }
935 }
936 (
937 InlineAsmRegClass::Arm(
938 ArmInlineAsmRegClass::dreg
939 | ArmInlineAsmRegClass::dreg_low8
940 | ArmInlineAsmRegClass::dreg_low16,
941 ),
942 Abi::Scalar(s),
943 ) => {
944 if let Primitive::Int(Integer::I64, _) = s.value {
945 bx.bitcast(value, bx.cx.type_i64())
946 } else {
947 value
948 }
949 }
950 (InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg), Abi::Scalar(s)) => match s.value {
951 // MIPS only supports register-length arithmetics.
952 Primitive::Int(Integer::I8, _) => bx.trunc(value, bx.cx.type_i8()),
953 Primitive::Int(Integer::I16, _) => bx.trunc(value, bx.cx.type_i16()),
954 Primitive::F32 => bx.bitcast(value, bx.cx.type_f32()),
955 Primitive::F64 => bx.bitcast(value, bx.cx.type_f64()),
956 _ => value,
957 },
958 _ => value,
959 }
960 }
961
962 /// Output type to use for llvm_fixup_output.
963 fn llvm_fixup_output_type(
964 cx: &CodegenCx<'ll, 'tcx>,
965 reg: InlineAsmRegClass,
966 layout: &TyAndLayout<'tcx>,
967 ) -> &'ll Type {
968 match (reg, &layout.abi) {
969 (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg), Abi::Scalar(s)) => {
970 if let Primitive::Int(Integer::I8, _) = s.value {
971 cx.type_vector(cx.type_i8(), 8)
972 } else {
973 layout.llvm_type(cx)
974 }
975 }
976 (InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16), Abi::Scalar(s)) => {
977 let elem_ty = llvm_asm_scalar_type(cx, s);
978 let count = 16 / layout.size.bytes();
979 cx.type_vector(elem_ty, count)
980 }
981 (
982 InlineAsmRegClass::AArch64(AArch64InlineAsmRegClass::vreg_low16),
983 Abi::Vector { element, count },
984 ) if layout.size.bytes() == 8 => {
985 let elem_ty = llvm_asm_scalar_type(cx, element);
986 cx.type_vector(elem_ty, count * 2)
987 }
988 (InlineAsmRegClass::X86(X86InlineAsmRegClass::reg_abcd), Abi::Scalar(s))
989 if s.value == Primitive::F64 =>
990 {
991 cx.type_i64()
992 }
993 (
994 InlineAsmRegClass::X86(X86InlineAsmRegClass::xmm_reg | X86InlineAsmRegClass::zmm_reg),
995 Abi::Vector { .. },
996 ) if layout.size.bytes() == 64 => cx.type_vector(cx.type_f64(), 8),
997 (
998 InlineAsmRegClass::Arm(ArmInlineAsmRegClass::sreg | ArmInlineAsmRegClass::sreg_low16),
999 Abi::Scalar(s),
1000 ) => {
1001 if let Primitive::Int(Integer::I32, _) = s.value {
1002 cx.type_f32()
1003 } else {
1004 layout.llvm_type(cx)
1005 }
1006 }
1007 (
1008 InlineAsmRegClass::Arm(
1009 ArmInlineAsmRegClass::dreg
1010 | ArmInlineAsmRegClass::dreg_low8
1011 | ArmInlineAsmRegClass::dreg_low16,
1012 ),
1013 Abi::Scalar(s),
1014 ) => {
1015 if let Primitive::Int(Integer::I64, _) = s.value {
1016 cx.type_f64()
1017 } else {
1018 layout.llvm_type(cx)
1019 }
1020 }
1021 (InlineAsmRegClass::Mips(MipsInlineAsmRegClass::reg), Abi::Scalar(s)) => match s.value {
1022 // MIPS only supports register-length arithmetics.
1023 Primitive::Int(Integer::I8 | Integer::I16, _) => cx.type_i32(),
1024 Primitive::F32 => cx.type_i32(),
1025 Primitive::F64 => cx.type_i64(),
1026 _ => layout.llvm_type(cx),
1027 },
1028 _ => layout.llvm_type(cx),
1029 }
1030 }