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