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