1 // Copyright 2012 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.
14 use llvm::{ConstFCmp, ConstICmp, SetLinkage, SetUnnamedAddr};
15 use llvm::{InternalLinkage, ValueRef, Bool, True};
16 use middle::{check_const, def};
17 use middle::cstore::LOCAL_CRATE;
18 use middle::const_eval::{self, ConstVal, ConstEvalErr};
19 use middle::const_eval::{const_int_checked_neg, const_uint_checked_neg};
20 use middle::const_eval::{const_int_checked_add, const_uint_checked_add};
21 use middle::const_eval::{const_int_checked_sub, const_uint_checked_sub};
22 use middle::const_eval::{const_int_checked_mul, const_uint_checked_mul};
23 use middle::const_eval::{const_int_checked_div, const_uint_checked_div};
24 use middle::const_eval::{const_int_checked_rem, const_uint_checked_rem};
25 use middle::const_eval::{const_int_checked_shl, const_uint_checked_shl};
26 use middle::const_eval::{const_int_checked_shr, const_uint_checked_shr};
27 use middle::const_eval::EvalHint::ExprTypeChecked;
28 use middle::const_eval::eval_const_expr_partial;
29 use middle::def_id::DefId;
30 use trans::{adt, closure, debuginfo, expr, inline, machine};
31 use trans::base::{self, push_ctxt};
32 use trans::common::{self, type_is_sized, ExprOrMethodCall, node_id_substs, C_nil, const_get_elt};
33 use trans::common::{CrateContext, C_integral, C_floating, C_bool, C_str_slice, C_bytes, val_ty};
34 use trans::common::C_floating_f64;
35 use trans::common::{C_struct, C_undef, const_to_opt_int, const_to_opt_uint, VariantInfo, C_uint};
36 use trans::common::{type_is_fat_ptr, Field, C_vector, C_array, C_null, ExprId, MethodCallKey};
38 use trans::monomorphize;
39 use trans::type_::Type;
41 use middle::subst::Substs;
42 use middle::ty::adjustment::{AdjustDerefRef, AdjustReifyFnPointer};
43 use middle::ty::adjustment::AdjustUnsafeFnPointer;
44 use middle::ty::{self, Ty};
45 use middle::ty::cast::{CastTy,IntTy};
46 use util::nodemap::NodeMap;
50 use std::ffi::{CStr, CString};
55 use syntax::parse::token;
58 pub type FnArgMap<'a> = Option<&'a NodeMap<ValueRef>>;
60 pub fn const_lit(cx: &CrateContext, e: &hir::Expr, lit: &ast::Lit)
62 let _icx = push_ctxt("trans_lit");
63 debug!("const_lit: {:?}", lit);
65 ast::LitByte(b) => C_integral(Type::uint_from_ty(cx, ast::TyU8), b as u64, false),
66 ast::LitChar(i) => C_integral(Type::char(cx), i as u64, false),
67 ast::LitInt(i, ast::SignedIntLit(t, _)) => {
68 C_integral(Type::int_from_ty(cx, t), i, true)
70 ast::LitInt(u, ast::UnsignedIntLit(t)) => {
71 C_integral(Type::uint_from_ty(cx, t), u, false)
73 ast::LitInt(i, ast::UnsuffixedIntLit(_)) => {
74 let lit_int_ty = cx.tcx().node_id_to_type(e.id);
75 match lit_int_ty.sty {
77 C_integral(Type::int_from_ty(cx, t), i as u64, true)
80 C_integral(Type::uint_from_ty(cx, t), i as u64, false)
82 _ => cx.sess().span_bug(lit.span,
83 &format!("integer literal has type {:?} (expected int \
88 ast::LitFloat(ref fs, t) => {
89 C_floating(&fs, Type::float_from_ty(cx, t))
91 ast::LitFloatUnsuffixed(ref fs) => {
92 let lit_float_ty = cx.tcx().node_id_to_type(e.id);
93 match lit_float_ty.sty {
95 C_floating(&fs, Type::float_from_ty(cx, t))
98 cx.sess().span_bug(lit.span,
99 "floating point literal doesn't have the right type");
103 ast::LitBool(b) => C_bool(cx, b),
104 ast::LitStr(ref s, _) => C_str_slice(cx, (*s).clone()),
105 ast::LitByteStr(ref data) => {
106 addr_of(cx, C_bytes(cx, &data[..]), 1, "byte_str")
111 pub fn trans_constval<'blk, 'tcx>(bcx: common::Block<'blk, 'tcx>,
114 param_substs: &'tcx Substs<'tcx>)
118 let llty = type_of::type_of(ccx, ty);
120 ConstVal::Float(v) => C_floating_f64(v, llty),
121 ConstVal::Bool(v) => C_bool(ccx, v),
122 ConstVal::Int(v) => C_integral(llty, v as u64, true),
123 ConstVal::Uint(v) => C_integral(llty, v, false),
124 ConstVal::Str(ref v) => C_str_slice(ccx, v.clone()),
125 ConstVal::ByteStr(ref v) => addr_of(ccx, C_bytes(ccx, v), 1, "byte_str"),
126 ConstVal::Struct(id) | ConstVal::Tuple(id) => {
127 let expr = bcx.tcx().map.expect_expr(id);
128 match const_expr(ccx, expr, param_substs, None, TrueConst::Yes) {
130 Err(e) => panic!("const eval failure: {}", e.description()),
133 ConstVal::Array(id, _) | ConstVal::Repeat(id, _) => {
134 let expr = bcx.tcx().map.expect_expr(id);
135 expr::trans(bcx, expr).datum.val
137 ConstVal::Function(_) => {
143 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
145 llvm::LLVMConstPointerCast(val, ty.to_ref())
149 fn addr_of_mut(ccx: &CrateContext,
151 align: machine::llalign,
155 // FIXME: this totally needs a better name generation scheme, perhaps a simple global
156 // counter? Also most other uses of gensym in trans.
157 let gsym = token::gensym("_");
158 let name = format!("{}{}", kind, gsym.0);
159 let gv = declare::define_global(ccx, &name[..], val_ty(cv)).unwrap_or_else(||{
160 ccx.sess().bug(&format!("symbol `{}` is already defined", name));
162 llvm::LLVMSetInitializer(gv, cv);
163 llvm::LLVMSetAlignment(gv, align);
164 SetLinkage(gv, InternalLinkage);
165 SetUnnamedAddr(gv, true);
170 pub fn addr_of(ccx: &CrateContext,
172 align: machine::llalign,
175 match ccx.const_globals().borrow().get(&cv) {
178 // Upgrade the alignment in cases where the same constant is used with different
179 // alignment requirements
180 if align > llvm::LLVMGetAlignment(gv) {
181 llvm::LLVMSetAlignment(gv, align);
188 let gv = addr_of_mut(ccx, cv, align, kind);
190 llvm::LLVMSetGlobalConstant(gv, True);
192 ccx.const_globals().borrow_mut().insert(cv, gv);
196 fn const_deref_ptr(cx: &CrateContext, v: ValueRef) -> ValueRef {
197 let v = match cx.const_unsized().borrow().get(&v) {
202 llvm::LLVMGetInitializer(v)
206 fn const_deref<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
209 -> (ValueRef, Ty<'tcx>) {
210 match ty.builtin_deref(true, ty::NoPreference) {
212 if type_is_sized(cx.tcx(), mt.ty) {
213 (const_deref_ptr(cx, v), mt.ty)
215 // Derefing a fat pointer does not change the representation,
216 // just the type to the unsized contents.
221 cx.sess().bug(&format!("unexpected dereferenceable type {:?}",
227 fn const_fn_call<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
228 node: ExprOrMethodCall,
230 arg_vals: &[ValueRef],
231 param_substs: &'tcx Substs<'tcx>,
232 trueconst: TrueConst) -> Result<ValueRef, ConstEvalFailure> {
233 let fn_like = const_eval::lookup_const_fn_by_id(ccx.tcx(), def_id);
234 let fn_like = fn_like.expect("lookup_const_fn_by_id failed in const_fn_call");
236 let args = &fn_like.decl().inputs;
237 assert_eq!(args.len(), arg_vals.len());
239 let arg_ids = args.iter().map(|arg| arg.pat.id);
240 let fn_args = arg_ids.zip(arg_vals.iter().cloned()).collect();
242 let substs = ccx.tcx().mk_substs(node_id_substs(ccx, node, param_substs));
243 match fn_like.body().expr {
245 const_expr(ccx, &**expr, substs, Some(&fn_args), trueconst).map(|(res, _)| res)
247 None => Ok(C_nil(ccx)),
251 pub fn get_const_expr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
253 ref_expr: &hir::Expr)
255 let def_id = inline::maybe_instantiate_inline(ccx, def_id);
257 if def_id.krate != LOCAL_CRATE {
258 ccx.sess().span_bug(ref_expr.span,
259 "cross crate constant could not be inlined");
262 match const_eval::lookup_const_by_id(ccx.tcx(), def_id, Some(ref_expr.id)) {
263 Some(ref expr) => expr,
265 ccx.sess().span_bug(ref_expr.span, "constant item not found")
270 pub enum ConstEvalFailure {
271 /// in case the const evaluator failed on something that panic at runtime
272 /// as defined in RFC 1229
273 Runtime(ConstEvalErr),
274 // in case we found a true constant
275 Compiletime(ConstEvalErr),
278 impl ConstEvalFailure {
279 fn into_inner(self) -> ConstEvalErr {
285 pub fn description(&self) -> Cow<str> {
287 &Runtime(ref e) => e.description(),
288 &Compiletime(ref e) => e.description(),
293 #[derive(Copy, Clone)]
298 use self::ConstEvalFailure::*;
300 fn get_const_val(ccx: &CrateContext,
302 ref_expr: &hir::Expr) -> Result<ValueRef, ConstEvalFailure> {
303 let expr = get_const_expr(ccx, def_id, ref_expr);
304 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
305 match get_const_expr_as_global(ccx, expr, check_const::ConstQualif::empty(),
306 empty_substs, TrueConst::Yes) {
307 Err(Runtime(err)) => {
308 ccx.tcx().sess.span_err(expr.span, &err.description());
309 Err(Compiletime(err))
315 pub fn get_const_expr_as_global<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
317 qualif: check_const::ConstQualif,
318 param_substs: &'tcx Substs<'tcx>,
319 trueconst: TrueConst)
320 -> Result<ValueRef, ConstEvalFailure> {
321 debug!("get_const_expr_as_global: {:?}", expr.id);
322 // Special-case constants to cache a common global for all uses.
323 if let hir::ExprPath(..) = expr.node {
324 // `def` must be its own statement and cannot be in the `match`
325 // otherwise the `def_map` will be borrowed for the entire match instead
326 // of just to get the `def` value
327 let def = ccx.tcx().def_map.borrow().get(&expr.id).unwrap().full_def();
329 def::DefConst(def_id) | def::DefAssociatedConst(def_id) => {
330 if !ccx.tcx().tables.borrow().adjustments.contains_key(&expr.id) {
331 debug!("get_const_expr_as_global ({:?}): found const {:?}",
333 return get_const_val(ccx, def_id, expr);
340 let key = (expr.id, param_substs);
341 if let Some(&val) = ccx.const_values().borrow().get(&key) {
344 let ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs,
345 &ccx.tcx().expr_ty(expr));
346 let val = if qualif.intersects(check_const::ConstQualif::NON_STATIC_BORROWS) {
347 // Avoid autorefs as they would create global instead of stack
348 // references, even when only the latter are correct.
349 try!(const_expr_unadjusted(ccx, expr, ty, param_substs, None, trueconst))
351 try!(const_expr(ccx, expr, param_substs, None, trueconst)).0
354 // boolean SSA values are i1, but they have to be stored in i8 slots,
355 // otherwise some LLVM optimization passes don't work as expected
357 if llvm::LLVMTypeOf(val) == Type::i1(ccx).to_ref() {
358 llvm::LLVMConstZExt(val, Type::i8(ccx).to_ref())
364 let lvalue = addr_of(ccx, val, type_of::align_of(ccx, ty), "const");
365 ccx.const_values().borrow_mut().insert(key, lvalue);
369 pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
371 param_substs: &'tcx Substs<'tcx>,
373 trueconst: TrueConst)
374 -> Result<(ValueRef, Ty<'tcx>), ConstEvalFailure> {
375 let ety = monomorphize::apply_param_substs(cx.tcx(), param_substs,
376 &cx.tcx().expr_ty(e));
377 let llconst = try!(const_expr_unadjusted(cx, e, ety, param_substs, fn_args, trueconst));
378 let mut llconst = llconst;
379 let mut ety_adjusted = monomorphize::apply_param_substs(cx.tcx(), param_substs,
380 &cx.tcx().expr_ty_adjusted(e));
381 let opt_adj = cx.tcx().tables.borrow().adjustments.get(&e.id).cloned();
383 Some(AdjustReifyFnPointer) => {
384 // FIXME(#19925) once fn item types are
385 // zero-sized, we'll need to do something here
387 Some(AdjustUnsafeFnPointer) => {
388 // purely a type-level thing
390 Some(AdjustDerefRef(adj)) => {
392 // Save the last autoderef in case we can avoid it.
393 if adj.autoderefs > 0 {
394 for _ in 0..adj.autoderefs-1 {
395 let (dv, dt) = const_deref(cx, llconst, ty);
401 if adj.autoref.is_some() {
402 if adj.autoderefs == 0 {
403 // Don't copy data to do a deref+ref
404 // (i.e., skip the last auto-deref).
405 llconst = addr_of(cx, llconst, type_of::align_of(cx, ty), "autoref");
406 ty = cx.tcx().mk_imm_ref(cx.tcx().mk_region(ty::ReStatic), ty);
409 let (dv, dt) = const_deref(cx, llconst, ty);
412 // If we derefed a fat pointer then we will have an
413 // open type here. So we need to update the type with
414 // the one returned from const_deref.
418 if let Some(target) = adj.unsize {
419 let target = monomorphize::apply_param_substs(cx.tcx(),
423 let pointee_ty = ty.builtin_deref(true, ty::NoPreference)
424 .expect("consts: unsizing got non-pointer type").ty;
425 let (base, old_info) = if !type_is_sized(cx.tcx(), pointee_ty) {
426 // Normally, the source is a thin pointer and we are
427 // adding extra info to make a fat pointer. The exception
428 // is when we are upcasting an existing object fat pointer
429 // to use a different vtable. In that case, we want to
430 // load out the original data pointer so we can repackage
432 (const_get_elt(cx, llconst, &[abi::FAT_PTR_ADDR as u32]),
433 Some(const_get_elt(cx, llconst, &[abi::FAT_PTR_EXTRA as u32])))
438 let unsized_ty = target.builtin_deref(true, ty::NoPreference)
439 .expect("consts: unsizing got non-pointer target type").ty;
440 let ptr_ty = type_of::in_memory_type_of(cx, unsized_ty).ptr_to();
441 let base = ptrcast(base, ptr_ty);
442 let info = base::unsized_info(cx, pointee_ty, unsized_ty,
443 old_info, param_substs);
445 if old_info.is_none() {
446 let prev_const = cx.const_unsized().borrow_mut()
447 .insert(base, llconst);
448 assert!(prev_const.is_none() || prev_const == Some(llconst));
450 assert_eq!(abi::FAT_PTR_ADDR, 0);
451 assert_eq!(abi::FAT_PTR_EXTRA, 1);
452 llconst = C_struct(cx, &[base, info], false);
458 let llty = type_of::sizing_type_of(cx, ety_adjusted);
459 let csize = machine::llsize_of_alloc(cx, val_ty(llconst));
460 let tsize = machine::llsize_of_alloc(cx, llty);
462 cx.sess().abort_if_errors();
464 // FIXME these values could use some context
465 llvm::LLVMDumpValue(llconst);
466 llvm::LLVMDumpValue(C_undef(llty));
468 cx.sess().bug(&format!("const {:?} of type {:?} has size {} instead of {}",
472 Ok((llconst, ety_adjusted))
475 fn check_unary_expr_validity(cx: &CrateContext, e: &hir::Expr, t: Ty,
476 te: ValueRef, trueconst: TrueConst) -> Result<(), ConstEvalFailure> {
477 // The only kind of unary expression that we check for validity
478 // here is `-expr`, to check if it "overflows" (e.g. `-i32::MIN`).
479 if let hir::ExprUnary(hir::UnNeg, ref inner_e) = e.node {
481 // An unfortunate special case: we parse e.g. -128 as a
482 // negation of the literal 128, which means if we're expecting
483 // a i8 (or if it was already suffixed, e.g. `-128_i8`), then
484 // 128 will have already overflowed to -128, and so then the
485 // constant evaluator thinks we're trying to negate -128.
487 // Catch this up front by looking for ExprLit directly,
488 // and just accepting it.
489 if let hir::ExprLit(_) = inner_e.node { return Ok(()); }
491 let result = match t.sty {
492 ty::TyInt(int_type) => {
493 let input = match const_to_opt_int(te) {
495 None => return Ok(()),
497 const_int_checked_neg(
498 input, e, Some(const_eval::IntTy::from(cx.tcx(), int_type)))
500 ty::TyUint(uint_type) => {
501 let input = match const_to_opt_uint(te) {
503 None => return Ok(()),
505 const_uint_checked_neg(
506 input, e, Some(const_eval::UintTy::from(cx.tcx(), uint_type)))
510 const_err(cx, e, result, trueconst)
516 fn const_err(cx: &CrateContext,
518 result: Result<ConstVal, ConstEvalErr>,
519 trueconst: TrueConst)
520 -> Result<(), ConstEvalFailure> {
521 match (result, trueconst) {
523 // We do not actually care about a successful result.
526 (Err(err), TrueConst::Yes) => {
527 cx.tcx().sess.span_err(e.span, &err.description());
528 Err(Compiletime(err))
530 (Err(err), TrueConst::No) => {
531 cx.tcx().sess.span_warn(e.span, &err.description());
537 fn check_binary_expr_validity(cx: &CrateContext, e: &hir::Expr, t: Ty,
538 te1: ValueRef, te2: ValueRef,
539 trueconst: TrueConst) -> Result<(), ConstEvalFailure> {
540 let b = if let hir::ExprBinary(b, _, _) = e.node { b } else { unreachable!() };
542 let result = match t.sty {
543 ty::TyInt(int_type) => {
544 let (lhs, rhs) = match (const_to_opt_int(te1),
545 const_to_opt_int(te2)) {
546 (Some(v1), Some(v2)) => (v1, v2),
550 let opt_ety = Some(const_eval::IntTy::from(cx.tcx(), int_type));
552 hir::BiAdd => const_int_checked_add(lhs, rhs, e, opt_ety),
553 hir::BiSub => const_int_checked_sub(lhs, rhs, e, opt_ety),
554 hir::BiMul => const_int_checked_mul(lhs, rhs, e, opt_ety),
555 hir::BiDiv => const_int_checked_div(lhs, rhs, e, opt_ety),
556 hir::BiRem => const_int_checked_rem(lhs, rhs, e, opt_ety),
557 hir::BiShl => const_int_checked_shl(lhs, rhs, e, opt_ety),
558 hir::BiShr => const_int_checked_shr(lhs, rhs, e, opt_ety),
562 ty::TyUint(uint_type) => {
563 let (lhs, rhs) = match (const_to_opt_uint(te1),
564 const_to_opt_uint(te2)) {
565 (Some(v1), Some(v2)) => (v1, v2),
569 let opt_ety = Some(const_eval::UintTy::from(cx.tcx(), uint_type));
571 hir::BiAdd => const_uint_checked_add(lhs, rhs, e, opt_ety),
572 hir::BiSub => const_uint_checked_sub(lhs, rhs, e, opt_ety),
573 hir::BiMul => const_uint_checked_mul(lhs, rhs, e, opt_ety),
574 hir::BiDiv => const_uint_checked_div(lhs, rhs, e, opt_ety),
575 hir::BiRem => const_uint_checked_rem(lhs, rhs, e, opt_ety),
576 hir::BiShl => const_uint_checked_shl(lhs, rhs, e, opt_ety),
577 hir::BiShr => const_uint_checked_shr(lhs, rhs, e, opt_ety),
583 const_err(cx, e, result, trueconst)
586 fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
589 param_substs: &'tcx Substs<'tcx>,
591 trueconst: TrueConst)
592 -> Result<ValueRef, ConstEvalFailure>
594 debug!("const_expr_unadjusted(e={:?}, ety={:?}, param_substs={:?})",
599 let map_list = |exprs: &[P<hir::Expr>]| -> Result<Vec<ValueRef>, ConstEvalFailure> {
601 .map(|e| const_expr(cx, &**e, param_substs, fn_args, trueconst).map(|(l, _)| l))
602 .collect::<Vec<Result<ValueRef, ConstEvalFailure>>>()
605 // this dance is necessary to eagerly run const_expr so all errors are reported
607 let _icx = push_ctxt("const_expr");
609 hir::ExprLit(ref lit) => const_lit(cx, e, &**lit),
610 hir::ExprBinary(b, ref e1, ref e2) => {
611 /* Neither type is bottom, and we expect them to be unified
612 * already, so the following is safe. */
613 let (te1, ty) = try!(const_expr(cx, &**e1, param_substs, fn_args, trueconst));
614 debug!("const_expr_unadjusted: te1={}, ty={:?}",
615 cx.tn().val_to_string(te1),
617 assert!(!ty.is_simd());
618 let is_float = ty.is_fp();
619 let signed = ty.is_signed();
621 let (te2, _) = try!(const_expr(cx, &**e2, param_substs, fn_args, trueconst));
623 try!(check_binary_expr_validity(cx, e, ty, te1, te2, trueconst));
625 unsafe { match b.node {
626 hir::BiAdd if is_float => llvm::LLVMConstFAdd(te1, te2),
627 hir::BiAdd => llvm::LLVMConstAdd(te1, te2),
629 hir::BiSub if is_float => llvm::LLVMConstFSub(te1, te2),
630 hir::BiSub => llvm::LLVMConstSub(te1, te2),
632 hir::BiMul if is_float => llvm::LLVMConstFMul(te1, te2),
633 hir::BiMul => llvm::LLVMConstMul(te1, te2),
635 hir::BiDiv if is_float => llvm::LLVMConstFDiv(te1, te2),
636 hir::BiDiv if signed => llvm::LLVMConstSDiv(te1, te2),
637 hir::BiDiv => llvm::LLVMConstUDiv(te1, te2),
639 hir::BiRem if is_float => llvm::LLVMConstFRem(te1, te2),
640 hir::BiRem if signed => llvm::LLVMConstSRem(te1, te2),
641 hir::BiRem => llvm::LLVMConstURem(te1, te2),
643 hir::BiAnd => llvm::LLVMConstAnd(te1, te2),
644 hir::BiOr => llvm::LLVMConstOr(te1, te2),
645 hir::BiBitXor => llvm::LLVMConstXor(te1, te2),
646 hir::BiBitAnd => llvm::LLVMConstAnd(te1, te2),
647 hir::BiBitOr => llvm::LLVMConstOr(te1, te2),
649 let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
650 llvm::LLVMConstShl(te1, te2)
653 let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
654 if signed { llvm::LLVMConstAShr(te1, te2) }
655 else { llvm::LLVMConstLShr(te1, te2) }
657 hir::BiEq | hir::BiNe | hir::BiLt | hir::BiLe | hir::BiGt | hir::BiGe => {
659 let cmp = base::bin_op_to_fcmp_predicate(cx, b.node);
660 ConstFCmp(cmp, te1, te2)
662 let cmp = base::bin_op_to_icmp_predicate(cx, b.node, signed);
663 ConstICmp(cmp, te1, te2)
666 } } // unsafe { match b.node {
668 hir::ExprUnary(u, ref inner_e) => {
669 let (te, ty) = try!(const_expr(cx, &**inner_e, param_substs, fn_args, trueconst));
671 try!(check_unary_expr_validity(cx, e, ty, te, trueconst));
673 let is_float = ty.is_fp();
675 hir::UnDeref => const_deref(cx, te, ty).0,
676 hir::UnNot => llvm::LLVMConstNot(te),
677 hir::UnNeg if is_float => llvm::LLVMConstFNeg(te),
678 hir::UnNeg => llvm::LLVMConstNeg(te),
681 hir::ExprField(ref base, field) => {
682 let (bv, bt) = try!(const_expr(cx, &**base, param_substs, fn_args, trueconst));
683 let brepr = adt::represent_type(cx, bt);
684 let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
685 let ix = vinfo.field_index(field.node);
686 adt::const_get_field(cx, &*brepr, bv, vinfo.discr, ix)
688 hir::ExprTupField(ref base, idx) => {
689 let (bv, bt) = try!(const_expr(cx, &**base, param_substs, fn_args, trueconst));
690 let brepr = adt::represent_type(cx, bt);
691 let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
692 adt::const_get_field(cx, &*brepr, bv, vinfo.discr, idx.node)
694 hir::ExprIndex(ref base, ref index) => {
695 let (bv, bt) = try!(const_expr(cx, &**base, param_substs, fn_args, trueconst));
696 let iv = match eval_const_expr_partial(cx.tcx(), &index, ExprTypeChecked, None) {
697 Ok(ConstVal::Int(i)) => i as u64,
698 Ok(ConstVal::Uint(u)) => u,
699 _ => cx.sess().span_bug(index.span,
700 "index is not an integer-constant expression")
702 let (arr, len) = match bt.sty {
703 ty::TyArray(_, u) => (bv, C_uint(cx, u)),
704 ty::TySlice(_) | ty::TyStr => {
705 let e1 = const_get_elt(cx, bv, &[0]);
706 (const_deref_ptr(cx, e1), const_get_elt(cx, bv, &[1]))
708 ty::TyRef(_, mt) => match mt.ty.sty {
709 ty::TyArray(_, u) => {
710 (const_deref_ptr(cx, bv), C_uint(cx, u))
712 _ => cx.sess().span_bug(base.span,
713 &format!("index-expr base must be a vector \
714 or string type, found {:?}",
717 _ => cx.sess().span_bug(base.span,
718 &format!("index-expr base must be a vector \
719 or string type, found {:?}",
723 let len = unsafe { llvm::LLVMConstIntGetZExtValue(len) as u64 };
724 let len = match bt.sty {
725 ty::TyBox(ty) | ty::TyRef(_, ty::TypeAndMut{ty, ..}) => match ty.sty {
735 // FIXME #3170: report this earlier on in the const-eval
736 // pass. Reporting here is a bit late.
737 span_err!(cx.sess(), e.span, E0515,
738 "const index-expr is out of bounds");
739 C_undef(val_ty(arr).element_type())
741 const_get_elt(cx, arr, &[iv as c_uint])
744 hir::ExprCast(ref base, _) => {
746 let llty = type_of::type_of(cx, t_cast);
747 let (v, t_expr) = try!(const_expr(cx, &**base, param_substs, fn_args, trueconst));
748 debug!("trans_const_cast({:?} as {:?})", t_expr, t_cast);
749 if expr::cast_is_noop(cx.tcx(), base, t_expr, t_cast) {
752 if type_is_fat_ptr(cx.tcx(), t_expr) {
753 // Fat pointer casts.
755 t_cast.builtin_deref(true, ty::NoPreference).expect("cast to non-pointer").ty;
756 let ptr_ty = type_of::in_memory_type_of(cx, t_cast_inner).ptr_to();
757 let addr = ptrcast(const_get_elt(cx, v, &[abi::FAT_PTR_ADDR as u32]),
759 if type_is_fat_ptr(cx.tcx(), t_cast) {
760 let info = const_get_elt(cx, v, &[abi::FAT_PTR_EXTRA as u32]);
761 return Ok(C_struct(cx, &[addr, info], false))
767 CastTy::from_ty(t_expr).expect("bad input type for cast"),
768 CastTy::from_ty(t_cast).expect("bad output type for cast"),
770 (CastTy::Int(IntTy::CEnum), CastTy::Int(_)) => {
771 let repr = adt::represent_type(cx, t_expr);
772 let discr = adt::const_get_discrim(cx, &*repr, v);
773 let iv = C_integral(cx.int_type(), discr, false);
774 let s = adt::is_discr_signed(&*repr) as Bool;
775 llvm::LLVMConstIntCast(iv, llty.to_ref(), s)
777 (CastTy::Int(_), CastTy::Int(_)) => {
778 let s = t_expr.is_signed() as Bool;
779 llvm::LLVMConstIntCast(v, llty.to_ref(), s)
781 (CastTy::Int(_), CastTy::Float) => {
782 if t_expr.is_signed() {
783 llvm::LLVMConstSIToFP(v, llty.to_ref())
785 llvm::LLVMConstUIToFP(v, llty.to_ref())
788 (CastTy::Float, CastTy::Float) => llvm::LLVMConstFPCast(v, llty.to_ref()),
789 (CastTy::Float, CastTy::Int(IntTy::I)) => llvm::LLVMConstFPToSI(v, llty.to_ref()),
790 (CastTy::Float, CastTy::Int(_)) => llvm::LLVMConstFPToUI(v, llty.to_ref()),
791 (CastTy::Ptr(_), CastTy::Ptr(_)) | (CastTy::FnPtr, CastTy::Ptr(_))
792 | (CastTy::RPtr(_), CastTy::Ptr(_)) => {
795 (CastTy::FnPtr, CastTy::FnPtr) => ptrcast(v, llty), // isn't this a coercion?
796 (CastTy::Int(_), CastTy::Ptr(_)) => llvm::LLVMConstIntToPtr(v, llty.to_ref()),
797 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
798 llvm::LLVMConstPtrToInt(v, llty.to_ref())
801 cx.sess().impossible_case(e.span,
802 "bad combination of types for cast")
804 } } // unsafe { match ( ... ) {
806 hir::ExprAddrOf(hir::MutImmutable, ref sub) => {
807 // If this is the address of some static, then we need to return
808 // the actual address of the static itself (short circuit the rest
813 hir::ExprBlock(ref blk) => {
814 if let Some(ref sub) = blk.expr {
823 let opt_def = cx.tcx().def_map.borrow().get(&cur.id).map(|d| d.full_def());
824 if let Some(def::DefStatic(def_id, _)) = opt_def {
825 common::get_static_val(cx, def_id, ety)
827 // If this isn't the address of a static, then keep going through
828 // normal constant evaluation.
829 let (v, ty) = try!(const_expr(cx, &**sub, param_substs, fn_args, trueconst));
830 addr_of(cx, v, type_of::align_of(cx, ty), "ref")
833 hir::ExprAddrOf(hir::MutMutable, ref sub) => {
834 let (v, ty) = try!(const_expr(cx, &**sub, param_substs, fn_args, trueconst));
835 addr_of_mut(cx, v, type_of::align_of(cx, ty), "ref_mut_slice")
837 hir::ExprTup(ref es) => {
838 let repr = adt::represent_type(cx, ety);
839 let vals = try!(map_list(&es[..]));
840 adt::trans_const(cx, &*repr, 0, &vals[..])
842 hir::ExprStruct(_, ref fs, ref base_opt) => {
843 let repr = adt::represent_type(cx, ety);
845 let base_val = match *base_opt {
846 Some(ref base) => Some(try!(const_expr(
856 let VariantInfo { discr, fields } = VariantInfo::of_node(cx.tcx(), ety, e.id);
857 let cs = fields.iter().enumerate().map(|(ix, &Field(f_name, _))| {
858 match (fs.iter().find(|f| f_name == f.name.node), base_val) {
859 (Some(ref f), _) => {
860 const_expr(cx, &*f.expr, param_substs, fn_args, trueconst).map(|(l, _)| l)
862 (_, Some((bv, _))) => Ok(adt::const_get_field(cx, &*repr, bv, discr, ix)),
863 (_, None) => cx.sess().span_bug(e.span, "missing struct field"),
866 .collect::<Vec<Result<_, ConstEvalFailure>>>()
868 .collect::<Result<Vec<_>,ConstEvalFailure>>();
873 adt::trans_const(cx, &*repr, discr, &cs[..])
876 hir::ExprVec(ref es) => {
877 let unit_ty = ety.sequence_element_type(cx.tcx());
878 let llunitty = type_of::type_of(cx, unit_ty);
887 .collect::<Vec<Result<_, ConstEvalFailure>>>()
889 .collect::<Result<Vec<_>, ConstEvalFailure>>();
891 // If the vector contains enums, an LLVM array won't work.
892 if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
893 C_struct(cx, &vs[..], false)
895 C_array(llunitty, &vs[..])
898 hir::ExprRepeat(ref elem, ref count) => {
899 let unit_ty = ety.sequence_element_type(cx.tcx());
900 let llunitty = type_of::type_of(cx, unit_ty);
901 let n = cx.tcx().eval_repeat_count(count);
902 let unit_val = try!(const_expr(cx, &**elem, param_substs, fn_args, trueconst)).0;
903 let vs = vec![unit_val; n];
904 if val_ty(unit_val) != llunitty {
905 C_struct(cx, &vs[..], false)
907 C_array(llunitty, &vs[..])
910 hir::ExprPath(..) => {
911 let def = cx.tcx().def_map.borrow().get(&e.id).unwrap().full_def();
913 def::DefLocal(_, id) => {
914 if let Some(val) = fn_args.and_then(|args| args.get(&id).cloned()) {
917 cx.sess().span_bug(e.span, "const fn argument not found")
920 def::DefFn(..) | def::DefMethod(..) => {
921 expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
923 def::DefConst(def_id) | def::DefAssociatedConst(def_id) => {
924 const_deref_ptr(cx, try!(get_const_val(cx, def_id, e)))
926 def::DefVariant(enum_did, variant_did, _) => {
927 let vinfo = cx.tcx().lookup_adt_def(enum_did).variant_with_id(variant_did);
929 ty::VariantKind::Unit => {
930 let repr = adt::represent_type(cx, ety);
931 adt::trans_const(cx, &*repr, vinfo.disr_val, &[])
933 ty::VariantKind::Tuple => {
934 expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
936 ty::VariantKind::Struct => {
937 cx.sess().span_bug(e.span, "path-expr refers to a dict variant!")
941 def::DefStruct(_) => {
942 if let ty::TyBareFn(..) = ety.sty {
944 expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
947 C_null(type_of::type_of(cx, ety))
951 cx.sess().span_bug(e.span, "expected a const, fn, struct, \
956 hir::ExprCall(ref callee, ref args) => {
957 let mut callee = &**callee;
959 callee = match callee.node {
960 hir::ExprBlock(ref block) => match block.expr {
961 Some(ref tail) => &**tail,
967 let def = cx.tcx().def_map.borrow()[&callee.id].full_def();
968 let arg_vals = try!(map_list(args));
970 def::DefFn(did, _) | def::DefMethod(did) => {
980 def::DefStruct(_) => {
982 C_vector(&arg_vals[..])
984 let repr = adt::represent_type(cx, ety);
985 adt::trans_const(cx, &*repr, 0, &arg_vals[..])
988 def::DefVariant(enum_did, variant_did, _) => {
989 let repr = adt::represent_type(cx, ety);
990 let vinfo = cx.tcx().lookup_adt_def(enum_did).variant_with_id(variant_did);
996 _ => cx.sess().span_bug(e.span, "expected a struct, variant, or const fn def"),
999 hir::ExprMethodCall(_, _, ref args) => {
1000 let arg_vals = try!(map_list(args));
1001 let method_call = ty::MethodCall::expr(e.id);
1002 let method_did = cx.tcx().tables.borrow().method_map[&method_call].def_id;
1003 try!(const_fn_call(cx, MethodCallKey(method_call),
1004 method_did, &arg_vals, param_substs, trueconst))
1006 hir::ExprBlock(ref block) => {
1008 Some(ref expr) => try!(const_expr(
1018 hir::ExprClosure(_, ref decl, ref body) => {
1020 ty::TyClosure(def_id, ref substs) => {
1021 closure::trans_closure_expr(closure::Dest::Ignore(cx), decl,
1022 body, e.id, def_id, substs);
1027 &format!("bad type for closure expr: {:?}", ety))
1029 C_null(type_of::type_of(cx, ety))
1031 _ => cx.sess().span_bug(e.span,
1032 "bad constant expression type in consts::const_expr"),
1036 pub fn trans_static(ccx: &CrateContext,
1040 attrs: &[ast::Attribute])
1041 -> Result<ValueRef, ConstEvalErr> {
1043 let _icx = push_ctxt("trans_static");
1044 let g = base::get_item_val(ccx, id);
1046 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
1047 let (v, _) = try!(const_expr(
1053 ).map_err(|e| e.into_inner()));
1055 // boolean SSA values are i1, but they have to be stored in i8 slots,
1056 // otherwise some LLVM optimization passes don't work as expected
1057 let mut val_llty = llvm::LLVMTypeOf(v);
1058 let v = if val_llty == Type::i1(ccx).to_ref() {
1059 val_llty = Type::i8(ccx).to_ref();
1060 llvm::LLVMConstZExt(v, val_llty)
1065 let ty = ccx.tcx().node_id_to_type(id);
1066 let llty = type_of::type_of(ccx, ty);
1067 let g = if val_llty == llty.to_ref() {
1070 // If we created the global with the wrong type,
1071 // correct the type.
1072 let empty_string = CString::new("").unwrap();
1073 let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
1074 let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
1075 llvm::LLVMSetValueName(g, empty_string.as_ptr());
1076 let new_g = llvm::LLVMGetOrInsertGlobal(
1077 ccx.llmod(), name_string.as_ptr(), val_llty);
1078 // To avoid breaking any invariants, we leave around the old
1079 // global for the moment; we'll replace all references to it
1080 // with the new global later. (See base::trans_crate.)
1081 ccx.statics_to_rauw().borrow_mut().push((g, new_g));
1084 llvm::LLVMSetAlignment(g, type_of::align_of(ccx, ty));
1085 llvm::LLVMSetInitializer(g, v);
1087 // As an optimization, all shared statics which do not have interior
1088 // mutability are placed into read-only memory.
1089 if m != hir::MutMutable {
1090 let tcontents = ty.type_contents(ccx.tcx());
1091 if !tcontents.interior_unsafe() {
1092 llvm::LLVMSetGlobalConstant(g, llvm::True);
1096 debuginfo::create_global_var_metadata(ccx, id, g);
1098 if attr::contains_name(attrs,
1100 llvm::set_thread_local(g, true);