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.
13 use llvm::{ConstFCmp, ConstICmp, SetLinkage, SetUnnamedAddr};
14 use llvm::{InternalLinkage, ValueRef, Bool, True};
15 use middle::const_qualif::ConstQualif;
16 use rustc_const_eval::{ConstEvalErr, lookup_const_fn_by_id, lookup_const_by_id, ErrKind};
17 use rustc_const_eval::eval_repeat_count;
18 use rustc::hir::def::Def;
19 use rustc::hir::def_id::DefId;
20 use rustc::hir::map as hir_map;
21 use {abi, adt, closure, debuginfo, expr, machine};
22 use base::{self, push_ctxt};
25 use trans_item::TransItem;
26 use common::{type_is_sized, C_nil, const_get_elt};
27 use common::{CrateContext, C_integral, C_floating, C_bool, C_str_slice, C_bytes, val_ty};
28 use common::{C_struct, C_undef, const_to_opt_int, const_to_opt_uint, VariantInfo, C_uint};
29 use common::{type_is_fat_ptr, Field, C_vector, C_array, C_null};
30 use datum::{Datum, Lvalue};
32 use monomorphize::{self, Instance};
37 use rustc::ty::subst::Substs;
38 use rustc::ty::adjustment::{AdjustDerefRef, AdjustReifyFnPointer};
39 use rustc::ty::adjustment::{AdjustUnsafeFnPointer, AdjustMutToConstPointer};
40 use rustc::ty::{self, Ty, TyCtxt};
41 use rustc::ty::cast::{CastTy,IntTy};
42 use util::nodemap::NodeMap;
43 use rustc_const_math::{ConstInt, ConstUsize, ConstIsize};
47 use std::ffi::{CStr, CString};
50 use syntax::ast::{self, LitKind};
51 use syntax::attr::{self, AttrMetaMethods};
52 use syntax::parse::token;
56 pub type FnArgMap<'a> = Option<&'a NodeMap<ValueRef>>;
58 pub fn const_lit(cx: &CrateContext, e: &hir::Expr, lit: &ast::Lit)
60 let _icx = push_ctxt("trans_lit");
61 debug!("const_lit: {:?}", lit);
63 LitKind::Byte(b) => C_integral(Type::uint_from_ty(cx, ast::UintTy::U8), b as u64, false),
64 LitKind::Char(i) => C_integral(Type::char(cx), i as u64, false),
65 LitKind::Int(i, ast::LitIntType::Signed(t)) => {
66 C_integral(Type::int_from_ty(cx, t), i, true)
68 LitKind::Int(u, ast::LitIntType::Unsigned(t)) => {
69 C_integral(Type::uint_from_ty(cx, t), u, false)
71 LitKind::Int(i, ast::LitIntType::Unsuffixed) => {
72 let lit_int_ty = cx.tcx().node_id_to_type(e.id);
73 match lit_int_ty.sty {
75 C_integral(Type::int_from_ty(cx, t), i as u64, true)
78 C_integral(Type::uint_from_ty(cx, t), i as u64, false)
80 _ => span_bug!(lit.span,
81 "integer literal has type {:?} (expected int \
86 LitKind::Float(ref fs, t) => {
87 C_floating(&fs, Type::float_from_ty(cx, t))
89 LitKind::FloatUnsuffixed(ref fs) => {
90 let lit_float_ty = cx.tcx().node_id_to_type(e.id);
91 match lit_float_ty.sty {
93 C_floating(&fs, Type::float_from_ty(cx, t))
97 "floating point literal doesn't have the right type");
101 LitKind::Bool(b) => C_bool(cx, b),
102 LitKind::Str(ref s, _) => C_str_slice(cx, (*s).clone()),
103 LitKind::ByteStr(ref data) => {
104 addr_of(cx, C_bytes(cx, &data[..]), 1, "byte_str")
109 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
111 llvm::LLVMConstPointerCast(val, ty.to_ref())
115 pub fn addr_of_mut(ccx: &CrateContext,
117 align: machine::llalign,
121 // FIXME: this totally needs a better name generation scheme, perhaps a simple global
122 // counter? Also most other uses of gensym in trans.
123 let gsym = token::gensym("_");
124 let name = format!("{}{}", kind, gsym.0);
125 let gv = declare::define_global(ccx, &name[..], val_ty(cv)).unwrap_or_else(||{
126 bug!("symbol `{}` is already defined", name);
128 llvm::LLVMSetInitializer(gv, cv);
129 llvm::LLVMSetAlignment(gv, align);
130 SetLinkage(gv, InternalLinkage);
131 SetUnnamedAddr(gv, true);
136 pub fn addr_of(ccx: &CrateContext,
138 align: machine::llalign,
141 if let Some(&gv) = ccx.const_globals().borrow().get(&cv) {
143 // Upgrade the alignment in cases where the same constant is used with different
144 // alignment requirements
145 if align > llvm::LLVMGetAlignment(gv) {
146 llvm::LLVMSetAlignment(gv, align);
151 let gv = addr_of_mut(ccx, cv, align, kind);
153 llvm::LLVMSetGlobalConstant(gv, True);
155 ccx.const_globals().borrow_mut().insert(cv, gv);
159 /// Deref a constant pointer
160 pub fn load_const(cx: &CrateContext, v: ValueRef, t: Ty) -> ValueRef {
161 let v = match cx.const_unsized().borrow().get(&v) {
165 let d = unsafe { llvm::LLVMGetInitializer(v) };
166 if !d.is_null() && t.is_bool() {
167 unsafe { llvm::LLVMConstTrunc(d, Type::i1(cx).to_ref()) }
173 fn const_deref<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
176 -> (ValueRef, Ty<'tcx>) {
177 match ty.builtin_deref(true, ty::NoPreference) {
179 if type_is_sized(cx.tcx(), mt.ty) {
180 (load_const(cx, v, mt.ty), mt.ty)
182 // Derefing a fat pointer does not change the representation,
183 // just the type to the unsized contents.
188 bug!("unexpected dereferenceable type {:?}", ty)
193 fn const_fn_call<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
195 substs: &'tcx Substs<'tcx>,
196 arg_vals: &[ValueRef],
197 param_substs: &'tcx Substs<'tcx>,
198 trueconst: TrueConst) -> Result<ValueRef, ConstEvalFailure> {
199 let fn_like = lookup_const_fn_by_id(ccx.tcx(), def_id);
200 let fn_like = fn_like.expect("lookup_const_fn_by_id failed in const_fn_call");
202 let body = match fn_like.body().expr {
203 Some(ref expr) => expr,
204 None => return Ok(C_nil(ccx))
207 let args = &fn_like.decl().inputs;
208 assert_eq!(args.len(), arg_vals.len());
210 let arg_ids = args.iter().map(|arg| arg.pat.id);
211 let fn_args = arg_ids.zip(arg_vals.iter().cloned()).collect();
213 let substs = ccx.tcx().mk_substs(substs.clone().erase_regions());
214 let substs = monomorphize::apply_param_substs(ccx.tcx(),
218 const_expr(ccx, body, substs, Some(&fn_args), trueconst).map(|(res, _)| res)
221 pub fn get_const_expr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
223 ref_expr: &hir::Expr,
224 param_substs: &'tcx Substs<'tcx>)
226 let substs = ccx.tcx().node_id_item_substs(ref_expr.id).substs;
227 let substs = ccx.tcx().mk_substs(substs.clone().erase_regions());
228 let substs = monomorphize::apply_param_substs(ccx.tcx(),
231 match lookup_const_by_id(ccx.tcx(), def_id, Some(substs)) {
232 Some((ref expr, _ty)) => expr,
234 span_bug!(ref_expr.span, "constant item not found")
239 pub enum ConstEvalFailure {
240 /// in case the const evaluator failed on something that panic at runtime
241 /// as defined in RFC 1229
242 Runtime(ConstEvalErr),
243 // in case we found a true constant
244 Compiletime(ConstEvalErr),
247 impl ConstEvalFailure {
248 fn into_inner(self) -> ConstEvalErr {
254 pub fn description(&self) -> Cow<str> {
256 &Runtime(ref e) => e.description(),
257 &Compiletime(ref e) => e.description(),
262 #[derive(Copy, Clone, Debug, Eq, PartialEq)]
267 use self::ConstEvalFailure::*;
269 fn get_const_val<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
271 ref_expr: &hir::Expr,
272 param_substs: &'tcx Substs<'tcx>)
273 -> Result<ValueRef, ConstEvalFailure> {
274 let expr = get_const_expr(ccx, def_id, ref_expr, param_substs);
275 let empty_substs = ccx.tcx().mk_substs(Substs::empty());
276 match get_const_expr_as_global(ccx, expr, ConstQualif::empty(), empty_substs, TrueConst::Yes) {
277 Err(Runtime(err)) => {
278 ccx.tcx().sess.span_err(expr.span, &err.description());
279 Err(Compiletime(err))
285 pub fn get_const_expr_as_global<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
288 param_substs: &'tcx Substs<'tcx>,
289 trueconst: TrueConst)
290 -> Result<ValueRef, ConstEvalFailure> {
291 debug!("get_const_expr_as_global: {:?}", expr.id);
292 // Special-case constants to cache a common global for all uses.
293 if let hir::ExprPath(..) = expr.node {
294 // `def` must be its own statement and cannot be in the `match`
295 // otherwise the `def_map` will be borrowed for the entire match instead
296 // of just to get the `def` value
297 match ccx.tcx().expect_def(expr.id) {
298 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
299 if !ccx.tcx().tables.borrow().adjustments.contains_key(&expr.id) {
300 debug!("get_const_expr_as_global ({:?}): found const {:?}",
302 return get_const_val(ccx, def_id, expr, param_substs);
309 let key = (expr.id, param_substs);
310 if let Some(&val) = ccx.const_values().borrow().get(&key) {
313 let ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs,
314 &ccx.tcx().expr_ty(expr));
315 let val = if qualif.intersects(ConstQualif::NON_STATIC_BORROWS) {
316 // Avoid autorefs as they would create global instead of stack
317 // references, even when only the latter are correct.
318 const_expr_unadjusted(ccx, expr, ty, param_substs, None, trueconst)?
320 const_expr(ccx, expr, param_substs, None, trueconst)?.0
323 // boolean SSA values are i1, but they have to be stored in i8 slots,
324 // otherwise some LLVM optimization passes don't work as expected
326 if llvm::LLVMTypeOf(val) == Type::i1(ccx).to_ref() {
327 llvm::LLVMConstZExt(val, Type::i8(ccx).to_ref())
333 let lvalue = addr_of(ccx, val, type_of::align_of(ccx, ty), "const");
334 ccx.const_values().borrow_mut().insert(key, lvalue);
338 pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
340 param_substs: &'tcx Substs<'tcx>,
342 trueconst: TrueConst)
343 -> Result<(ValueRef, Ty<'tcx>), ConstEvalFailure> {
344 let ety = monomorphize::apply_param_substs(cx.tcx(), param_substs,
345 &cx.tcx().expr_ty(e));
346 let llconst = const_expr_unadjusted(cx, e, ety, param_substs, fn_args, trueconst)?;
347 let mut llconst = llconst;
348 let mut ety_adjusted = monomorphize::apply_param_substs(cx.tcx(), param_substs,
349 &cx.tcx().expr_ty_adjusted(e));
350 let opt_adj = cx.tcx().tables.borrow().adjustments.get(&e.id).cloned();
352 Some(AdjustReifyFnPointer) => {
354 ty::TyFnDef(def_id, substs, _) => {
355 llconst = Callee::def(cx, def_id, substs).reify(cx).val;
358 bug!("{} cannot be reified to a fn ptr", ety)
362 Some(AdjustUnsafeFnPointer) | Some(AdjustMutToConstPointer) => {
363 // purely a type-level thing
365 Some(AdjustDerefRef(adj)) => {
367 // Save the last autoderef in case we can avoid it.
368 if adj.autoderefs > 0 {
369 for _ in 0..adj.autoderefs-1 {
370 let (dv, dt) = const_deref(cx, llconst, ty);
376 if adj.autoref.is_some() {
377 if adj.autoderefs == 0 {
378 // Don't copy data to do a deref+ref
379 // (i.e., skip the last auto-deref).
380 llconst = addr_of(cx, llconst, type_of::align_of(cx, ty), "autoref");
381 ty = cx.tcx().mk_imm_ref(cx.tcx().mk_region(ty::ReErased), ty);
383 } else if adj.autoderefs > 0 {
384 let (dv, dt) = const_deref(cx, llconst, ty);
387 // If we derefed a fat pointer then we will have an
388 // open type here. So we need to update the type with
389 // the one returned from const_deref.
393 if let Some(target) = adj.unsize {
394 let target = monomorphize::apply_param_substs(cx.tcx(),
398 let pointee_ty = ty.builtin_deref(true, ty::NoPreference)
399 .expect("consts: unsizing got non-pointer type").ty;
400 let (base, old_info) = if !type_is_sized(cx.tcx(), pointee_ty) {
401 // Normally, the source is a thin pointer and we are
402 // adding extra info to make a fat pointer. The exception
403 // is when we are upcasting an existing object fat pointer
404 // to use a different vtable. In that case, we want to
405 // load out the original data pointer so we can repackage
407 (const_get_elt(llconst, &[abi::FAT_PTR_ADDR as u32]),
408 Some(const_get_elt(llconst, &[abi::FAT_PTR_EXTRA as u32])))
413 let unsized_ty = target.builtin_deref(true, ty::NoPreference)
414 .expect("consts: unsizing got non-pointer target type").ty;
415 let ptr_ty = type_of::in_memory_type_of(cx, unsized_ty).ptr_to();
416 let base = ptrcast(base, ptr_ty);
417 let info = base::unsized_info(cx, pointee_ty, unsized_ty, old_info);
419 if old_info.is_none() {
420 let prev_const = cx.const_unsized().borrow_mut()
421 .insert(base, llconst);
422 assert!(prev_const.is_none() || prev_const == Some(llconst));
424 assert_eq!(abi::FAT_PTR_ADDR, 0);
425 assert_eq!(abi::FAT_PTR_EXTRA, 1);
426 llconst = C_struct(cx, &[base, info], false);
432 let llty = type_of::sizing_type_of(cx, ety_adjusted);
433 let csize = machine::llsize_of_alloc(cx, val_ty(llconst));
434 let tsize = machine::llsize_of_alloc(cx, llty);
436 cx.sess().abort_if_errors();
438 // FIXME these values could use some context
439 llvm::LLVMDumpValue(llconst);
440 llvm::LLVMDumpValue(C_undef(llty));
442 bug!("const {:?} of type {:?} has size {} instead of {}",
446 Ok((llconst, ety_adjusted))
449 fn check_unary_expr_validity(cx: &CrateContext, e: &hir::Expr, t: Ty,
450 te: ValueRef, trueconst: TrueConst) -> Result<(), ConstEvalFailure> {
451 // The only kind of unary expression that we check for validity
452 // here is `-expr`, to check if it "overflows" (e.g. `-i32::MIN`).
453 if let hir::ExprUnary(hir::UnNeg, ref inner_e) = e.node {
455 // An unfortunate special case: we parse e.g. -128 as a
456 // negation of the literal 128, which means if we're expecting
457 // a i8 (or if it was already suffixed, e.g. `-128_i8`), then
458 // 128 will have already overflowed to -128, and so then the
459 // constant evaluator thinks we're trying to negate -128.
461 // Catch this up front by looking for ExprLit directly,
462 // and just accepting it.
463 if let hir::ExprLit(_) = inner_e.node { return Ok(()); }
464 let cval = match to_const_int(te, t, cx.tcx()) {
466 None => return Ok(()),
468 const_err(cx, e.span, (-cval).map_err(ErrKind::Math), trueconst)?;
473 pub fn to_const_int(value: ValueRef, t: Ty, tcx: TyCtxt) -> Option<ConstInt> {
475 ty::TyInt(int_type) => const_to_opt_int(value).and_then(|input| match int_type {
477 assert_eq!(input as i8 as i64, input);
478 Some(ConstInt::I8(input as i8))
481 assert_eq!(input as i16 as i64, input);
482 Some(ConstInt::I16(input as i16))
485 assert_eq!(input as i32 as i64, input);
486 Some(ConstInt::I32(input as i32))
489 Some(ConstInt::I64(input))
492 ConstIsize::new(input, tcx.sess.target.int_type)
493 .ok().map(ConstInt::Isize)
496 ty::TyUint(uint_type) => const_to_opt_uint(value).and_then(|input| match uint_type {
498 assert_eq!(input as u8 as u64, input);
499 Some(ConstInt::U8(input as u8))
501 ast::UintTy::U16 => {
502 assert_eq!(input as u16 as u64, input);
503 Some(ConstInt::U16(input as u16))
505 ast::UintTy::U32 => {
506 assert_eq!(input as u32 as u64, input);
507 Some(ConstInt::U32(input as u32))
509 ast::UintTy::U64 => {
510 Some(ConstInt::U64(input))
513 ConstUsize::new(input, tcx.sess.target.uint_type)
514 .ok().map(ConstInt::Usize)
521 pub fn const_err<T>(cx: &CrateContext,
523 result: Result<T, ErrKind>,
524 trueconst: TrueConst)
525 -> Result<T, ConstEvalFailure> {
526 match (result, trueconst) {
528 (Err(err), TrueConst::Yes) => {
529 let err = ConstEvalErr{ span: span, kind: err };
530 cx.tcx().sess.span_err(span, &err.description());
531 Err(Compiletime(err))
533 (Err(err), TrueConst::No) => {
534 let err = ConstEvalErr{ span: span, kind: err };
535 cx.tcx().sess.span_warn(span, &err.description());
541 fn check_binary_expr_validity(cx: &CrateContext, e: &hir::Expr, t: Ty,
542 te1: ValueRef, te2: ValueRef,
543 trueconst: TrueConst) -> Result<(), ConstEvalFailure> {
544 let b = if let hir::ExprBinary(b, _, _) = e.node { b } else { bug!() };
545 let (lhs, rhs) = match (to_const_int(te1, t, cx.tcx()), to_const_int(te2, t, cx.tcx())) {
546 (Some(v1), Some(v2)) => (v1, v2),
549 let result = match b.node {
550 hir::BiAdd => lhs + rhs,
551 hir::BiSub => lhs - rhs,
552 hir::BiMul => lhs * rhs,
553 hir::BiDiv => lhs / rhs,
554 hir::BiRem => lhs % rhs,
555 hir::BiShl => lhs << rhs,
556 hir::BiShr => lhs >> rhs,
559 const_err(cx, e.span, result.map_err(ErrKind::Math), trueconst)?;
563 fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
566 param_substs: &'tcx Substs<'tcx>,
568 trueconst: TrueConst)
569 -> Result<ValueRef, ConstEvalFailure>
571 debug!("const_expr_unadjusted(e={:?}, ety={:?}, param_substs={:?})",
576 let map_list = |exprs: &[P<hir::Expr>]| -> Result<Vec<ValueRef>, ConstEvalFailure> {
578 .map(|e| const_expr(cx, &e, param_substs, fn_args, trueconst).map(|(l, _)| l))
579 .collect::<Vec<Result<ValueRef, ConstEvalFailure>>>()
582 // this dance is necessary to eagerly run const_expr so all errors are reported
584 let _icx = push_ctxt("const_expr");
586 hir::ExprLit(ref lit) => const_lit(cx, e, &lit),
587 hir::ExprBinary(b, ref e1, ref e2) => {
588 /* Neither type is bottom, and we expect them to be unified
589 * already, so the following is safe. */
590 let (te1, ty) = const_expr(cx, &e1, param_substs, fn_args, trueconst)?;
591 debug!("const_expr_unadjusted: te1={:?}, ty={:?}",
593 assert!(!ty.is_simd());
594 let is_float = ty.is_fp();
595 let signed = ty.is_signed();
597 let (te2, ty2) = const_expr(cx, &e2, param_substs, fn_args, trueconst)?;
598 debug!("const_expr_unadjusted: te2={:?}, ty={:?}",
601 check_binary_expr_validity(cx, e, ty, te1, te2, trueconst)?;
603 unsafe { match b.node {
604 hir::BiAdd if is_float => llvm::LLVMConstFAdd(te1, te2),
605 hir::BiAdd => llvm::LLVMConstAdd(te1, te2),
607 hir::BiSub if is_float => llvm::LLVMConstFSub(te1, te2),
608 hir::BiSub => llvm::LLVMConstSub(te1, te2),
610 hir::BiMul if is_float => llvm::LLVMConstFMul(te1, te2),
611 hir::BiMul => llvm::LLVMConstMul(te1, te2),
613 hir::BiDiv if is_float => llvm::LLVMConstFDiv(te1, te2),
614 hir::BiDiv if signed => llvm::LLVMConstSDiv(te1, te2),
615 hir::BiDiv => llvm::LLVMConstUDiv(te1, te2),
617 hir::BiRem if is_float => llvm::LLVMConstFRem(te1, te2),
618 hir::BiRem if signed => llvm::LLVMConstSRem(te1, te2),
619 hir::BiRem => llvm::LLVMConstURem(te1, te2),
621 hir::BiAnd => llvm::LLVMConstAnd(te1, te2),
622 hir::BiOr => llvm::LLVMConstOr(te1, te2),
623 hir::BiBitXor => llvm::LLVMConstXor(te1, te2),
624 hir::BiBitAnd => llvm::LLVMConstAnd(te1, te2),
625 hir::BiBitOr => llvm::LLVMConstOr(te1, te2),
627 let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
628 llvm::LLVMConstShl(te1, te2)
631 let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
632 if signed { llvm::LLVMConstAShr(te1, te2) }
633 else { llvm::LLVMConstLShr(te1, te2) }
635 hir::BiEq | hir::BiNe | hir::BiLt | hir::BiLe | hir::BiGt | hir::BiGe => {
637 let cmp = base::bin_op_to_fcmp_predicate(b.node);
638 ConstFCmp(cmp, te1, te2)
640 let cmp = base::bin_op_to_icmp_predicate(b.node, signed);
641 ConstICmp(cmp, te1, te2)
644 } } // unsafe { match b.node {
646 hir::ExprUnary(u, ref inner_e) => {
647 let (te, ty) = const_expr(cx, &inner_e, param_substs, fn_args, trueconst)?;
649 check_unary_expr_validity(cx, e, ty, te, trueconst)?;
651 let is_float = ty.is_fp();
653 hir::UnDeref => const_deref(cx, te, ty).0,
654 hir::UnNot => llvm::LLVMConstNot(te),
655 hir::UnNeg if is_float => llvm::LLVMConstFNeg(te),
656 hir::UnNeg => llvm::LLVMConstNeg(te),
659 hir::ExprField(ref base, field) => {
660 let (bv, bt) = const_expr(cx, &base, param_substs, fn_args, trueconst)?;
661 let brepr = adt::represent_type(cx, bt);
662 let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
663 let ix = vinfo.field_index(field.node);
664 adt::const_get_field(&brepr, bv, vinfo.discr, ix)
666 hir::ExprTupField(ref base, idx) => {
667 let (bv, bt) = const_expr(cx, &base, param_substs, fn_args, trueconst)?;
668 let brepr = adt::represent_type(cx, bt);
669 let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
670 adt::const_get_field(&brepr, bv, vinfo.discr, idx.node)
672 hir::ExprIndex(ref base, ref index) => {
673 let (bv, bt) = const_expr(cx, &base, param_substs, fn_args, trueconst)?;
674 let iv = const_expr(cx, &index, param_substs, fn_args, TrueConst::Yes)?.0;
675 let iv = if let Some(iv) = const_to_opt_uint(iv) {
678 span_bug!(index.span, "index is not an integer-constant expression");
680 let (arr, len) = match bt.sty {
681 ty::TyArray(_, u) => (bv, C_uint(cx, u)),
682 ty::TySlice(..) | ty::TyStr => {
683 let e1 = const_get_elt(bv, &[0]);
684 (load_const(cx, e1, bt), const_get_elt(bv, &[1]))
686 ty::TyRef(_, mt) => match mt.ty.sty {
687 ty::TyArray(_, u) => {
688 (load_const(cx, bv, mt.ty), C_uint(cx, u))
690 _ => span_bug!(base.span,
691 "index-expr base must be a vector \
692 or string type, found {:?}",
695 _ => span_bug!(base.span,
696 "index-expr base must be a vector \
697 or string type, found {:?}",
701 let len = unsafe { llvm::LLVMConstIntGetZExtValue(len) as u64 };
702 let len = match bt.sty {
703 ty::TyBox(ty) | ty::TyRef(_, ty::TypeAndMut{ty, ..}) => match ty.sty {
713 // FIXME #3170: report this earlier on in the const-eval
714 // pass. Reporting here is a bit late.
715 const_err(cx, e.span, Err(ErrKind::IndexOutOfBounds {
719 C_undef(val_ty(arr).element_type())
721 const_get_elt(arr, &[iv as c_uint])
724 hir::ExprCast(ref base, _) => {
726 let llty = type_of::type_of(cx, t_cast);
727 let (v, t_expr) = const_expr(cx, &base, param_substs, fn_args, trueconst)?;
728 debug!("trans_const_cast({:?} as {:?})", t_expr, t_cast);
729 if expr::cast_is_noop(cx.tcx(), base, t_expr, t_cast) {
732 if type_is_fat_ptr(cx.tcx(), t_expr) {
733 // Fat pointer casts.
735 t_cast.builtin_deref(true, ty::NoPreference).expect("cast to non-pointer").ty;
736 let ptr_ty = type_of::in_memory_type_of(cx, t_cast_inner).ptr_to();
737 let addr = ptrcast(const_get_elt(v, &[abi::FAT_PTR_ADDR as u32]),
739 if type_is_fat_ptr(cx.tcx(), t_cast) {
740 let info = const_get_elt(v, &[abi::FAT_PTR_EXTRA as u32]);
741 return Ok(C_struct(cx, &[addr, info], false))
747 CastTy::from_ty(t_expr).expect("bad input type for cast"),
748 CastTy::from_ty(t_cast).expect("bad output type for cast"),
750 (CastTy::Int(IntTy::CEnum), CastTy::Int(_)) => {
751 let repr = adt::represent_type(cx, t_expr);
752 let discr = adt::const_get_discrim(&repr, v);
753 let iv = C_integral(cx.int_type(), discr.0, false);
754 let s = adt::is_discr_signed(&repr) as Bool;
755 llvm::LLVMConstIntCast(iv, llty.to_ref(), s)
757 (CastTy::Int(_), CastTy::Int(_)) => {
758 let s = t_expr.is_signed() as Bool;
759 llvm::LLVMConstIntCast(v, llty.to_ref(), s)
761 (CastTy::Int(_), CastTy::Float) => {
762 if t_expr.is_signed() {
763 llvm::LLVMConstSIToFP(v, llty.to_ref())
765 llvm::LLVMConstUIToFP(v, llty.to_ref())
768 (CastTy::Float, CastTy::Float) => llvm::LLVMConstFPCast(v, llty.to_ref()),
769 (CastTy::Float, CastTy::Int(IntTy::I)) => llvm::LLVMConstFPToSI(v, llty.to_ref()),
770 (CastTy::Float, CastTy::Int(_)) => llvm::LLVMConstFPToUI(v, llty.to_ref()),
771 (CastTy::Ptr(_), CastTy::Ptr(_)) | (CastTy::FnPtr, CastTy::Ptr(_))
772 | (CastTy::RPtr(_), CastTy::Ptr(_)) => {
775 (CastTy::FnPtr, CastTy::FnPtr) => ptrcast(v, llty), // isn't this a coercion?
776 (CastTy::Int(_), CastTy::Ptr(_)) => llvm::LLVMConstIntToPtr(v, llty.to_ref()),
777 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
778 llvm::LLVMConstPtrToInt(v, llty.to_ref())
781 span_bug!(e.span, "bad combination of types for cast")
783 } } // unsafe { match ( ... ) {
785 hir::ExprAddrOf(hir::MutImmutable, ref sub) => {
786 // If this is the address of some static, then we need to return
787 // the actual address of the static itself (short circuit the rest
792 hir::ExprBlock(ref blk) => {
793 if let Some(ref sub) = blk.expr {
802 if let Some(Def::Static(def_id, _)) = cx.tcx().expect_def_or_none(cur.id) {
803 get_static(cx, def_id).val
805 // If this isn't the address of a static, then keep going through
806 // normal constant evaluation.
807 let (v, ty) = const_expr(cx, &sub, param_substs, fn_args, trueconst)?;
808 addr_of(cx, v, type_of::align_of(cx, ty), "ref")
811 hir::ExprAddrOf(hir::MutMutable, ref sub) => {
812 let (v, ty) = const_expr(cx, &sub, param_substs, fn_args, trueconst)?;
813 addr_of_mut(cx, v, type_of::align_of(cx, ty), "ref_mut_slice")
815 hir::ExprTup(ref es) => {
816 let repr = adt::represent_type(cx, ety);
817 let vals = map_list(&es[..])?;
818 adt::trans_const(cx, &repr, Disr(0), &vals[..])
820 hir::ExprStruct(_, ref fs, ref base_opt) => {
821 let repr = adt::represent_type(cx, ety);
823 let base_val = match *base_opt {
824 Some(ref base) => Some(const_expr(
834 let VariantInfo { discr, fields } = VariantInfo::of_node(cx.tcx(), ety, e.id);
835 let cs = fields.iter().enumerate().map(|(ix, &Field(f_name, _))| {
836 match (fs.iter().find(|f| f_name == f.name.node), base_val) {
837 (Some(ref f), _) => {
838 const_expr(cx, &f.expr, param_substs, fn_args, trueconst).map(|(l, _)| l)
840 (_, Some((bv, _))) => Ok(adt::const_get_field(&repr, bv, discr, ix)),
841 (_, None) => span_bug!(e.span, "missing struct field"),
844 .collect::<Vec<Result<_, ConstEvalFailure>>>()
846 .collect::<Result<Vec<_>,ConstEvalFailure>>();
851 adt::trans_const(cx, &repr, discr, &cs[..])
854 hir::ExprVec(ref es) => {
855 let unit_ty = ety.sequence_element_type(cx.tcx());
856 let llunitty = type_of::type_of(cx, unit_ty);
865 .collect::<Vec<Result<_, ConstEvalFailure>>>()
867 .collect::<Result<Vec<_>, ConstEvalFailure>>();
869 // If the vector contains enums, an LLVM array won't work.
870 if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
871 C_struct(cx, &vs[..], false)
873 C_array(llunitty, &vs[..])
876 hir::ExprRepeat(ref elem, ref count) => {
877 let unit_ty = ety.sequence_element_type(cx.tcx());
878 let llunitty = type_of::type_of(cx, unit_ty);
879 let n = eval_repeat_count(cx.tcx(), count);
880 let unit_val = const_expr(cx, &elem, param_substs, fn_args, trueconst)?.0;
881 let vs = vec![unit_val; n];
882 if val_ty(unit_val) != llunitty {
883 C_struct(cx, &vs[..], false)
885 C_array(llunitty, &vs[..])
888 hir::ExprPath(..) => {
889 match cx.tcx().expect_def(e.id) {
890 Def::Local(_, id) => {
891 if let Some(val) = fn_args.and_then(|args| args.get(&id).cloned()) {
894 span_bug!(e.span, "const fn argument not found")
897 Def::Fn(..) | Def::Method(..) => C_nil(cx),
898 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
899 load_const(cx, get_const_val(cx, def_id, e, param_substs)?,
902 Def::Variant(enum_did, variant_did) => {
903 let vinfo = cx.tcx().lookup_adt_def(enum_did).variant_with_id(variant_did);
905 ty::VariantKind::Unit => {
906 let repr = adt::represent_type(cx, ety);
907 adt::trans_const(cx, &repr, Disr::from(vinfo.disr_val), &[])
909 ty::VariantKind::Tuple => C_nil(cx),
910 ty::VariantKind::Struct => {
911 span_bug!(e.span, "path-expr refers to a dict variant!")
915 // Unit struct or ctor.
916 Def::Struct(..) => C_null(type_of::type_of(cx, ety)),
918 span_bug!(e.span, "expected a const, fn, struct, \
923 hir::ExprCall(ref callee, ref args) => {
924 let mut callee = &**callee;
926 callee = match callee.node {
927 hir::ExprBlock(ref block) => match block.expr {
928 Some(ref tail) => &tail,
934 let arg_vals = map_list(args)?;
935 match cx.tcx().expect_def(callee.id) {
936 Def::Fn(did) | Def::Method(did) => {
940 cx.tcx().node_id_item_substs(callee.id).substs,
948 C_vector(&arg_vals[..])
950 let repr = adt::represent_type(cx, ety);
951 adt::trans_const(cx, &repr, Disr(0), &arg_vals[..])
954 Def::Variant(enum_did, variant_did) => {
955 let repr = adt::represent_type(cx, ety);
956 let vinfo = cx.tcx().lookup_adt_def(enum_did).variant_with_id(variant_did);
959 Disr::from(vinfo.disr_val),
962 _ => span_bug!(e.span, "expected a struct, variant, or const fn def"),
965 hir::ExprMethodCall(_, _, ref args) => {
966 let arg_vals = map_list(args)?;
967 let method_call = ty::MethodCall::expr(e.id);
968 let method = cx.tcx().tables.borrow().method_map[&method_call];
969 const_fn_call(cx, method.def_id, method.substs,
970 &arg_vals, param_substs, trueconst)?
972 hir::ExprType(ref e, _) => const_expr(cx, &e, param_substs, fn_args, trueconst)?.0,
973 hir::ExprBlock(ref block) => {
975 Some(ref expr) => const_expr(
985 hir::ExprClosure(_, ref decl, ref body, _) => {
987 ty::TyClosure(def_id, substs) => {
988 closure::trans_closure_expr(closure::Dest::Ignore(cx),
998 "bad type for closure expr: {:?}", ety)
1000 C_null(type_of::type_of(cx, ety))
1002 _ => span_bug!(e.span,
1003 "bad constant expression type in consts::const_expr"),
1007 pub fn get_static<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, def_id: DefId)
1008 -> Datum<'tcx, Lvalue> {
1009 let ty = ccx.tcx().lookup_item_type(def_id).ty;
1011 let instance = Instance::mono(ccx.shared(), def_id);
1012 if let Some(&g) = ccx.instances().borrow().get(&instance) {
1013 return Datum::new(g, ty, Lvalue::new("static"));
1016 let g = if let Some(id) = ccx.tcx().map.as_local_node_id(def_id) {
1018 let llty = type_of::type_of(ccx, ty);
1019 let (g, attrs) = match ccx.tcx().map.get(id) {
1020 hir_map::NodeItem(&hir::Item {
1021 ref attrs, span, node: hir::ItemStatic(..), ..
1023 let sym = ccx.symbol_map()
1024 .get(TransItem::Static(id))
1025 .expect("Local statics should always be in the SymbolMap");
1026 // Make sure that this is never executed for something inlined.
1027 assert!(!ccx.external_srcs().borrow().contains_key(&id));
1029 let defined_in_current_codegen_unit = ccx.codegen_unit()
1031 .contains_key(&TransItem::Static(id));
1032 if defined_in_current_codegen_unit {
1033 if declare::get_declared_value(ccx, sym).is_none() {
1034 span_bug!(span, "trans: Static not properly pre-defined?");
1037 if declare::get_declared_value(ccx, sym).is_some() {
1038 span_bug!(span, "trans: Conflicting symbol names for static?");
1042 let g = declare::define_global(ccx, sym, llty).unwrap();
1047 hir_map::NodeForeignItem(&hir::ForeignItem {
1048 ref attrs, span, node: hir::ForeignItemStatic(..), ..
1050 let sym = instance.symbol_name(ccx.shared());
1051 let g = if let Some(name) =
1052 attr::first_attr_value_str_by_name(&attrs, "linkage") {
1053 // If this is a static with a linkage specified, then we need to handle
1054 // it a little specially. The typesystem prevents things like &T and
1055 // extern "C" fn() from being non-null, so we can't just declare a
1056 // static and call it a day. Some linkages (like weak) will make it such
1057 // that the static actually has a null value.
1058 let linkage = match base::llvm_linkage_by_name(&name) {
1059 Some(linkage) => linkage,
1061 ccx.sess().span_fatal(span, "invalid linkage specified");
1064 let llty2 = match ty.sty {
1065 ty::TyRawPtr(ref mt) => type_of::type_of(ccx, mt.ty),
1067 ccx.sess().span_fatal(span, "must have type `*const T` or `*mut T`");
1071 // Declare a symbol `foo` with the desired linkage.
1072 let g1 = declare::declare_global(ccx, &sym, llty2);
1073 llvm::SetLinkage(g1, linkage);
1075 // Declare an internal global `extern_with_linkage_foo` which
1076 // is initialized with the address of `foo`. If `foo` is
1077 // discarded during linking (for example, if `foo` has weak
1078 // linkage and there are no definitions), then
1079 // `extern_with_linkage_foo` will instead be initialized to
1081 let mut real_name = "_rust_extern_with_linkage_".to_string();
1082 real_name.push_str(&sym);
1083 let g2 = declare::define_global(ccx, &real_name, llty).unwrap_or_else(||{
1084 ccx.sess().span_fatal(span,
1085 &format!("symbol `{}` is already defined", &sym))
1087 llvm::SetLinkage(g2, llvm::InternalLinkage);
1088 llvm::LLVMSetInitializer(g2, g1);
1092 // Generate an external declaration.
1093 declare::declare_global(ccx, &sym, llty)
1099 item => bug!("get_static: expected static, found {:?}", item)
1103 if attr.check_name("thread_local") {
1104 llvm::set_thread_local(g, true);
1110 let sym = instance.symbol_name(ccx.shared());
1112 // FIXME(nagisa): perhaps the map of externs could be offloaded to llvm somehow?
1113 // FIXME(nagisa): investigate whether it can be changed into define_global
1114 let g = declare::declare_global(ccx, &sym, type_of::type_of(ccx, ty));
1115 // Thread-local statics in some other crate need to *always* be linked
1116 // against in a thread-local fashion, so we need to be sure to apply the
1117 // thread-local attribute locally if it was present remotely. If we
1118 // don't do this then linker errors can be generated where the linker
1119 // complains that one object files has a thread local version of the
1120 // symbol and another one doesn't.
1121 for attr in ccx.tcx().get_attrs(def_id).iter() {
1122 if attr.check_name("thread_local") {
1123 llvm::set_thread_local(g, true);
1126 if ccx.use_dll_storage_attrs() {
1127 llvm::SetDLLStorageClass(g, llvm::DLLImportStorageClass);
1132 ccx.instances().borrow_mut().insert(instance, g);
1133 ccx.statics().borrow_mut().insert(g, def_id);
1134 Datum::new(g, ty, Lvalue::new("static"))
1137 pub fn trans_static(ccx: &CrateContext,
1141 attrs: &[ast::Attribute])
1142 -> Result<ValueRef, ConstEvalErr> {
1144 if collector::collecting_debug_information(ccx.shared()) {
1145 ccx.record_translation_item_as_generated(TransItem::Static(id));
1149 let _icx = push_ctxt("trans_static");
1150 let def_id = ccx.tcx().map.local_def_id(id);
1151 let datum = get_static(ccx, def_id);
1153 let check_attrs = |attrs: &[ast::Attribute]| {
1154 let default_to_mir = ccx.sess().opts.debugging_opts.orbit;
1155 let invert = if default_to_mir { "rustc_no_mir" } else { "rustc_mir" };
1156 default_to_mir ^ attrs.iter().any(|item| item.check_name(invert))
1158 let use_mir = check_attrs(ccx.tcx().map.attrs(id));
1160 let v = if use_mir {
1161 ::mir::trans_static_initializer(ccx, def_id)
1163 let empty_substs = ccx.tcx().mk_substs(Substs::empty());
1164 const_expr(ccx, expr, empty_substs, None, TrueConst::Yes)
1166 }.map_err(|e| e.into_inner())?;
1168 // boolean SSA values are i1, but they have to be stored in i8 slots,
1169 // otherwise some LLVM optimization passes don't work as expected
1170 let mut val_llty = val_ty(v);
1171 let v = if val_llty == Type::i1(ccx) {
1172 val_llty = Type::i8(ccx);
1173 llvm::LLVMConstZExt(v, val_llty.to_ref())
1178 let llty = type_of::type_of(ccx, datum.ty);
1179 let g = if val_llty == llty {
1182 // If we created the global with the wrong type,
1183 // correct the type.
1184 let empty_string = CString::new("").unwrap();
1185 let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(datum.val));
1186 let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
1187 llvm::LLVMSetValueName(datum.val, empty_string.as_ptr());
1188 let new_g = llvm::LLVMGetOrInsertGlobal(
1189 ccx.llmod(), name_string.as_ptr(), val_llty.to_ref());
1190 // To avoid breaking any invariants, we leave around the old
1191 // global for the moment; we'll replace all references to it
1192 // with the new global later. (See base::trans_crate.)
1193 ccx.statics_to_rauw().borrow_mut().push((datum.val, new_g));
1196 llvm::LLVMSetAlignment(g, type_of::align_of(ccx, datum.ty));
1197 llvm::LLVMSetInitializer(g, v);
1199 // As an optimization, all shared statics which do not have interior
1200 // mutability are placed into read-only memory.
1201 if m != hir::MutMutable {
1202 let tcontents = datum.ty.type_contents(ccx.tcx());
1203 if !tcontents.interior_unsafe() {
1204 llvm::LLVMSetGlobalConstant(g, llvm::True);
1208 debuginfo::create_global_var_metadata(ccx, id, g);
1210 if attr::contains_name(attrs,
1212 llvm::set_thread_local(g, true);
1215 base::set_link_section(ccx, g, attrs);