]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/consts.rs
Auto merge of #31020 - regexident:fix_16884, r=brson
[rust.git] / src / librustc_trans / trans / consts.rs
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.
4 //
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.
10
11
12 use back::abi;
13 use llvm;
14 use llvm::{ConstFCmp, ConstICmp, SetLinkage, SetUnnamedAddr};
15 use llvm::{InternalLinkage, ValueRef, Bool, True};
16 use middle::const_qualif::ConstQualif;
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::Def;
30 use middle::def_id::DefId;
31 use trans::{adt, closure, debuginfo, expr, inline, machine};
32 use trans::base::{self, push_ctxt};
33 use trans::common::{self, type_is_sized, ExprOrMethodCall, node_id_substs, C_nil, const_get_elt};
34 use trans::common::{CrateContext, C_integral, C_floating, C_bool, C_str_slice, C_bytes, val_ty};
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};
37 use trans::declare;
38 use trans::monomorphize;
39 use trans::type_::Type;
40 use trans::type_of;
41 use trans::Disr;
42 use middle::subst::Substs;
43 use middle::ty::adjustment::{AdjustDerefRef, AdjustReifyFnPointer};
44 use middle::ty::adjustment::AdjustUnsafeFnPointer;
45 use middle::ty::{self, Ty};
46 use middle::ty::cast::{CastTy,IntTy};
47 use util::nodemap::NodeMap;
48
49 use rustc_front::hir;
50
51 use std::ffi::{CStr, CString};
52 use std::borrow::Cow;
53 use libc::c_uint;
54 use syntax::ast;
55 use syntax::attr;
56 use syntax::parse::token;
57 use syntax::ptr::P;
58
59 pub type FnArgMap<'a> = Option<&'a NodeMap<ValueRef>>;
60
61 pub fn const_lit(cx: &CrateContext, e: &hir::Expr, lit: &ast::Lit)
62     -> ValueRef {
63     let _icx = push_ctxt("trans_lit");
64     debug!("const_lit: {:?}", lit);
65     match lit.node {
66         ast::LitByte(b) => C_integral(Type::uint_from_ty(cx, ast::TyU8), b as u64, false),
67         ast::LitChar(i) => C_integral(Type::char(cx), i as u64, false),
68         ast::LitInt(i, ast::SignedIntLit(t, _)) => {
69             C_integral(Type::int_from_ty(cx, t), i, true)
70         }
71         ast::LitInt(u, ast::UnsignedIntLit(t)) => {
72             C_integral(Type::uint_from_ty(cx, t), u, false)
73         }
74         ast::LitInt(i, ast::UnsuffixedIntLit(_)) => {
75             let lit_int_ty = cx.tcx().node_id_to_type(e.id);
76             match lit_int_ty.sty {
77                 ty::TyInt(t) => {
78                     C_integral(Type::int_from_ty(cx, t), i as u64, true)
79                 }
80                 ty::TyUint(t) => {
81                     C_integral(Type::uint_from_ty(cx, t), i as u64, false)
82                 }
83                 _ => cx.sess().span_bug(lit.span,
84                         &format!("integer literal has type {:?} (expected int \
85                                  or usize)",
86                                 lit_int_ty))
87             }
88         }
89         ast::LitFloat(ref fs, t) => {
90             C_floating(&fs, Type::float_from_ty(cx, t))
91         }
92         ast::LitFloatUnsuffixed(ref fs) => {
93             let lit_float_ty = cx.tcx().node_id_to_type(e.id);
94             match lit_float_ty.sty {
95                 ty::TyFloat(t) => {
96                     C_floating(&fs, Type::float_from_ty(cx, t))
97                 }
98                 _ => {
99                     cx.sess().span_bug(lit.span,
100                         "floating point literal doesn't have the right type");
101                 }
102             }
103         }
104         ast::LitBool(b) => C_bool(cx, b),
105         ast::LitStr(ref s, _) => C_str_slice(cx, (*s).clone()),
106         ast::LitByteStr(ref data) => {
107             addr_of(cx, C_bytes(cx, &data[..]), 1, "byte_str")
108         }
109     }
110 }
111
112 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
113     unsafe {
114         llvm::LLVMConstPointerCast(val, ty.to_ref())
115     }
116 }
117
118 fn addr_of_mut(ccx: &CrateContext,
119                cv: ValueRef,
120                align: machine::llalign,
121                kind: &str)
122                -> ValueRef {
123     unsafe {
124         // FIXME: this totally needs a better name generation scheme, perhaps a simple global
125         // counter? Also most other uses of gensym in trans.
126         let gsym = token::gensym("_");
127         let name = format!("{}{}", kind, gsym.0);
128         let gv = declare::define_global(ccx, &name[..], val_ty(cv)).unwrap_or_else(||{
129             ccx.sess().bug(&format!("symbol `{}` is already defined", name));
130         });
131         llvm::LLVMSetInitializer(gv, cv);
132         llvm::LLVMSetAlignment(gv, align);
133         SetLinkage(gv, InternalLinkage);
134         SetUnnamedAddr(gv, true);
135         gv
136     }
137 }
138
139 pub fn addr_of(ccx: &CrateContext,
140                cv: ValueRef,
141                align: machine::llalign,
142                kind: &str)
143                -> ValueRef {
144     match ccx.const_globals().borrow().get(&cv) {
145         Some(&gv) => {
146             unsafe {
147                 // Upgrade the alignment in cases where the same constant is used with different
148                 // alignment requirements
149                 if align > llvm::LLVMGetAlignment(gv) {
150                     llvm::LLVMSetAlignment(gv, align);
151                 }
152             }
153             return gv;
154         }
155         None => {}
156     }
157     let gv = addr_of_mut(ccx, cv, align, kind);
158     unsafe {
159         llvm::LLVMSetGlobalConstant(gv, True);
160     }
161     ccx.const_globals().borrow_mut().insert(cv, gv);
162     gv
163 }
164
165 fn const_deref_ptr(cx: &CrateContext, v: ValueRef) -> ValueRef {
166     let v = match cx.const_unsized().borrow().get(&v) {
167         Some(&v) => v,
168         None => v
169     };
170     unsafe {
171         llvm::LLVMGetInitializer(v)
172     }
173 }
174
175 fn const_deref<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
176                          v: ValueRef,
177                          ty: Ty<'tcx>)
178                          -> (ValueRef, Ty<'tcx>) {
179     match ty.builtin_deref(true, ty::NoPreference) {
180         Some(mt) => {
181             if type_is_sized(cx.tcx(), mt.ty) {
182                 (const_deref_ptr(cx, v), mt.ty)
183             } else {
184                 // Derefing a fat pointer does not change the representation,
185                 // just the type to the unsized contents.
186                 (v, mt.ty)
187             }
188         }
189         None => {
190             cx.sess().bug(&format!("unexpected dereferenceable type {:?}",
191                                    ty))
192         }
193     }
194 }
195
196 fn const_fn_call<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
197                            node: ExprOrMethodCall,
198                            def_id: DefId,
199                            arg_vals: &[ValueRef],
200                            param_substs: &'tcx Substs<'tcx>,
201                            trueconst: TrueConst) -> Result<ValueRef, ConstEvalFailure> {
202     let fn_like = const_eval::lookup_const_fn_by_id(ccx.tcx(), def_id);
203     let fn_like = fn_like.expect("lookup_const_fn_by_id failed in const_fn_call");
204
205     let args = &fn_like.decl().inputs;
206     assert_eq!(args.len(), arg_vals.len());
207
208     let arg_ids = args.iter().map(|arg| arg.pat.id);
209     let fn_args = arg_ids.zip(arg_vals.iter().cloned()).collect();
210
211     let substs = ccx.tcx().mk_substs(node_id_substs(ccx, node, param_substs));
212     match fn_like.body().expr {
213         Some(ref expr) => {
214             const_expr(ccx, &**expr, substs, Some(&fn_args), trueconst).map(|(res, _)| res)
215         },
216         None => Ok(C_nil(ccx)),
217     }
218 }
219
220 pub fn get_const_expr<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
221                                 def_id: DefId,
222                                 ref_expr: &hir::Expr,
223                                 param_substs: &'tcx Substs<'tcx>)
224                                 -> &'tcx hir::Expr {
225     let def_id = inline::maybe_instantiate_inline(ccx, def_id);
226
227     if def_id.krate != LOCAL_CRATE {
228         ccx.sess().span_bug(ref_expr.span,
229                             "cross crate constant could not be inlined");
230     }
231
232     match const_eval::lookup_const_by_id(ccx.tcx(), def_id, Some(ref_expr.id), Some(param_substs)) {
233         Some(ref expr) => expr,
234         None => {
235             ccx.sess().span_bug(ref_expr.span, "constant item not found")
236         }
237     }
238 }
239
240 pub enum ConstEvalFailure {
241     /// in case the const evaluator failed on something that panic at runtime
242     /// as defined in RFC 1229
243     Runtime(ConstEvalErr),
244     // in case we found a true constant
245     Compiletime(ConstEvalErr),
246 }
247
248 impl ConstEvalFailure {
249     fn into_inner(self) -> ConstEvalErr {
250         match self {
251             Runtime(e) => e,
252             Compiletime(e) => e,
253         }
254     }
255     pub fn description(&self) -> Cow<str> {
256         match self {
257             &Runtime(ref e) => e.description(),
258             &Compiletime(ref e) => e.description(),
259         }
260     }
261 }
262
263 #[derive(Copy, Clone)]
264 pub enum TrueConst {
265     Yes, No
266 }
267
268 use self::ConstEvalFailure::*;
269
270 fn get_const_val<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
271                            def_id: DefId,
272                            ref_expr: &hir::Expr,
273                            param_substs: &'tcx Substs<'tcx>)
274                            -> Result<ValueRef, ConstEvalFailure> {
275     let expr = get_const_expr(ccx, def_id, ref_expr, param_substs);
276     let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
277     match get_const_expr_as_global(ccx, expr, ConstQualif::empty(), empty_substs, TrueConst::Yes) {
278         Err(Runtime(err)) => {
279             ccx.tcx().sess.span_err(expr.span, &err.description());
280             Err(Compiletime(err))
281         },
282         other => other,
283     }
284 }
285
286 pub fn get_const_expr_as_global<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
287                                           expr: &hir::Expr,
288                                           qualif: ConstQualif,
289                                           param_substs: &'tcx Substs<'tcx>,
290                                           trueconst: TrueConst)
291                                           -> Result<ValueRef, ConstEvalFailure> {
292     debug!("get_const_expr_as_global: {:?}", expr.id);
293     // Special-case constants to cache a common global for all uses.
294     if let hir::ExprPath(..) = expr.node {
295         // `def` must be its own statement and cannot be in the `match`
296         // otherwise the `def_map` will be borrowed for the entire match instead
297         // of just to get the `def` value
298         let def = ccx.tcx().def_map.borrow().get(&expr.id).unwrap().full_def();
299         match def {
300             Def::Const(def_id) | Def::AssociatedConst(def_id) => {
301                 if !ccx.tcx().tables.borrow().adjustments.contains_key(&expr.id) {
302                     debug!("get_const_expr_as_global ({:?}): found const {:?}",
303                            expr.id, def_id);
304                     return get_const_val(ccx, def_id, expr, param_substs);
305                 }
306             },
307             _ => {},
308         }
309     }
310
311     let key = (expr.id, param_substs);
312     if let Some(&val) = ccx.const_values().borrow().get(&key) {
313         return Ok(val);
314     }
315     let ty = monomorphize::apply_param_substs(ccx.tcx(), param_substs,
316                                               &ccx.tcx().expr_ty(expr));
317     let val = if qualif.intersects(ConstQualif::NON_STATIC_BORROWS) {
318         // Avoid autorefs as they would create global instead of stack
319         // references, even when only the latter are correct.
320         try!(const_expr_unadjusted(ccx, expr, ty, param_substs, None, trueconst))
321     } else {
322         try!(const_expr(ccx, expr, param_substs, None, trueconst)).0
323     };
324
325     // boolean SSA values are i1, but they have to be stored in i8 slots,
326     // otherwise some LLVM optimization passes don't work as expected
327     let val = unsafe {
328         if llvm::LLVMTypeOf(val) == Type::i1(ccx).to_ref() {
329             llvm::LLVMConstZExt(val, Type::i8(ccx).to_ref())
330         } else {
331             val
332         }
333     };
334
335     let lvalue = addr_of(ccx, val, type_of::align_of(ccx, ty), "const");
336     ccx.const_values().borrow_mut().insert(key, lvalue);
337     Ok(lvalue)
338 }
339
340 pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
341                             e: &hir::Expr,
342                             param_substs: &'tcx Substs<'tcx>,
343                             fn_args: FnArgMap,
344                             trueconst: TrueConst)
345                             -> Result<(ValueRef, Ty<'tcx>), ConstEvalFailure> {
346     let ety = monomorphize::apply_param_substs(cx.tcx(), param_substs,
347                                                &cx.tcx().expr_ty(e));
348     let llconst = try!(const_expr_unadjusted(cx, e, ety, param_substs, fn_args, trueconst));
349     let mut llconst = llconst;
350     let mut ety_adjusted = monomorphize::apply_param_substs(cx.tcx(), param_substs,
351                                                             &cx.tcx().expr_ty_adjusted(e));
352     let opt_adj = cx.tcx().tables.borrow().adjustments.get(&e.id).cloned();
353     match opt_adj {
354         Some(AdjustReifyFnPointer) => {
355             // FIXME(#19925) once fn item types are
356             // zero-sized, we'll need to do something here
357         }
358         Some(AdjustUnsafeFnPointer) => {
359             // purely a type-level thing
360         }
361         Some(AdjustDerefRef(adj)) => {
362             let mut ty = ety;
363             // Save the last autoderef in case we can avoid it.
364             if adj.autoderefs > 0 {
365                 for _ in 0..adj.autoderefs-1 {
366                     let (dv, dt) = const_deref(cx, llconst, ty);
367                     llconst = dv;
368                     ty = dt;
369                 }
370             }
371
372             if adj.autoref.is_some() {
373                 if adj.autoderefs == 0 {
374                     // Don't copy data to do a deref+ref
375                     // (i.e., skip the last auto-deref).
376                     llconst = addr_of(cx, llconst, type_of::align_of(cx, ty), "autoref");
377                     ty = cx.tcx().mk_imm_ref(cx.tcx().mk_region(ty::ReStatic), ty);
378                 }
379             } else {
380                 let (dv, dt) = const_deref(cx, llconst, ty);
381                 llconst = dv;
382
383                 // If we derefed a fat pointer then we will have an
384                 // open type here. So we need to update the type with
385                 // the one returned from const_deref.
386                 ety_adjusted = dt;
387             }
388
389             if let Some(target) = adj.unsize {
390                 let target = monomorphize::apply_param_substs(cx.tcx(),
391                                                               param_substs,
392                                                               &target);
393
394                 let pointee_ty = ty.builtin_deref(true, ty::NoPreference)
395                     .expect("consts: unsizing got non-pointer type").ty;
396                 let (base, old_info) = if !type_is_sized(cx.tcx(), pointee_ty) {
397                     // Normally, the source is a thin pointer and we are
398                     // adding extra info to make a fat pointer. The exception
399                     // is when we are upcasting an existing object fat pointer
400                     // to use a different vtable. In that case, we want to
401                     // load out the original data pointer so we can repackage
402                     // it.
403                     (const_get_elt(cx, llconst, &[abi::FAT_PTR_ADDR as u32]),
404                      Some(const_get_elt(cx, llconst, &[abi::FAT_PTR_EXTRA as u32])))
405                 } else {
406                     (llconst, None)
407                 };
408
409                 let unsized_ty = target.builtin_deref(true, ty::NoPreference)
410                     .expect("consts: unsizing got non-pointer target type").ty;
411                 let ptr_ty = type_of::in_memory_type_of(cx, unsized_ty).ptr_to();
412                 let base = ptrcast(base, ptr_ty);
413                 let info = base::unsized_info(cx, pointee_ty, unsized_ty,
414                                               old_info, param_substs);
415
416                 if old_info.is_none() {
417                     let prev_const = cx.const_unsized().borrow_mut()
418                                        .insert(base, llconst);
419                     assert!(prev_const.is_none() || prev_const == Some(llconst));
420                 }
421                 assert_eq!(abi::FAT_PTR_ADDR, 0);
422                 assert_eq!(abi::FAT_PTR_EXTRA, 1);
423                 llconst = C_struct(cx, &[base, info], false);
424             }
425         }
426         None => {}
427     };
428
429     let llty = type_of::sizing_type_of(cx, ety_adjusted);
430     let csize = machine::llsize_of_alloc(cx, val_ty(llconst));
431     let tsize = machine::llsize_of_alloc(cx, llty);
432     if csize != tsize {
433         cx.sess().abort_if_errors();
434         unsafe {
435             // FIXME these values could use some context
436             llvm::LLVMDumpValue(llconst);
437             llvm::LLVMDumpValue(C_undef(llty));
438         }
439         cx.sess().bug(&format!("const {:?} of type {:?} has size {} instead of {}",
440                          e, ety_adjusted,
441                          csize, tsize));
442     }
443     Ok((llconst, ety_adjusted))
444 }
445
446 fn check_unary_expr_validity(cx: &CrateContext, e: &hir::Expr, t: Ty,
447                              te: ValueRef, trueconst: TrueConst) -> Result<(), ConstEvalFailure> {
448     // The only kind of unary expression that we check for validity
449     // here is `-expr`, to check if it "overflows" (e.g. `-i32::MIN`).
450     if let hir::ExprUnary(hir::UnNeg, ref inner_e) = e.node {
451
452         // An unfortunate special case: we parse e.g. -128 as a
453         // negation of the literal 128, which means if we're expecting
454         // a i8 (or if it was already suffixed, e.g. `-128_i8`), then
455         // 128 will have already overflowed to -128, and so then the
456         // constant evaluator thinks we're trying to negate -128.
457         //
458         // Catch this up front by looking for ExprLit directly,
459         // and just accepting it.
460         if let hir::ExprLit(_) = inner_e.node { return Ok(()); }
461
462         let result = match t.sty {
463             ty::TyInt(int_type) => {
464                 let input = match const_to_opt_int(te) {
465                     Some(v) => v,
466                     None => return Ok(()),
467                 };
468                 const_int_checked_neg(
469                     input, e, Some(const_eval::IntTy::from(cx.tcx(), int_type)))
470             }
471             ty::TyUint(uint_type) => {
472                 let input = match const_to_opt_uint(te) {
473                     Some(v) => v,
474                     None => return Ok(()),
475                 };
476                 const_uint_checked_neg(
477                     input, e, Some(const_eval::UintTy::from(cx.tcx(), uint_type)))
478             }
479             _ => return Ok(()),
480         };
481         const_err(cx, e, result, trueconst)
482     } else {
483         Ok(())
484     }
485 }
486
487 fn const_err(cx: &CrateContext,
488              e: &hir::Expr,
489              result: Result<ConstVal, ConstEvalErr>,
490              trueconst: TrueConst)
491              -> Result<(), ConstEvalFailure> {
492     match (result, trueconst) {
493         (Ok(_), _) => {
494             // We do not actually care about a successful result.
495             Ok(())
496         },
497         (Err(err), TrueConst::Yes) => {
498             cx.tcx().sess.span_err(e.span, &err.description());
499             Err(Compiletime(err))
500         },
501         (Err(err), TrueConst::No) => {
502             cx.tcx().sess.span_warn(e.span, &err.description());
503             Err(Runtime(err))
504         },
505     }
506 }
507
508 fn check_binary_expr_validity(cx: &CrateContext, e: &hir::Expr, t: Ty,
509                               te1: ValueRef, te2: ValueRef,
510                               trueconst: TrueConst) -> Result<(), ConstEvalFailure> {
511     let b = if let hir::ExprBinary(b, _, _) = e.node { b } else { unreachable!() };
512
513     let result = match t.sty {
514         ty::TyInt(int_type) => {
515             let (lhs, rhs) = match (const_to_opt_int(te1),
516                                     const_to_opt_int(te2)) {
517                 (Some(v1), Some(v2)) => (v1, v2),
518                 _ => return Ok(()),
519             };
520
521             let opt_ety = Some(const_eval::IntTy::from(cx.tcx(), int_type));
522             match b.node {
523                 hir::BiAdd => const_int_checked_add(lhs, rhs, e, opt_ety),
524                 hir::BiSub => const_int_checked_sub(lhs, rhs, e, opt_ety),
525                 hir::BiMul => const_int_checked_mul(lhs, rhs, e, opt_ety),
526                 hir::BiDiv => const_int_checked_div(lhs, rhs, e, opt_ety),
527                 hir::BiRem => const_int_checked_rem(lhs, rhs, e, opt_ety),
528                 hir::BiShl => const_int_checked_shl(lhs, rhs, e, opt_ety),
529                 hir::BiShr => const_int_checked_shr(lhs, rhs, e, opt_ety),
530                 _ => return Ok(()),
531             }
532         }
533         ty::TyUint(uint_type) => {
534             let (lhs, rhs) = match (const_to_opt_uint(te1),
535                                     const_to_opt_uint(te2)) {
536                 (Some(v1), Some(v2)) => (v1, v2),
537                 _ => return Ok(()),
538             };
539
540             let opt_ety = Some(const_eval::UintTy::from(cx.tcx(), uint_type));
541             match b.node {
542                 hir::BiAdd => const_uint_checked_add(lhs, rhs, e, opt_ety),
543                 hir::BiSub => const_uint_checked_sub(lhs, rhs, e, opt_ety),
544                 hir::BiMul => const_uint_checked_mul(lhs, rhs, e, opt_ety),
545                 hir::BiDiv => const_uint_checked_div(lhs, rhs, e, opt_ety),
546                 hir::BiRem => const_uint_checked_rem(lhs, rhs, e, opt_ety),
547                 hir::BiShl => const_uint_checked_shl(lhs, rhs, e, opt_ety),
548                 hir::BiShr => const_uint_checked_shr(lhs, rhs, e, opt_ety),
549                 _ => return Ok(()),
550             }
551         }
552         _ => return Ok(()),
553     };
554     const_err(cx, e, result, trueconst)
555 }
556
557 fn const_expr_unadjusted<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>,
558                                    e: &hir::Expr,
559                                    ety: Ty<'tcx>,
560                                    param_substs: &'tcx Substs<'tcx>,
561                                    fn_args: FnArgMap,
562                                    trueconst: TrueConst)
563                                    -> Result<ValueRef, ConstEvalFailure>
564 {
565     debug!("const_expr_unadjusted(e={:?}, ety={:?}, param_substs={:?})",
566            e,
567            ety,
568            param_substs);
569
570     let map_list = |exprs: &[P<hir::Expr>]| -> Result<Vec<ValueRef>, ConstEvalFailure> {
571         exprs.iter()
572              .map(|e| const_expr(cx, &**e, param_substs, fn_args, trueconst).map(|(l, _)| l))
573              .collect::<Vec<Result<ValueRef, ConstEvalFailure>>>()
574              .into_iter()
575              .collect()
576          // this dance is necessary to eagerly run const_expr so all errors are reported
577     };
578     let _icx = push_ctxt("const_expr");
579     Ok(match e.node {
580         hir::ExprLit(ref lit) => const_lit(cx, e, &**lit),
581         hir::ExprBinary(b, ref e1, ref e2) => {
582             /* Neither type is bottom, and we expect them to be unified
583              * already, so the following is safe. */
584             let (te1, ty) = try!(const_expr(cx, &**e1, param_substs, fn_args, trueconst));
585             debug!("const_expr_unadjusted: te1={}, ty={:?}",
586                    cx.tn().val_to_string(te1),
587                    ty);
588             assert!(!ty.is_simd());
589             let is_float = ty.is_fp();
590             let signed = ty.is_signed();
591
592             let (te2, _) = try!(const_expr(cx, &**e2, param_substs, fn_args, trueconst));
593
594             try!(check_binary_expr_validity(cx, e, ty, te1, te2, trueconst));
595
596             unsafe { match b.node {
597                 hir::BiAdd if is_float => llvm::LLVMConstFAdd(te1, te2),
598                 hir::BiAdd             => llvm::LLVMConstAdd(te1, te2),
599
600                 hir::BiSub if is_float => llvm::LLVMConstFSub(te1, te2),
601                 hir::BiSub             => llvm::LLVMConstSub(te1, te2),
602
603                 hir::BiMul if is_float => llvm::LLVMConstFMul(te1, te2),
604                 hir::BiMul             => llvm::LLVMConstMul(te1, te2),
605
606                 hir::BiDiv if is_float => llvm::LLVMConstFDiv(te1, te2),
607                 hir::BiDiv if signed   => llvm::LLVMConstSDiv(te1, te2),
608                 hir::BiDiv             => llvm::LLVMConstUDiv(te1, te2),
609
610                 hir::BiRem if is_float => llvm::LLVMConstFRem(te1, te2),
611                 hir::BiRem if signed   => llvm::LLVMConstSRem(te1, te2),
612                 hir::BiRem             => llvm::LLVMConstURem(te1, te2),
613
614                 hir::BiAnd    => llvm::LLVMConstAnd(te1, te2),
615                 hir::BiOr     => llvm::LLVMConstOr(te1, te2),
616                 hir::BiBitXor => llvm::LLVMConstXor(te1, te2),
617                 hir::BiBitAnd => llvm::LLVMConstAnd(te1, te2),
618                 hir::BiBitOr  => llvm::LLVMConstOr(te1, te2),
619                 hir::BiShl    => {
620                     let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
621                     llvm::LLVMConstShl(te1, te2)
622                 },
623                 hir::BiShr    => {
624                     let te2 = base::cast_shift_const_rhs(b.node, te1, te2);
625                     if signed { llvm::LLVMConstAShr(te1, te2) }
626                     else      { llvm::LLVMConstLShr(te1, te2) }
627                 },
628                 hir::BiEq | hir::BiNe | hir::BiLt | hir::BiLe | hir::BiGt | hir::BiGe => {
629                     if is_float {
630                         let cmp = base::bin_op_to_fcmp_predicate(cx, b.node);
631                         ConstFCmp(cmp, te1, te2)
632                     } else {
633                         let cmp = base::bin_op_to_icmp_predicate(cx, b.node, signed);
634                         ConstICmp(cmp, te1, te2)
635                     }
636                 },
637             } } // unsafe { match b.node {
638         },
639         hir::ExprUnary(u, ref inner_e) => {
640             let (te, ty) = try!(const_expr(cx, &**inner_e, param_substs, fn_args, trueconst));
641
642             try!(check_unary_expr_validity(cx, e, ty, te, trueconst));
643
644             let is_float = ty.is_fp();
645             unsafe { match u {
646                 hir::UnDeref           => const_deref(cx, te, ty).0,
647                 hir::UnNot             => llvm::LLVMConstNot(te),
648                 hir::UnNeg if is_float => llvm::LLVMConstFNeg(te),
649                 hir::UnNeg             => llvm::LLVMConstNeg(te),
650             } }
651         },
652         hir::ExprField(ref base, field) => {
653             let (bv, bt) = try!(const_expr(cx, &**base, param_substs, fn_args, trueconst));
654             let brepr = adt::represent_type(cx, bt);
655             let vinfo = VariantInfo::from_ty(cx.tcx(), bt, None);
656             let ix = vinfo.field_index(field.node);
657             adt::const_get_field(cx, &*brepr, bv, vinfo.discr, ix)
658         },
659         hir::ExprTupField(ref base, idx) => {
660             let (bv, bt) = try!(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             adt::const_get_field(cx, &*brepr, bv, vinfo.discr, idx.node)
664         },
665         hir::ExprIndex(ref base, ref index) => {
666             let (bv, bt) = try!(const_expr(cx, &**base, param_substs, fn_args, trueconst));
667             let iv = match eval_const_expr_partial(cx.tcx(), &index, ExprTypeChecked, None) {
668                 Ok(ConstVal::Int(i)) => i as u64,
669                 Ok(ConstVal::Uint(u)) => u,
670                 _ => cx.sess().span_bug(index.span,
671                                         "index is not an integer-constant expression")
672             };
673             let (arr, len) = match bt.sty {
674                 ty::TyArray(_, u) => (bv, C_uint(cx, u)),
675                 ty::TySlice(_) | ty::TyStr => {
676                     let e1 = const_get_elt(cx, bv, &[0]);
677                     (const_deref_ptr(cx, e1), const_get_elt(cx, bv, &[1]))
678                 },
679                 ty::TyRef(_, mt) => match mt.ty.sty {
680                     ty::TyArray(_, u) => {
681                         (const_deref_ptr(cx, bv), C_uint(cx, u))
682                     },
683                     _ => cx.sess().span_bug(base.span,
684                                             &format!("index-expr base must be a vector \
685                                                       or string type, found {:?}",
686                                                      bt)),
687                 },
688                 _ => cx.sess().span_bug(base.span,
689                                         &format!("index-expr base must be a vector \
690                                                   or string type, found {:?}",
691                                                  bt)),
692             };
693
694             let len = unsafe { llvm::LLVMConstIntGetZExtValue(len) as u64 };
695             let len = match bt.sty {
696                 ty::TyBox(ty) | ty::TyRef(_, ty::TypeAndMut{ty, ..}) => match ty.sty {
697                     ty::TyStr => {
698                         assert!(len > 0);
699                         len - 1
700                     },
701                     _ => len,
702                 },
703                 _ => len,
704             };
705             if iv >= len {
706                 // FIXME #3170: report this earlier on in the const-eval
707                 // pass. Reporting here is a bit late.
708                 span_err!(cx.sess(), e.span, E0515,
709                           "const index-expr is out of bounds");
710                 C_undef(val_ty(arr).element_type())
711             } else {
712                 const_get_elt(cx, arr, &[iv as c_uint])
713             }
714         },
715         hir::ExprCast(ref base, _) => {
716             let t_cast = ety;
717             let llty = type_of::type_of(cx, t_cast);
718             let (v, t_expr) = try!(const_expr(cx, &**base, param_substs, fn_args, trueconst));
719             debug!("trans_const_cast({:?} as {:?})", t_expr, t_cast);
720             if expr::cast_is_noop(cx.tcx(), base, t_expr, t_cast) {
721                 return Ok(v);
722             }
723             if type_is_fat_ptr(cx.tcx(), t_expr) {
724                 // Fat pointer casts.
725                 let t_cast_inner =
726                     t_cast.builtin_deref(true, ty::NoPreference).expect("cast to non-pointer").ty;
727                 let ptr_ty = type_of::in_memory_type_of(cx, t_cast_inner).ptr_to();
728                 let addr = ptrcast(const_get_elt(cx, v, &[abi::FAT_PTR_ADDR as u32]),
729                                    ptr_ty);
730                 if type_is_fat_ptr(cx.tcx(), t_cast) {
731                     let info = const_get_elt(cx, v, &[abi::FAT_PTR_EXTRA as u32]);
732                     return Ok(C_struct(cx, &[addr, info], false))
733                 } else {
734                     return Ok(addr);
735                 }
736             }
737             unsafe { match (
738                 CastTy::from_ty(t_expr).expect("bad input type for cast"),
739                 CastTy::from_ty(t_cast).expect("bad output type for cast"),
740             ) {
741                 (CastTy::Int(IntTy::CEnum), CastTy::Int(_)) => {
742                     let repr = adt::represent_type(cx, t_expr);
743                     let discr = adt::const_get_discrim(cx, &*repr, v);
744                     let iv = C_integral(cx.int_type(), discr.0, false);
745                     let s = adt::is_discr_signed(&*repr) as Bool;
746                     llvm::LLVMConstIntCast(iv, llty.to_ref(), s)
747                 },
748                 (CastTy::Int(_), CastTy::Int(_)) => {
749                     let s = t_expr.is_signed() as Bool;
750                     llvm::LLVMConstIntCast(v, llty.to_ref(), s)
751                 },
752                 (CastTy::Int(_), CastTy::Float) => {
753                     if t_expr.is_signed() {
754                         llvm::LLVMConstSIToFP(v, llty.to_ref())
755                     } else {
756                         llvm::LLVMConstUIToFP(v, llty.to_ref())
757                     }
758                 },
759                 (CastTy::Float, CastTy::Float) => llvm::LLVMConstFPCast(v, llty.to_ref()),
760                 (CastTy::Float, CastTy::Int(IntTy::I)) => llvm::LLVMConstFPToSI(v, llty.to_ref()),
761                 (CastTy::Float, CastTy::Int(_)) => llvm::LLVMConstFPToUI(v, llty.to_ref()),
762                 (CastTy::Ptr(_), CastTy::Ptr(_)) | (CastTy::FnPtr, CastTy::Ptr(_))
763                 | (CastTy::RPtr(_), CastTy::Ptr(_)) => {
764                     ptrcast(v, llty)
765                 },
766                 (CastTy::FnPtr, CastTy::FnPtr) => ptrcast(v, llty), // isn't this a coercion?
767                 (CastTy::Int(_), CastTy::Ptr(_)) => llvm::LLVMConstIntToPtr(v, llty.to_ref()),
768                 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
769                   llvm::LLVMConstPtrToInt(v, llty.to_ref())
770                 },
771                 _ => {
772                   cx.sess().impossible_case(e.span,
773                                             "bad combination of types for cast")
774                 },
775             } } // unsafe { match ( ... ) {
776         },
777         hir::ExprAddrOf(hir::MutImmutable, ref sub) => {
778             // If this is the address of some static, then we need to return
779             // the actual address of the static itself (short circuit the rest
780             // of const eval).
781             let mut cur = sub;
782             loop {
783                 match cur.node {
784                     hir::ExprBlock(ref blk) => {
785                         if let Some(ref sub) = blk.expr {
786                             cur = sub;
787                         } else {
788                             break;
789                         }
790                     },
791                     _ => break,
792                 }
793             }
794             let opt_def = cx.tcx().def_map.borrow().get(&cur.id).map(|d| d.full_def());
795             if let Some(Def::Static(def_id, _)) = opt_def {
796                 common::get_static_val(cx, def_id, ety)
797             } else {
798                 // If this isn't the address of a static, then keep going through
799                 // normal constant evaluation.
800                 let (v, ty) = try!(const_expr(cx, &**sub, param_substs, fn_args, trueconst));
801                 addr_of(cx, v, type_of::align_of(cx, ty), "ref")
802             }
803         },
804         hir::ExprAddrOf(hir::MutMutable, ref sub) => {
805             let (v, ty) = try!(const_expr(cx, &**sub, param_substs, fn_args, trueconst));
806             addr_of_mut(cx, v, type_of::align_of(cx, ty), "ref_mut_slice")
807         },
808         hir::ExprTup(ref es) => {
809             let repr = adt::represent_type(cx, ety);
810             let vals = try!(map_list(&es[..]));
811             adt::trans_const(cx, &*repr, Disr(0), &vals[..])
812         },
813         hir::ExprStruct(_, ref fs, ref base_opt) => {
814             let repr = adt::represent_type(cx, ety);
815
816             let base_val = match *base_opt {
817                 Some(ref base) => Some(try!(const_expr(
818                     cx,
819                     &**base,
820                     param_substs,
821                     fn_args,
822                     trueconst,
823                 ))),
824                 None => None
825             };
826
827             let VariantInfo { discr, fields } = VariantInfo::of_node(cx.tcx(), ety, e.id);
828             let cs = fields.iter().enumerate().map(|(ix, &Field(f_name, _))| {
829                 match (fs.iter().find(|f| f_name == f.name.node), base_val) {
830                     (Some(ref f), _) => {
831                         const_expr(cx, &*f.expr, param_substs, fn_args, trueconst).map(|(l, _)| l)
832                     },
833                     (_, Some((bv, _))) => Ok(adt::const_get_field(cx, &*repr, bv, discr, ix)),
834                     (_, None) => cx.sess().span_bug(e.span, "missing struct field"),
835                 }
836             })
837             .collect::<Vec<Result<_, ConstEvalFailure>>>()
838             .into_iter()
839             .collect::<Result<Vec<_>,ConstEvalFailure>>();
840             let cs = try!(cs);
841             if ety.is_simd() {
842                 C_vector(&cs[..])
843             } else {
844                 adt::trans_const(cx, &*repr, discr, &cs[..])
845             }
846         },
847         hir::ExprVec(ref es) => {
848             let unit_ty = ety.sequence_element_type(cx.tcx());
849             let llunitty = type_of::type_of(cx, unit_ty);
850             let vs = es.iter()
851                        .map(|e| const_expr(
852                            cx,
853                            &**e,
854                            param_substs,
855                            fn_args,
856                            trueconst,
857                        ).map(|(l, _)| l))
858                        .collect::<Vec<Result<_, ConstEvalFailure>>>()
859                        .into_iter()
860                        .collect::<Result<Vec<_>, ConstEvalFailure>>();
861             let vs = try!(vs);
862             // If the vector contains enums, an LLVM array won't work.
863             if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
864                 C_struct(cx, &vs[..], false)
865             } else {
866                 C_array(llunitty, &vs[..])
867             }
868         },
869         hir::ExprRepeat(ref elem, ref count) => {
870             let unit_ty = ety.sequence_element_type(cx.tcx());
871             let llunitty = type_of::type_of(cx, unit_ty);
872             let n = cx.tcx().eval_repeat_count(count);
873             let unit_val = try!(const_expr(cx, &**elem, param_substs, fn_args, trueconst)).0;
874             let vs = vec![unit_val; n];
875             if val_ty(unit_val) != llunitty {
876                 C_struct(cx, &vs[..], false)
877             } else {
878                 C_array(llunitty, &vs[..])
879             }
880         },
881         hir::ExprPath(..) => {
882             let def = cx.tcx().def_map.borrow().get(&e.id).unwrap().full_def();
883             match def {
884                 Def::Local(_, id) => {
885                     if let Some(val) = fn_args.and_then(|args| args.get(&id).cloned()) {
886                         val
887                     } else {
888                         cx.sess().span_bug(e.span, "const fn argument not found")
889                     }
890                 }
891                 Def::Fn(..) | Def::Method(..) => {
892                     expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
893                 }
894                 Def::Const(def_id) | Def::AssociatedConst(def_id) => {
895                     const_deref_ptr(cx, try!(get_const_val(cx, def_id, e, param_substs)))
896                 }
897                 Def::Variant(enum_did, variant_did) => {
898                     let vinfo = cx.tcx().lookup_adt_def(enum_did).variant_with_id(variant_did);
899                     match vinfo.kind() {
900                         ty::VariantKind::Unit => {
901                             let repr = adt::represent_type(cx, ety);
902                             adt::trans_const(cx, &*repr, Disr::from(vinfo.disr_val), &[])
903                         }
904                         ty::VariantKind::Tuple => {
905                             expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
906                         }
907                         ty::VariantKind::Struct => {
908                             cx.sess().span_bug(e.span, "path-expr refers to a dict variant!")
909                         }
910                     }
911                 }
912                 Def::Struct(..) => {
913                     if let ty::TyBareFn(..) = ety.sty {
914                         // Tuple struct.
915                         expr::trans_def_fn_unadjusted(cx, e, def, param_substs).val
916                     } else {
917                         // Unit struct.
918                         C_null(type_of::type_of(cx, ety))
919                     }
920                 }
921                 _ => {
922                     cx.sess().span_bug(e.span, "expected a const, fn, struct, \
923                                                 or variant def")
924                 }
925             }
926         },
927         hir::ExprCall(ref callee, ref args) => {
928             let mut callee = &**callee;
929             loop {
930                 callee = match callee.node {
931                     hir::ExprBlock(ref block) => match block.expr {
932                         Some(ref tail) => &**tail,
933                         None => break,
934                     },
935                     _ => break,
936                 };
937             }
938             let def = cx.tcx().def_map.borrow()[&callee.id].full_def();
939             let arg_vals = try!(map_list(args));
940             match def {
941                 Def::Fn(did) | Def::Method(did) => {
942                     try!(const_fn_call(
943                         cx,
944                         ExprId(callee.id),
945                         did,
946                         &arg_vals,
947                         param_substs,
948                         trueconst,
949                     ))
950                 }
951                 Def::Struct(..) => {
952                     if ety.is_simd() {
953                         C_vector(&arg_vals[..])
954                     } else {
955                         let repr = adt::represent_type(cx, ety);
956                         adt::trans_const(cx, &*repr, Disr(0), &arg_vals[..])
957                     }
958                 }
959                 Def::Variant(enum_did, variant_did) => {
960                     let repr = adt::represent_type(cx, ety);
961                     let vinfo = cx.tcx().lookup_adt_def(enum_did).variant_with_id(variant_did);
962                     adt::trans_const(cx,
963                                      &*repr,
964                                      Disr::from(vinfo.disr_val),
965                                      &arg_vals[..])
966                 }
967                 _ => cx.sess().span_bug(e.span, "expected a struct, variant, or const fn def"),
968             }
969         },
970         hir::ExprMethodCall(_, _, ref args) => {
971             let arg_vals = try!(map_list(args));
972             let method_call = ty::MethodCall::expr(e.id);
973             let method_did = cx.tcx().tables.borrow().method_map[&method_call].def_id;
974             try!(const_fn_call(cx, MethodCallKey(method_call),
975                                method_did, &arg_vals, param_substs, trueconst))
976         },
977         hir::ExprType(ref e, _) => try!(const_expr(cx, &**e, param_substs, fn_args, trueconst)).0,
978         hir::ExprBlock(ref block) => {
979             match block.expr {
980                 Some(ref expr) => try!(const_expr(
981                     cx,
982                     &**expr,
983                     param_substs,
984                     fn_args,
985                     trueconst,
986                 )).0,
987                 None => C_nil(cx),
988             }
989         },
990         hir::ExprClosure(_, ref decl, ref body) => {
991             match ety.sty {
992                 ty::TyClosure(def_id, ref substs) => {
993                     closure::trans_closure_expr(closure::Dest::Ignore(cx),
994                                                 decl,
995                                                 body,
996                                                 e.id,
997                                                 def_id,
998                                                 substs,
999                                                 &e.attrs);
1000                 }
1001                 _ =>
1002                     cx.sess().span_bug(
1003                         e.span,
1004                         &format!("bad type for closure expr: {:?}", ety))
1005             }
1006             C_null(type_of::type_of(cx, ety))
1007         },
1008         _ => cx.sess().span_bug(e.span,
1009                                 "bad constant expression type in consts::const_expr"),
1010     })
1011 }
1012
1013 pub fn trans_static(ccx: &CrateContext,
1014                     m: hir::Mutability,
1015                     expr: &hir::Expr,
1016                     id: ast::NodeId,
1017                     attrs: &[ast::Attribute])
1018                     -> Result<ValueRef, ConstEvalErr> {
1019     unsafe {
1020         let _icx = push_ctxt("trans_static");
1021         let g = base::get_item_val(ccx, id);
1022
1023         let empty_substs = ccx.tcx().mk_substs(Substs::trans_empty());
1024         let (v, _) = try!(const_expr(
1025             ccx,
1026             expr,
1027             empty_substs,
1028             None,
1029             TrueConst::Yes,
1030         ).map_err(|e| e.into_inner()));
1031
1032         // boolean SSA values are i1, but they have to be stored in i8 slots,
1033         // otherwise some LLVM optimization passes don't work as expected
1034         let mut val_llty = llvm::LLVMTypeOf(v);
1035         let v = if val_llty == Type::i1(ccx).to_ref() {
1036             val_llty = Type::i8(ccx).to_ref();
1037             llvm::LLVMConstZExt(v, val_llty)
1038         } else {
1039             v
1040         };
1041
1042         let ty = ccx.tcx().node_id_to_type(id);
1043         let llty = type_of::type_of(ccx, ty);
1044         let g = if val_llty == llty.to_ref() {
1045             g
1046         } else {
1047             // If we created the global with the wrong type,
1048             // correct the type.
1049             let empty_string = CString::new("").unwrap();
1050             let name_str_ref = CStr::from_ptr(llvm::LLVMGetValueName(g));
1051             let name_string = CString::new(name_str_ref.to_bytes()).unwrap();
1052             llvm::LLVMSetValueName(g, empty_string.as_ptr());
1053             let new_g = llvm::LLVMGetOrInsertGlobal(
1054                 ccx.llmod(), name_string.as_ptr(), val_llty);
1055             // To avoid breaking any invariants, we leave around the old
1056             // global for the moment; we'll replace all references to it
1057             // with the new global later. (See base::trans_crate.)
1058             ccx.statics_to_rauw().borrow_mut().push((g, new_g));
1059             new_g
1060         };
1061         llvm::LLVMSetAlignment(g, type_of::align_of(ccx, ty));
1062         llvm::LLVMSetInitializer(g, v);
1063
1064         // As an optimization, all shared statics which do not have interior
1065         // mutability are placed into read-only memory.
1066         if m != hir::MutMutable {
1067             let tcontents = ty.type_contents(ccx.tcx());
1068             if !tcontents.interior_unsafe() {
1069                 llvm::LLVMSetGlobalConstant(g, llvm::True);
1070             }
1071         }
1072
1073         debuginfo::create_global_var_metadata(ccx, id, g);
1074
1075         if attr::contains_name(attrs,
1076                                "thread_local") {
1077             llvm::set_thread_local(g, true);
1078         }
1079         Ok(g)
1080     }
1081 }