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