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