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, const_eval, def};
17 use middle::const_eval::{const_int_checked_neg, const_uint_checked_neg};
18 use middle::const_eval::{const_int_checked_add, const_uint_checked_add};
19 use middle::const_eval::{const_int_checked_sub, const_uint_checked_sub};
20 use middle::const_eval::{const_int_checked_mul, const_uint_checked_mul};
21 use middle::const_eval::{const_int_checked_div, const_uint_checked_div};
22 use middle::const_eval::{const_int_checked_rem, const_uint_checked_rem};
23 use middle::const_eval::{const_int_checked_shl, const_uint_checked_shl};
24 use middle::const_eval::{const_int_checked_shr, const_uint_checked_shr};
25 use trans::{adt, closure, debuginfo, expr, inline, machine};
26 use trans::base::{self, push_ctxt};
29 use trans::monomorphize;
30 use trans::type_::Type;
32 use middle::cast::{CastTy,IntTy};
33 use middle::subst::Substs;
34 use middle::ty::{self, Ty};
35 use util::ppaux::{Repr, ty_to_string};
37 use std::iter::repeat;
39 use syntax::{ast, ast_util};
40 use syntax::parse::token;
43 pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: &ast::Lit)
45 let _icx = push_ctxt("trans_lit");
46 debug!("const_lit: {:?}", lit);
48 ast::LitByte(b) => C_integral(Type::uint_from_ty(cx, ast::TyU8), b as u64, false),
49 ast::LitChar(i) => C_integral(Type::char(cx), i as u64, false),
50 ast::LitInt(i, ast::SignedIntLit(t, _)) => {
51 C_integral(Type::int_from_ty(cx, t), i, true)
53 ast::LitInt(u, ast::UnsignedIntLit(t)) => {
54 C_integral(Type::uint_from_ty(cx, t), u, false)
56 ast::LitInt(i, ast::UnsuffixedIntLit(_)) => {
57 let lit_int_ty = ty::node_id_to_type(cx.tcx(), e.id);
58 match lit_int_ty.sty {
60 C_integral(Type::int_from_ty(cx, t), i as u64, true)
63 C_integral(Type::uint_from_ty(cx, t), i as u64, false)
65 _ => cx.sess().span_bug(lit.span,
66 &format!("integer literal has type {} (expected int \
68 ty_to_string(cx.tcx(), lit_int_ty)))
71 ast::LitFloat(ref fs, t) => {
72 C_floating(&fs, Type::float_from_ty(cx, t))
74 ast::LitFloatUnsuffixed(ref fs) => {
75 let lit_float_ty = ty::node_id_to_type(cx.tcx(), e.id);
76 match lit_float_ty.sty {
78 C_floating(&fs, Type::float_from_ty(cx, t))
81 cx.sess().span_bug(lit.span,
82 "floating point literal doesn't have the right type");
86 ast::LitBool(b) => C_bool(cx, b),
87 ast::LitStr(ref s, _) => C_str_slice(cx, (*s).clone()),
88 ast::LitBinary(ref data) => {
89 addr_of(cx, C_bytes(cx, &data[..]), "binary")
94 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
96 llvm::LLVMConstPointerCast(val, ty.to_ref())
100 fn addr_of_mut(ccx: &CrateContext,
105 // FIXME: this totally needs a better name generation scheme, perhaps a simple global
106 // counter? Also most other uses of gensym in trans.
107 let gsym = token::gensym("_");
108 let name = format!("{}{}", kind, gsym.usize());
109 let gv = declare::define_global(ccx, &name[..], val_ty(cv)).unwrap_or_else(||{
110 ccx.sess().bug(&format!("symbol `{}` is already defined", name));
112 llvm::LLVMSetInitializer(gv, cv);
113 SetLinkage(gv, InternalLinkage);
114 SetUnnamedAddr(gv, true);
119 pub fn addr_of(ccx: &CrateContext,
123 match ccx.const_globals().borrow().get(&cv) {
124 Some(&gv) => return gv,
127 let gv = addr_of_mut(ccx, cv, kind);
129 llvm::LLVMSetGlobalConstant(gv, True);
131 ccx.const_globals().borrow_mut().insert(cv, gv);
135 fn const_deref_ptr(cx: &CrateContext, v: ValueRef) -> ValueRef {
136 let v = match cx.const_unsized().borrow().get(&v) {
141 llvm::LLVMGetInitializer(v)
145 fn const_deref<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
148 -> (ValueRef, Ty<'tcx>) {
149 match ty::deref(ty, true) {
151 if type_is_sized(cx.tcx(), mt.ty) {
152 (const_deref_ptr(cx, v), mt.ty)
154 // Derefing a fat pointer does not change the representation,
155 // just the type to the unsized contents.
160 cx.sess().bug(&format!("unexpected dereferenceable type {}",
161 ty_to_string(cx.tcx(), ty)))
166 pub fn get_const_expr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
168 ref_expr: &ast::Expr)
170 let def_id = inline::maybe_instantiate_inline(ccx, def_id);
172 if def_id.krate != ast::LOCAL_CRATE {
173 ccx.sess().span_bug(ref_expr.span,
174 "cross crate constant could not be inlined");
177 match const_eval::lookup_const_by_id(ccx.tcx(), def_id, Some(ref_expr.id)) {
178 Some(ref expr) => expr,
180 ccx.sess().span_bug(ref_expr.span, "constant item not found")
185 fn get_const_val(ccx: &CrateContext,
187 ref_expr: &ast::Expr) -> ValueRef {
188 let expr = get_const_expr(ccx, def_id, ref_expr);
189 let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
190 get_const_expr_as_global(ccx, expr, check_const::ConstQualif::empty(), empty_substs)
193 pub fn get_const_expr_as_global<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
195 qualif: check_const::ConstQualif,
196 param_substs: &'tcx Substs<'tcx>)
198 // Special-case constants to cache a common global for all uses.
200 ast::ExprPath(..) => {
201 let def = ccx.tcx().def_map.borrow().get(&expr.id).unwrap().full_def();
203 def::DefConst(def_id) | def::DefAssociatedConst(def_id, _) => {
204 if !ccx.tcx().adjustments.borrow().contains_key(&expr.id) {
205 return get_const_val(ccx, def_id, expr);
214 let key = (expr.id, param_substs);
215 match ccx.const_values().borrow().get(&key) {
216 Some(&val) => return val,
219 let val = if qualif.intersects(check_const::ConstQualif::NON_STATIC_BORROWS) {
220 // Avoid autorefs as they would create global instead of stack
221 // references, even when only the latter are correct.
222 let ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs,
223 &ty::expr_ty(ccx.tcx(), expr));
224 const_expr_unadjusted(ccx, expr, ty, param_substs)
226 const_expr(ccx, expr, param_substs).0
229 // boolean SSA values are i1, but they have to be stored in i8 slots,
230 // otherwise some LLVM optimization passes don't work as expected
232 if llvm::LLVMTypeOf(val) == Type::i1(ccx).to_ref() {
233 llvm::LLVMConstZExt(val, Type::i8(ccx).to_ref())
239 let lvalue = addr_of(ccx, val, "const");
240 ccx.const_values().borrow_mut().insert(key, lvalue);
244 pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
246 param_substs: &'tcx Substs<'tcx>)
247 -> (ValueRef, Ty<'tcx>) {
248 let ety = monomorphize::apply_param_substs(cx.tcx(), param_substs,
249 &ty::expr_ty(cx.tcx(), e));
250 let llconst = const_expr_unadjusted(cx, e, ety, param_substs);
251 let mut llconst = llconst;
252 let mut ety_adjusted = monomorphize::apply_param_substs(cx.tcx(), param_substs,
253 &ty::expr_ty_adjusted(cx.tcx(), e));
254 let opt_adj = cx.tcx().adjustments.borrow().get(&e.id).cloned();
256 Some(ty::AdjustReifyFnPointer) => {
257 // FIXME(#19925) once fn item types are
258 // zero-sized, we'll need to do something here
260 Some(ty::AdjustUnsafeFnPointer) => {
261 // purely a type-level thing
263 Some(ty::AdjustDerefRef(adj)) => {
265 // Save the last autoderef in case we can avoid it.
266 if adj.autoderefs > 0 {
267 for _ in 0..adj.autoderefs-1 {
268 let (dv, dt) = const_deref(cx, llconst, ty);
274 if adj.autoref.is_some() {
275 if adj.autoderefs == 0 {
276 // Don't copy data to do a deref+ref
277 // (i.e., skip the last auto-deref).
278 llconst = addr_of(cx, llconst, "autoref");
279 ty = ty::mk_imm_rptr(cx.tcx(), cx.tcx().mk_region(ty::ReStatic), ty);
282 let (dv, dt) = const_deref(cx, llconst, ty);
285 // If we derefed a fat pointer then we will have an
286 // open type here. So we need to update the type with
287 // the one returned from const_deref.
291 if let Some(target) = adj.unsize {
292 let target = monomorphize::apply_param_substs(cx.tcx(),
296 let pointee_ty = ty::deref(ty, true)
297 .expect("consts: unsizing got non-pointer type").ty;
298 let (base, old_info) = if !type_is_sized(cx.tcx(), pointee_ty) {
299 // Normally, the source is a thin pointer and we are
300 // adding extra info to make a fat pointer. The exception
301 // is when we are upcasting an existing object fat pointer
302 // to use a different vtable. In that case, we want to
303 // load out the original data pointer so we can repackage
305 (const_get_elt(cx, llconst, &[abi::FAT_PTR_ADDR as u32]),
306 Some(const_get_elt(cx, llconst, &[abi::FAT_PTR_EXTRA as u32])))
311 let unsized_ty = ty::deref(target, true)
312 .expect("consts: unsizing got non-pointer target type").ty;
313 let ptr_ty = type_of::in_memory_type_of(cx, unsized_ty).ptr_to();
314 let base = ptrcast(base, ptr_ty);
315 let info = expr::unsized_info(cx, pointee_ty, unsized_ty,
316 old_info, param_substs);
318 let prev_const = cx.const_unsized().borrow_mut()
319 .insert(base, llconst);
320 assert!(prev_const.is_none() || prev_const == Some(llconst));
321 assert_eq!(abi::FAT_PTR_ADDR, 0);
322 assert_eq!(abi::FAT_PTR_EXTRA, 1);
323 llconst = C_struct(cx, &[base, info], false);
329 let llty = type_of::sizing_type_of(cx, ety_adjusted);
330 let csize = machine::llsize_of_alloc(cx, val_ty(llconst));
331 let tsize = machine::llsize_of_alloc(cx, llty);
333 cx.sess().abort_if_errors();
335 // FIXME these values could use some context
336 llvm::LLVMDumpValue(llconst);
337 llvm::LLVMDumpValue(C_undef(llty));
339 cx.sess().bug(&format!("const {} of type {} has size {} instead of {}",
340 e.repr(cx.tcx()), ty_to_string(cx.tcx(), ety_adjusted),
343 (llconst, ety_adjusted)
346 fn check_unary_expr_validity(cx: &CrateContext, e: &ast::Expr, t: Ty,
348 // The only kind of unary expression that we check for validity
349 // here is `-expr`, to check if it "overflows" (e.g. `-i32::MIN`).
350 if let ast::ExprUnary(ast::UnNeg, ref inner_e) = e.node {
352 // An unfortunate special case: we parse e.g. -128 as a
353 // negation of the literal 128, which means if we're expecting
354 // a i8 (or if it was already suffixed, e.g. `-128_i8`), then
355 // 128 will have already overflowed to -128, and so then the
356 // constant evaluator thinks we're trying to negate -128.
358 // Catch this up front by looking for ExprLit directly,
359 // and just accepting it.
360 if let ast::ExprLit(_) = inner_e.node { return; }
362 let result = match t.sty {
363 ty::ty_int(int_type) => {
364 let input = match const_to_opt_int(te) {
368 const_int_checked_neg(
369 input, e, Some(const_eval::IntTy::from(cx.tcx(), int_type)))
371 ty::ty_uint(uint_type) => {
372 let input = match const_to_opt_uint(te) {
376 const_uint_checked_neg(
377 input, e, Some(const_eval::UintTy::from(cx.tcx(), uint_type)))
382 // We do not actually care about a successful result.
383 if let Err(err) = result {
384 cx.tcx().sess.span_err(e.span, &err.description());
389 fn check_binary_expr_validity(cx: &CrateContext, e: &ast::Expr, t: Ty,
390 te1: ValueRef, te2: ValueRef) {
391 let b = if let ast::ExprBinary(b, _, _) = e.node { b } else { return };
393 let result = match t.sty {
394 ty::ty_int(int_type) => {
395 let (lhs, rhs) = match (const_to_opt_int(te1),
396 const_to_opt_int(te2)) {
397 (Some(v1), Some(v2)) => (v1, v2),
401 let opt_ety = Some(const_eval::IntTy::from(cx.tcx(), int_type));
403 ast::BiAdd => const_int_checked_add(lhs, rhs, e, opt_ety),
404 ast::BiSub => const_int_checked_sub(lhs, rhs, e, opt_ety),
405 ast::BiMul => const_int_checked_mul(lhs, rhs, e, opt_ety),
406 ast::BiDiv => const_int_checked_div(lhs, rhs, e, opt_ety),
407 ast::BiRem => const_int_checked_rem(lhs, rhs, e, opt_ety),
408 ast::BiShl => const_int_checked_shl(lhs, rhs, e, opt_ety),
409 ast::BiShr => const_int_checked_shr(lhs, rhs, e, opt_ety),
413 ty::ty_uint(uint_type) => {
414 let (lhs, rhs) = match (const_to_opt_uint(te1),
415 const_to_opt_uint(te2)) {
416 (Some(v1), Some(v2)) => (v1, v2),
420 let opt_ety = Some(const_eval::UintTy::from(cx.tcx(), uint_type));
422 ast::BiAdd => const_uint_checked_add(lhs, rhs, e, opt_ety),
423 ast::BiSub => const_uint_checked_sub(lhs, rhs, e, opt_ety),
424 ast::BiMul => const_uint_checked_mul(lhs, rhs, e, opt_ety),
425 ast::BiDiv => const_uint_checked_div(lhs, rhs, e, opt_ety),
426 ast::BiRem => const_uint_checked_rem(lhs, rhs, e, opt_ety),
427 ast::BiShl => const_uint_checked_shl(lhs, rhs, e, opt_ety),
428 ast::BiShr => const_uint_checked_shr(lhs, rhs, e, opt_ety),
434 // We do not actually care about a successful result.
435 if let Err(err) = result {
436 cx.tcx().sess.span_err(e.span, &err.description());
440 fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
443 param_substs: &'tcx Substs<'tcx>)
446 debug!("const_expr_unadjusted(e={}, ety={}, param_substs={})",
449 param_substs.repr(cx.tcx()));
451 let map_list = |exprs: &[P<ast::Expr>]| {
452 exprs.iter().map(|e| const_expr(cx, &**e, param_substs).0)
453 .fold(Vec::new(), |mut l, val| { l.push(val); l })
456 let _icx = push_ctxt("const_expr");
458 ast::ExprLit(ref lit) => {
459 const_lit(cx, e, &**lit)
461 ast::ExprBinary(b, ref e1, ref e2) => {
462 /* Neither type is bottom, and we expect them to be unified
463 * already, so the following is safe. */
464 let (te1, ty) = const_expr(cx, &**e1, param_substs);
465 debug!("const_expr_unadjusted: te1={}, ty={}",
466 cx.tn().val_to_string(te1),
468 let is_simd = ty::type_is_simd(cx.tcx(), ty);
469 let intype = if is_simd {
470 ty::simd_type(cx.tcx(), ty)
474 let is_float = ty::type_is_fp(intype);
475 let signed = ty::type_is_signed(intype);
477 let (te2, _) = const_expr(cx, &**e2, param_substs);
479 check_binary_expr_validity(cx, e, ty, te1, te2);
483 if is_float { llvm::LLVMConstFAdd(te1, te2) }
484 else { llvm::LLVMConstAdd(te1, te2) }
487 if is_float { llvm::LLVMConstFSub(te1, te2) }
488 else { llvm::LLVMConstSub(te1, te2) }
491 if is_float { llvm::LLVMConstFMul(te1, te2) }
492 else { llvm::LLVMConstMul(te1, te2) }
495 if is_float { llvm::LLVMConstFDiv(te1, te2) }
496 else if signed { llvm::LLVMConstSDiv(te1, te2) }
497 else { llvm::LLVMConstUDiv(te1, te2) }
500 if is_float { llvm::LLVMConstFRem(te1, te2) }
501 else if signed { llvm::LLVMConstSRem(te1, te2) }
502 else { llvm::LLVMConstURem(te1, te2) }
504 ast::BiAnd => llvm::LLVMConstAnd(te1, te2),
505 ast::BiOr => llvm::LLVMConstOr(te1, te2),
506 ast::BiBitXor => llvm::LLVMConstXor(te1, te2),
507 ast::BiBitAnd => llvm::LLVMConstAnd(te1, te2),
508 ast::BiBitOr => llvm::LLVMConstOr(te1, te2),
510 let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
511 llvm::LLVMConstShl(te1, te2)
514 let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
515 if signed { llvm::LLVMConstAShr(te1, te2) }
516 else { llvm::LLVMConstLShr(te1, te2) }
518 ast::BiEq | ast::BiNe | ast::BiLt | ast::BiLe | ast::BiGt | ast::BiGe => {
520 let cmp = base::bin_op_to_fcmp_predicate(cx, b.node);
521 ConstFCmp(cmp, te1, te2)
523 let cmp = base::bin_op_to_icmp_predicate(cx, b.node, signed);
524 let bool_val = ConstICmp(cmp, te1, te2);
526 // LLVM outputs an `< size x i1 >`, so we need to perform
527 // a sign extension to get the correctly sized type.
528 llvm::LLVMConstIntCast(bool_val, val_ty(te1).to_ref(), True)
536 ast::ExprUnary(u, ref inner_e) => {
537 let (te, ty) = const_expr(cx, &**inner_e, param_substs);
539 check_unary_expr_validity(cx, e, ty, te);
541 let is_float = ty::type_is_fp(ty);
543 ast::UnUniq | ast::UnDeref => {
544 const_deref(cx, te, ty).0
546 ast::UnNot => llvm::LLVMConstNot(te),
548 if is_float { llvm::LLVMConstFNeg(te) }
549 else { llvm::LLVMConstNeg(te) }
553 ast::ExprField(ref base, field) => {
554 let (bv, bt) = const_expr(cx, &**base, param_substs);
555 let brepr = adt::represent_type(cx, bt);
556 expr::with_field_tys(cx.tcx(), bt, None, |discr, field_tys| {
557 let ix = ty::field_idx_strict(cx.tcx(), field.node.name, field_tys);
558 adt::const_get_field(cx, &*brepr, bv, discr, ix)
561 ast::ExprTupField(ref base, idx) => {
562 let (bv, bt) = const_expr(cx, &**base, param_substs);
563 let brepr = adt::represent_type(cx, bt);
564 expr::with_field_tys(cx.tcx(), bt, None, |discr, _| {
565 adt::const_get_field(cx, &*brepr, bv, discr, idx.node)
569 ast::ExprIndex(ref base, ref index) => {
570 let (bv, bt) = const_expr(cx, &**base, param_substs);
571 let iv = match const_eval::eval_const_expr_partial(cx.tcx(), &**index, None) {
572 Ok(const_eval::const_int(i)) => i as u64,
573 Ok(const_eval::const_uint(u)) => u,
574 _ => cx.sess().span_bug(index.span,
575 "index is not an integer-constant expression")
577 let (arr, len) = match bt.sty {
578 ty::ty_vec(_, Some(u)) => (bv, C_uint(cx, u)),
579 ty::ty_vec(_, None) | ty::ty_str => {
580 let e1 = const_get_elt(cx, bv, &[0]);
581 (const_deref_ptr(cx, e1), const_get_elt(cx, bv, &[1]))
583 ty::ty_rptr(_, mt) => match mt.ty.sty {
584 ty::ty_vec(_, Some(u)) => {
585 (const_deref_ptr(cx, bv), C_uint(cx, u))
587 _ => cx.sess().span_bug(base.span,
588 &format!("index-expr base must be a vector \
589 or string type, found {}",
590 ty_to_string(cx.tcx(), bt)))
592 _ => cx.sess().span_bug(base.span,
593 &format!("index-expr base must be a vector \
594 or string type, found {}",
595 ty_to_string(cx.tcx(), bt)))
598 let len = llvm::LLVMConstIntGetZExtValue(len) as u64;
599 let len = match bt.sty {
600 ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) => match ty.sty {
610 // FIXME #3170: report this earlier on in the const-eval
611 // pass. Reporting here is a bit late.
612 cx.sess().span_err(e.span,
613 "const index-expr is out of bounds");
614 C_undef(type_of::type_of(cx, bt).element_type())
616 const_get_elt(cx, arr, &[iv as c_uint])
619 ast::ExprCast(ref base, _) => {
621 let llty = type_of::type_of(cx, t_cast);
622 let (v, t_expr) = const_expr(cx, &**base, param_substs);
623 debug!("trans_const_cast({} as {})", t_expr.repr(cx.tcx()), t_cast.repr(cx.tcx()));
624 if expr::cast_is_noop(cx.tcx(), base, t_expr, t_cast) {
627 if type_is_fat_ptr(cx.tcx(), t_expr) {
628 // Fat pointer casts.
629 let t_cast_inner = ty::deref(t_cast, true).expect("cast to non-pointer").ty;
630 let ptr_ty = type_of::in_memory_type_of(cx, t_cast_inner).ptr_to();
631 let addr = ptrcast(const_get_elt(cx, v, &[abi::FAT_PTR_ADDR as u32]),
633 if type_is_fat_ptr(cx.tcx(), t_cast) {
634 let info = const_get_elt(cx, v, &[abi::FAT_PTR_EXTRA as u32]);
635 return C_struct(cx, &[addr, info], false)
640 match (CastTy::from_ty(cx.tcx(), t_expr).expect("bad input type for cast"),
641 CastTy::from_ty(cx.tcx(), t_cast).expect("bad output type for cast")) {
642 (CastTy::Int(IntTy::CEnum), CastTy::Int(_)) => {
643 let repr = adt::represent_type(cx, t_expr);
644 let discr = adt::const_get_discrim(cx, &*repr, v);
645 let iv = C_integral(cx.int_type(), discr, false);
646 let s = adt::is_discr_signed(&*repr) as Bool;
647 llvm::LLVMConstIntCast(iv, llty.to_ref(), s)
649 (CastTy::Int(_), CastTy::Int(_)) => {
650 let s = ty::type_is_signed(t_expr) as Bool;
651 llvm::LLVMConstIntCast(v, llty.to_ref(), s)
653 (CastTy::Int(_), CastTy::Float) => {
654 if ty::type_is_signed(t_expr) {
655 llvm::LLVMConstSIToFP(v, llty.to_ref())
657 llvm::LLVMConstUIToFP(v, llty.to_ref())
660 (CastTy::Float, CastTy::Float) => {
661 llvm::LLVMConstFPCast(v, llty.to_ref())
663 (CastTy::Float, CastTy::Int(IntTy::I)) => {
664 llvm::LLVMConstFPToSI(v, llty.to_ref())
666 (CastTy::Float, CastTy::Int(_)) => {
667 llvm::LLVMConstFPToUI(v, llty.to_ref())
669 (CastTy::Ptr(_), CastTy::Ptr(_)) | (CastTy::FnPtr, CastTy::Ptr(_))
670 | (CastTy::RPtr(_), CastTy::Ptr(_)) => {
673 (CastTy::FnPtr, CastTy::FnPtr) => ptrcast(v, llty), // isn't this a coercion?
674 (CastTy::Int(_), CastTy::Ptr(_)) => {
675 llvm::LLVMConstIntToPtr(v, llty.to_ref())
677 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
678 llvm::LLVMConstPtrToInt(v, llty.to_ref())
681 cx.sess().impossible_case(e.span,
682 "bad combination of types for cast")
686 ast::ExprAddrOf(ast::MutImmutable, ref sub) => {
687 // If this is the address of some static, then we need to return
688 // the actual address of the static itself (short circuit the rest
693 ast::ExprParen(ref sub) => cur = sub,
694 ast::ExprBlock(ref blk) => {
695 if let Some(ref sub) = blk.expr {
704 let opt_def = cx.tcx().def_map.borrow().get(&cur.id).map(|d| d.full_def());
705 if let Some(def::DefStatic(def_id, _)) = opt_def {
706 get_static_val(cx, def_id, ety)
708 // If this isn't the address of a static, then keep going through
709 // normal constant evaluation.
710 let (v, _) = const_expr(cx, &**sub, param_substs);
711 addr_of(cx, v, "ref")
714 ast::ExprAddrOf(ast::MutMutable, ref sub) => {
715 let (v, _) = const_expr(cx, &**sub, param_substs);
716 addr_of_mut(cx, v, "ref_mut_slice")
718 ast::ExprTup(ref es) => {
719 let repr = adt::represent_type(cx, ety);
720 let vals = map_list(&es[..]);
721 adt::trans_const(cx, &*repr, 0, &vals[..])
723 ast::ExprStruct(_, ref fs, ref base_opt) => {
724 let repr = adt::represent_type(cx, ety);
726 let base_val = match *base_opt {
727 Some(ref base) => Some(const_expr(cx, &**base, param_substs)),
731 expr::with_field_tys(cx.tcx(), ety, Some(e.id), |discr, field_tys| {
732 let cs = field_tys.iter().enumerate()
733 .map(|(ix, &field_ty)| {
734 match fs.iter().find(|f| field_ty.name == f.ident.node.name) {
735 Some(ref f) => const_expr(cx, &*f.expr, param_substs).0,
739 adt::const_get_field(cx, &*repr, bv,
743 cx.sess().span_bug(e.span,
744 "missing struct field")
749 }).collect::<Vec<_>>();
750 if ty::type_is_simd(cx.tcx(), ety) {
753 adt::trans_const(cx, &*repr, discr, &cs[..])
757 ast::ExprVec(ref es) => {
758 let unit_ty = ty::sequence_element_type(cx.tcx(), ety);
759 let llunitty = type_of::type_of(cx, unit_ty);
760 let vs = es.iter().map(|e| const_expr(cx, &**e, param_substs).0)
761 .collect::<Vec<_>>();
762 // If the vector contains enums, an LLVM array won't work.
763 if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
764 C_struct(cx, &vs[..], false)
766 C_array(llunitty, &vs[..])
769 ast::ExprRepeat(ref elem, ref count) => {
770 let unit_ty = ty::sequence_element_type(cx.tcx(), ety);
771 let llunitty = type_of::type_of(cx, unit_ty);
772 let n = ty::eval_repeat_count(cx.tcx(), count);
773 let unit_val = const_expr(cx, &**elem, param_substs).0;
774 let vs: Vec<_> = repeat(unit_val).take(n).collect();
775 if val_ty(unit_val) != llunitty {
776 C_struct(cx, &vs[..], false)
778 C_array(llunitty, &vs[..])
781 ast::ExprPath(..) => {
782 let def = cx.tcx().def_map.borrow().get(&e.id).unwrap().full_def();
784 def::DefFn(..) | def::DefMethod(..) => {
785 expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
787 def::DefConst(def_id) | def::DefAssociatedConst(def_id, _) => {
788 const_deref_ptr(cx, get_const_val(cx, def_id, e))
790 def::DefVariant(enum_did, variant_did, _) => {
791 let vinfo = ty::enum_variant_with_id(cx.tcx(),
794 if !vinfo.args.is_empty() {
796 expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
799 let repr = adt::represent_type(cx, ety);
800 adt::trans_const(cx, &*repr, vinfo.disr_val, &[])
803 def::DefStruct(_) => {
804 if let ty::ty_bare_fn(..) = ety.sty {
806 expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
809 C_null(type_of::type_of(cx, ety))
813 cx.sess().span_bug(e.span, "expected a const, fn, struct, \
818 ast::ExprCall(ref callee, ref args) => {
819 let opt_def = cx.tcx().def_map.borrow().get(&callee.id).map(|d| d.full_def());
820 let arg_vals = map_list(&args[..]);
822 Some(def::DefStruct(_)) => {
823 if ty::type_is_simd(cx.tcx(), ety) {
824 C_vector(&arg_vals[..])
826 let repr = adt::represent_type(cx, ety);
827 adt::trans_const(cx, &*repr, 0, &arg_vals[..])
830 Some(def::DefVariant(enum_did, variant_did, _)) => {
831 let repr = adt::represent_type(cx, ety);
832 let vinfo = ty::enum_variant_with_id(cx.tcx(),
840 _ => cx.sess().span_bug(e.span, "expected a struct or variant def")
843 ast::ExprParen(ref e) => const_expr(cx, &**e, param_substs).0,
844 ast::ExprBlock(ref block) => {
846 Some(ref expr) => const_expr(cx, &**expr, param_substs).0,
850 ast::ExprClosure(_, ref decl, ref body) => {
851 closure::trans_closure_expr(closure::Dest::Ignore(cx),
852 &**decl, &**body, e.id,
854 C_null(type_of::type_of(cx, ety))
856 _ => cx.sess().span_bug(e.span,
857 "bad constant expression type in consts::const_expr")
862 pub fn trans_static(ccx: &CrateContext, m: ast::Mutability, id: ast::NodeId) -> ValueRef {
864 let _icx = push_ctxt("trans_static");
865 let g = base::get_item_val(ccx, id);
866 // At this point, get_item_val has already translated the
867 // constant's initializer to determine its LLVM type.
868 let v = ccx.static_values().borrow().get(&id).unwrap().clone();
869 // boolean SSA values are i1, but they have to be stored in i8 slots,
870 // otherwise some LLVM optimization passes don't work as expected
871 let v = if llvm::LLVMTypeOf(v) == Type::i1(ccx).to_ref() {
872 llvm::LLVMConstZExt(v, Type::i8(ccx).to_ref())
876 llvm::LLVMSetInitializer(g, v);
878 // As an optimization, all shared statics which do not have interior
879 // mutability are placed into read-only memory.
880 if m != ast::MutMutable {
881 let node_ty = ty::node_id_to_type(ccx.tcx(), id);
882 let tcontents = ty::type_contents(ccx.tcx(), node_ty);
883 if !tcontents.interior_unsafe() {
884 llvm::LLVMSetGlobalConstant(g, True);
887 debuginfo::create_global_var_metadata(ccx, id, g);
892 fn get_static_val<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: ast::DefId,
893 ty: Ty<'tcx>) -> ValueRef {
894 if ast_util::is_local(did) { return base::get_item_val(ccx, did.node) }
895 base::trans_external_path(ccx, did, ty)