1 // Copyright 2012-2014 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use rustc::mir::interpret::{ErrorHandled, read_target_uint};
13 use rustc_mir::const_eval::const_field;
14 use rustc::hir::def_id::DefId;
16 use rustc_data_structures::indexed_vec::Idx;
17 use rustc::mir::interpret::{GlobalId, Pointer, Scalar, Allocation, ConstValue, AllocType};
18 use rustc::ty::{self, Ty};
19 use rustc::ty::layout::{self, HasDataLayout, LayoutOf, Size};
21 use common::{CodegenCx};
23 use type_of::LayoutLlvmExt;
25 use syntax::ast::Mutability;
26 use syntax::source_map::Span;
28 use interfaces::{BuilderMethods, CommonMethods};
30 use super::super::callee;
31 use super::FunctionCx;
33 pub fn scalar_to_llvm(
34 cx: &CodegenCx<'ll, '_>,
36 layout: &layout::Scalar,
39 let bitsize = if layout.is_bool() { 1 } else { layout.value.size(cx).bits() };
41 Scalar::Bits { size: 0, .. } => {
42 assert_eq!(0, layout.value.size(cx).bytes());
43 cx.c_undef(Type::ix(cx, 0))
45 Scalar::Bits { bits, size } => {
46 assert_eq!(size as u64, layout.value.size(cx).bytes());
47 let llval = cx.c_uint_big(Type::ix(cx, bitsize), bits);
48 if layout.value == layout::Pointer {
49 unsafe { llvm::LLVMConstIntToPtr(llval, llty) }
51 consts::bitcast(llval, llty)
55 let alloc_type = cx.tcx.alloc_map.lock().get(ptr.alloc_id);
56 let base_addr = match alloc_type {
57 Some(AllocType::Memory(alloc)) => {
58 let init = const_alloc_to_llvm(cx, alloc);
59 if alloc.mutability == Mutability::Mutable {
60 consts::addr_of_mut(cx, init, alloc.align, None)
62 consts::addr_of(cx, init, alloc.align, None)
65 Some(AllocType::Function(fn_instance)) => {
66 callee::get_fn(cx, fn_instance)
68 Some(AllocType::Static(def_id)) => {
69 assert!(cx.tcx.is_static(def_id).is_some());
70 consts::get_static(cx, def_id)
72 None => bug!("missing allocation {:?}", ptr.alloc_id),
74 let llval = unsafe { llvm::LLVMConstInBoundsGEP(
75 consts::bitcast(base_addr, Type::i8p(cx)),
76 &cx.c_usize(ptr.offset.bytes()),
79 if layout.value != layout::Pointer {
80 unsafe { llvm::LLVMConstPtrToInt(llval, llty) }
82 consts::bitcast(llval, llty)
88 pub fn const_alloc_to_llvm(cx: &CodegenCx<'ll, '_>, alloc: &Allocation) -> &'ll Value {
89 let mut llvals = Vec::with_capacity(alloc.relocations.len() + 1);
90 let dl = cx.data_layout();
91 let pointer_size = dl.pointer_size.bytes() as usize;
93 let mut next_offset = 0;
94 for &(offset, ((), alloc_id)) in alloc.relocations.iter() {
95 let offset = offset.bytes();
96 assert_eq!(offset as usize as u64, offset);
97 let offset = offset as usize;
98 if offset > next_offset {
99 llvals.push(CodegenCx::c_bytes(cx, &alloc.bytes[next_offset..offset]));
101 let ptr_offset = read_target_uint(
103 &alloc.bytes[offset..(offset + pointer_size)],
104 ).expect("const_alloc_to_llvm: could not read relocation pointer") as u64;
105 llvals.push(scalar_to_llvm(
107 Pointer::new(alloc_id, Size::from_bytes(ptr_offset)).into(),
109 value: layout::Primitive::Pointer,
114 next_offset = offset + pointer_size;
116 if alloc.bytes.len() >= next_offset {
117 llvals.push(CodegenCx::c_bytes(cx, &alloc.bytes[next_offset ..]));
120 CodegenCx::c_struct(cx, &llvals, true)
123 pub fn codegen_static_initializer(
124 cx: &CodegenCx<'ll, 'tcx>,
126 ) -> Result<(&'ll Value, &'tcx Allocation), ErrorHandled> {
127 let instance = ty::Instance::mono(cx.tcx, def_id);
132 let param_env = ty::ParamEnv::reveal_all();
133 let static_ = cx.tcx.const_eval(param_env.and(cid))?;
135 let alloc = match static_.val {
136 ConstValue::ByRef(_, alloc, n) if n.bytes() == 0 => alloc,
137 _ => bug!("static const eval returned {:#?}", static_),
139 Ok((const_alloc_to_llvm(cx, alloc), alloc))
142 impl FunctionCx<'a, 'll, 'tcx, &'ll Value> {
145 bx: &Builder<'a, 'll, 'tcx>,
146 constant: &'tcx ty::Const<'tcx>,
147 ) -> Result<&'tcx ty::Const<'tcx>, ErrorHandled> {
149 ConstValue::Unevaluated(def_id, ref substs) => {
151 let param_env = ty::ParamEnv::reveal_all();
152 let instance = ty::Instance::resolve(tcx, param_env, def_id, substs).unwrap();
157 tcx.const_eval(param_env.and(cid))
163 pub fn eval_mir_constant(
165 bx: &Builder<'a, 'll, 'tcx>,
166 constant: &mir::Constant<'tcx>,
167 ) -> Result<&'tcx ty::Const<'tcx>, ErrorHandled> {
168 let c = self.monomorphize(&constant.literal);
169 self.fully_evaluate(bx, c)
172 /// process constant containing SIMD shuffle indices
173 pub fn simd_shuffle_indices(
175 bx: &Builder<'a, 'll, 'tcx>,
178 constant: Result<&'tcx ty::Const<'tcx>, ErrorHandled>,
179 ) -> (&'ll Value, Ty<'tcx>) {
182 let field_ty = c.ty.builtin_index().unwrap();
183 let fields = match c.ty.sty {
184 ty::Array(_, n) => n.unwrap_usize(bx.tcx()),
185 ref other => bug!("invalid simd shuffle type: {}", other),
187 let values: Result<Vec<_>, ErrorHandled> = (0..fields).map(|field| {
188 let field = const_field(
190 ty::ParamEnv::reveal_all(),
193 mir::Field::new(field as usize),
196 if let Some(prim) = field.val.try_to_scalar() {
197 let layout = bx.cx().layout_of(field_ty);
198 let scalar = match layout.abi {
199 layout::Abi::Scalar(ref x) => x,
200 _ => bug!("from_const: invalid ByVal layout: {:#?}", layout)
203 bx.cx(), prim, scalar,
204 layout.immediate_llvm_type(bx.cx()),
207 bug!("simd shuffle field {:?}", field)
210 let llval = CodegenCx::c_struct(bx.cx(), &values?, false);
213 .unwrap_or_else(|_| {
214 bx.tcx().sess.span_err(
216 "could not evaluate shuffle_indices at compile time",
218 // We've errored, so we don't have to produce working code.
219 let ty = self.monomorphize(&ty);
220 let llty = bx.cx().layout_of(ty).llvm_type(bx.cx());
221 (bx.cx().c_undef(llty), ty)