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(F32(v)) => C_floating_f64(v as f64, llty),
99 ConstVal::Float(F64(v)) => C_floating_f64(v, llty),
100 ConstVal::Bool(v) => C_bool(ccx, v),
101 ConstVal::Integral(ref i) => return Const::from_constint(ccx, i),
102 ConstVal::Str(ref v) => C_str_slice(ccx, v.clone()),
103 ConstVal::ByteStr(ref v) => consts::addr_of(ccx, C_bytes(ccx, v), 1, "byte_str"),
104 ConstVal::Char(c) => C_integral(Type::char(ccx), c as u64, false),
105 ConstVal::Function(..) => C_null(type_of::type_of(ccx, ty)),
106 ConstVal::Variant(_) |
107 ConstVal::Struct(_) | ConstVal::Tuple(_) |
108 ConstVal::Array(..) | ConstVal::Repeat(..) => {
109 bug!("MIR must not use `{:?}` (aggregates are expanded to MIR rvalues)", cv)
113 assert!(!ty.has_erasable_regions());
118 fn get_pair(&self) -> (ValueRef, ValueRef) {
119 (const_get_elt(self.llval, &[0]),
120 const_get_elt(self.llval, &[1]))
123 fn get_fat_ptr(&self) -> (ValueRef, ValueRef) {
124 assert_eq!(abi::FAT_PTR_ADDR, 0);
125 assert_eq!(abi::FAT_PTR_EXTRA, 1);
129 fn as_lvalue(&self) -> ConstLvalue<'tcx> {
131 base: Base::Value(self.llval),
132 llextra: ptr::null_mut(),
137 pub fn to_operand<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> OperandRef<'tcx> {
138 let llty = type_of::immediate_type_of(ccx, self.ty);
139 let llvalty = val_ty(self.llval);
141 let val = if llty == llvalty && common::type_is_imm_pair(ccx, self.ty) {
142 let (a, b) = self.get_pair();
143 OperandValue::Pair(a, b)
144 } else if llty == llvalty && common::type_is_immediate(ccx, self.ty) {
145 // If the types match, we can use the value directly.
146 OperandValue::Immediate(self.llval)
148 // Otherwise, or if the value is not immediate, we create
149 // a constant LLVM global and cast its address if necessary.
150 let align = ccx.align_of(self.ty);
151 let ptr = consts::addr_of(ccx, self.llval, align, "const");
152 OperandValue::Ref(consts::ptrcast(ptr, llty.ptr_to()), Alignment::AbiAligned)
162 impl<'tcx> fmt::Debug for Const<'tcx> {
163 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
164 write!(f, "Const({:?}: {:?})", Value(self.llval), self.ty)
168 #[derive(Copy, Clone)]
170 /// A constant value without an unique address.
173 /// String literal base pointer (cast from array).
176 /// The address of a static.
180 /// An lvalue as seen from a constant.
181 #[derive(Copy, Clone)]
182 struct ConstLvalue<'tcx> {
188 impl<'tcx> ConstLvalue<'tcx> {
189 fn to_const(&self, span: Span) -> Const<'tcx> {
191 Base::Value(val) => Const::new(val, self.ty),
193 span_bug!(span, "loading from `str` ({:?}) in constant",
196 Base::Static(val) => {
197 span_bug!(span, "loading from `static` ({:?}) in constant",
203 pub fn len<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> ValueRef {
205 ty::TyArray(_, n) => C_uint(ccx, n),
206 ty::TySlice(_) | ty::TyStr => {
207 assert!(self.llextra != ptr::null_mut());
210 _ => bug!("unexpected type `{}` in ConstLvalue::len", self.ty)
215 /// Machinery for translating a constant's MIR to LLVM values.
216 /// FIXME(eddyb) use miri and lower its allocations to LLVM.
217 struct MirConstContext<'a, 'tcx: 'a> {
218 ccx: &'a CrateContext<'a, 'tcx>,
219 mir: &'a mir::Mir<'tcx>,
221 /// Type parameters for const fn and associated constants.
222 substs: &'tcx Substs<'tcx>,
224 /// Values of locals in a constant or const fn.
225 locals: IndexVec<mir::Local, Option<Result<Const<'tcx>, ConstEvalErr<'tcx>>>>
228 fn add_err<'tcx, U, V>(failure: &mut Result<U, ConstEvalErr<'tcx>>,
229 value: &Result<V, ConstEvalErr<'tcx>>)
231 if let &Err(ref err) = value {
233 *failure = Err(err.clone());
238 impl<'a, 'tcx> MirConstContext<'a, 'tcx> {
239 fn new(ccx: &'a CrateContext<'a, 'tcx>,
240 mir: &'a mir::Mir<'tcx>,
241 substs: &'tcx Substs<'tcx>,
242 args: IndexVec<mir::Local, Result<Const<'tcx>, ConstEvalErr<'tcx>>>)
243 -> MirConstContext<'a, 'tcx> {
244 let mut context = MirConstContext {
248 locals: (0..mir.local_decls.len()).map(|_| None).collect(),
250 for (i, arg) in args.into_iter().enumerate() {
251 // Locals after local 0 are the function arguments
252 let index = mir::Local::new(i + 1);
253 context.locals[index] = Some(arg);
258 fn trans_def(ccx: &'a CrateContext<'a, 'tcx>,
260 substs: &'tcx Substs<'tcx>,
261 args: IndexVec<mir::Local, Result<Const<'tcx>, ConstEvalErr<'tcx>>>)
262 -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
263 let instance = monomorphize::resolve(ccx.shared(), def_id, substs);
264 let mir = ccx.tcx().instance_mir(instance.def);
265 MirConstContext::new(ccx, &mir, instance.substs, args).trans()
268 fn monomorphize<T>(&self, value: &T) -> T
269 where T: TransNormalize<'tcx>
271 self.ccx.tcx().trans_apply_param_substs(self.substs, value)
274 fn trans(&mut self) -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
275 let tcx = self.ccx.tcx();
276 let mut bb = mir::START_BLOCK;
278 // Make sure to evaluate all statemenets to
279 // report as many errors as we possibly can.
280 let mut failure = Ok(());
283 let data = &self.mir[bb];
284 for statement in &data.statements {
285 let span = statement.source_info.span;
286 match statement.kind {
287 mir::StatementKind::Assign(ref dest, ref rvalue) => {
288 let ty = dest.ty(self.mir, tcx);
289 let ty = self.monomorphize(&ty).to_ty(tcx);
290 let value = self.const_rvalue(rvalue, ty, span);
291 add_err(&mut failure, &value);
292 self.store(dest, value, span);
294 mir::StatementKind::StorageLive(_) |
295 mir::StatementKind::StorageDead(_) |
296 mir::StatementKind::EndRegion(_) |
297 mir::StatementKind::Nop => {}
298 mir::StatementKind::InlineAsm { .. } |
299 mir::StatementKind::SetDiscriminant{ .. } => {
300 span_bug!(span, "{:?} should not appear in constants?", statement.kind);
305 let terminator = data.terminator();
306 let span = terminator.source_info.span;
307 bb = match terminator.kind {
308 mir::TerminatorKind::Drop { target, .. } | // No dropping.
309 mir::TerminatorKind::Goto { target } => target,
310 mir::TerminatorKind::Return => {
312 return self.locals[mir::RETURN_POINTER].clone().unwrap_or_else(|| {
313 span_bug!(span, "no returned value in constant");
317 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, .. } => {
318 let cond = self.const_operand(cond, span)?;
319 let cond_bool = common::const_to_uint(cond.llval) != 0;
320 if cond_bool != expected {
321 let err = match *msg {
322 mir::AssertMessage::BoundsCheck { ref len, ref index } => {
323 let len = self.const_operand(len, span)?;
324 let index = self.const_operand(index, span)?;
325 ErrKind::IndexOutOfBounds {
326 len: common::const_to_uint(len.llval),
327 index: common::const_to_uint(index.llval)
330 mir::AssertMessage::Math(ref err) => {
331 ErrKind::Math(err.clone())
335 let err = ConstEvalErr { span: span, kind: err };
336 err.report(tcx, span, "expression");
342 mir::TerminatorKind::Call { ref func, ref args, ref destination, .. } => {
343 let fn_ty = func.ty(self.mir, tcx);
344 let fn_ty = self.monomorphize(&fn_ty);
345 let (def_id, substs) = match fn_ty.sty {
346 ty::TyFnDef(def_id, substs) => (def_id, substs),
347 _ => span_bug!(span, "calling {:?} (of type {}) in constant",
351 let mut arg_vals = IndexVec::with_capacity(args.len());
353 let arg_val = self.const_operand(arg, span);
354 add_err(&mut failure, &arg_val);
355 arg_vals.push(arg_val);
357 if let Some((ref dest, target)) = *destination {
358 let result = if fn_ty.fn_sig(tcx).abi() == Abi::RustIntrinsic {
359 match &tcx.item_name(def_id).as_str()[..] {
361 let llval = C_uint(self.ccx,
362 self.ccx.size_of(substs.type_at(0)));
363 Ok(Const::new(llval, tcx.types.usize))
366 let llval = C_uint(self.ccx,
367 self.ccx.align_of(substs.type_at(0)));
368 Ok(Const::new(llval, tcx.types.usize))
370 _ => span_bug!(span, "{:?} in constant", terminator.kind)
373 MirConstContext::trans_def(self.ccx, def_id, substs, arg_vals)
375 add_err(&mut failure, &result);
376 self.store(dest, result, span);
379 span_bug!(span, "diverging {:?} in constant", terminator.kind);
382 _ => span_bug!(span, "{:?} in constant", terminator.kind)
388 dest: &mir::Lvalue<'tcx>,
389 value: Result<Const<'tcx>, ConstEvalErr<'tcx>>,
391 if let mir::Lvalue::Local(index) = *dest {
392 self.locals[index] = Some(value);
394 span_bug!(span, "assignment to {:?} in constant", dest);
398 fn const_lvalue(&self, lvalue: &mir::Lvalue<'tcx>, span: Span)
399 -> Result<ConstLvalue<'tcx>, ConstEvalErr<'tcx>> {
400 let tcx = self.ccx.tcx();
402 if let mir::Lvalue::Local(index) = *lvalue {
403 return self.locals[index].clone().unwrap_or_else(|| {
404 span_bug!(span, "{:?} not initialized", lvalue)
405 }).map(|v| v.as_lvalue());
408 let lvalue = match *lvalue {
409 mir::Lvalue::Local(_) => bug!(), // handled above
410 mir::Lvalue::Static(box mir::Static { def_id, ty }) => {
412 base: Base::Static(consts::get_static(self.ccx, def_id)),
413 llextra: ptr::null_mut(),
414 ty: self.monomorphize(&ty),
417 mir::Lvalue::Projection(ref projection) => {
418 let tr_base = self.const_lvalue(&projection.base, span)?;
419 let projected_ty = LvalueTy::Ty { ty: tr_base.ty }
420 .projection_ty(tcx, &projection.elem);
421 let base = tr_base.to_const(span);
422 let projected_ty = self.monomorphize(&projected_ty).to_ty(tcx);
423 let is_sized = self.ccx.shared().type_is_sized(projected_ty);
425 let (projected, llextra) = match projection.elem {
426 mir::ProjectionElem::Deref => {
427 let (base, extra) = if is_sized {
428 (base.llval, ptr::null_mut())
432 if self.ccx.statics().borrow().contains_key(&base) {
433 (Base::Static(base), extra)
434 } else if let ty::TyStr = projected_ty.sty {
435 (Base::Str(base), extra)
438 let v = self.ccx.const_unsized().borrow().get(&v).map_or(v, |&v| v);
439 let mut val = unsafe { llvm::LLVMGetInitializer(v) };
441 span_bug!(span, "dereference of non-constant pointer `{:?}`",
444 if projected_ty.is_bool() {
445 let i1_type = Type::i1(self.ccx);
446 if val_ty(val) != i1_type {
448 val = llvm::LLVMConstTrunc(val, i1_type.to_ref());
452 (Base::Value(val), extra)
455 mir::ProjectionElem::Field(ref field, _) => {
456 let llprojected = adt::const_get_field(self.ccx, tr_base.ty, base.llval,
458 let llextra = if is_sized {
463 (Base::Value(llprojected), llextra)
465 mir::ProjectionElem::Index(ref index) => {
466 let llindex = self.const_operand(index, span)?.llval;
468 let iv = if let Some(iv) = common::const_to_opt_u128(llindex, false) {
471 span_bug!(span, "index is not an integer-constant expression")
474 // Produce an undef instead of a LLVM assertion on OOB.
475 let len = common::const_to_uint(tr_base.len(self.ccx));
476 let llelem = if iv < len as u128 {
477 const_get_elt(base.llval, &[iv as u32])
479 C_undef(type_of::type_of(self.ccx, projected_ty))
482 (Base::Value(llelem), ptr::null_mut())
484 _ => span_bug!(span, "{:?} in constant", projection.elem)
496 fn const_operand(&self, operand: &mir::Operand<'tcx>, span: Span)
497 -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
498 debug!("const_operand({:?} @ {:?})", operand, span);
499 let result = match *operand {
500 mir::Operand::Consume(ref lvalue) => {
501 Ok(self.const_lvalue(lvalue, span)?.to_const(span))
504 mir::Operand::Constant(ref constant) => {
505 let ty = self.monomorphize(&constant.ty);
506 match constant.literal.clone() {
507 mir::Literal::Item { def_id, substs } => {
508 let substs = self.monomorphize(&substs);
509 MirConstContext::trans_def(self.ccx, def_id, substs, IndexVec::new())
511 mir::Literal::Promoted { index } => {
512 let mir = &self.mir.promoted[index];
513 MirConstContext::new(self.ccx, mir, self.substs, IndexVec::new()).trans()
515 mir::Literal::Value { value } => {
516 Ok(Const::from_constval(self.ccx, value, ty))
521 debug!("const_operand({:?} @ {:?}) = {:?}", operand, span,
522 result.as_ref().ok());
526 fn const_array(&self, array_ty: Ty<'tcx>, fields: &[ValueRef])
529 let elem_ty = array_ty.builtin_index().unwrap_or_else(|| {
530 bug!("bad array type {:?}", array_ty)
532 let llunitty = type_of::type_of(self.ccx, elem_ty);
533 // If the array contains enums, an LLVM array won't work.
534 let val = if fields.iter().all(|&f| val_ty(f) == llunitty) {
535 C_array(llunitty, fields)
537 C_struct(self.ccx, fields, false)
539 Const::new(val, array_ty)
542 fn const_rvalue(&self, rvalue: &mir::Rvalue<'tcx>,
543 dest_ty: Ty<'tcx>, span: Span)
544 -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
545 let tcx = self.ccx.tcx();
546 debug!("const_rvalue({:?}: {:?} @ {:?})", rvalue, dest_ty, span);
547 let val = match *rvalue {
548 mir::Rvalue::Use(ref operand) => self.const_operand(operand, span)?,
550 mir::Rvalue::Repeat(ref elem, ref count) => {
551 let elem = self.const_operand(elem, span)?;
552 let size = count.as_u64(tcx.sess.target.uint_type);
553 let fields = vec![elem.llval; size as usize];
554 self.const_array(dest_ty, &fields)
557 mir::Rvalue::Aggregate(ref kind, ref operands) => {
558 // Make sure to evaluate all operands to
559 // report as many errors as we possibly can.
560 let mut fields = Vec::with_capacity(operands.len());
561 let mut failure = Ok(());
562 for operand in operands {
563 match self.const_operand(operand, span) {
564 Ok(val) => fields.push(val.llval),
565 Err(err) => if failure.is_ok() { failure = Err(err); }
571 mir::AggregateKind::Array(_) => {
572 self.const_array(dest_ty, &fields)
574 mir::AggregateKind::Adt(..) |
575 mir::AggregateKind::Closure(..) |
576 mir::AggregateKind::Tuple => {
577 Const::new(trans_const(self.ccx, dest_ty, kind, &fields), dest_ty)
582 mir::Rvalue::Cast(ref kind, ref source, cast_ty) => {
583 let operand = self.const_operand(source, span)?;
584 let cast_ty = self.monomorphize(&cast_ty);
586 let val = match *kind {
587 mir::CastKind::ReifyFnPointer => {
588 match operand.ty.sty {
589 ty::TyFnDef(def_id, substs) => {
590 callee::resolve_and_get_fn(self.ccx, def_id, substs)
593 span_bug!(span, "{} cannot be reified to a fn ptr",
598 mir::CastKind::ClosureFnPointer => {
599 match operand.ty.sty {
600 ty::TyClosure(def_id, substs) => {
601 // Get the def_id for FnOnce::call_once
602 let fn_once = tcx.lang_items.fn_once_trait().unwrap();
604 .global_tcx().associated_items(fn_once)
605 .find(|it| it.kind == ty::AssociatedKind::Method)
607 // Now create its substs [Closure, Tuple]
608 let input = tcx.fn_sig(def_id)
609 .subst(tcx, substs.substs).input(0);
610 let input = tcx.erase_late_bound_regions_and_normalize(&input);
611 let substs = tcx.mk_substs([operand.ty, input]
612 .iter().cloned().map(Kind::from));
613 callee::resolve_and_get_fn(self.ccx, call_once, substs)
616 bug!("{} cannot be cast to a fn ptr", operand.ty)
620 mir::CastKind::UnsafeFnPointer => {
621 // this is a no-op at the LLVM level
624 mir::CastKind::Unsize => {
625 // unsize targets other than to a fat pointer currently
626 // can't be in constants.
627 assert!(common::type_is_fat_ptr(self.ccx, cast_ty));
629 let pointee_ty = operand.ty.builtin_deref(true, ty::NoPreference)
630 .expect("consts: unsizing got non-pointer type").ty;
631 let (base, old_info) = if !self.ccx.shared().type_is_sized(pointee_ty) {
632 // Normally, the source is a thin pointer and we are
633 // adding extra info to make a fat pointer. The exception
634 // is when we are upcasting an existing object fat pointer
635 // to use a different vtable. In that case, we want to
636 // load out the original data pointer so we can repackage
638 let (base, extra) = operand.get_fat_ptr();
641 (operand.llval, None)
644 let unsized_ty = cast_ty.builtin_deref(true, ty::NoPreference)
645 .expect("consts: unsizing got non-pointer target type").ty;
646 let ptr_ty = type_of::in_memory_type_of(self.ccx, unsized_ty).ptr_to();
647 let base = consts::ptrcast(base, ptr_ty);
648 let info = base::unsized_info(self.ccx, pointee_ty,
649 unsized_ty, old_info);
651 if old_info.is_none() {
652 let prev_const = self.ccx.const_unsized().borrow_mut()
653 .insert(base, operand.llval);
654 assert!(prev_const.is_none() || prev_const == Some(operand.llval));
656 assert_eq!(abi::FAT_PTR_ADDR, 0);
657 assert_eq!(abi::FAT_PTR_EXTRA, 1);
658 C_struct(self.ccx, &[base, info], false)
660 mir::CastKind::Misc if common::type_is_immediate(self.ccx, operand.ty) => {
661 debug_assert!(common::type_is_immediate(self.ccx, cast_ty));
662 let r_t_in = CastTy::from_ty(operand.ty).expect("bad input type for cast");
663 let r_t_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
664 let ll_t_out = type_of::immediate_type_of(self.ccx, cast_ty);
665 let llval = operand.llval;
666 let signed = if let CastTy::Int(IntTy::CEnum) = r_t_in {
667 let l = self.ccx.layout_of(operand.ty);
668 adt::is_discr_signed(&l)
670 operand.ty.is_signed()
674 match (r_t_in, r_t_out) {
675 (CastTy::Int(_), CastTy::Int(_)) => {
676 let s = signed as llvm::Bool;
677 llvm::LLVMConstIntCast(llval, ll_t_out.to_ref(), s)
679 (CastTy::Int(_), CastTy::Float) => {
681 llvm::LLVMConstSIToFP(llval, ll_t_out.to_ref())
683 llvm::LLVMConstUIToFP(llval, ll_t_out.to_ref())
686 (CastTy::Float, CastTy::Float) => {
687 llvm::LLVMConstFPCast(llval, ll_t_out.to_ref())
689 (CastTy::Float, CastTy::Int(IntTy::I)) => {
690 llvm::LLVMConstFPToSI(llval, ll_t_out.to_ref())
692 (CastTy::Float, CastTy::Int(_)) => {
693 llvm::LLVMConstFPToUI(llval, ll_t_out.to_ref())
695 (CastTy::Ptr(_), CastTy::Ptr(_)) |
696 (CastTy::FnPtr, CastTy::Ptr(_)) |
697 (CastTy::RPtr(_), CastTy::Ptr(_)) => {
698 consts::ptrcast(llval, ll_t_out)
700 (CastTy::Int(_), CastTy::Ptr(_)) => {
701 llvm::LLVMConstIntToPtr(llval, ll_t_out.to_ref())
703 (CastTy::Ptr(_), CastTy::Int(_)) |
704 (CastTy::FnPtr, CastTy::Int(_)) => {
705 llvm::LLVMConstPtrToInt(llval, ll_t_out.to_ref())
707 _ => bug!("unsupported cast: {:?} to {:?}", operand.ty, cast_ty)
711 mir::CastKind::Misc => { // Casts from a fat-ptr.
712 let ll_cast_ty = type_of::immediate_type_of(self.ccx, cast_ty);
713 let ll_from_ty = type_of::immediate_type_of(self.ccx, operand.ty);
714 if common::type_is_fat_ptr(self.ccx, operand.ty) {
715 let (data_ptr, meta_ptr) = operand.get_fat_ptr();
716 if common::type_is_fat_ptr(self.ccx, cast_ty) {
717 let ll_cft = ll_cast_ty.field_types();
718 let ll_fft = ll_from_ty.field_types();
719 let data_cast = consts::ptrcast(data_ptr, ll_cft[0]);
720 assert_eq!(ll_cft[1].kind(), ll_fft[1].kind());
721 C_struct(self.ccx, &[data_cast, meta_ptr], false)
722 } else { // cast to thin-ptr
723 // Cast of fat-ptr to thin-ptr is an extraction of data-ptr and
724 // pointer-cast of that pointer to desired pointer type.
725 consts::ptrcast(data_ptr, ll_cast_ty)
728 bug!("Unexpected non-fat-pointer operand")
732 Const::new(val, cast_ty)
735 mir::Rvalue::Ref(_, bk, ref lvalue) => {
736 let tr_lvalue = self.const_lvalue(lvalue, span)?;
738 let ty = tr_lvalue.ty;
739 let ref_ty = tcx.mk_ref(tcx.types.re_erased,
740 ty::TypeAndMut { ty: ty, mutbl: bk.to_mutbl_lossy() });
742 let base = match tr_lvalue.base {
743 Base::Value(llval) => {
744 // FIXME: may be wrong for &*(&simd_vec as &fmt::Debug)
745 let align = if self.ccx.shared().type_is_sized(ty) {
746 self.ccx.align_of(ty)
748 self.ccx.tcx().data_layout.pointer_align.abi() as machine::llalign
750 if bk == mir::BorrowKind::Mut {
751 consts::addr_of_mut(self.ccx, llval, align, "ref_mut")
753 consts::addr_of(self.ccx, llval, align, "ref")
757 Base::Static(llval) => llval
760 let ptr = if self.ccx.shared().type_is_sized(ty) {
763 C_struct(self.ccx, &[base, tr_lvalue.llextra], false)
765 Const::new(ptr, ref_ty)
768 mir::Rvalue::Len(ref lvalue) => {
769 let tr_lvalue = self.const_lvalue(lvalue, span)?;
770 Const::new(tr_lvalue.len(self.ccx), tcx.types.usize)
773 mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
774 let lhs = self.const_operand(lhs, span)?;
775 let rhs = self.const_operand(rhs, span)?;
777 let binop_ty = op.ty(tcx, lhs.ty, rhs.ty);
778 let (lhs, rhs) = (lhs.llval, rhs.llval);
779 Const::new(const_scalar_binop(op, lhs, rhs, ty), binop_ty)
782 mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
783 let lhs = self.const_operand(lhs, span)?;
784 let rhs = self.const_operand(rhs, span)?;
786 let val_ty = op.ty(tcx, lhs.ty, rhs.ty);
787 let binop_ty = tcx.intern_tup(&[val_ty, tcx.types.bool], false);
788 let (lhs, rhs) = (lhs.llval, rhs.llval);
789 assert!(!ty.is_fp());
791 match const_scalar_checked_binop(tcx, op, lhs, rhs, ty) {
792 Some((llval, of)) => {
793 let llof = C_bool(self.ccx, of);
794 Const::new(C_struct(self.ccx, &[llval, llof], false), binop_ty)
797 span_bug!(span, "{:?} got non-integer operands: {:?} and {:?}",
798 rvalue, Value(lhs), Value(rhs));
803 mir::Rvalue::UnaryOp(op, ref operand) => {
804 let operand = self.const_operand(operand, span)?;
805 let lloperand = operand.llval;
806 let llval = match op {
809 llvm::LLVMConstNot(lloperand)
813 let is_float = operand.ty.is_fp();
816 llvm::LLVMConstFNeg(lloperand)
818 llvm::LLVMConstNeg(lloperand)
823 Const::new(llval, operand.ty)
826 mir::Rvalue::NullaryOp(mir::NullOp::SizeOf, ty) => {
827 assert!(self.ccx.shared().type_is_sized(ty));
828 let llval = C_uint(self.ccx, self.ccx.size_of(ty));
829 Const::new(llval, tcx.types.usize)
832 _ => span_bug!(span, "{:?} in constant", rvalue)
835 debug!("const_rvalue({:?}: {:?} @ {:?}) = {:?}", rvalue, dest_ty, span, val);
842 fn to_const_int(value: ValueRef, t: Ty, tcx: TyCtxt) -> Option<ConstInt> {
844 ty::TyInt(int_type) => const_to_opt_u128(value, true)
845 .and_then(|input| ConstInt::new_signed(input as i128, int_type,
846 tcx.sess.target.int_type)),
847 ty::TyUint(uint_type) => const_to_opt_u128(value, false)
848 .and_then(|input| ConstInt::new_unsigned(input, uint_type,
849 tcx.sess.target.uint_type)),
855 pub fn const_scalar_binop(op: mir::BinOp,
858 input_ty: Ty) -> ValueRef {
859 assert!(!input_ty.is_simd());
860 let is_float = input_ty.is_fp();
861 let signed = input_ty.is_signed();
865 mir::BinOp::Add if is_float => llvm::LLVMConstFAdd(lhs, rhs),
866 mir::BinOp::Add => llvm::LLVMConstAdd(lhs, rhs),
868 mir::BinOp::Sub if is_float => llvm::LLVMConstFSub(lhs, rhs),
869 mir::BinOp::Sub => llvm::LLVMConstSub(lhs, rhs),
871 mir::BinOp::Mul if is_float => llvm::LLVMConstFMul(lhs, rhs),
872 mir::BinOp::Mul => llvm::LLVMConstMul(lhs, rhs),
874 mir::BinOp::Div if is_float => llvm::LLVMConstFDiv(lhs, rhs),
875 mir::BinOp::Div if signed => llvm::LLVMConstSDiv(lhs, rhs),
876 mir::BinOp::Div => llvm::LLVMConstUDiv(lhs, rhs),
878 mir::BinOp::Rem if is_float => llvm::LLVMConstFRem(lhs, rhs),
879 mir::BinOp::Rem if signed => llvm::LLVMConstSRem(lhs, rhs),
880 mir::BinOp::Rem => llvm::LLVMConstURem(lhs, rhs),
882 mir::BinOp::BitXor => llvm::LLVMConstXor(lhs, rhs),
883 mir::BinOp::BitAnd => llvm::LLVMConstAnd(lhs, rhs),
884 mir::BinOp::BitOr => llvm::LLVMConstOr(lhs, rhs),
886 let rhs = base::cast_shift_const_rhs(op.to_hir_binop(), lhs, rhs);
887 llvm::LLVMConstShl(lhs, rhs)
890 let rhs = base::cast_shift_const_rhs(op.to_hir_binop(), lhs, rhs);
891 if signed { llvm::LLVMConstAShr(lhs, rhs) }
892 else { llvm::LLVMConstLShr(lhs, rhs) }
894 mir::BinOp::Eq | mir::BinOp::Ne |
895 mir::BinOp::Lt | mir::BinOp::Le |
896 mir::BinOp::Gt | mir::BinOp::Ge => {
898 let cmp = base::bin_op_to_fcmp_predicate(op.to_hir_binop());
899 llvm::LLVMConstFCmp(cmp, lhs, rhs)
901 let cmp = base::bin_op_to_icmp_predicate(op.to_hir_binop(),
903 llvm::LLVMConstICmp(cmp, lhs, rhs)
906 mir::BinOp::Offset => unreachable!("BinOp::Offset in const-eval!")
911 pub fn const_scalar_checked_binop<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
916 -> Option<(ValueRef, bool)> {
917 if let (Some(lhs), Some(rhs)) = (to_const_int(lllhs, input_ty, tcx),
918 to_const_int(llrhs, input_ty, tcx)) {
919 let result = match op {
920 mir::BinOp::Add => lhs + rhs,
921 mir::BinOp::Sub => lhs - rhs,
922 mir::BinOp::Mul => lhs * rhs,
923 mir::BinOp::Shl => lhs << rhs,
924 mir::BinOp::Shr => lhs >> rhs,
926 bug!("Operator `{:?}` is not a checkable operator", op)
930 let of = match result {
932 Err(ConstMathErr::Overflow(_)) |
933 Err(ConstMathErr::ShiftNegative) => true,
935 bug!("Operator `{:?}` on `{:?}` and `{:?}` errored: {}",
936 op, lhs, rhs, err.description());
940 Some((const_scalar_binop(op, lllhs, llrhs, input_ty), of))
946 impl<'a, 'tcx> MirContext<'a, 'tcx> {
947 pub fn trans_constant(&mut self,
948 bcx: &Builder<'a, 'tcx>,
949 constant: &mir::Constant<'tcx>)
952 debug!("trans_constant({:?})", constant);
953 let ty = self.monomorphize(&constant.ty);
954 let result = match constant.literal.clone() {
955 mir::Literal::Item { def_id, substs } => {
956 let substs = self.monomorphize(&substs);
957 MirConstContext::trans_def(bcx.ccx, def_id, substs, IndexVec::new())
959 mir::Literal::Promoted { index } => {
960 let mir = &self.mir.promoted[index];
961 MirConstContext::new(bcx.ccx, mir, self.param_substs, IndexVec::new()).trans()
963 mir::Literal::Value { value } => {
964 Ok(Const::from_constval(bcx.ccx, value, ty))
968 let result = result.unwrap_or_else(|_| {
969 // We've errored, so we don't have to produce working code.
970 let llty = type_of::type_of(bcx.ccx, ty);
971 Const::new(C_undef(llty), ty)
974 debug!("trans_constant({:?}) = {:?}", constant, result);
980 pub fn trans_static_initializer<'a, 'tcx>(
981 ccx: &CrateContext<'a, 'tcx>,
983 -> Result<ValueRef, ConstEvalErr<'tcx>>
985 MirConstContext::trans_def(ccx, def_id, Substs::empty(), IndexVec::new())
989 /// Construct a constant value, suitable for initializing a
990 /// GlobalVariable, given a case and constant values for its fields.
991 /// Note that this may have a different LLVM type (and different
992 /// alignment!) from the representation's `type_of`, so it needs a
993 /// pointer cast before use.
995 /// The LLVM type system does not directly support unions, and only
996 /// pointers can be bitcast, so a constant (and, by extension, the
997 /// GlobalVariable initialized by it) will have a type that can vary
998 /// depending on which case of an enum it is.
1000 /// To understand the alignment situation, consider `enum E { V64(u64),
1001 /// V32(u32, u32) }` on Windows. The type has 8-byte alignment to
1002 /// accommodate the u64, but `V32(x, y)` would have LLVM type `{i32,
1003 /// i32, i32}`, which is 4-byte aligned.
1005 /// Currently the returned value has the same size as the type, but
1006 /// this could be changed in the future to avoid allocating unnecessary
1007 /// space after values of shorter-than-maximum cases.
1008 fn trans_const<'a, 'tcx>(
1009 ccx: &CrateContext<'a, 'tcx>,
1011 kind: &mir::AggregateKind,
1014 let l = ccx.layout_of(t);
1015 let variant_index = match *kind {
1016 mir::AggregateKind::Adt(_, index, _, _) => index,
1020 layout::CEnum { discr: d, min, max, .. } => {
1021 let discr = match *kind {
1022 mir::AggregateKind::Adt(adt_def, _, _, _) => {
1023 adt_def.discriminant_for_variant(ccx.tcx(), variant_index)
1024 .to_u128_unchecked() as u64
1028 assert_eq!(vals.len(), 0);
1029 adt::assert_discr_in_range(min, max, discr);
1030 C_integral(Type::from_integer(ccx, d), discr, true)
1032 layout::General { discr: d, ref variants, .. } => {
1033 let variant = &variants[variant_index];
1034 let lldiscr = C_integral(Type::from_integer(ccx, d), variant_index as u64, true);
1035 let mut vals_with_discr = vec![lldiscr];
1036 vals_with_discr.extend_from_slice(vals);
1037 let mut contents = build_const_struct(ccx, &variant, &vals_with_discr[..]);
1038 let needed_padding = l.size(ccx).bytes() - variant.stride().bytes();
1039 if needed_padding > 0 {
1040 contents.push(padding(ccx, needed_padding));
1042 C_struct(ccx, &contents[..], false)
1044 layout::UntaggedUnion { ref variants, .. }=> {
1045 assert_eq!(variant_index, 0);
1046 let contents = build_const_union(ccx, variants, vals[0]);
1047 C_struct(ccx, &contents, variants.packed)
1049 layout::Univariant { ref variant, .. } => {
1050 assert_eq!(variant_index, 0);
1051 let contents = build_const_struct(ccx, &variant, vals);
1052 C_struct(ccx, &contents[..], variant.packed)
1054 layout::Vector { .. } => {
1057 layout::RawNullablePointer { nndiscr, .. } => {
1058 if variant_index as u64 == nndiscr {
1059 assert_eq!(vals.len(), 1);
1062 C_null(type_of::type_of(ccx, t))
1065 layout::StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
1066 if variant_index as u64 == nndiscr {
1067 C_struct(ccx, &build_const_struct(ccx, &nonnull, vals), false)
1069 // Always use null even if it's not the `discrfield`th
1070 // field; see #8506.
1071 C_null(type_of::type_of(ccx, t))
1074 _ => bug!("trans_const: cannot handle type {} repreented as {:#?}", t, l)
1078 /// Building structs is a little complicated, because we might need to
1079 /// insert padding if a field's value is less aligned than its type.
1081 /// Continuing the example from `trans_const`, a value of type `(u32,
1082 /// E)` should have the `E` at offset 8, but if that field's
1083 /// initializer is 4-byte aligned then simply translating the tuple as
1084 /// a two-element struct will locate it at offset 4, and accesses to it
1085 /// will read the wrong memory.
1086 fn build_const_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1087 st: &layout::Struct,
1090 assert_eq!(vals.len(), st.offsets.len());
1092 if vals.len() == 0 {
1096 // offset of current value
1098 let mut cfields = Vec::new();
1099 cfields.reserve(st.offsets.len()*2);
1101 let parts = st.field_index_by_increasing_offset().map(|i| {
1102 (&vals[i], st.offsets[i].bytes())
1104 for (&val, target_offset) in parts {
1105 if offset < target_offset {
1106 cfields.push(padding(ccx, target_offset - offset));
1107 offset = target_offset;
1109 assert!(!is_undef(val));
1111 offset += machine::llsize_of_alloc(ccx, val_ty(val));
1114 if offset < st.stride().bytes() {
1115 cfields.push(padding(ccx, st.stride().bytes() - offset));
1121 fn build_const_union<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1123 field_val: ValueRef)
1125 let mut cfields = vec![field_val];
1127 let offset = machine::llsize_of_alloc(ccx, val_ty(field_val));
1128 let size = un.stride().bytes();
1130 cfields.push(padding(ccx, size - offset));
1136 fn padding(ccx: &CrateContext, size: u64) -> ValueRef {
1137 C_undef(Type::array(&Type::i8(ccx), size))