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