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.
11 use llvm::{self, ValueRef};
12 use rustc::middle::const_val::{ConstEvalErr, ConstVal, ErrKind};
13 use rustc_const_math::ConstInt::*;
14 use rustc_const_math::ConstFloat;
15 use rustc_const_math::{ConstInt, ConstMathErr};
16 use rustc::hir::def_id::DefId;
17 use rustc::infer::TransNormalize;
19 use rustc::mir::tcx::LvalueTy;
20 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
21 use rustc::ty::layout::{self, LayoutTyper};
22 use rustc::ty::cast::{CastTy, IntTy};
23 use rustc::ty::subst::{Kind, Substs, Subst};
24 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
25 use {adt, base, machine};
29 use common::{self, CrateContext, const_get_elt, val_ty};
30 use common::{C_array, C_bool, C_bytes, C_floating_f64, C_integral, C_big_integral};
31 use common::{C_null, C_struct, C_str_slice, C_undef, C_uint, C_vector, is_undef};
32 use common::const_to_opt_u128;
44 use super::lvalue::Alignment;
45 use super::operand::{OperandRef, OperandValue};
46 use super::MirContext;
48 /// A sized constant rvalue.
49 /// The LLVM type might not be the same for a single Rust type,
50 /// e.g. each enum variant would have its own LLVM struct type.
51 #[derive(Copy, Clone)]
52 pub struct Const<'tcx> {
57 impl<'tcx> Const<'tcx> {
58 pub fn new(llval: ValueRef, ty: Ty<'tcx>) -> Const<'tcx> {
65 pub fn from_constint<'a>(ccx: &CrateContext<'a, 'tcx>, ci: &ConstInt)
68 let (llval, ty) = match *ci {
69 I8(v) => (C_integral(Type::i8(ccx), v as u64, true), tcx.types.i8),
70 I16(v) => (C_integral(Type::i16(ccx), v as u64, true), tcx.types.i16),
71 I32(v) => (C_integral(Type::i32(ccx), v as u64, true), tcx.types.i32),
72 I64(v) => (C_integral(Type::i64(ccx), v as u64, true), tcx.types.i64),
73 I128(v) => (C_big_integral(Type::i128(ccx), v as u128), tcx.types.i128),
75 let i = v.as_i64(ccx.tcx().sess.target.int_type);
76 (C_integral(Type::int(ccx), i as u64, true), tcx.types.isize)
78 U8(v) => (C_integral(Type::i8(ccx), v as u64, false), tcx.types.u8),
79 U16(v) => (C_integral(Type::i16(ccx), v as u64, false), tcx.types.u16),
80 U32(v) => (C_integral(Type::i32(ccx), v as u64, false), tcx.types.u32),
81 U64(v) => (C_integral(Type::i64(ccx), v, false), tcx.types.u64),
82 U128(v) => (C_big_integral(Type::i128(ccx), v), tcx.types.u128),
84 let u = v.as_u64(ccx.tcx().sess.target.uint_type);
85 (C_integral(Type::int(ccx), u, false), tcx.types.usize)
88 Const { llval: llval, ty: ty }
91 /// Translate ConstVal into a LLVM constant value.
92 pub fn from_constval<'a>(ccx: &CrateContext<'a, 'tcx>,
96 let llty = type_of::type_of(ccx, ty);
98 ConstVal::Float(v) => {
100 ConstFloat::F32(v) => f32::from_bits(v) as f64,
101 ConstFloat::F64(v) => f64::from_bits(v)
103 C_floating_f64(v_f64, llty)
105 ConstVal::Bool(v) => C_bool(ccx, v),
106 ConstVal::Integral(ref i) => return Const::from_constint(ccx, i),
107 ConstVal::Str(ref v) => C_str_slice(ccx, v.clone()),
108 ConstVal::ByteStr(ref v) => consts::addr_of(ccx, C_bytes(ccx, v), 1, "byte_str"),
109 ConstVal::Char(c) => C_integral(Type::char(ccx), c as u64, false),
110 ConstVal::Function(..) => C_null(type_of::type_of(ccx, ty)),
111 ConstVal::Variant(_) |
112 ConstVal::Struct(_) | ConstVal::Tuple(_) |
113 ConstVal::Array(..) | ConstVal::Repeat(..) => {
114 bug!("MIR must not use `{:?}` (aggregates are expanded to MIR rvalues)", cv)
118 assert!(!ty.has_erasable_regions());
123 fn get_pair(&self) -> (ValueRef, ValueRef) {
124 (const_get_elt(self.llval, &[0]),
125 const_get_elt(self.llval, &[1]))
128 fn get_fat_ptr(&self) -> (ValueRef, ValueRef) {
129 assert_eq!(abi::FAT_PTR_ADDR, 0);
130 assert_eq!(abi::FAT_PTR_EXTRA, 1);
134 fn as_lvalue(&self) -> ConstLvalue<'tcx> {
136 base: Base::Value(self.llval),
137 llextra: ptr::null_mut(),
142 pub fn to_operand<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> OperandRef<'tcx> {
143 let llty = type_of::immediate_type_of(ccx, self.ty);
144 let llvalty = val_ty(self.llval);
146 let val = if llty == llvalty && common::type_is_imm_pair(ccx, self.ty) {
147 let (a, b) = self.get_pair();
148 OperandValue::Pair(a, b)
149 } else if llty == llvalty && common::type_is_immediate(ccx, self.ty) {
150 // If the types match, we can use the value directly.
151 OperandValue::Immediate(self.llval)
153 // Otherwise, or if the value is not immediate, we create
154 // a constant LLVM global and cast its address if necessary.
155 let align = ccx.align_of(self.ty);
156 let ptr = consts::addr_of(ccx, self.llval, align, "const");
157 OperandValue::Ref(consts::ptrcast(ptr, llty.ptr_to()), Alignment::AbiAligned)
167 impl<'tcx> fmt::Debug for Const<'tcx> {
168 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
169 write!(f, "Const({:?}: {:?})", Value(self.llval), self.ty)
173 #[derive(Copy, Clone)]
175 /// A constant value without an unique address.
178 /// String literal base pointer (cast from array).
181 /// The address of a static.
185 /// An lvalue as seen from a constant.
186 #[derive(Copy, Clone)]
187 struct ConstLvalue<'tcx> {
193 impl<'tcx> ConstLvalue<'tcx> {
194 fn to_const(&self, span: Span) -> Const<'tcx> {
196 Base::Value(val) => Const::new(val, self.ty),
198 span_bug!(span, "loading from `str` ({:?}) in constant",
201 Base::Static(val) => {
202 span_bug!(span, "loading from `static` ({:?}) in constant",
208 pub fn len<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> ValueRef {
210 ty::TyArray(_, n) => C_uint(ccx, n),
211 ty::TySlice(_) | ty::TyStr => {
212 assert!(self.llextra != ptr::null_mut());
215 _ => bug!("unexpected type `{}` in ConstLvalue::len", self.ty)
220 /// Machinery for translating a constant's MIR to LLVM values.
221 /// FIXME(eddyb) use miri and lower its allocations to LLVM.
222 struct MirConstContext<'a, 'tcx: 'a> {
223 ccx: &'a CrateContext<'a, 'tcx>,
224 mir: &'a mir::Mir<'tcx>,
226 /// Type parameters for const fn and associated constants.
227 substs: &'tcx Substs<'tcx>,
229 /// Values of locals in a constant or const fn.
230 locals: IndexVec<mir::Local, Option<Result<Const<'tcx>, ConstEvalErr<'tcx>>>>
233 fn add_err<'tcx, U, V>(failure: &mut Result<U, ConstEvalErr<'tcx>>,
234 value: &Result<V, ConstEvalErr<'tcx>>)
236 if let &Err(ref err) = value {
238 *failure = Err(err.clone());
243 impl<'a, 'tcx> MirConstContext<'a, 'tcx> {
244 fn new(ccx: &'a CrateContext<'a, 'tcx>,
245 mir: &'a mir::Mir<'tcx>,
246 substs: &'tcx Substs<'tcx>,
247 args: IndexVec<mir::Local, Result<Const<'tcx>, ConstEvalErr<'tcx>>>)
248 -> MirConstContext<'a, 'tcx> {
249 let mut context = MirConstContext {
253 locals: (0..mir.local_decls.len()).map(|_| None).collect(),
255 for (i, arg) in args.into_iter().enumerate() {
256 // Locals after local 0 are the function arguments
257 let index = mir::Local::new(i + 1);
258 context.locals[index] = Some(arg);
263 fn trans_def(ccx: &'a CrateContext<'a, 'tcx>,
265 substs: &'tcx Substs<'tcx>,
266 args: IndexVec<mir::Local, Result<Const<'tcx>, ConstEvalErr<'tcx>>>)
267 -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
268 let instance = monomorphize::resolve(ccx.shared(), def_id, substs);
269 let mir = ccx.tcx().instance_mir(instance.def);
270 MirConstContext::new(ccx, &mir, instance.substs, args).trans()
273 fn monomorphize<T>(&self, value: &T) -> T
274 where T: TransNormalize<'tcx>
276 self.ccx.tcx().trans_apply_param_substs(self.substs, value)
279 fn trans(&mut self) -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
280 let tcx = self.ccx.tcx();
281 let mut bb = mir::START_BLOCK;
283 // Make sure to evaluate all statemenets to
284 // report as many errors as we possibly can.
285 let mut failure = Ok(());
288 let data = &self.mir[bb];
289 for statement in &data.statements {
290 let span = statement.source_info.span;
291 match statement.kind {
292 mir::StatementKind::Assign(ref dest, ref rvalue) => {
293 let ty = dest.ty(self.mir, tcx);
294 let ty = self.monomorphize(&ty).to_ty(tcx);
295 let value = self.const_rvalue(rvalue, ty, span);
296 add_err(&mut failure, &value);
297 self.store(dest, value, span);
299 mir::StatementKind::StorageLive(_) |
300 mir::StatementKind::StorageDead(_) |
301 mir::StatementKind::EndRegion(_) |
302 mir::StatementKind::Nop => {}
303 mir::StatementKind::InlineAsm { .. } |
304 mir::StatementKind::SetDiscriminant{ .. } => {
305 span_bug!(span, "{:?} should not appear in constants?", statement.kind);
310 let terminator = data.terminator();
311 let span = terminator.source_info.span;
312 bb = match terminator.kind {
313 mir::TerminatorKind::Drop { target, .. } | // No dropping.
314 mir::TerminatorKind::Goto { target } => target,
315 mir::TerminatorKind::Return => {
317 return self.locals[mir::RETURN_POINTER].clone().unwrap_or_else(|| {
318 span_bug!(span, "no returned value in constant");
322 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, .. } => {
323 let cond = self.const_operand(cond, span)?;
324 let cond_bool = common::const_to_uint(cond.llval) != 0;
325 if cond_bool != expected {
326 let err = match *msg {
327 mir::AssertMessage::BoundsCheck { ref len, ref index } => {
328 let len = self.const_operand(len, span)?;
329 let index = self.const_operand(index, span)?;
330 ErrKind::IndexOutOfBounds {
331 len: common::const_to_uint(len.llval),
332 index: common::const_to_uint(index.llval)
335 mir::AssertMessage::Math(ref err) => {
336 ErrKind::Math(err.clone())
340 let err = ConstEvalErr { span: span, kind: err };
341 err.report(tcx, span, "expression");
347 mir::TerminatorKind::Call { ref func, ref args, ref destination, .. } => {
348 let fn_ty = func.ty(self.mir, tcx);
349 let fn_ty = self.monomorphize(&fn_ty);
350 let (def_id, substs) = match fn_ty.sty {
351 ty::TyFnDef(def_id, substs) => (def_id, substs),
352 _ => span_bug!(span, "calling {:?} (of type {}) in constant",
356 let mut arg_vals = IndexVec::with_capacity(args.len());
358 let arg_val = self.const_operand(arg, span);
359 add_err(&mut failure, &arg_val);
360 arg_vals.push(arg_val);
362 if let Some((ref dest, target)) = *destination {
363 let result = if fn_ty.fn_sig(tcx).abi() == Abi::RustIntrinsic {
364 match &tcx.item_name(def_id).as_str()[..] {
366 let llval = C_uint(self.ccx,
367 self.ccx.size_of(substs.type_at(0)));
368 Ok(Const::new(llval, tcx.types.usize))
371 let llval = C_uint(self.ccx,
372 self.ccx.align_of(substs.type_at(0)));
373 Ok(Const::new(llval, tcx.types.usize))
375 _ => span_bug!(span, "{:?} in constant", terminator.kind)
378 MirConstContext::trans_def(self.ccx, def_id, substs, arg_vals)
380 add_err(&mut failure, &result);
381 self.store(dest, result, span);
384 span_bug!(span, "diverging {:?} in constant", terminator.kind);
387 _ => span_bug!(span, "{:?} in constant", terminator.kind)
393 dest: &mir::Lvalue<'tcx>,
394 value: Result<Const<'tcx>, ConstEvalErr<'tcx>>,
396 if let mir::Lvalue::Local(index) = *dest {
397 self.locals[index] = Some(value);
399 span_bug!(span, "assignment to {:?} in constant", dest);
403 fn const_lvalue(&self, lvalue: &mir::Lvalue<'tcx>, span: Span)
404 -> Result<ConstLvalue<'tcx>, ConstEvalErr<'tcx>> {
405 let tcx = self.ccx.tcx();
407 if let mir::Lvalue::Local(index) = *lvalue {
408 return self.locals[index].clone().unwrap_or_else(|| {
409 span_bug!(span, "{:?} not initialized", lvalue)
410 }).map(|v| v.as_lvalue());
413 let lvalue = match *lvalue {
414 mir::Lvalue::Local(_) => bug!(), // handled above
415 mir::Lvalue::Static(box mir::Static { def_id, ty }) => {
417 base: Base::Static(consts::get_static(self.ccx, def_id)),
418 llextra: ptr::null_mut(),
419 ty: self.monomorphize(&ty),
422 mir::Lvalue::Projection(ref projection) => {
423 let tr_base = self.const_lvalue(&projection.base, span)?;
424 let projected_ty = LvalueTy::Ty { ty: tr_base.ty }
425 .projection_ty(tcx, &projection.elem);
426 let base = tr_base.to_const(span);
427 let projected_ty = self.monomorphize(&projected_ty).to_ty(tcx);
428 let is_sized = self.ccx.shared().type_is_sized(projected_ty);
430 let (projected, llextra) = match projection.elem {
431 mir::ProjectionElem::Deref => {
432 let (base, extra) = if is_sized {
433 (base.llval, ptr::null_mut())
437 if self.ccx.statics().borrow().contains_key(&base) {
438 (Base::Static(base), extra)
439 } else if let ty::TyStr = projected_ty.sty {
440 (Base::Str(base), extra)
443 let v = self.ccx.const_unsized().borrow().get(&v).map_or(v, |&v| v);
444 let mut val = unsafe { llvm::LLVMGetInitializer(v) };
446 span_bug!(span, "dereference of non-constant pointer `{:?}`",
449 if projected_ty.is_bool() {
450 let i1_type = Type::i1(self.ccx);
451 if val_ty(val) != i1_type {
453 val = llvm::LLVMConstTrunc(val, i1_type.to_ref());
457 (Base::Value(val), extra)
460 mir::ProjectionElem::Field(ref field, _) => {
461 let llprojected = adt::const_get_field(self.ccx, tr_base.ty, base.llval,
463 let llextra = if is_sized {
468 (Base::Value(llprojected), llextra)
470 mir::ProjectionElem::Index(ref index) => {
471 let llindex = self.const_operand(index, span)?.llval;
473 let iv = if let Some(iv) = common::const_to_opt_u128(llindex, false) {
476 span_bug!(span, "index is not an integer-constant expression")
479 // Produce an undef instead of a LLVM assertion on OOB.
480 let len = common::const_to_uint(tr_base.len(self.ccx));
481 let llelem = if iv < len as u128 {
482 const_get_elt(base.llval, &[iv as u32])
484 C_undef(type_of::type_of(self.ccx, projected_ty))
487 (Base::Value(llelem), ptr::null_mut())
489 _ => span_bug!(span, "{:?} in constant", projection.elem)
501 fn const_operand(&self, operand: &mir::Operand<'tcx>, span: Span)
502 -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
503 debug!("const_operand({:?} @ {:?})", operand, span);
504 let result = match *operand {
505 mir::Operand::Consume(ref lvalue) => {
506 Ok(self.const_lvalue(lvalue, span)?.to_const(span))
509 mir::Operand::Constant(ref constant) => {
510 let ty = self.monomorphize(&constant.ty);
511 match constant.literal.clone() {
512 mir::Literal::Item { def_id, substs } => {
513 let substs = self.monomorphize(&substs);
514 MirConstContext::trans_def(self.ccx, def_id, substs, IndexVec::new())
516 mir::Literal::Promoted { index } => {
517 let mir = &self.mir.promoted[index];
518 MirConstContext::new(self.ccx, mir, self.substs, IndexVec::new()).trans()
520 mir::Literal::Value { value } => {
521 Ok(Const::from_constval(self.ccx, value, ty))
526 debug!("const_operand({:?} @ {:?}) = {:?}", operand, span,
527 result.as_ref().ok());
531 fn const_array(&self, array_ty: Ty<'tcx>, fields: &[ValueRef])
534 let elem_ty = array_ty.builtin_index().unwrap_or_else(|| {
535 bug!("bad array type {:?}", array_ty)
537 let llunitty = type_of::type_of(self.ccx, elem_ty);
538 // If the array contains enums, an LLVM array won't work.
539 let val = if fields.iter().all(|&f| val_ty(f) == llunitty) {
540 C_array(llunitty, fields)
542 C_struct(self.ccx, fields, false)
544 Const::new(val, array_ty)
547 fn const_rvalue(&self, rvalue: &mir::Rvalue<'tcx>,
548 dest_ty: Ty<'tcx>, span: Span)
549 -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
550 let tcx = self.ccx.tcx();
551 debug!("const_rvalue({:?}: {:?} @ {:?})", rvalue, dest_ty, span);
552 let val = match *rvalue {
553 mir::Rvalue::Use(ref operand) => self.const_operand(operand, span)?,
555 mir::Rvalue::Repeat(ref elem, ref count) => {
556 let elem = self.const_operand(elem, span)?;
557 let size = count.as_u64(tcx.sess.target.uint_type);
558 let fields = vec![elem.llval; size as usize];
559 self.const_array(dest_ty, &fields)
562 mir::Rvalue::Aggregate(ref kind, ref operands) => {
563 // Make sure to evaluate all operands to
564 // report as many errors as we possibly can.
565 let mut fields = Vec::with_capacity(operands.len());
566 let mut failure = Ok(());
567 for operand in operands {
568 match self.const_operand(operand, span) {
569 Ok(val) => fields.push(val.llval),
570 Err(err) => if failure.is_ok() { failure = Err(err); }
576 mir::AggregateKind::Array(_) => {
577 self.const_array(dest_ty, &fields)
579 mir::AggregateKind::Adt(..) |
580 mir::AggregateKind::Closure(..) |
581 mir::AggregateKind::Tuple => {
582 Const::new(trans_const(self.ccx, dest_ty, kind, &fields), dest_ty)
587 mir::Rvalue::Cast(ref kind, ref source, cast_ty) => {
588 let operand = self.const_operand(source, span)?;
589 let cast_ty = self.monomorphize(&cast_ty);
591 let val = match *kind {
592 mir::CastKind::ReifyFnPointer => {
593 match operand.ty.sty {
594 ty::TyFnDef(def_id, substs) => {
595 callee::resolve_and_get_fn(self.ccx, def_id, substs)
598 span_bug!(span, "{} cannot be reified to a fn ptr",
603 mir::CastKind::ClosureFnPointer => {
604 match operand.ty.sty {
605 ty::TyClosure(def_id, substs) => {
606 // Get the def_id for FnOnce::call_once
607 let fn_once = tcx.lang_items.fn_once_trait().unwrap();
609 .global_tcx().associated_items(fn_once)
610 .find(|it| it.kind == ty::AssociatedKind::Method)
612 // Now create its substs [Closure, Tuple]
613 let input = tcx.fn_sig(def_id)
614 .subst(tcx, substs.substs).input(0);
615 let input = tcx.erase_late_bound_regions_and_normalize(&input);
616 let substs = tcx.mk_substs([operand.ty, input]
617 .iter().cloned().map(Kind::from));
618 callee::resolve_and_get_fn(self.ccx, call_once, substs)
621 bug!("{} cannot be cast to a fn ptr", operand.ty)
625 mir::CastKind::UnsafeFnPointer => {
626 // this is a no-op at the LLVM level
629 mir::CastKind::Unsize => {
630 // unsize targets other than to a fat pointer currently
631 // can't be in constants.
632 assert!(common::type_is_fat_ptr(self.ccx, cast_ty));
634 let pointee_ty = operand.ty.builtin_deref(true, ty::NoPreference)
635 .expect("consts: unsizing got non-pointer type").ty;
636 let (base, old_info) = if !self.ccx.shared().type_is_sized(pointee_ty) {
637 // Normally, the source is a thin pointer and we are
638 // adding extra info to make a fat pointer. The exception
639 // is when we are upcasting an existing object fat pointer
640 // to use a different vtable. In that case, we want to
641 // load out the original data pointer so we can repackage
643 let (base, extra) = operand.get_fat_ptr();
646 (operand.llval, None)
649 let unsized_ty = cast_ty.builtin_deref(true, ty::NoPreference)
650 .expect("consts: unsizing got non-pointer target type").ty;
651 let ptr_ty = type_of::in_memory_type_of(self.ccx, unsized_ty).ptr_to();
652 let base = consts::ptrcast(base, ptr_ty);
653 let info = base::unsized_info(self.ccx, pointee_ty,
654 unsized_ty, old_info);
656 if old_info.is_none() {
657 let prev_const = self.ccx.const_unsized().borrow_mut()
658 .insert(base, operand.llval);
659 assert!(prev_const.is_none() || prev_const == Some(operand.llval));
661 assert_eq!(abi::FAT_PTR_ADDR, 0);
662 assert_eq!(abi::FAT_PTR_EXTRA, 1);
663 C_struct(self.ccx, &[base, info], false)
665 mir::CastKind::Misc if common::type_is_immediate(self.ccx, operand.ty) => {
666 debug_assert!(common::type_is_immediate(self.ccx, cast_ty));
667 let r_t_in = CastTy::from_ty(operand.ty).expect("bad input type for cast");
668 let r_t_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
669 let ll_t_out = type_of::immediate_type_of(self.ccx, cast_ty);
670 let llval = operand.llval;
671 let signed = if let CastTy::Int(IntTy::CEnum) = r_t_in {
672 let l = self.ccx.layout_of(operand.ty);
673 adt::is_discr_signed(&l)
675 operand.ty.is_signed()
679 match (r_t_in, r_t_out) {
680 (CastTy::Int(_), CastTy::Int(_)) => {
681 let s = signed as llvm::Bool;
682 llvm::LLVMConstIntCast(llval, ll_t_out.to_ref(), s)
684 (CastTy::Int(_), CastTy::Float) => {
686 llvm::LLVMConstSIToFP(llval, ll_t_out.to_ref())
688 llvm::LLVMConstUIToFP(llval, ll_t_out.to_ref())
691 (CastTy::Float, CastTy::Float) => {
692 llvm::LLVMConstFPCast(llval, ll_t_out.to_ref())
694 (CastTy::Float, CastTy::Int(IntTy::I)) => {
695 llvm::LLVMConstFPToSI(llval, ll_t_out.to_ref())
697 (CastTy::Float, CastTy::Int(_)) => {
698 llvm::LLVMConstFPToUI(llval, ll_t_out.to_ref())
700 (CastTy::Ptr(_), CastTy::Ptr(_)) |
701 (CastTy::FnPtr, CastTy::Ptr(_)) |
702 (CastTy::RPtr(_), CastTy::Ptr(_)) => {
703 consts::ptrcast(llval, ll_t_out)
705 (CastTy::Int(_), CastTy::Ptr(_)) => {
706 llvm::LLVMConstIntToPtr(llval, ll_t_out.to_ref())
708 (CastTy::Ptr(_), CastTy::Int(_)) |
709 (CastTy::FnPtr, CastTy::Int(_)) => {
710 llvm::LLVMConstPtrToInt(llval, ll_t_out.to_ref())
712 _ => bug!("unsupported cast: {:?} to {:?}", operand.ty, cast_ty)
716 mir::CastKind::Misc => { // Casts from a fat-ptr.
717 let ll_cast_ty = type_of::immediate_type_of(self.ccx, cast_ty);
718 let ll_from_ty = type_of::immediate_type_of(self.ccx, operand.ty);
719 if common::type_is_fat_ptr(self.ccx, operand.ty) {
720 let (data_ptr, meta_ptr) = operand.get_fat_ptr();
721 if common::type_is_fat_ptr(self.ccx, cast_ty) {
722 let ll_cft = ll_cast_ty.field_types();
723 let ll_fft = ll_from_ty.field_types();
724 let data_cast = consts::ptrcast(data_ptr, ll_cft[0]);
725 assert_eq!(ll_cft[1].kind(), ll_fft[1].kind());
726 C_struct(self.ccx, &[data_cast, meta_ptr], false)
727 } else { // cast to thin-ptr
728 // Cast of fat-ptr to thin-ptr is an extraction of data-ptr and
729 // pointer-cast of that pointer to desired pointer type.
730 consts::ptrcast(data_ptr, ll_cast_ty)
733 bug!("Unexpected non-fat-pointer operand")
737 Const::new(val, cast_ty)
740 mir::Rvalue::Ref(_, bk, ref lvalue) => {
741 let tr_lvalue = self.const_lvalue(lvalue, span)?;
743 let ty = tr_lvalue.ty;
744 let ref_ty = tcx.mk_ref(tcx.types.re_erased,
745 ty::TypeAndMut { ty: ty, mutbl: bk.to_mutbl_lossy() });
747 let base = match tr_lvalue.base {
748 Base::Value(llval) => {
749 // FIXME: may be wrong for &*(&simd_vec as &fmt::Debug)
750 let align = if self.ccx.shared().type_is_sized(ty) {
751 self.ccx.align_of(ty)
753 self.ccx.tcx().data_layout.pointer_align.abi() as machine::llalign
755 if bk == mir::BorrowKind::Mut {
756 consts::addr_of_mut(self.ccx, llval, align, "ref_mut")
758 consts::addr_of(self.ccx, llval, align, "ref")
762 Base::Static(llval) => llval
765 let ptr = if self.ccx.shared().type_is_sized(ty) {
768 C_struct(self.ccx, &[base, tr_lvalue.llextra], false)
770 Const::new(ptr, ref_ty)
773 mir::Rvalue::Len(ref lvalue) => {
774 let tr_lvalue = self.const_lvalue(lvalue, span)?;
775 Const::new(tr_lvalue.len(self.ccx), tcx.types.usize)
778 mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
779 let lhs = self.const_operand(lhs, span)?;
780 let rhs = self.const_operand(rhs, span)?;
782 let binop_ty = op.ty(tcx, lhs.ty, rhs.ty);
783 let (lhs, rhs) = (lhs.llval, rhs.llval);
784 Const::new(const_scalar_binop(op, lhs, rhs, ty), binop_ty)
787 mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
788 let lhs = self.const_operand(lhs, span)?;
789 let rhs = self.const_operand(rhs, span)?;
791 let val_ty = op.ty(tcx, lhs.ty, rhs.ty);
792 let binop_ty = tcx.intern_tup(&[val_ty, tcx.types.bool], false);
793 let (lhs, rhs) = (lhs.llval, rhs.llval);
794 assert!(!ty.is_fp());
796 match const_scalar_checked_binop(tcx, op, lhs, rhs, ty) {
797 Some((llval, of)) => {
798 let llof = C_bool(self.ccx, of);
799 Const::new(C_struct(self.ccx, &[llval, llof], false), binop_ty)
802 span_bug!(span, "{:?} got non-integer operands: {:?} and {:?}",
803 rvalue, Value(lhs), Value(rhs));
808 mir::Rvalue::UnaryOp(op, ref operand) => {
809 let operand = self.const_operand(operand, span)?;
810 let lloperand = operand.llval;
811 let llval = match op {
814 llvm::LLVMConstNot(lloperand)
818 let is_float = operand.ty.is_fp();
821 llvm::LLVMConstFNeg(lloperand)
823 llvm::LLVMConstNeg(lloperand)
828 Const::new(llval, operand.ty)
831 mir::Rvalue::NullaryOp(mir::NullOp::SizeOf, ty) => {
832 assert!(self.ccx.shared().type_is_sized(ty));
833 let llval = C_uint(self.ccx, self.ccx.size_of(ty));
834 Const::new(llval, tcx.types.usize)
837 _ => span_bug!(span, "{:?} in constant", rvalue)
840 debug!("const_rvalue({:?}: {:?} @ {:?}) = {:?}", rvalue, dest_ty, span, val);
847 fn to_const_int(value: ValueRef, t: Ty, tcx: TyCtxt) -> Option<ConstInt> {
849 ty::TyInt(int_type) => const_to_opt_u128(value, true)
850 .and_then(|input| ConstInt::new_signed(input as i128, int_type,
851 tcx.sess.target.int_type)),
852 ty::TyUint(uint_type) => const_to_opt_u128(value, false)
853 .and_then(|input| ConstInt::new_unsigned(input, uint_type,
854 tcx.sess.target.uint_type)),
860 pub fn const_scalar_binop(op: mir::BinOp,
863 input_ty: Ty) -> ValueRef {
864 assert!(!input_ty.is_simd());
865 let is_float = input_ty.is_fp();
866 let signed = input_ty.is_signed();
870 mir::BinOp::Add if is_float => llvm::LLVMConstFAdd(lhs, rhs),
871 mir::BinOp::Add => llvm::LLVMConstAdd(lhs, rhs),
873 mir::BinOp::Sub if is_float => llvm::LLVMConstFSub(lhs, rhs),
874 mir::BinOp::Sub => llvm::LLVMConstSub(lhs, rhs),
876 mir::BinOp::Mul if is_float => llvm::LLVMConstFMul(lhs, rhs),
877 mir::BinOp::Mul => llvm::LLVMConstMul(lhs, rhs),
879 mir::BinOp::Div if is_float => llvm::LLVMConstFDiv(lhs, rhs),
880 mir::BinOp::Div if signed => llvm::LLVMConstSDiv(lhs, rhs),
881 mir::BinOp::Div => llvm::LLVMConstUDiv(lhs, rhs),
883 mir::BinOp::Rem if is_float => llvm::LLVMConstFRem(lhs, rhs),
884 mir::BinOp::Rem if signed => llvm::LLVMConstSRem(lhs, rhs),
885 mir::BinOp::Rem => llvm::LLVMConstURem(lhs, rhs),
887 mir::BinOp::BitXor => llvm::LLVMConstXor(lhs, rhs),
888 mir::BinOp::BitAnd => llvm::LLVMConstAnd(lhs, rhs),
889 mir::BinOp::BitOr => llvm::LLVMConstOr(lhs, rhs),
891 let rhs = base::cast_shift_const_rhs(op.to_hir_binop(), lhs, rhs);
892 llvm::LLVMConstShl(lhs, rhs)
895 let rhs = base::cast_shift_const_rhs(op.to_hir_binop(), lhs, rhs);
896 if signed { llvm::LLVMConstAShr(lhs, rhs) }
897 else { llvm::LLVMConstLShr(lhs, rhs) }
899 mir::BinOp::Eq | mir::BinOp::Ne |
900 mir::BinOp::Lt | mir::BinOp::Le |
901 mir::BinOp::Gt | mir::BinOp::Ge => {
903 let cmp = base::bin_op_to_fcmp_predicate(op.to_hir_binop());
904 llvm::LLVMConstFCmp(cmp, lhs, rhs)
906 let cmp = base::bin_op_to_icmp_predicate(op.to_hir_binop(),
908 llvm::LLVMConstICmp(cmp, lhs, rhs)
911 mir::BinOp::Offset => unreachable!("BinOp::Offset in const-eval!")
916 pub fn const_scalar_checked_binop<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
921 -> Option<(ValueRef, bool)> {
922 if let (Some(lhs), Some(rhs)) = (to_const_int(lllhs, input_ty, tcx),
923 to_const_int(llrhs, input_ty, tcx)) {
924 let result = match op {
925 mir::BinOp::Add => lhs + rhs,
926 mir::BinOp::Sub => lhs - rhs,
927 mir::BinOp::Mul => lhs * rhs,
928 mir::BinOp::Shl => lhs << rhs,
929 mir::BinOp::Shr => lhs >> rhs,
931 bug!("Operator `{:?}` is not a checkable operator", op)
935 let of = match result {
937 Err(ConstMathErr::Overflow(_)) |
938 Err(ConstMathErr::ShiftNegative) => true,
940 bug!("Operator `{:?}` on `{:?}` and `{:?}` errored: {}",
941 op, lhs, rhs, err.description());
945 Some((const_scalar_binop(op, lllhs, llrhs, input_ty), of))
951 impl<'a, 'tcx> MirContext<'a, 'tcx> {
952 pub fn trans_constant(&mut self,
953 bcx: &Builder<'a, 'tcx>,
954 constant: &mir::Constant<'tcx>)
957 debug!("trans_constant({:?})", constant);
958 let ty = self.monomorphize(&constant.ty);
959 let result = match constant.literal.clone() {
960 mir::Literal::Item { def_id, substs } => {
961 let substs = self.monomorphize(&substs);
962 MirConstContext::trans_def(bcx.ccx, def_id, substs, IndexVec::new())
964 mir::Literal::Promoted { index } => {
965 let mir = &self.mir.promoted[index];
966 MirConstContext::new(bcx.ccx, mir, self.param_substs, IndexVec::new()).trans()
968 mir::Literal::Value { value } => {
969 Ok(Const::from_constval(bcx.ccx, value, ty))
973 let result = result.unwrap_or_else(|_| {
974 // We've errored, so we don't have to produce working code.
975 let llty = type_of::type_of(bcx.ccx, ty);
976 Const::new(C_undef(llty), ty)
979 debug!("trans_constant({:?}) = {:?}", constant, result);
985 pub fn trans_static_initializer<'a, 'tcx>(
986 ccx: &CrateContext<'a, 'tcx>,
988 -> Result<ValueRef, ConstEvalErr<'tcx>>
990 MirConstContext::trans_def(ccx, def_id, Substs::empty(), IndexVec::new())
994 /// Construct a constant value, suitable for initializing a
995 /// GlobalVariable, given a case and constant values for its fields.
996 /// Note that this may have a different LLVM type (and different
997 /// alignment!) from the representation's `type_of`, so it needs a
998 /// pointer cast before use.
1000 /// The LLVM type system does not directly support unions, and only
1001 /// pointers can be bitcast, so a constant (and, by extension, the
1002 /// GlobalVariable initialized by it) will have a type that can vary
1003 /// depending on which case of an enum it is.
1005 /// To understand the alignment situation, consider `enum E { V64(u64),
1006 /// V32(u32, u32) }` on Windows. The type has 8-byte alignment to
1007 /// accommodate the u64, but `V32(x, y)` would have LLVM type `{i32,
1008 /// i32, i32}`, which is 4-byte aligned.
1010 /// Currently the returned value has the same size as the type, but
1011 /// this could be changed in the future to avoid allocating unnecessary
1012 /// space after values of shorter-than-maximum cases.
1013 fn trans_const<'a, 'tcx>(
1014 ccx: &CrateContext<'a, 'tcx>,
1016 kind: &mir::AggregateKind,
1019 let l = ccx.layout_of(t);
1020 let variant_index = match *kind {
1021 mir::AggregateKind::Adt(_, index, _, _) => index,
1025 layout::CEnum { discr: d, min, max, .. } => {
1026 let discr = match *kind {
1027 mir::AggregateKind::Adt(adt_def, _, _, _) => {
1028 adt_def.discriminant_for_variant(ccx.tcx(), variant_index)
1029 .to_u128_unchecked() as u64
1033 assert_eq!(vals.len(), 0);
1034 adt::assert_discr_in_range(min, max, discr);
1035 C_integral(Type::from_integer(ccx, d), discr, true)
1037 layout::General { discr: d, ref variants, .. } => {
1038 let variant = &variants[variant_index];
1039 let lldiscr = C_integral(Type::from_integer(ccx, d), variant_index as u64, true);
1040 let mut vals_with_discr = vec![lldiscr];
1041 vals_with_discr.extend_from_slice(vals);
1042 let mut contents = build_const_struct(ccx, &variant, &vals_with_discr[..]);
1043 let needed_padding = l.size(ccx).bytes() - variant.stride().bytes();
1044 if needed_padding > 0 {
1045 contents.push(padding(ccx, needed_padding));
1047 C_struct(ccx, &contents[..], false)
1049 layout::UntaggedUnion { ref variants, .. }=> {
1050 assert_eq!(variant_index, 0);
1051 let contents = build_const_union(ccx, variants, vals[0]);
1052 C_struct(ccx, &contents, variants.packed)
1054 layout::Univariant { ref variant, .. } => {
1055 assert_eq!(variant_index, 0);
1056 let contents = build_const_struct(ccx, &variant, vals);
1057 C_struct(ccx, &contents[..], variant.packed)
1059 layout::Vector { .. } => {
1062 layout::RawNullablePointer { nndiscr, .. } => {
1063 if variant_index as u64 == nndiscr {
1064 assert_eq!(vals.len(), 1);
1067 C_null(type_of::type_of(ccx, t))
1070 layout::StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
1071 if variant_index as u64 == nndiscr {
1072 C_struct(ccx, &build_const_struct(ccx, &nonnull, vals), false)
1074 // Always use null even if it's not the `discrfield`th
1075 // field; see #8506.
1076 C_null(type_of::type_of(ccx, t))
1079 _ => bug!("trans_const: cannot handle type {} repreented as {:#?}", t, l)
1083 /// Building structs is a little complicated, because we might need to
1084 /// insert padding if a field's value is less aligned than its type.
1086 /// Continuing the example from `trans_const`, a value of type `(u32,
1087 /// E)` should have the `E` at offset 8, but if that field's
1088 /// initializer is 4-byte aligned then simply translating the tuple as
1089 /// a two-element struct will locate it at offset 4, and accesses to it
1090 /// will read the wrong memory.
1091 fn build_const_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1092 st: &layout::Struct,
1095 assert_eq!(vals.len(), st.offsets.len());
1097 if vals.len() == 0 {
1101 // offset of current value
1103 let mut cfields = Vec::new();
1104 cfields.reserve(st.offsets.len()*2);
1106 let parts = st.field_index_by_increasing_offset().map(|i| {
1107 (&vals[i], st.offsets[i].bytes())
1109 for (&val, target_offset) in parts {
1110 if offset < target_offset {
1111 cfields.push(padding(ccx, target_offset - offset));
1112 offset = target_offset;
1114 assert!(!is_undef(val));
1116 offset += machine::llsize_of_alloc(ccx, val_ty(val));
1119 if offset < st.stride().bytes() {
1120 cfields.push(padding(ccx, st.stride().bytes() - offset));
1126 fn build_const_union<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1128 field_val: ValueRef)
1130 let mut cfields = vec![field_val];
1132 let offset = machine::llsize_of_alloc(ccx, val_ty(field_val));
1133 let size = un.stride().bytes();
1135 cfields.push(padding(ccx, size - offset));
1141 fn padding(ccx: &CrateContext, size: u64) -> ValueRef {
1142 C_undef(Type::array(&Type::i8(ccx), size))