]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/asm.rs
9763d523a2ac405ecf1d75261c378893e557d91d
[rust.git] / src / librustc_codegen_llvm / asm.rs
1 use crate::llvm;
2 use crate::context::CodegenCx;
3 use crate::type_of::LayoutLlvmExt;
4 use crate::builder::Builder;
5 use crate::value::Value;
6
7 use rustc::hir;
8 use rustc_codegen_ssa::traits::*;
9
10 use rustc_codegen_ssa::mir::place::PlaceRef;
11 use rustc_codegen_ssa::mir::operand::OperandValue;
12
13 use std::ffi::{CStr, CString};
14 use libc::{c_uint, c_char};
15
16
17 impl AsmBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
18     fn codegen_inline_asm(
19         &mut self,
20         ia: &hir::InlineAsm,
21         outputs: Vec<PlaceRef<'tcx, &'ll Value>>,
22         mut inputs: Vec<&'ll Value>
23     ) -> bool {
24         let mut ext_constraints = vec![];
25         let mut output_types = vec![];
26
27         // Prepare the output operands
28         let mut indirect_outputs = vec![];
29         for (i, (out, &place)) in ia.outputs.iter().zip(&outputs).enumerate() {
30             if out.is_rw {
31                 inputs.push(self.load_operand(place).immediate());
32                 ext_constraints.push(i.to_string());
33             }
34             if out.is_indirect {
35                 indirect_outputs.push(self.load_operand(place).immediate());
36             } else {
37                 output_types.push(place.layout.llvm_type(self.cx()));
38             }
39         }
40         if !indirect_outputs.is_empty() {
41             indirect_outputs.extend_from_slice(&inputs);
42             inputs = indirect_outputs;
43         }
44
45         let clobbers = ia.clobbers.iter()
46                                   .map(|s| format!("~{{{}}}", &s));
47
48         // Default per-arch clobbers
49         // Basically what clang does
50         let arch_clobbers = match &self.sess().target.target.arch[..] {
51             "x86" | "x86_64"  => vec!["~{dirflag}", "~{fpsr}", "~{flags}"],
52             "mips" | "mips64" => vec!["~{$1}"],
53             _                 => Vec::new()
54         };
55
56         let all_constraints =
57             ia.outputs.iter().map(|out| out.constraint.to_string())
58               .chain(ia.inputs.iter().map(|s| s.to_string()))
59               .chain(ext_constraints)
60               .chain(clobbers)
61               .chain(arch_clobbers.iter().map(|s| s.to_string()))
62               .collect::<Vec<String>>().join(",");
63
64         debug!("Asm Constraints: {}", &all_constraints);
65
66         // Depending on how many outputs we have, the return type is different
67         let num_outputs = output_types.len();
68         let output_type = match num_outputs {
69             0 => self.type_void(),
70             1 => output_types[0],
71             _ => self.type_struct(&output_types, false)
72         };
73
74         let asm = CString::new(ia.asm.as_str().as_bytes()).unwrap();
75         let constraint_cstr = CString::new(all_constraints).unwrap();
76         let r = inline_asm_call(
77             self,
78             &asm,
79             &constraint_cstr,
80             &inputs,
81             output_type,
82             ia.volatile,
83             ia.alignstack,
84             ia.dialect
85         );
86         if r.is_none() {
87             return false;
88         }
89         let r = r.unwrap();
90
91         // Again, based on how many outputs we have
92         let outputs = ia.outputs.iter().zip(&outputs).filter(|&(ref o, _)| !o.is_indirect);
93         for (i, (_, &place)) in outputs.enumerate() {
94             let v = if num_outputs == 1 { r } else { self.extract_value(r, i as u64) };
95             OperandValue::Immediate(v).store(self, place);
96         }
97
98         // Store mark in a metadata node so we can map LLVM errors
99         // back to source locations.  See #17552.
100         unsafe {
101             let key = "srcloc";
102             let kind = llvm::LLVMGetMDKindIDInContext(self.llcx,
103                 key.as_ptr() as *const c_char, key.len() as c_uint);
104
105             let val: &'ll Value = self.const_i32(ia.ctxt.outer_expn().as_u32() as i32);
106
107             llvm::LLVMSetMetadata(r, kind,
108                 llvm::LLVMMDNodeInContext(self.llcx, &val, 1));
109         }
110
111         true
112     }
113 }
114
115 impl AsmMethods for CodegenCx<'ll, 'tcx> {
116     fn codegen_global_asm(&self, ga: &hir::GlobalAsm) {
117         let asm = CString::new(ga.asm.as_str().as_bytes()).unwrap();
118         unsafe {
119             llvm::LLVMRustAppendModuleInlineAsm(self.llmod, asm.as_ptr());
120         }
121     }
122 }
123
124 fn inline_asm_call(
125     bx: &mut Builder<'a, 'll, 'tcx>,
126     asm: &CStr,
127     cons: &CStr,
128     inputs: &[&'ll Value],
129     output: &'ll llvm::Type,
130     volatile: bool,
131     alignstack: bool,
132     dia: ::syntax::ast::AsmDialect,
133 ) -> Option<&'ll Value> {
134     let volatile = if volatile { llvm::True }
135                     else        { llvm::False };
136     let alignstack = if alignstack { llvm::True }
137                         else          { llvm::False };
138
139     let argtys = inputs.iter().map(|v| {
140         debug!("Asm Input Type: {:?}", *v);
141         bx.cx.val_ty(*v)
142     }).collect::<Vec<_>>();
143
144     debug!("Asm Output Type: {:?}", output);
145     let fty = bx.cx.type_func(&argtys[..], output);
146     unsafe {
147         // Ask LLVM to verify that the constraints are well-formed.
148         let constraints_ok = llvm::LLVMRustInlineAsmVerify(fty, cons.as_ptr());
149         debug!("constraint verification result: {:?}", constraints_ok);
150         if constraints_ok {
151             let v = llvm::LLVMRustInlineAsm(
152                 fty,
153                 asm.as_ptr(),
154                 cons.as_ptr(),
155                 volatile,
156                 alignstack,
157                 llvm::AsmDialect::from_generic(dia),
158             );
159             Some(bx.call(v, inputs, None))
160         } else {
161             // LLVM has detected an issue with our constraints, bail out
162             None
163         }
164     }
165 }