]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/consts.rs
remove AdjustAddEnv
[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, PrivateLinkage, ValueRef, Bool, True, False};
15 use llvm::{IntEQ, IntNE, IntUGT, IntUGE, IntULT, IntULE, IntSGT, IntSGE, IntSLT, IntSLE,
16            RealOEQ, RealOGT, RealOGE, RealOLT, RealOLE, RealONE};
17 use middle::{const_eval, def};
18 use trans::{adt, closure, consts, debuginfo, expr, inline, machine};
19 use trans::base::{self, push_ctxt};
20 use trans::common::*;
21 use trans::type_::Type;
22 use trans::type_of;
23 use middle::subst::Substs;
24 use middle::ty::{self, Ty};
25 use util::ppaux::{Repr, ty_to_string};
26
27 use std::c_str::ToCStr;
28 use std::iter::repeat;
29 use libc::c_uint;
30 use syntax::{ast, ast_util};
31 use syntax::ptr::P;
32
33 pub fn const_lit(cx: &CrateContext, e: &ast::Expr, lit: &ast::Lit)
34     -> ValueRef {
35     let _icx = push_ctxt("trans_lit");
36     debug!("const_lit: {}", lit);
37     match lit.node {
38         ast::LitByte(b) => C_integral(Type::uint_from_ty(cx, ast::TyU8), b as u64, false),
39         ast::LitChar(i) => C_integral(Type::char(cx), i as u64, false),
40         ast::LitInt(i, ast::SignedIntLit(t, _)) => {
41             C_integral(Type::int_from_ty(cx, t), i, true)
42         }
43         ast::LitInt(u, ast::UnsignedIntLit(t)) => {
44             C_integral(Type::uint_from_ty(cx, t), u, false)
45         }
46         ast::LitInt(i, ast::UnsuffixedIntLit(_)) => {
47             let lit_int_ty = ty::node_id_to_type(cx.tcx(), e.id);
48             match lit_int_ty.sty {
49                 ty::ty_int(t) => {
50                     C_integral(Type::int_from_ty(cx, t), i as u64, true)
51                 }
52                 ty::ty_uint(t) => {
53                     C_integral(Type::uint_from_ty(cx, t), i as u64, false)
54                 }
55                 _ => cx.sess().span_bug(lit.span,
56                         format!("integer literal has type {} (expected int \
57                                  or uint)",
58                                 ty_to_string(cx.tcx(), lit_int_ty))[])
59             }
60         }
61         ast::LitFloat(ref fs, t) => {
62             C_floating(fs.get(), Type::float_from_ty(cx, t))
63         }
64         ast::LitFloatUnsuffixed(ref fs) => {
65             let lit_float_ty = ty::node_id_to_type(cx.tcx(), e.id);
66             match lit_float_ty.sty {
67                 ty::ty_float(t) => {
68                     C_floating(fs.get(), Type::float_from_ty(cx, t))
69                 }
70                 _ => {
71                     cx.sess().span_bug(lit.span,
72                         "floating point literal doesn't have the right type");
73                 }
74             }
75         }
76         ast::LitBool(b) => C_bool(cx, b),
77         ast::LitStr(ref s, _) => C_str_slice(cx, (*s).clone()),
78         ast::LitBinary(ref data) => C_binary_slice(cx, data[]),
79     }
80 }
81
82 pub fn ptrcast(val: ValueRef, ty: Type) -> ValueRef {
83     unsafe {
84         llvm::LLVMConstPointerCast(val, ty.to_ref())
85     }
86 }
87
88 fn const_vec(cx: &CrateContext, e: &ast::Expr,
89              es: &[P<ast::Expr>]) -> (ValueRef, Type) {
90     let vec_ty = ty::expr_ty(cx.tcx(), e);
91     let unit_ty = ty::sequence_element_type(cx.tcx(), vec_ty);
92     let llunitty = type_of::type_of(cx, unit_ty);
93     let vs = es.iter().map(|e| const_expr(cx, &**e).0)
94                       .collect::<Vec<_>>();
95     // If the vector contains enums, an LLVM array won't work.
96     let v = if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
97         C_struct(cx, vs[], false)
98     } else {
99         C_array(llunitty, vs[])
100     };
101     (v, llunitty)
102 }
103
104 pub fn const_addr_of(cx: &CrateContext, cv: ValueRef, mutbl: ast::Mutability) -> ValueRef {
105     unsafe {
106         let gv = "const".with_c_str(|name| {
107             llvm::LLVMAddGlobal(cx.llmod(), val_ty(cv).to_ref(), name)
108         });
109         llvm::LLVMSetInitializer(gv, cv);
110         llvm::LLVMSetGlobalConstant(gv,
111                                     if mutbl == ast::MutImmutable {True} else {False});
112         SetLinkage(gv, PrivateLinkage);
113         gv
114     }
115 }
116
117 fn const_deref_ptr(cx: &CrateContext, v: ValueRef) -> ValueRef {
118     let v = match cx.const_globals().borrow().get(&(v as int)) {
119         Some(&v) => v,
120         None => v
121     };
122     unsafe {
123         llvm::LLVMGetInitializer(v)
124     }
125 }
126
127 fn const_deref_newtype<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, v: ValueRef, t: Ty<'tcx>)
128     -> ValueRef {
129     let repr = adt::represent_type(cx, t);
130     adt::const_get_field(cx, &*repr, v, 0, 0)
131 }
132
133 fn const_deref<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, v: ValueRef,
134                          t: Ty<'tcx>, explicit: bool)
135                          -> (ValueRef, Ty<'tcx>) {
136     match ty::deref(t, explicit) {
137         Some(ref mt) => {
138             match t.sty {
139                 ty::ty_ptr(mt) | ty::ty_rptr(_, mt) => {
140                     if type_is_sized(cx.tcx(), mt.ty) {
141                         (const_deref_ptr(cx, v), mt.ty)
142                     } else {
143                         // Derefing a fat pointer does not change the representation,
144                         // just the type to ty_open.
145                         (v, ty::mk_open(cx.tcx(), mt.ty))
146                     }
147                 }
148                 ty::ty_enum(..) | ty::ty_struct(..) => {
149                     assert!(mt.mutbl != ast::MutMutable);
150                     (const_deref_newtype(cx, v, t), mt.ty)
151                 }
152                 _ => {
153                     cx.sess().bug(format!("unexpected dereferenceable type {}",
154                                           ty_to_string(cx.tcx(), t))[])
155                 }
156             }
157         }
158         None => {
159             cx.sess().bug(format!("cannot dereference const of type {}",
160                                   ty_to_string(cx.tcx(), t))[])
161         }
162     }
163 }
164
165 pub fn get_const_val(cx: &CrateContext,
166                      mut def_id: ast::DefId) -> ValueRef {
167     let contains_key = cx.const_values().borrow().contains_key(&def_id.node);
168     if !ast_util::is_local(def_id) || !contains_key {
169         if !ast_util::is_local(def_id) {
170             def_id = inline::maybe_instantiate_inline(cx, def_id);
171         }
172
173         if let ast::ItemConst(..) = cx.tcx().map.expect_item(def_id.node).node {
174             base::get_item_val(cx, def_id.node);
175         }
176     }
177
178     cx.const_values().borrow()[def_id.node].clone()
179 }
180
181 pub fn const_expr<'a, 'tcx>(cx: &CrateContext<'a, 'tcx>, e: &ast::Expr)
182                             -> (ValueRef, Ty<'tcx>) {
183     let llconst = const_expr_unadjusted(cx, e);
184     let mut llconst = llconst;
185     let ety = ty::expr_ty(cx.tcx(), e);
186     let mut ety_adjusted = ty::expr_ty_adjusted(cx.tcx(), e);
187     let opt_adj = cx.tcx().adjustments.borrow().get(&e.id).cloned();
188     match opt_adj {
189         None => { }
190         Some(adj) => {
191             match adj {
192                 ty::AdjustReifyFnPointer(_def_id) => {
193                     // FIXME(#19925) once fn item types are
194                     // zero-sized, we'll need to do something here
195                 }
196                 ty::AdjustDerefRef(ref adj) => {
197                     let mut ty = ety;
198                     // Save the last autoderef in case we can avoid it.
199                     if adj.autoderefs > 0 {
200                         for _ in range(0, adj.autoderefs-1) {
201                             let (dv, dt) = const_deref(cx, llconst, ty, false);
202                             llconst = dv;
203                             ty = dt;
204                         }
205                     }
206
207                     match adj.autoref {
208                         None => {
209                             let (dv, dt) = const_deref(cx, llconst, ty, false);
210                             llconst = dv;
211
212                             // If we derefed a fat pointer then we will have an
213                             // open type here. So we need to update the type with
214                             // the one returned from const_deref.
215                             ety_adjusted = dt;
216                         }
217                         Some(ref autoref) => {
218                             match *autoref {
219                                 ty::AutoUnsafe(_, None) |
220                                 ty::AutoPtr(ty::ReStatic, _, None) => {
221                                     // Don't copy data to do a deref+ref
222                                     // (i.e., skip the last auto-deref).
223                                     if adj.autoderefs == 0 {
224                                         llconst = const_addr_of(cx, llconst, ast::MutImmutable);
225                                     }
226                                 }
227                                 ty::AutoPtr(ty::ReStatic, _, Some(box ty::AutoUnsize(..))) => {
228                                     if adj.autoderefs > 0 {
229                                         // Seeing as we are deref'ing here and take a reference
230                                         // again to make the pointer part of the far pointer below,
231                                         // we just skip the whole thing. We still need the type
232                                         // though. This works even if we don't need to deref
233                                         // because of byref semantics. Note that this is not just
234                                         // an optimisation, it is necessary for mutable vectors to
235                                         // work properly.
236                                         let (_, dt) = const_deref(cx, llconst, ty, false);
237                                         ty = dt;
238                                     } else {
239                                         llconst = const_addr_of(cx, llconst, ast::MutImmutable)
240                                     }
241
242                                     match ty.sty {
243                                         ty::ty_vec(unit_ty, Some(len)) => {
244                                             let llunitty = type_of::type_of(cx, unit_ty);
245                                             let llptr = ptrcast(llconst, llunitty.ptr_to());
246                                             assert!(cx.const_globals().borrow_mut()
247                                                       .insert(llptr as int, llconst).is_none());
248                                             assert_eq!(abi::FAT_PTR_ADDR, 0);
249                                             assert_eq!(abi::FAT_PTR_EXTRA, 1);
250                                             llconst = C_struct(cx, &[
251                                                 llptr,
252                                                 C_uint(cx, len)
253                                             ], false);
254                                         }
255                                         _ => cx.sess().span_bug(e.span,
256                                             format!("unimplemented type in const unsize: {}",
257                                                     ty_to_string(cx.tcx(), ty))[])
258                                     }
259                                 }
260                                 _ => {
261                                     cx.sess()
262                                       .span_bug(e.span,
263                                                 format!("unimplemented const \
264                                                          autoref {}",
265                                                         autoref)[])
266                                 }
267                             }
268                         }
269                     }
270                 }
271             }
272         }
273     }
274
275     let llty = type_of::sizing_type_of(cx, ety_adjusted);
276     let csize = machine::llsize_of_alloc(cx, val_ty(llconst));
277     let tsize = machine::llsize_of_alloc(cx, llty);
278     if csize != tsize {
279         unsafe {
280             // FIXME these values could use some context
281             llvm::LLVMDumpValue(llconst);
282             llvm::LLVMDumpValue(C_undef(llty));
283         }
284         cx.sess().bug(format!("const {} of type {} has size {} instead of {}",
285                          e.repr(cx.tcx()), ty_to_string(cx.tcx(), ety),
286                          csize, tsize)[]);
287     }
288     (llconst, ety_adjusted)
289 }
290
291 // the bool returned is whether this expression can be inlined into other crates
292 // if it's assigned to a static.
293 fn const_expr_unadjusted(cx: &CrateContext, e: &ast::Expr) -> ValueRef {
294     let map_list = |&: exprs: &[P<ast::Expr>]| {
295         exprs.iter().map(|e| const_expr(cx, &**e).0)
296              .fold(Vec::new(), |mut l, val| { l.push(val); l })
297     };
298     unsafe {
299         let _icx = push_ctxt("const_expr");
300         return match e.node {
301           ast::ExprLit(ref lit) => {
302               consts::const_lit(cx, e, &**lit)
303           }
304           ast::ExprBinary(b, ref e1, ref e2) => {
305             let (te1, _) = const_expr(cx, &**e1);
306             let (te2, _) = const_expr(cx, &**e2);
307
308             let te2 = base::cast_shift_const_rhs(b, te1, te2);
309
310             /* Neither type is bottom, and we expect them to be unified
311              * already, so the following is safe. */
312             let ty = ty::expr_ty(cx.tcx(), &**e1);
313             let is_float = ty::type_is_fp(ty);
314             let signed = ty::type_is_signed(ty);
315             return match b {
316               ast::BiAdd   => {
317                 if is_float { llvm::LLVMConstFAdd(te1, te2) }
318                 else        { llvm::LLVMConstAdd(te1, te2) }
319               }
320               ast::BiSub => {
321                 if is_float { llvm::LLVMConstFSub(te1, te2) }
322                 else        { llvm::LLVMConstSub(te1, te2) }
323               }
324               ast::BiMul    => {
325                 if is_float { llvm::LLVMConstFMul(te1, te2) }
326                 else        { llvm::LLVMConstMul(te1, te2) }
327               }
328               ast::BiDiv    => {
329                 if is_float    { llvm::LLVMConstFDiv(te1, te2) }
330                 else if signed { llvm::LLVMConstSDiv(te1, te2) }
331                 else           { llvm::LLVMConstUDiv(te1, te2) }
332               }
333               ast::BiRem    => {
334                 if is_float    { llvm::LLVMConstFRem(te1, te2) }
335                 else if signed { llvm::LLVMConstSRem(te1, te2) }
336                 else           { llvm::LLVMConstURem(te1, te2) }
337               }
338               ast::BiAnd    => llvm::LLVMConstAnd(te1, te2),
339               ast::BiOr     => llvm::LLVMConstOr(te1, te2),
340               ast::BiBitXor => llvm::LLVMConstXor(te1, te2),
341               ast::BiBitAnd => llvm::LLVMConstAnd(te1, te2),
342               ast::BiBitOr  => llvm::LLVMConstOr(te1, te2),
343               ast::BiShl    => llvm::LLVMConstShl(te1, te2),
344               ast::BiShr    => {
345                 if signed { llvm::LLVMConstAShr(te1, te2) }
346                 else      { llvm::LLVMConstLShr(te1, te2) }
347               }
348               ast::BiEq     => {
349                   if is_float { ConstFCmp(RealOEQ, te1, te2) }
350                   else        { ConstICmp(IntEQ, te1, te2)   }
351               },
352               ast::BiLt     => {
353                   if is_float { ConstFCmp(RealOLT, te1, te2) }
354                   else        {
355                       if signed { ConstICmp(IntSLT, te1, te2) }
356                       else      { ConstICmp(IntULT, te1, te2) }
357                   }
358               },
359               ast::BiLe     => {
360                   if is_float { ConstFCmp(RealOLE, te1, te2) }
361                   else        {
362                       if signed { ConstICmp(IntSLE, te1, te2) }
363                       else      { ConstICmp(IntULE, te1, te2) }
364                   }
365               },
366               ast::BiNe     => {
367                   if is_float { ConstFCmp(RealONE, te1, te2) }
368                   else        { ConstICmp(IntNE, te1, te2) }
369               },
370               ast::BiGe     => {
371                   if is_float { ConstFCmp(RealOGE, te1, te2) }
372                   else        {
373                       if signed { ConstICmp(IntSGE, te1, te2) }
374                       else      { ConstICmp(IntUGE, te1, te2) }
375                   }
376               },
377               ast::BiGt     => {
378                   if is_float { ConstFCmp(RealOGT, te1, te2) }
379                   else        {
380                       if signed { ConstICmp(IntSGT, te1, te2) }
381                       else      { ConstICmp(IntUGT, te1, te2) }
382                   }
383               },
384             }
385           },
386           ast::ExprUnary(u, ref e) => {
387             let (te, _) = const_expr(cx, &**e);
388             let ty = ty::expr_ty(cx.tcx(), &**e);
389             let is_float = ty::type_is_fp(ty);
390             return match u {
391               ast::UnUniq | ast::UnDeref => {
392                 let (dv, _dt) = const_deref(cx, te, ty, true);
393                 dv
394               }
395               ast::UnNot    => llvm::LLVMConstNot(te),
396               ast::UnNeg    => {
397                 if is_float { llvm::LLVMConstFNeg(te) }
398                 else        { llvm::LLVMConstNeg(te) }
399               }
400             }
401           }
402           ast::ExprField(ref base, field) => {
403               let (bv, bt) = const_expr(cx, &**base);
404               let brepr = adt::represent_type(cx, bt);
405               expr::with_field_tys(cx.tcx(), bt, None, |discr, field_tys| {
406                   let ix = ty::field_idx_strict(cx.tcx(), field.node.name, field_tys);
407                   adt::const_get_field(cx, &*brepr, bv, discr, ix)
408               })
409           }
410           ast::ExprTupField(ref base, idx) => {
411               let (bv, bt) = const_expr(cx, &**base);
412               let brepr = adt::represent_type(cx, bt);
413               expr::with_field_tys(cx.tcx(), bt, None, |discr, _| {
414                   adt::const_get_field(cx, &*brepr, bv, discr, idx.node)
415               })
416           }
417
418           ast::ExprIndex(ref base, ref index) => {
419               let (bv, bt) = const_expr(cx, &**base);
420               let iv = match const_eval::eval_const_expr(cx.tcx(), &**index) {
421                   const_eval::const_int(i) => i as u64,
422                   const_eval::const_uint(u) => u,
423                   _ => cx.sess().span_bug(index.span,
424                                           "index is not an integer-constant expression")
425               };
426               let (arr, len) = match bt.sty {
427                   ty::ty_vec(_, Some(u)) => (bv, C_uint(cx, u)),
428                   ty::ty_open(ty) => match ty.sty {
429                       ty::ty_vec(_, None) | ty::ty_str => {
430                           let e1 = const_get_elt(cx, bv, &[0]);
431                           (const_deref_ptr(cx, e1), const_get_elt(cx, bv, &[1]))
432                       },
433                       _ => cx.sess().span_bug(base.span,
434                                               format!("index-expr base must be a vector \
435                                                        or string type, found {}",
436                                                       ty_to_string(cx.tcx(), bt))[])
437                   },
438                   ty::ty_rptr(_, mt) => match mt.ty.sty {
439                       ty::ty_vec(_, Some(u)) => {
440                           (const_deref_ptr(cx, bv), C_uint(cx, u))
441                       },
442                       _ => cx.sess().span_bug(base.span,
443                                               format!("index-expr base must be a vector \
444                                                        or string type, found {}",
445                                                       ty_to_string(cx.tcx(), bt))[])
446                   },
447                   _ => cx.sess().span_bug(base.span,
448                                           format!("index-expr base must be a vector \
449                                                    or string type, found {}",
450                                                   ty_to_string(cx.tcx(), bt))[])
451               };
452
453               let len = llvm::LLVMConstIntGetZExtValue(len) as u64;
454               let len = match bt.sty {
455                   ty::ty_uniq(ty) | ty::ty_rptr(_, ty::mt{ty, ..}) => match ty.sty {
456                       ty::ty_str => {
457                           assert!(len > 0);
458                           len - 1
459                       }
460                       _ => len
461                   },
462                   _ => len
463               };
464               if iv >= len {
465                   // FIXME #3170: report this earlier on in the const-eval
466                   // pass. Reporting here is a bit late.
467                   cx.sess().span_err(e.span,
468                                      "const index-expr is out of bounds");
469               }
470               const_get_elt(cx, arr, &[iv as c_uint])
471           }
472           ast::ExprCast(ref base, _) => {
473             let ety = ty::expr_ty(cx.tcx(), e);
474             let llty = type_of::type_of(cx, ety);
475             let (v, basety) = const_expr(cx, &**base);
476             return match (expr::cast_type_kind(cx.tcx(), basety),
477                            expr::cast_type_kind(cx.tcx(), ety)) {
478
479               (expr::cast_integral, expr::cast_integral) => {
480                 let s = ty::type_is_signed(basety) as Bool;
481                 llvm::LLVMConstIntCast(v, llty.to_ref(), s)
482               }
483               (expr::cast_integral, expr::cast_float) => {
484                 if ty::type_is_signed(basety) {
485                     llvm::LLVMConstSIToFP(v, llty.to_ref())
486                 } else {
487                     llvm::LLVMConstUIToFP(v, llty.to_ref())
488                 }
489               }
490               (expr::cast_float, expr::cast_float) => {
491                 llvm::LLVMConstFPCast(v, llty.to_ref())
492               }
493               (expr::cast_float, expr::cast_integral) => {
494                 if ty::type_is_signed(ety) { llvm::LLVMConstFPToSI(v, llty.to_ref()) }
495                 else { llvm::LLVMConstFPToUI(v, llty.to_ref()) }
496               }
497               (expr::cast_enum, expr::cast_integral) => {
498                 let repr = adt::represent_type(cx, basety);
499                 let discr = adt::const_get_discrim(cx, &*repr, v);
500                 let iv = C_integral(cx.int_type(), discr, false);
501                 let ety_cast = expr::cast_type_kind(cx.tcx(), ety);
502                 match ety_cast {
503                     expr::cast_integral => {
504                         let s = ty::type_is_signed(ety) as Bool;
505                         llvm::LLVMConstIntCast(iv, llty.to_ref(), s)
506                     }
507                     _ => cx.sess().bug("enum cast destination is not \
508                                         integral")
509                 }
510               }
511               (expr::cast_pointer, expr::cast_pointer) => {
512                 ptrcast(v, llty)
513               }
514               (expr::cast_integral, expr::cast_pointer) => {
515                 llvm::LLVMConstIntToPtr(v, llty.to_ref())
516               }
517               (expr::cast_pointer, expr::cast_integral) => {
518                 llvm::LLVMConstPtrToInt(v, llty.to_ref())
519               }
520               _ => {
521                 cx.sess().impossible_case(e.span,
522                                           "bad combination of types for cast")
523               }
524             }
525           }
526           ast::ExprAddrOf(mutbl, ref sub) => {
527               // If this is the address of some static, then we need to return
528               // the actual address of the static itself (short circuit the rest
529               // of const eval).
530               let mut cur = sub;
531               loop {
532                   match cur.node {
533                       ast::ExprParen(ref sub) => cur = sub,
534                       _ => break,
535                   }
536               }
537               let opt_def = cx.tcx().def_map.borrow().get(&cur.id).cloned();
538               if let Some(def::DefStatic(def_id, _)) = opt_def {
539                   let ty = ty::expr_ty(cx.tcx(), e);
540                   return get_static_val(cx, def_id, ty);
541               }
542
543               // If this isn't the address of a static, then keep going through
544               // normal constant evaluation.
545               let (e, _) = const_expr(cx, &**sub);
546               const_addr_of(cx, e, mutbl)
547           }
548           ast::ExprTup(ref es) => {
549               let ety = ty::expr_ty(cx.tcx(), e);
550               let repr = adt::represent_type(cx, ety);
551               let vals = map_list(es[]);
552               adt::trans_const(cx, &*repr, 0, vals[])
553           }
554           ast::ExprStruct(_, ref fs, ref base_opt) => {
555               let ety = ty::expr_ty(cx.tcx(), e);
556               let repr = adt::represent_type(cx, ety);
557               let tcx = cx.tcx();
558
559               let base_val = match *base_opt {
560                 Some(ref base) => Some(const_expr(cx, &**base)),
561                 None => None
562               };
563
564               expr::with_field_tys(tcx, ety, Some(e.id), |discr, field_tys| {
565                   let cs = field_tys.iter().enumerate()
566                                     .map(|(ix, &field_ty)| {
567                       match fs.iter().find(|f| field_ty.name == f.ident.node.name) {
568                           Some(ref f) => const_expr(cx, &*f.expr).0,
569                           None => {
570                               match base_val {
571                                   Some((bv, _)) => {
572                                       adt::const_get_field(cx, &*repr, bv,
573                                                            discr, ix)
574                                   }
575                                   None => {
576                                       cx.sess().span_bug(e.span,
577                                                          "missing struct field")
578                                   }
579                               }
580                           }
581                       }
582                   }).collect::<Vec<_>>();
583                   adt::trans_const(cx, &*repr, discr, cs[])
584               })
585           }
586           ast::ExprVec(ref es) => {
587             const_vec(cx, e, es.as_slice()).0
588           }
589           ast::ExprRepeat(ref elem, ref count) => {
590             let vec_ty = ty::expr_ty(cx.tcx(), e);
591             let unit_ty = ty::sequence_element_type(cx.tcx(), vec_ty);
592             let llunitty = type_of::type_of(cx, unit_ty);
593             let n = match const_eval::eval_const_expr(cx.tcx(), &**count) {
594                 const_eval::const_int(i)  => i as uint,
595                 const_eval::const_uint(i) => i as uint,
596                 _ => cx.sess().span_bug(count.span, "count must be integral const expression.")
597             };
598             let vs: Vec<_> = repeat(const_expr(cx, &**elem).0).take(n).collect();
599             if vs.iter().any(|vi| val_ty(*vi) != llunitty) {
600                 C_struct(cx, vs[], false)
601             } else {
602                 C_array(llunitty, vs[])
603             }
604           }
605           ast::ExprPath(_) => {
606             let def = cx.tcx().def_map.borrow()[e.id];
607             match def {
608                 def::DefFn(..) | def::DefStaticMethod(..) | def::DefMethod(..) => {
609                     expr::trans_def_fn_unadjusted(cx, e, def, &Substs::trans_empty()).val
610                 }
611                 def::DefConst(def_id) => {
612                     get_const_val(cx, def_id)
613                 }
614                 def::DefVariant(enum_did, variant_did, _) => {
615                     let vinfo = ty::enum_variant_with_id(cx.tcx(),
616                                                          enum_did,
617                                                          variant_did);
618                     if vinfo.args.len() > 0 {
619                         // N-ary variant.
620                         expr::trans_def_fn_unadjusted(cx, e, def, &Substs::trans_empty()).val
621                     } else {
622                         // Nullary variant.
623                         let ety = ty::expr_ty(cx.tcx(), e);
624                         let repr = adt::represent_type(cx, ety);
625                         adt::trans_const(cx, &*repr, vinfo.disr_val, &[])
626                     }
627                 }
628                 def::DefStruct(_) => {
629                     let ety = ty::expr_ty(cx.tcx(), e);
630                     if let ty::ty_bare_fn(..) = ety.sty {
631                         // Tuple struct.
632                         expr::trans_def_fn_unadjusted(cx, e, def, &Substs::trans_empty()).val
633                     } else {
634                         // Unit struct.
635                         C_null(type_of::type_of(cx, ety))
636                     }
637                 }
638                 _ => {
639                     cx.sess().span_bug(e.span, "expected a const, fn, struct, \
640                                                 or variant def")
641                 }
642             }
643           }
644           ast::ExprCall(ref callee, ref args) => {
645               let opt_def = cx.tcx().def_map.borrow().get(&callee.id).cloned();
646               match opt_def {
647                   Some(def::DefStruct(_)) => {
648                       let ety = ty::expr_ty(cx.tcx(), e);
649                       let repr = adt::represent_type(cx, ety);
650                       let arg_vals = map_list(args[]);
651                       adt::trans_const(cx, &*repr, 0, arg_vals[])
652                   }
653                   Some(def::DefVariant(enum_did, variant_did, _)) => {
654                       let ety = ty::expr_ty(cx.tcx(), e);
655                       let repr = adt::represent_type(cx, ety);
656                       let vinfo = ty::enum_variant_with_id(cx.tcx(),
657                                                            enum_did,
658                                                            variant_did);
659                       let arg_vals = map_list(args[]);
660                       adt::trans_const(cx,
661                                        &*repr,
662                                        vinfo.disr_val,
663                                        arg_vals[])
664                   }
665                   _ => cx.sess().span_bug(e.span, "expected a struct or variant def")
666               }
667           }
668           ast::ExprParen(ref e) => const_expr(cx, &**e).0,
669           ast::ExprBlock(ref block) => {
670             match block.expr {
671                 Some(ref expr) => const_expr(cx, &**expr).0,
672                 None => C_nil(cx)
673             }
674           }
675           _ => cx.sess().span_bug(e.span,
676                   "bad constant expression type in consts::const_expr")
677         };
678     }
679 }
680
681 pub fn trans_static(ccx: &CrateContext, m: ast::Mutability, id: ast::NodeId) {
682     unsafe {
683         let _icx = push_ctxt("trans_static");
684         let g = base::get_item_val(ccx, id);
685         // At this point, get_item_val has already translated the
686         // constant's initializer to determine its LLVM type.
687         let v = ccx.static_values().borrow()[id].clone();
688         // boolean SSA values are i1, but they have to be stored in i8 slots,
689         // otherwise some LLVM optimization passes don't work as expected
690         let v = if llvm::LLVMTypeOf(v) == Type::i1(ccx).to_ref() {
691             llvm::LLVMConstZExt(v, Type::i8(ccx).to_ref())
692         } else {
693             v
694         };
695         llvm::LLVMSetInitializer(g, v);
696
697         // As an optimization, all shared statics which do not have interior
698         // mutability are placed into read-only memory.
699         if m != ast::MutMutable {
700             let node_ty = ty::node_id_to_type(ccx.tcx(), id);
701             let tcontents = ty::type_contents(ccx.tcx(), node_ty);
702             if !tcontents.interior_unsafe() {
703                 llvm::LLVMSetGlobalConstant(g, True);
704             }
705         }
706         debuginfo::create_global_var_metadata(ccx, id, g);
707     }
708 }
709
710 fn get_static_val<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, did: ast::DefId,
711                             ty: Ty<'tcx>) -> ValueRef {
712     if ast_util::is_local(did) { return base::get_item_val(ccx, did.node) }
713     base::trans_external_path(ccx, did, ty)
714 }