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