]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/abi.rs
Rollup merge of #66503 - thomasetter:panic-error-msg, r=joshtriplett
[rust.git] / src / librustc_codegen_llvm / abi.rs
1 use crate::builder::Builder;
2 use crate::context::CodegenCx;
3 use crate::llvm::{self, AttributePlace};
4 use crate::type_::Type;
5 use crate::type_of::LayoutLlvmExt;
6 use crate::value::Value;
7
8 use rustc_codegen_ssa::MemFlags;
9 use rustc_codegen_ssa::mir::place::PlaceRef;
10 use rustc_codegen_ssa::mir::operand::OperandValue;
11 use rustc_codegen_ssa::traits::*;
12 use rustc_target::abi::call::ArgAbi;
13 use rustc_target::abi::{HasDataLayout, LayoutOf};
14 use rustc::ty::{Ty};
15 use rustc::ty::layout::{self};
16
17 use libc::c_uint;
18
19 pub use rustc_target::spec::abi::Abi;
20 pub use rustc::ty::layout::{FAT_PTR_ADDR, FAT_PTR_EXTRA};
21 pub use rustc_target::abi::call::*;
22
23 macro_rules! for_each_kind {
24     ($flags: ident, $f: ident, $($kind: ident),+) => ({
25         $(if $flags.contains(ArgAttribute::$kind) { $f(llvm::Attribute::$kind) })+
26     })
27 }
28
29 trait ArgAttributeExt {
30     fn for_each_kind<F>(&self, f: F) where F: FnMut(llvm::Attribute);
31 }
32
33 impl ArgAttributeExt for ArgAttribute {
34     fn for_each_kind<F>(&self, mut f: F) where F: FnMut(llvm::Attribute) {
35         for_each_kind!(self, f,
36                        NoAlias, NoCapture, NonNull, ReadOnly, SExt, StructRet, ZExt, InReg)
37     }
38 }
39
40 pub trait ArgAttributesExt {
41     fn apply_llfn(&self, idx: AttributePlace, llfn: &Value, ty: Option<&Type>);
42     fn apply_callsite(&self, idx: AttributePlace, callsite: &Value, ty: Option<&Type>);
43 }
44
45 impl ArgAttributesExt for ArgAttributes {
46     fn apply_llfn(&self, idx: AttributePlace, llfn: &Value, ty: Option<&Type>) {
47         let mut regular = self.regular;
48         unsafe {
49             let deref = self.pointee_size.bytes();
50             if deref != 0 {
51                 if regular.contains(ArgAttribute::NonNull) {
52                     llvm::LLVMRustAddDereferenceableAttr(llfn,
53                                                          idx.as_uint(),
54                                                          deref);
55                 } else {
56                     llvm::LLVMRustAddDereferenceableOrNullAttr(llfn,
57                                                                idx.as_uint(),
58                                                                deref);
59                 }
60                 regular -= ArgAttribute::NonNull;
61             }
62             if let Some(align) = self.pointee_align {
63                 llvm::LLVMRustAddAlignmentAttr(llfn,
64                                                idx.as_uint(),
65                                                align.bytes() as u32);
66             }
67             if regular.contains(ArgAttribute::ByVal) {
68                 llvm::LLVMRustAddByValAttr(llfn, idx.as_uint(), ty.unwrap());
69             }
70             regular.for_each_kind(|attr| attr.apply_llfn(idx, llfn));
71         }
72     }
73
74     fn apply_callsite(&self, idx: AttributePlace, callsite: &Value, ty: Option<&Type>) {
75         let mut regular = self.regular;
76         unsafe {
77             let deref = self.pointee_size.bytes();
78             if deref != 0 {
79                 if regular.contains(ArgAttribute::NonNull) {
80                     llvm::LLVMRustAddDereferenceableCallSiteAttr(callsite,
81                                                                  idx.as_uint(),
82                                                                  deref);
83                 } else {
84                     llvm::LLVMRustAddDereferenceableOrNullCallSiteAttr(callsite,
85                                                                        idx.as_uint(),
86                                                                        deref);
87                 }
88                 regular -= ArgAttribute::NonNull;
89             }
90             if let Some(align) = self.pointee_align {
91                 llvm::LLVMRustAddAlignmentCallSiteAttr(callsite,
92                                                        idx.as_uint(),
93                                                        align.bytes() as u32);
94             }
95             if regular.contains(ArgAttribute::ByVal) {
96                 llvm::LLVMRustAddByValCallSiteAttr(callsite, idx.as_uint(), ty.unwrap());
97             }
98             regular.for_each_kind(|attr| attr.apply_callsite(idx, callsite));
99         }
100     }
101 }
102
103 pub trait LlvmType {
104     fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type;
105 }
106
107 impl LlvmType for Reg {
108     fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
109         match self.kind {
110             RegKind::Integer => cx.type_ix(self.size.bits()),
111             RegKind::Float => {
112                 match self.size.bits() {
113                     32 => cx.type_f32(),
114                     64 => cx.type_f64(),
115                     _ => bug!("unsupported float: {:?}", self)
116                 }
117             }
118             RegKind::Vector => {
119                 cx.type_vector(cx.type_i8(), self.size.bytes())
120             }
121         }
122     }
123 }
124
125 impl LlvmType for CastTarget {
126     fn llvm_type(&self, cx: &CodegenCx<'ll, '_>) -> &'ll Type {
127         let rest_ll_unit = self.rest.unit.llvm_type(cx);
128         let (rest_count, rem_bytes) = if self.rest.unit.size.bytes() == 0 {
129             (0, 0)
130         } else {
131             (self.rest.total.bytes() / self.rest.unit.size.bytes(),
132             self.rest.total.bytes() % self.rest.unit.size.bytes())
133         };
134
135         if self.prefix.iter().all(|x| x.is_none()) {
136             // Simplify to a single unit when there is no prefix and size <= unit size
137             if self.rest.total <= self.rest.unit.size {
138                 return rest_ll_unit;
139             }
140
141             // Simplify to array when all chunks are the same size and type
142             if rem_bytes == 0 {
143                 return cx.type_array(rest_ll_unit, rest_count);
144             }
145         }
146
147         // Create list of fields in the main structure
148         let mut args: Vec<_> =
149             self.prefix.iter().flat_map(|option_kind| option_kind.map(
150                 |kind| Reg { kind: kind, size: self.prefix_chunk }.llvm_type(cx)))
151             .chain((0..rest_count).map(|_| rest_ll_unit))
152             .collect();
153
154         // Append final integer
155         if rem_bytes != 0 {
156             // Only integers can be really split further.
157             assert_eq!(self.rest.unit.kind, RegKind::Integer);
158             args.push(cx.type_ix(rem_bytes * 8));
159         }
160
161         cx.type_struct(&args, false)
162     }
163 }
164
165 pub trait ArgAbiExt<'ll, 'tcx> {
166     fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
167     fn store(
168         &self,
169         bx: &mut Builder<'_, 'll, 'tcx>,
170         val: &'ll Value,
171         dst: PlaceRef<'tcx, &'ll Value>,
172     );
173     fn store_fn_arg(
174         &self,
175         bx: &mut Builder<'_, 'll, 'tcx>,
176         idx: &mut usize,
177         dst: PlaceRef<'tcx, &'ll Value>,
178     );
179 }
180
181 impl ArgAbiExt<'ll, 'tcx> for ArgAbi<'tcx, Ty<'tcx>> {
182     /// Gets the LLVM type for a place of the original Rust type of
183     /// this argument/return, i.e., the result of `type_of::type_of`.
184     fn memory_ty(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
185         self.layout.llvm_type(cx)
186     }
187
188     /// Stores a direct/indirect value described by this ArgAbi into a
189     /// place for the original Rust type of this argument/return.
190     /// Can be used for both storing formal arguments into Rust variables
191     /// or results of call/invoke instructions into their destinations.
192     fn store(
193         &self,
194         bx: &mut Builder<'_, 'll, 'tcx>,
195         val: &'ll Value,
196         dst: PlaceRef<'tcx, &'ll Value>,
197     ) {
198         if self.is_ignore() {
199             return;
200         }
201         if self.is_sized_indirect() {
202             OperandValue::Ref(val, None, self.layout.align.abi).store(bx, dst)
203         } else if self.is_unsized_indirect() {
204             bug!("unsized `ArgAbi` must be handled through `store_fn_arg`");
205         } else if let PassMode::Cast(cast) = self.mode {
206             // FIXME(eddyb): Figure out when the simpler Store is safe, clang
207             // uses it for i16 -> {i8, i8}, but not for i24 -> {i8, i8, i8}.
208             let can_store_through_cast_ptr = false;
209             if can_store_through_cast_ptr {
210                 let cast_ptr_llty = bx.type_ptr_to(cast.llvm_type(bx));
211                 let cast_dst = bx.pointercast(dst.llval, cast_ptr_llty);
212                 bx.store(val, cast_dst, self.layout.align.abi);
213             } else {
214                 // The actual return type is a struct, but the ABI
215                 // adaptation code has cast it into some scalar type.  The
216                 // code that follows is the only reliable way I have
217                 // found to do a transform like i64 -> {i32,i32}.
218                 // Basically we dump the data onto the stack then memcpy it.
219                 //
220                 // Other approaches I tried:
221                 // - Casting rust ret pointer to the foreign type and using Store
222                 //   is (a) unsafe if size of foreign type > size of rust type and
223                 //   (b) runs afoul of strict aliasing rules, yielding invalid
224                 //   assembly under -O (specifically, the store gets removed).
225                 // - Truncating foreign type to correct integral type and then
226                 //   bitcasting to the struct type yields invalid cast errors.
227
228                 // We instead thus allocate some scratch space...
229                 let scratch_size = cast.size(bx);
230                 let scratch_align = cast.align(bx);
231                 let llscratch = bx.alloca(cast.llvm_type(bx), scratch_align);
232                 bx.lifetime_start(llscratch, scratch_size);
233
234                 // ... where we first store the value...
235                 bx.store(val, llscratch, scratch_align);
236
237                 // ... and then memcpy it to the intended destination.
238                 bx.memcpy(
239                     dst.llval,
240                     self.layout.align.abi,
241                     llscratch,
242                     scratch_align,
243                     bx.const_usize(self.layout.size.bytes()),
244                     MemFlags::empty()
245                 );
246
247                 bx.lifetime_end(llscratch, scratch_size);
248             }
249         } else {
250             OperandValue::Immediate(val).store(bx, dst);
251         }
252     }
253
254     fn store_fn_arg(
255         &self,
256         bx: &mut Builder<'a, 'll, 'tcx>,
257         idx: &mut usize,
258         dst: PlaceRef<'tcx, &'ll Value>,
259     ) {
260         let mut next = || {
261             let val = llvm::get_param(bx.llfn(), *idx as c_uint);
262             *idx += 1;
263             val
264         };
265         match self.mode {
266             PassMode::Ignore => {}
267             PassMode::Pair(..) => {
268                 OperandValue::Pair(next(), next()).store(bx, dst);
269             }
270             PassMode::Indirect(_, Some(_)) => {
271                 OperandValue::Ref(next(), Some(next()), self.layout.align.abi).store(bx, dst);
272             }
273             PassMode::Direct(_) | PassMode::Indirect(_, None) | PassMode::Cast(_) => {
274                 let next_arg = next();
275                 self.store(bx, next_arg, dst);
276             }
277         }
278     }
279 }
280
281 impl ArgAbiMethods<'tcx> for Builder<'a, 'll, 'tcx> {
282     fn store_fn_arg(
283         &mut self,
284         arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
285         idx: &mut usize, dst: PlaceRef<'tcx, Self::Value>
286     ) {
287         arg_abi.store_fn_arg(self, idx, dst)
288     }
289     fn store_arg(
290         &mut self,
291         arg_abi: &ArgAbi<'tcx, Ty<'tcx>>,
292         val: &'ll Value,
293         dst: PlaceRef<'tcx, &'ll Value>
294     ) {
295         arg_abi.store(self, val, dst)
296     }
297     fn arg_memory_ty(&self, arg_abi: &ArgAbi<'tcx, Ty<'tcx>>) -> &'ll Type {
298         arg_abi.memory_ty(self)
299     }
300 }
301
302 pub trait FnAbiLlvmExt<'tcx> {
303     fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
304     fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type;
305     fn llvm_cconv(&self) -> llvm::CallConv;
306     fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value);
307     fn apply_attrs_callsite(&self, bx: &mut Builder<'a, 'll, 'tcx>, callsite: &'ll Value);
308 }
309
310 impl<'tcx> FnAbiLlvmExt<'tcx> for FnAbi<'tcx, Ty<'tcx>> {
311     fn llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
312         let args_capacity: usize = self.args.iter().map(|arg|
313             if arg.pad.is_some() { 1 } else { 0 } +
314             if let PassMode::Pair(_, _) = arg.mode { 2 } else { 1 }
315         ).sum();
316         let mut llargument_tys = Vec::with_capacity(
317             if let PassMode::Indirect(..) = self.ret.mode { 1 } else { 0 } + args_capacity
318         );
319
320         let llreturn_ty = match self.ret.mode {
321             PassMode::Ignore => cx.type_void(),
322             PassMode::Direct(_) | PassMode::Pair(..) => {
323                 self.ret.layout.immediate_llvm_type(cx)
324             }
325             PassMode::Cast(cast) => cast.llvm_type(cx),
326             PassMode::Indirect(..) => {
327                 llargument_tys.push(cx.type_ptr_to(self.ret.memory_ty(cx)));
328                 cx.type_void()
329             }
330         };
331
332         for arg in &self.args {
333             // add padding
334             if let Some(ty) = arg.pad {
335                 llargument_tys.push(ty.llvm_type(cx));
336             }
337
338             let llarg_ty = match arg.mode {
339                 PassMode::Ignore => continue,
340                 PassMode::Direct(_) => arg.layout.immediate_llvm_type(cx),
341                 PassMode::Pair(..) => {
342                     llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 0, true));
343                     llargument_tys.push(arg.layout.scalar_pair_element_llvm_type(cx, 1, true));
344                     continue;
345                 }
346                 PassMode::Indirect(_, Some(_)) => {
347                     let ptr_ty = cx.tcx.mk_mut_ptr(arg.layout.ty);
348                     let ptr_layout = cx.layout_of(ptr_ty);
349                     llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 0, true));
350                     llargument_tys.push(ptr_layout.scalar_pair_element_llvm_type(cx, 1, true));
351                     continue;
352                 }
353                 PassMode::Cast(cast) => cast.llvm_type(cx),
354                 PassMode::Indirect(_, None) => cx.type_ptr_to(arg.memory_ty(cx)),
355             };
356             llargument_tys.push(llarg_ty);
357         }
358
359         if self.c_variadic {
360             cx.type_variadic_func(&llargument_tys, llreturn_ty)
361         } else {
362             cx.type_func(&llargument_tys, llreturn_ty)
363         }
364     }
365
366     fn ptr_to_llvm_type(&self, cx: &CodegenCx<'ll, 'tcx>) -> &'ll Type {
367         unsafe {
368             llvm::LLVMPointerType(self.llvm_type(cx),
369                                   cx.data_layout().instruction_address_space as c_uint)
370         }
371     }
372
373     fn llvm_cconv(&self) -> llvm::CallConv {
374         match self.conv {
375             Conv::C => llvm::CCallConv,
376             Conv::AmdGpuKernel => llvm::AmdGpuKernel,
377             Conv::ArmAapcs => llvm::ArmAapcsCallConv,
378             Conv::Msp430Intr => llvm::Msp430Intr,
379             Conv::PtxKernel => llvm::PtxKernel,
380             Conv::X86Fastcall => llvm::X86FastcallCallConv,
381             Conv::X86Intr => llvm::X86_Intr,
382             Conv::X86Stdcall => llvm::X86StdcallCallConv,
383             Conv::X86ThisCall => llvm::X86_ThisCall,
384             Conv::X86VectorCall => llvm::X86_VectorCall,
385             Conv::X86_64SysV => llvm::X86_64_SysV,
386             Conv::X86_64Win64 => llvm::X86_64_Win64,
387         }
388     }
389
390     fn apply_attrs_llfn(&self, cx: &CodegenCx<'ll, 'tcx>, llfn: &'ll Value) {
391         let mut i = 0;
392         let mut apply = |attrs: &ArgAttributes, ty: Option<&Type>| {
393             attrs.apply_llfn(llvm::AttributePlace::Argument(i), llfn, ty);
394             i += 1;
395         };
396         match self.ret.mode {
397             PassMode::Direct(ref attrs) => {
398                 attrs.apply_llfn(llvm::AttributePlace::ReturnValue, llfn, None);
399             }
400             PassMode::Indirect(ref attrs, _) => apply(attrs, Some(self.ret.layout.llvm_type(cx))),
401             _ => {}
402         }
403         for arg in &self.args {
404             if arg.pad.is_some() {
405                 apply(&ArgAttributes::new(), None);
406             }
407             match arg.mode {
408                 PassMode::Ignore => {}
409                 PassMode::Direct(ref attrs) |
410                 PassMode::Indirect(ref attrs, None) => apply(attrs, Some(arg.layout.llvm_type(cx))),
411                 PassMode::Indirect(ref attrs, Some(ref extra_attrs)) => {
412                     apply(attrs, None);
413                     apply(extra_attrs, None);
414                 }
415                 PassMode::Pair(ref a, ref b) => {
416                     apply(a, None);
417                     apply(b, None);
418                 }
419                 PassMode::Cast(_) => apply(&ArgAttributes::new(), None),
420             }
421         }
422     }
423
424     fn apply_attrs_callsite(&self, bx: &mut Builder<'a, 'll, 'tcx>, callsite: &'ll Value) {
425         let mut i = 0;
426         let mut apply = |attrs: &ArgAttributes, ty: Option<&Type>| {
427             attrs.apply_callsite(llvm::AttributePlace::Argument(i), callsite, ty);
428             i += 1;
429         };
430         match self.ret.mode {
431             PassMode::Direct(ref attrs) => {
432                 attrs.apply_callsite(llvm::AttributePlace::ReturnValue, callsite, None);
433             }
434             PassMode::Indirect(ref attrs, _) => apply(attrs, Some(self.ret.layout.llvm_type(bx))),
435             _ => {}
436         }
437         if let layout::Abi::Scalar(ref scalar) = self.ret.layout.abi {
438             // If the value is a boolean, the range is 0..2 and that ultimately
439             // become 0..0 when the type becomes i1, which would be rejected
440             // by the LLVM verifier.
441             if let layout::Int(..) = scalar.value {
442                 if !scalar.is_bool() {
443                     let range = scalar.valid_range_exclusive(bx);
444                     if range.start != range.end {
445                         bx.range_metadata(callsite, range);
446                     }
447                 }
448             }
449         }
450         for arg in &self.args {
451             if arg.pad.is_some() {
452                 apply(&ArgAttributes::new(), None);
453             }
454             match arg.mode {
455                 PassMode::Ignore => {}
456                 PassMode::Direct(ref attrs) |
457                 PassMode::Indirect(ref attrs, None) => apply(attrs, Some(arg.layout.llvm_type(bx))),
458                 PassMode::Indirect(ref attrs, Some(ref extra_attrs)) => {
459                     apply(attrs, None);
460                     apply(extra_attrs, None);
461                 }
462                 PassMode::Pair(ref a, ref b) => {
463                     apply(a, None);
464                     apply(b, None);
465                 }
466                 PassMode::Cast(_) => apply(&ArgAttributes::new(), None),
467             }
468         }
469
470         let cconv = self.llvm_cconv();
471         if cconv != llvm::CCallConv {
472             llvm::SetInstructionCallConv(callsite, cconv);
473         }
474     }
475 }
476
477 impl AbiBuilderMethods<'tcx> for Builder<'a, 'll, 'tcx> {
478     fn apply_attrs_callsite(
479         &mut self,
480         fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
481         callsite: Self::Value
482     ) {
483         fn_abi.apply_attrs_callsite(self, callsite)
484     }
485
486     fn get_param(&self, index: usize) -> Self::Value {
487         llvm::get_param(self.llfn(), index as c_uint)
488     }
489 }