]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/mir/constant.rs
393fa9c0c8e0e8291072d856ccf90f70cbe05e6d
[rust.git] / src / librustc_trans / mir / constant.rs
1 // Copyright 2012-2014 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 use llvm::{self, ValueRef};
12 use rustc::middle::const_val::{ConstEvalErr, ConstVal, ErrKind};
13 use rustc_const_math::ConstInt::*;
14 use rustc_const_math::ConstFloat::*;
15 use rustc_const_math::{ConstInt, ConstMathErr};
16 use rustc::hir::def_id::DefId;
17 use rustc::infer::TransNormalize;
18 use rustc::mir;
19 use rustc::mir::tcx::LvalueTy;
20 use rustc::ty::{self, Ty, TyCtxt, TypeFoldable};
21 use rustc::ty::layout::{self, LayoutTyper};
22 use rustc::ty::cast::{CastTy, IntTy};
23 use rustc::ty::subst::{Kind, Substs, Subst};
24 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
25 use {adt, base, machine};
26 use abi::{self, Abi};
27 use callee;
28 use builder::Builder;
29 use common::{self, CrateContext, const_get_elt, val_ty};
30 use common::{C_array, C_bool, C_bytes, C_floating_f64, C_integral, C_big_integral};
31 use common::{C_null, C_struct, C_str_slice, C_undef, C_uint, C_vector, is_undef};
32 use common::const_to_opt_u128;
33 use consts;
34 use monomorphize;
35 use type_of;
36 use type_::Type;
37 use value::Value;
38
39 use syntax_pos::Span;
40
41 use std::fmt;
42 use std::ptr;
43
44 use super::lvalue::Alignment;
45 use super::operand::{OperandRef, OperandValue};
46 use super::MirContext;
47
48 /// A sized constant rvalue.
49 /// The LLVM type might not be the same for a single Rust type,
50 /// e.g. each enum variant would have its own LLVM struct type.
51 #[derive(Copy, Clone)]
52 pub struct Const<'tcx> {
53     pub llval: ValueRef,
54     pub ty: Ty<'tcx>
55 }
56
57 impl<'tcx> Const<'tcx> {
58     pub fn new(llval: ValueRef, ty: Ty<'tcx>) -> Const<'tcx> {
59         Const {
60             llval: llval,
61             ty: ty
62         }
63     }
64
65     pub fn from_constint<'a>(ccx: &CrateContext<'a, 'tcx>, ci: &ConstInt)
66     -> Const<'tcx> {
67         let tcx = ccx.tcx();
68         let (llval, ty) = match *ci {
69             I8(v) => (C_integral(Type::i8(ccx), v as u64, true), tcx.types.i8),
70             I16(v) => (C_integral(Type::i16(ccx), v as u64, true), tcx.types.i16),
71             I32(v) => (C_integral(Type::i32(ccx), v as u64, true), tcx.types.i32),
72             I64(v) => (C_integral(Type::i64(ccx), v as u64, true), tcx.types.i64),
73             I128(v) => (C_big_integral(Type::i128(ccx), v as u128), tcx.types.i128),
74             Isize(v) => {
75                 let i = v.as_i64(ccx.tcx().sess.target.int_type);
76                 (C_integral(Type::int(ccx), i as u64, true), tcx.types.isize)
77             },
78             U8(v) => (C_integral(Type::i8(ccx), v as u64, false), tcx.types.u8),
79             U16(v) => (C_integral(Type::i16(ccx), v as u64, false), tcx.types.u16),
80             U32(v) => (C_integral(Type::i32(ccx), v as u64, false), tcx.types.u32),
81             U64(v) => (C_integral(Type::i64(ccx), v, false), tcx.types.u64),
82             U128(v) => (C_big_integral(Type::i128(ccx), v), tcx.types.u128),
83             Usize(v) => {
84                 let u = v.as_u64(ccx.tcx().sess.target.uint_type);
85                 (C_integral(Type::int(ccx), u, false), tcx.types.usize)
86             },
87         };
88         Const { llval: llval, ty: ty }
89     }
90
91     /// Translate ConstVal into a LLVM constant value.
92     pub fn from_constval<'a>(ccx: &CrateContext<'a, 'tcx>,
93                              cv: ConstVal,
94                              ty: Ty<'tcx>)
95                              -> Const<'tcx> {
96         let llty = type_of::type_of(ccx, ty);
97         let val = match cv {
98             ConstVal::Float(F32(v)) => C_floating_f64(v as f64, llty),
99             ConstVal::Float(F64(v)) => C_floating_f64(v, llty),
100             ConstVal::Bool(v) => C_bool(ccx, v),
101             ConstVal::Integral(ref i) => return Const::from_constint(ccx, i),
102             ConstVal::Str(ref v) => C_str_slice(ccx, v.clone()),
103             ConstVal::ByteStr(ref v) => consts::addr_of(ccx, C_bytes(ccx, v), 1, "byte_str"),
104             ConstVal::Char(c) => C_integral(Type::char(ccx), c as u64, false),
105             ConstVal::Function(..) => C_null(type_of::type_of(ccx, ty)),
106             ConstVal::Variant(_) |
107             ConstVal::Struct(_) | ConstVal::Tuple(_) |
108             ConstVal::Array(..) | ConstVal::Repeat(..) => {
109                 bug!("MIR must not use `{:?}` (aggregates are expanded to MIR rvalues)", cv)
110             }
111         };
112
113         assert!(!ty.has_erasable_regions());
114
115         Const::new(val, ty)
116     }
117
118     fn get_pair(&self) -> (ValueRef, ValueRef) {
119         (const_get_elt(self.llval, &[0]),
120          const_get_elt(self.llval, &[1]))
121     }
122
123     fn get_fat_ptr(&self) -> (ValueRef, ValueRef) {
124         assert_eq!(abi::FAT_PTR_ADDR, 0);
125         assert_eq!(abi::FAT_PTR_EXTRA, 1);
126         self.get_pair()
127     }
128
129     fn as_lvalue(&self) -> ConstLvalue<'tcx> {
130         ConstLvalue {
131             base: Base::Value(self.llval),
132             llextra: ptr::null_mut(),
133             ty: self.ty
134         }
135     }
136
137     pub fn to_operand<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> OperandRef<'tcx> {
138         let llty = type_of::immediate_type_of(ccx, self.ty);
139         let llvalty = val_ty(self.llval);
140
141         let val = if llty == llvalty && common::type_is_imm_pair(ccx, self.ty) {
142             let (a, b) = self.get_pair();
143             OperandValue::Pair(a, b)
144         } else if llty == llvalty && common::type_is_immediate(ccx, self.ty) {
145             // If the types match, we can use the value directly.
146             OperandValue::Immediate(self.llval)
147         } else {
148             // Otherwise, or if the value is not immediate, we create
149             // a constant LLVM global and cast its address if necessary.
150             let align = ccx.align_of(self.ty);
151             let ptr = consts::addr_of(ccx, self.llval, align, "const");
152             OperandValue::Ref(consts::ptrcast(ptr, llty.ptr_to()), Alignment::AbiAligned)
153         };
154
155         OperandRef {
156             val: val,
157             ty: self.ty
158         }
159     }
160 }
161
162 impl<'tcx> fmt::Debug for Const<'tcx> {
163     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
164         write!(f, "Const({:?}: {:?})", Value(self.llval), self.ty)
165     }
166 }
167
168 #[derive(Copy, Clone)]
169 enum Base {
170     /// A constant value without an unique address.
171     Value(ValueRef),
172
173     /// String literal base pointer (cast from array).
174     Str(ValueRef),
175
176     /// The address of a static.
177     Static(ValueRef)
178 }
179
180 /// An lvalue as seen from a constant.
181 #[derive(Copy, Clone)]
182 struct ConstLvalue<'tcx> {
183     base: Base,
184     llextra: ValueRef,
185     ty: Ty<'tcx>
186 }
187
188 impl<'tcx> ConstLvalue<'tcx> {
189     fn to_const(&self, span: Span) -> Const<'tcx> {
190         match self.base {
191             Base::Value(val) => Const::new(val, self.ty),
192             Base::Str(ptr) => {
193                 span_bug!(span, "loading from `str` ({:?}) in constant",
194                           Value(ptr))
195             }
196             Base::Static(val) => {
197                 span_bug!(span, "loading from `static` ({:?}) in constant",
198                           Value(val))
199             }
200         }
201     }
202
203     pub fn len<'a>(&self, ccx: &CrateContext<'a, 'tcx>) -> ValueRef {
204         match self.ty.sty {
205             ty::TyArray(_, n) => C_uint(ccx, n),
206             ty::TySlice(_) | ty::TyStr => {
207                 assert!(self.llextra != ptr::null_mut());
208                 self.llextra
209             }
210             _ => bug!("unexpected type `{}` in ConstLvalue::len", self.ty)
211         }
212     }
213 }
214
215 /// Machinery for translating a constant's MIR to LLVM values.
216 /// FIXME(eddyb) use miri and lower its allocations to LLVM.
217 struct MirConstContext<'a, 'tcx: 'a> {
218     ccx: &'a CrateContext<'a, 'tcx>,
219     mir: &'a mir::Mir<'tcx>,
220
221     /// Type parameters for const fn and associated constants.
222     substs: &'tcx Substs<'tcx>,
223
224     /// Values of locals in a constant or const fn.
225     locals: IndexVec<mir::Local, Option<Result<Const<'tcx>, ConstEvalErr<'tcx>>>>
226 }
227
228 fn add_err<'tcx, U, V>(failure: &mut Result<U, ConstEvalErr<'tcx>>,
229                        value: &Result<V, ConstEvalErr<'tcx>>)
230 {
231     if let &Err(ref err) = value {
232         if failure.is_ok() {
233             *failure = Err(err.clone());
234         }
235     }
236 }
237
238 impl<'a, 'tcx> MirConstContext<'a, 'tcx> {
239     fn new(ccx: &'a CrateContext<'a, 'tcx>,
240            mir: &'a mir::Mir<'tcx>,
241            substs: &'tcx Substs<'tcx>,
242            args: IndexVec<mir::Local, Result<Const<'tcx>, ConstEvalErr<'tcx>>>)
243            -> MirConstContext<'a, 'tcx> {
244         let mut context = MirConstContext {
245             ccx: ccx,
246             mir: mir,
247             substs: substs,
248             locals: (0..mir.local_decls.len()).map(|_| None).collect(),
249         };
250         for (i, arg) in args.into_iter().enumerate() {
251             // Locals after local 0 are the function arguments
252             let index = mir::Local::new(i + 1);
253             context.locals[index] = Some(arg);
254         }
255         context
256     }
257
258     fn trans_def(ccx: &'a CrateContext<'a, 'tcx>,
259                  def_id: DefId,
260                  substs: &'tcx Substs<'tcx>,
261                  args: IndexVec<mir::Local, Result<Const<'tcx>, ConstEvalErr<'tcx>>>)
262                  -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
263         let instance = monomorphize::resolve(ccx.shared(), def_id, substs);
264         let mir = ccx.tcx().instance_mir(instance.def);
265         MirConstContext::new(ccx, &mir, instance.substs, args).trans()
266     }
267
268     fn monomorphize<T>(&self, value: &T) -> T
269         where T: TransNormalize<'tcx>
270     {
271         self.ccx.tcx().trans_apply_param_substs(self.substs, value)
272     }
273
274     fn trans(&mut self) -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
275         let tcx = self.ccx.tcx();
276         let mut bb = mir::START_BLOCK;
277
278         // Make sure to evaluate all statemenets to
279         // report as many errors as we possibly can.
280         let mut failure = Ok(());
281
282         loop {
283             let data = &self.mir[bb];
284             for statement in &data.statements {
285                 let span = statement.source_info.span;
286                 match statement.kind {
287                     mir::StatementKind::Assign(ref dest, ref rvalue) => {
288                         let ty = dest.ty(self.mir, tcx);
289                         let ty = self.monomorphize(&ty).to_ty(tcx);
290                         let value = self.const_rvalue(rvalue, ty, span);
291                         add_err(&mut failure, &value);
292                         self.store(dest, value, span);
293                     }
294                     mir::StatementKind::StorageLive(_) |
295                     mir::StatementKind::StorageDead(_) |
296                     mir::StatementKind::EndRegion(_) |
297                     mir::StatementKind::Nop => {}
298                     mir::StatementKind::InlineAsm { .. } |
299                     mir::StatementKind::SetDiscriminant{ .. } => {
300                         span_bug!(span, "{:?} should not appear in constants?", statement.kind);
301                     }
302                 }
303             }
304
305             let terminator = data.terminator();
306             let span = terminator.source_info.span;
307             bb = match terminator.kind {
308                 mir::TerminatorKind::Drop { target, .. } | // No dropping.
309                 mir::TerminatorKind::Goto { target } => target,
310                 mir::TerminatorKind::Return => {
311                     failure?;
312                     return self.locals[mir::RETURN_POINTER].clone().unwrap_or_else(|| {
313                         span_bug!(span, "no returned value in constant");
314                     });
315                 }
316
317                 mir::TerminatorKind::Assert { ref cond, expected, ref msg, target, .. } => {
318                     let cond = self.const_operand(cond, span)?;
319                     let cond_bool = common::const_to_uint(cond.llval) != 0;
320                     if cond_bool != expected {
321                         let err = match *msg {
322                             mir::AssertMessage::BoundsCheck { ref len, ref index } => {
323                                 let len = self.const_operand(len, span)?;
324                                 let index = self.const_operand(index, span)?;
325                                 ErrKind::IndexOutOfBounds {
326                                     len: common::const_to_uint(len.llval),
327                                     index: common::const_to_uint(index.llval)
328                                 }
329                             }
330                             mir::AssertMessage::Math(ref err) => {
331                                 ErrKind::Math(err.clone())
332                             }
333                         };
334
335                         let err = ConstEvalErr { span: span, kind: err };
336                         err.report(tcx, span, "expression");
337                         failure = Err(err);
338                     }
339                     target
340                 }
341
342                 mir::TerminatorKind::Call { ref func, ref args, ref destination, .. } => {
343                     let fn_ty = func.ty(self.mir, tcx);
344                     let fn_ty = self.monomorphize(&fn_ty);
345                     let (def_id, substs) = match fn_ty.sty {
346                         ty::TyFnDef(def_id, substs) => (def_id, substs),
347                         _ => span_bug!(span, "calling {:?} (of type {}) in constant",
348                                        func, fn_ty)
349                     };
350
351                     let mut arg_vals = IndexVec::with_capacity(args.len());
352                     for arg in args {
353                         let arg_val = self.const_operand(arg, span);
354                         add_err(&mut failure, &arg_val);
355                         arg_vals.push(arg_val);
356                     }
357                     if let Some((ref dest, target)) = *destination {
358                         let result = if fn_ty.fn_sig(tcx).abi() == Abi::RustIntrinsic {
359                             match &tcx.item_name(def_id).as_str()[..] {
360                                 "size_of" => {
361                                     let llval = C_uint(self.ccx,
362                                         self.ccx.size_of(substs.type_at(0)));
363                                     Ok(Const::new(llval, tcx.types.usize))
364                                 }
365                                 "min_align_of" => {
366                                     let llval = C_uint(self.ccx,
367                                         self.ccx.align_of(substs.type_at(0)));
368                                     Ok(Const::new(llval, tcx.types.usize))
369                                 }
370                                 _ => span_bug!(span, "{:?} in constant", terminator.kind)
371                             }
372                         } else {
373                             MirConstContext::trans_def(self.ccx, def_id, substs, arg_vals)
374                         };
375                         add_err(&mut failure, &result);
376                         self.store(dest, result, span);
377                         target
378                     } else {
379                         span_bug!(span, "diverging {:?} in constant", terminator.kind);
380                     }
381                 }
382                 _ => span_bug!(span, "{:?} in constant", terminator.kind)
383             };
384         }
385     }
386
387     fn store(&mut self,
388              dest: &mir::Lvalue<'tcx>,
389              value: Result<Const<'tcx>, ConstEvalErr<'tcx>>,
390              span: Span) {
391         if let mir::Lvalue::Local(index) = *dest {
392             self.locals[index] = Some(value);
393         } else {
394             span_bug!(span, "assignment to {:?} in constant", dest);
395         }
396     }
397
398     fn const_lvalue(&self, lvalue: &mir::Lvalue<'tcx>, span: Span)
399                     -> Result<ConstLvalue<'tcx>, ConstEvalErr<'tcx>> {
400         let tcx = self.ccx.tcx();
401
402         if let mir::Lvalue::Local(index) = *lvalue {
403             return self.locals[index].clone().unwrap_or_else(|| {
404                 span_bug!(span, "{:?} not initialized", lvalue)
405             }).map(|v| v.as_lvalue());
406         }
407
408         let lvalue = match *lvalue {
409             mir::Lvalue::Local(_)  => bug!(), // handled above
410             mir::Lvalue::Static(box mir::Static { def_id, ty }) => {
411                 ConstLvalue {
412                     base: Base::Static(consts::get_static(self.ccx, def_id)),
413                     llextra: ptr::null_mut(),
414                     ty: self.monomorphize(&ty),
415                 }
416             }
417             mir::Lvalue::Projection(ref projection) => {
418                 let tr_base = self.const_lvalue(&projection.base, span)?;
419                 let projected_ty = LvalueTy::Ty { ty: tr_base.ty }
420                     .projection_ty(tcx, &projection.elem);
421                 let base = tr_base.to_const(span);
422                 let projected_ty = self.monomorphize(&projected_ty).to_ty(tcx);
423                 let is_sized = self.ccx.shared().type_is_sized(projected_ty);
424
425                 let (projected, llextra) = match projection.elem {
426                     mir::ProjectionElem::Deref => {
427                         let (base, extra) = if is_sized {
428                             (base.llval, ptr::null_mut())
429                         } else {
430                             base.get_fat_ptr()
431                         };
432                         if self.ccx.statics().borrow().contains_key(&base) {
433                             (Base::Static(base), extra)
434                         } else if let ty::TyStr = projected_ty.sty {
435                             (Base::Str(base), extra)
436                         } else {
437                             let v = base;
438                             let v = self.ccx.const_unsized().borrow().get(&v).map_or(v, |&v| v);
439                             let mut val = unsafe { llvm::LLVMGetInitializer(v) };
440                             if val.is_null() {
441                                 span_bug!(span, "dereference of non-constant pointer `{:?}`",
442                                           Value(base));
443                             }
444                             if projected_ty.is_bool() {
445                                 let i1_type = Type::i1(self.ccx);
446                                 if val_ty(val) != i1_type {
447                                     unsafe {
448                                         val = llvm::LLVMConstTrunc(val, i1_type.to_ref());
449                                     }
450                                 }
451                             }
452                             (Base::Value(val), extra)
453                         }
454                     }
455                     mir::ProjectionElem::Field(ref field, _) => {
456                         let llprojected = adt::const_get_field(self.ccx, tr_base.ty, base.llval,
457                                                                field.index());
458                         let llextra = if is_sized {
459                             ptr::null_mut()
460                         } else {
461                             tr_base.llextra
462                         };
463                         (Base::Value(llprojected), llextra)
464                     }
465                     mir::ProjectionElem::Index(ref index) => {
466                         let llindex = self.const_operand(index, span)?.llval;
467
468                         let iv = if let Some(iv) = common::const_to_opt_u128(llindex, false) {
469                             iv
470                         } else {
471                             span_bug!(span, "index is not an integer-constant expression")
472                         };
473
474                         // Produce an undef instead of a LLVM assertion on OOB.
475                         let len = common::const_to_uint(tr_base.len(self.ccx));
476                         let llelem = if iv < len as u128 {
477                             const_get_elt(base.llval, &[iv as u32])
478                         } else {
479                             C_undef(type_of::type_of(self.ccx, projected_ty))
480                         };
481
482                         (Base::Value(llelem), ptr::null_mut())
483                     }
484                     _ => span_bug!(span, "{:?} in constant", projection.elem)
485                 };
486                 ConstLvalue {
487                     base: projected,
488                     llextra: llextra,
489                     ty: projected_ty
490                 }
491             }
492         };
493         Ok(lvalue)
494     }
495
496     fn const_operand(&self, operand: &mir::Operand<'tcx>, span: Span)
497                      -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
498         debug!("const_operand({:?} @ {:?})", operand, span);
499         let result = match *operand {
500             mir::Operand::Consume(ref lvalue) => {
501                 Ok(self.const_lvalue(lvalue, span)?.to_const(span))
502             }
503
504             mir::Operand::Constant(ref constant) => {
505                 let ty = self.monomorphize(&constant.ty);
506                 match constant.literal.clone() {
507                     mir::Literal::Item { def_id, substs } => {
508                         let substs = self.monomorphize(&substs);
509                         MirConstContext::trans_def(self.ccx, def_id, substs, IndexVec::new())
510                     }
511                     mir::Literal::Promoted { index } => {
512                         let mir = &self.mir.promoted[index];
513                         MirConstContext::new(self.ccx, mir, self.substs, IndexVec::new()).trans()
514                     }
515                     mir::Literal::Value { value } => {
516                         Ok(Const::from_constval(self.ccx, value, ty))
517                     }
518                 }
519             }
520         };
521         debug!("const_operand({:?} @ {:?}) = {:?}", operand, span,
522                result.as_ref().ok());
523         result
524     }
525
526     fn const_array(&self, array_ty: Ty<'tcx>, fields: &[ValueRef])
527                    -> Const<'tcx>
528     {
529         let elem_ty = array_ty.builtin_index().unwrap_or_else(|| {
530             bug!("bad array type {:?}", array_ty)
531         });
532         let llunitty = type_of::type_of(self.ccx, elem_ty);
533         // If the array contains enums, an LLVM array won't work.
534         let val = if fields.iter().all(|&f| val_ty(f) == llunitty) {
535             C_array(llunitty, fields)
536         } else {
537             C_struct(self.ccx, fields, false)
538         };
539         Const::new(val, array_ty)
540     }
541
542     fn const_rvalue(&self, rvalue: &mir::Rvalue<'tcx>,
543                     dest_ty: Ty<'tcx>, span: Span)
544                     -> Result<Const<'tcx>, ConstEvalErr<'tcx>> {
545         let tcx = self.ccx.tcx();
546         debug!("const_rvalue({:?}: {:?} @ {:?})", rvalue, dest_ty, span);
547         let val = match *rvalue {
548             mir::Rvalue::Use(ref operand) => self.const_operand(operand, span)?,
549
550             mir::Rvalue::Repeat(ref elem, ref count) => {
551                 let elem = self.const_operand(elem, span)?;
552                 let size = count.as_u64(tcx.sess.target.uint_type);
553                 let fields = vec![elem.llval; size as usize];
554                 self.const_array(dest_ty, &fields)
555             }
556
557             mir::Rvalue::Aggregate(ref kind, ref operands) => {
558                 // Make sure to evaluate all operands to
559                 // report as many errors as we possibly can.
560                 let mut fields = Vec::with_capacity(operands.len());
561                 let mut failure = Ok(());
562                 for operand in operands {
563                     match self.const_operand(operand, span) {
564                         Ok(val) => fields.push(val.llval),
565                         Err(err) => if failure.is_ok() { failure = Err(err); }
566                     }
567                 }
568                 failure?;
569
570                 match **kind {
571                     mir::AggregateKind::Array(_) => {
572                         self.const_array(dest_ty, &fields)
573                     }
574                     mir::AggregateKind::Adt(..) |
575                     mir::AggregateKind::Closure(..) |
576                     mir::AggregateKind::Tuple => {
577                         Const::new(trans_const(self.ccx, dest_ty, kind, &fields), dest_ty)
578                     }
579                 }
580             }
581
582             mir::Rvalue::Cast(ref kind, ref source, cast_ty) => {
583                 let operand = self.const_operand(source, span)?;
584                 let cast_ty = self.monomorphize(&cast_ty);
585
586                 let val = match *kind {
587                     mir::CastKind::ReifyFnPointer => {
588                         match operand.ty.sty {
589                             ty::TyFnDef(def_id, substs) => {
590                                 callee::resolve_and_get_fn(self.ccx, def_id, substs)
591                             }
592                             _ => {
593                                 span_bug!(span, "{} cannot be reified to a fn ptr",
594                                           operand.ty)
595                             }
596                         }
597                     }
598                     mir::CastKind::ClosureFnPointer => {
599                         match operand.ty.sty {
600                             ty::TyClosure(def_id, substs) => {
601                                 // Get the def_id for FnOnce::call_once
602                                 let fn_once = tcx.lang_items.fn_once_trait().unwrap();
603                                 let call_once = tcx
604                                     .global_tcx().associated_items(fn_once)
605                                     .find(|it| it.kind == ty::AssociatedKind::Method)
606                                     .unwrap().def_id;
607                                 // Now create its substs [Closure, Tuple]
608                                 let input = tcx.fn_sig(def_id)
609                                     .subst(tcx, substs.substs).input(0);
610                                 let input = tcx.erase_late_bound_regions_and_normalize(&input);
611                                 let substs = tcx.mk_substs([operand.ty, input]
612                                     .iter().cloned().map(Kind::from));
613                                 callee::resolve_and_get_fn(self.ccx, call_once, substs)
614                             }
615                             _ => {
616                                 bug!("{} cannot be cast to a fn ptr", operand.ty)
617                             }
618                         }
619                     }
620                     mir::CastKind::UnsafeFnPointer => {
621                         // this is a no-op at the LLVM level
622                         operand.llval
623                     }
624                     mir::CastKind::Unsize => {
625                         // unsize targets other than to a fat pointer currently
626                         // can't be in constants.
627                         assert!(common::type_is_fat_ptr(self.ccx, cast_ty));
628
629                         let pointee_ty = operand.ty.builtin_deref(true, ty::NoPreference)
630                             .expect("consts: unsizing got non-pointer type").ty;
631                         let (base, old_info) = if !self.ccx.shared().type_is_sized(pointee_ty) {
632                             // Normally, the source is a thin pointer and we are
633                             // adding extra info to make a fat pointer. The exception
634                             // is when we are upcasting an existing object fat pointer
635                             // to use a different vtable. In that case, we want to
636                             // load out the original data pointer so we can repackage
637                             // it.
638                             let (base, extra) = operand.get_fat_ptr();
639                             (base, Some(extra))
640                         } else {
641                             (operand.llval, None)
642                         };
643
644                         let unsized_ty = cast_ty.builtin_deref(true, ty::NoPreference)
645                             .expect("consts: unsizing got non-pointer target type").ty;
646                         let ptr_ty = type_of::in_memory_type_of(self.ccx, unsized_ty).ptr_to();
647                         let base = consts::ptrcast(base, ptr_ty);
648                         let info = base::unsized_info(self.ccx, pointee_ty,
649                                                       unsized_ty, old_info);
650
651                         if old_info.is_none() {
652                             let prev_const = self.ccx.const_unsized().borrow_mut()
653                                                      .insert(base, operand.llval);
654                             assert!(prev_const.is_none() || prev_const == Some(operand.llval));
655                         }
656                         assert_eq!(abi::FAT_PTR_ADDR, 0);
657                         assert_eq!(abi::FAT_PTR_EXTRA, 1);
658                         C_struct(self.ccx, &[base, info], false)
659                     }
660                     mir::CastKind::Misc if common::type_is_immediate(self.ccx, operand.ty) => {
661                         debug_assert!(common::type_is_immediate(self.ccx, cast_ty));
662                         let r_t_in = CastTy::from_ty(operand.ty).expect("bad input type for cast");
663                         let r_t_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
664                         let ll_t_out = type_of::immediate_type_of(self.ccx, cast_ty);
665                         let llval = operand.llval;
666                         let signed = if let CastTy::Int(IntTy::CEnum) = r_t_in {
667                             let l = self.ccx.layout_of(operand.ty);
668                             adt::is_discr_signed(&l)
669                         } else {
670                             operand.ty.is_signed()
671                         };
672
673                         unsafe {
674                             match (r_t_in, r_t_out) {
675                                 (CastTy::Int(_), CastTy::Int(_)) => {
676                                     let s = signed as llvm::Bool;
677                                     llvm::LLVMConstIntCast(llval, ll_t_out.to_ref(), s)
678                                 }
679                                 (CastTy::Int(_), CastTy::Float) => {
680                                     if signed {
681                                         llvm::LLVMConstSIToFP(llval, ll_t_out.to_ref())
682                                     } else {
683                                         llvm::LLVMConstUIToFP(llval, ll_t_out.to_ref())
684                                     }
685                                 }
686                                 (CastTy::Float, CastTy::Float) => {
687                                     llvm::LLVMConstFPCast(llval, ll_t_out.to_ref())
688                                 }
689                                 (CastTy::Float, CastTy::Int(IntTy::I)) => {
690                                     llvm::LLVMConstFPToSI(llval, ll_t_out.to_ref())
691                                 }
692                                 (CastTy::Float, CastTy::Int(_)) => {
693                                     llvm::LLVMConstFPToUI(llval, ll_t_out.to_ref())
694                                 }
695                                 (CastTy::Ptr(_), CastTy::Ptr(_)) |
696                                 (CastTy::FnPtr, CastTy::Ptr(_)) |
697                                 (CastTy::RPtr(_), CastTy::Ptr(_)) => {
698                                     consts::ptrcast(llval, ll_t_out)
699                                 }
700                                 (CastTy::Int(_), CastTy::Ptr(_)) => {
701                                     llvm::LLVMConstIntToPtr(llval, ll_t_out.to_ref())
702                                 }
703                                 (CastTy::Ptr(_), CastTy::Int(_)) |
704                                 (CastTy::FnPtr, CastTy::Int(_)) => {
705                                     llvm::LLVMConstPtrToInt(llval, ll_t_out.to_ref())
706                                 }
707                                 _ => bug!("unsupported cast: {:?} to {:?}", operand.ty, cast_ty)
708                             }
709                         }
710                     }
711                     mir::CastKind::Misc => { // Casts from a fat-ptr.
712                         let ll_cast_ty = type_of::immediate_type_of(self.ccx, cast_ty);
713                         let ll_from_ty = type_of::immediate_type_of(self.ccx, operand.ty);
714                         if common::type_is_fat_ptr(self.ccx, operand.ty) {
715                             let (data_ptr, meta_ptr) = operand.get_fat_ptr();
716                             if common::type_is_fat_ptr(self.ccx, cast_ty) {
717                                 let ll_cft = ll_cast_ty.field_types();
718                                 let ll_fft = ll_from_ty.field_types();
719                                 let data_cast = consts::ptrcast(data_ptr, ll_cft[0]);
720                                 assert_eq!(ll_cft[1].kind(), ll_fft[1].kind());
721                                 C_struct(self.ccx, &[data_cast, meta_ptr], false)
722                             } else { // cast to thin-ptr
723                                 // Cast of fat-ptr to thin-ptr is an extraction of data-ptr and
724                                 // pointer-cast of that pointer to desired pointer type.
725                                 consts::ptrcast(data_ptr, ll_cast_ty)
726                             }
727                         } else {
728                             bug!("Unexpected non-fat-pointer operand")
729                         }
730                     }
731                 };
732                 Const::new(val, cast_ty)
733             }
734
735             mir::Rvalue::Ref(_, bk, ref lvalue) => {
736                 let tr_lvalue = self.const_lvalue(lvalue, span)?;
737
738                 let ty = tr_lvalue.ty;
739                 let ref_ty = tcx.mk_ref(tcx.types.re_erased,
740                     ty::TypeAndMut { ty: ty, mutbl: bk.to_mutbl_lossy() });
741
742                 let base = match tr_lvalue.base {
743                     Base::Value(llval) => {
744                         // FIXME: may be wrong for &*(&simd_vec as &fmt::Debug)
745                         let align = if self.ccx.shared().type_is_sized(ty) {
746                             self.ccx.align_of(ty)
747                         } else {
748                             self.ccx.tcx().data_layout.pointer_align.abi() as machine::llalign
749                         };
750                         if bk == mir::BorrowKind::Mut {
751                             consts::addr_of_mut(self.ccx, llval, align, "ref_mut")
752                         } else {
753                             consts::addr_of(self.ccx, llval, align, "ref")
754                         }
755                     }
756                     Base::Str(llval) |
757                     Base::Static(llval) => llval
758                 };
759
760                 let ptr = if self.ccx.shared().type_is_sized(ty) {
761                     base
762                 } else {
763                     C_struct(self.ccx, &[base, tr_lvalue.llextra], false)
764                 };
765                 Const::new(ptr, ref_ty)
766             }
767
768             mir::Rvalue::Len(ref lvalue) => {
769                 let tr_lvalue = self.const_lvalue(lvalue, span)?;
770                 Const::new(tr_lvalue.len(self.ccx), tcx.types.usize)
771             }
772
773             mir::Rvalue::BinaryOp(op, ref lhs, ref rhs) => {
774                 let lhs = self.const_operand(lhs, span)?;
775                 let rhs = self.const_operand(rhs, span)?;
776                 let ty = lhs.ty;
777                 let binop_ty = op.ty(tcx, lhs.ty, rhs.ty);
778                 let (lhs, rhs) = (lhs.llval, rhs.llval);
779                 Const::new(const_scalar_binop(op, lhs, rhs, ty), binop_ty)
780             }
781
782             mir::Rvalue::CheckedBinaryOp(op, ref lhs, ref rhs) => {
783                 let lhs = self.const_operand(lhs, span)?;
784                 let rhs = self.const_operand(rhs, span)?;
785                 let ty = lhs.ty;
786                 let val_ty = op.ty(tcx, lhs.ty, rhs.ty);
787                 let binop_ty = tcx.intern_tup(&[val_ty, tcx.types.bool], false);
788                 let (lhs, rhs) = (lhs.llval, rhs.llval);
789                 assert!(!ty.is_fp());
790
791                 match const_scalar_checked_binop(tcx, op, lhs, rhs, ty) {
792                     Some((llval, of)) => {
793                         let llof = C_bool(self.ccx, of);
794                         Const::new(C_struct(self.ccx, &[llval, llof], false), binop_ty)
795                     }
796                     None => {
797                         span_bug!(span, "{:?} got non-integer operands: {:?} and {:?}",
798                                   rvalue, Value(lhs), Value(rhs));
799                     }
800                 }
801             }
802
803             mir::Rvalue::UnaryOp(op, ref operand) => {
804                 let operand = self.const_operand(operand, span)?;
805                 let lloperand = operand.llval;
806                 let llval = match op {
807                     mir::UnOp::Not => {
808                         unsafe {
809                             llvm::LLVMConstNot(lloperand)
810                         }
811                     }
812                     mir::UnOp::Neg => {
813                         let is_float = operand.ty.is_fp();
814                         unsafe {
815                             if is_float {
816                                 llvm::LLVMConstFNeg(lloperand)
817                             } else {
818                                 llvm::LLVMConstNeg(lloperand)
819                             }
820                         }
821                     }
822                 };
823                 Const::new(llval, operand.ty)
824             }
825
826             mir::Rvalue::NullaryOp(mir::NullOp::SizeOf, ty) => {
827                 assert!(self.ccx.shared().type_is_sized(ty));
828                 let llval = C_uint(self.ccx, self.ccx.size_of(ty));
829                 Const::new(llval, tcx.types.usize)
830             }
831
832             _ => span_bug!(span, "{:?} in constant", rvalue)
833         };
834
835         debug!("const_rvalue({:?}: {:?} @ {:?}) = {:?}", rvalue, dest_ty, span, val);
836
837         Ok(val)
838     }
839
840 }
841
842 fn to_const_int(value: ValueRef, t: Ty, tcx: TyCtxt) -> Option<ConstInt> {
843     match t.sty {
844         ty::TyInt(int_type) => const_to_opt_u128(value, true)
845             .and_then(|input| ConstInt::new_signed(input as i128, int_type,
846                                                    tcx.sess.target.int_type)),
847         ty::TyUint(uint_type) => const_to_opt_u128(value, false)
848             .and_then(|input| ConstInt::new_unsigned(input, uint_type,
849                                                      tcx.sess.target.uint_type)),
850         _ => None
851
852     }
853 }
854
855 pub fn const_scalar_binop(op: mir::BinOp,
856                           lhs: ValueRef,
857                           rhs: ValueRef,
858                           input_ty: Ty) -> ValueRef {
859     assert!(!input_ty.is_simd());
860     let is_float = input_ty.is_fp();
861     let signed = input_ty.is_signed();
862
863     unsafe {
864         match op {
865             mir::BinOp::Add if is_float => llvm::LLVMConstFAdd(lhs, rhs),
866             mir::BinOp::Add             => llvm::LLVMConstAdd(lhs, rhs),
867
868             mir::BinOp::Sub if is_float => llvm::LLVMConstFSub(lhs, rhs),
869             mir::BinOp::Sub             => llvm::LLVMConstSub(lhs, rhs),
870
871             mir::BinOp::Mul if is_float => llvm::LLVMConstFMul(lhs, rhs),
872             mir::BinOp::Mul             => llvm::LLVMConstMul(lhs, rhs),
873
874             mir::BinOp::Div if is_float => llvm::LLVMConstFDiv(lhs, rhs),
875             mir::BinOp::Div if signed   => llvm::LLVMConstSDiv(lhs, rhs),
876             mir::BinOp::Div             => llvm::LLVMConstUDiv(lhs, rhs),
877
878             mir::BinOp::Rem if is_float => llvm::LLVMConstFRem(lhs, rhs),
879             mir::BinOp::Rem if signed   => llvm::LLVMConstSRem(lhs, rhs),
880             mir::BinOp::Rem             => llvm::LLVMConstURem(lhs, rhs),
881
882             mir::BinOp::BitXor => llvm::LLVMConstXor(lhs, rhs),
883             mir::BinOp::BitAnd => llvm::LLVMConstAnd(lhs, rhs),
884             mir::BinOp::BitOr  => llvm::LLVMConstOr(lhs, rhs),
885             mir::BinOp::Shl    => {
886                 let rhs = base::cast_shift_const_rhs(op.to_hir_binop(), lhs, rhs);
887                 llvm::LLVMConstShl(lhs, rhs)
888             }
889             mir::BinOp::Shr    => {
890                 let rhs = base::cast_shift_const_rhs(op.to_hir_binop(), lhs, rhs);
891                 if signed { llvm::LLVMConstAShr(lhs, rhs) }
892                 else      { llvm::LLVMConstLShr(lhs, rhs) }
893             }
894             mir::BinOp::Eq | mir::BinOp::Ne |
895             mir::BinOp::Lt | mir::BinOp::Le |
896             mir::BinOp::Gt | mir::BinOp::Ge => {
897                 if is_float {
898                     let cmp = base::bin_op_to_fcmp_predicate(op.to_hir_binop());
899                     llvm::LLVMConstFCmp(cmp, lhs, rhs)
900                 } else {
901                     let cmp = base::bin_op_to_icmp_predicate(op.to_hir_binop(),
902                                                                 signed);
903                     llvm::LLVMConstICmp(cmp, lhs, rhs)
904                 }
905             }
906             mir::BinOp::Offset => unreachable!("BinOp::Offset in const-eval!")
907         }
908     }
909 }
910
911 pub fn const_scalar_checked_binop<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
912                                             op: mir::BinOp,
913                                             lllhs: ValueRef,
914                                             llrhs: ValueRef,
915                                             input_ty: Ty<'tcx>)
916                                             -> Option<(ValueRef, bool)> {
917     if let (Some(lhs), Some(rhs)) = (to_const_int(lllhs, input_ty, tcx),
918                                      to_const_int(llrhs, input_ty, tcx)) {
919         let result = match op {
920             mir::BinOp::Add => lhs + rhs,
921             mir::BinOp::Sub => lhs - rhs,
922             mir::BinOp::Mul => lhs * rhs,
923             mir::BinOp::Shl => lhs << rhs,
924             mir::BinOp::Shr => lhs >> rhs,
925             _ => {
926                 bug!("Operator `{:?}` is not a checkable operator", op)
927             }
928         };
929
930         let of = match result {
931             Ok(_) => false,
932             Err(ConstMathErr::Overflow(_)) |
933             Err(ConstMathErr::ShiftNegative) => true,
934             Err(err) => {
935                 bug!("Operator `{:?}` on `{:?}` and `{:?}` errored: {}",
936                      op, lhs, rhs, err.description());
937             }
938         };
939
940         Some((const_scalar_binop(op, lllhs, llrhs, input_ty), of))
941     } else {
942         None
943     }
944 }
945
946 impl<'a, 'tcx> MirContext<'a, 'tcx> {
947     pub fn trans_constant(&mut self,
948                           bcx: &Builder<'a, 'tcx>,
949                           constant: &mir::Constant<'tcx>)
950                           -> Const<'tcx>
951     {
952         debug!("trans_constant({:?})", constant);
953         let ty = self.monomorphize(&constant.ty);
954         let result = match constant.literal.clone() {
955             mir::Literal::Item { def_id, substs } => {
956                 let substs = self.monomorphize(&substs);
957                 MirConstContext::trans_def(bcx.ccx, def_id, substs, IndexVec::new())
958             }
959             mir::Literal::Promoted { index } => {
960                 let mir = &self.mir.promoted[index];
961                 MirConstContext::new(bcx.ccx, mir, self.param_substs, IndexVec::new()).trans()
962             }
963             mir::Literal::Value { value } => {
964                 Ok(Const::from_constval(bcx.ccx, value, ty))
965             }
966         };
967
968         let result = result.unwrap_or_else(|_| {
969             // We've errored, so we don't have to produce working code.
970             let llty = type_of::type_of(bcx.ccx, ty);
971             Const::new(C_undef(llty), ty)
972         });
973
974         debug!("trans_constant({:?}) = {:?}", constant, result);
975         result
976     }
977 }
978
979
980 pub fn trans_static_initializer<'a, 'tcx>(
981     ccx: &CrateContext<'a, 'tcx>,
982     def_id: DefId)
983     -> Result<ValueRef, ConstEvalErr<'tcx>>
984 {
985     MirConstContext::trans_def(ccx, def_id, Substs::empty(), IndexVec::new())
986         .map(|c| c.llval)
987 }
988
989 /// Construct a constant value, suitable for initializing a
990 /// GlobalVariable, given a case and constant values for its fields.
991 /// Note that this may have a different LLVM type (and different
992 /// alignment!) from the representation's `type_of`, so it needs a
993 /// pointer cast before use.
994 ///
995 /// The LLVM type system does not directly support unions, and only
996 /// pointers can be bitcast, so a constant (and, by extension, the
997 /// GlobalVariable initialized by it) will have a type that can vary
998 /// depending on which case of an enum it is.
999 ///
1000 /// To understand the alignment situation, consider `enum E { V64(u64),
1001 /// V32(u32, u32) }` on Windows.  The type has 8-byte alignment to
1002 /// accommodate the u64, but `V32(x, y)` would have LLVM type `{i32,
1003 /// i32, i32}`, which is 4-byte aligned.
1004 ///
1005 /// Currently the returned value has the same size as the type, but
1006 /// this could be changed in the future to avoid allocating unnecessary
1007 /// space after values of shorter-than-maximum cases.
1008 fn trans_const<'a, 'tcx>(
1009     ccx: &CrateContext<'a, 'tcx>,
1010     t: Ty<'tcx>,
1011     kind: &mir::AggregateKind,
1012     vals: &[ValueRef]
1013 ) -> ValueRef {
1014     let l = ccx.layout_of(t);
1015     let variant_index = match *kind {
1016         mir::AggregateKind::Adt(_, index, _, _) => index,
1017         _ => 0,
1018     };
1019     match *l {
1020         layout::CEnum { discr: d, min, max, .. } => {
1021             let discr = match *kind {
1022                 mir::AggregateKind::Adt(adt_def, _, _, _) => {
1023                     adt_def.discriminant_for_variant(ccx.tcx(), variant_index)
1024                            .to_u128_unchecked() as u64
1025                 },
1026                 _ => 0,
1027             };
1028             assert_eq!(vals.len(), 0);
1029             adt::assert_discr_in_range(min, max, discr);
1030             C_integral(Type::from_integer(ccx, d), discr, true)
1031         }
1032         layout::General { discr: d, ref variants, .. } => {
1033             let variant = &variants[variant_index];
1034             let lldiscr = C_integral(Type::from_integer(ccx, d), variant_index as u64, true);
1035             let mut vals_with_discr = vec![lldiscr];
1036             vals_with_discr.extend_from_slice(vals);
1037             let mut contents = build_const_struct(ccx, &variant, &vals_with_discr[..]);
1038             let needed_padding = l.size(ccx).bytes() - variant.stride().bytes();
1039             if needed_padding > 0 {
1040                 contents.push(padding(ccx, needed_padding));
1041             }
1042             C_struct(ccx, &contents[..], false)
1043         }
1044         layout::UntaggedUnion { ref variants, .. }=> {
1045             assert_eq!(variant_index, 0);
1046             let contents = build_const_union(ccx, variants, vals[0]);
1047             C_struct(ccx, &contents, variants.packed)
1048         }
1049         layout::Univariant { ref variant, .. } => {
1050             assert_eq!(variant_index, 0);
1051             let contents = build_const_struct(ccx, &variant, vals);
1052             C_struct(ccx, &contents[..], variant.packed)
1053         }
1054         layout::Vector { .. } => {
1055             C_vector(vals)
1056         }
1057         layout::RawNullablePointer { nndiscr, .. } => {
1058             if variant_index as u64 == nndiscr {
1059                 assert_eq!(vals.len(), 1);
1060                 vals[0]
1061             } else {
1062                 C_null(type_of::type_of(ccx, t))
1063             }
1064         }
1065         layout::StructWrappedNullablePointer { ref nonnull, nndiscr, .. } => {
1066             if variant_index as u64 == nndiscr {
1067                 C_struct(ccx, &build_const_struct(ccx, &nonnull, vals), false)
1068             } else {
1069                 // Always use null even if it's not the `discrfield`th
1070                 // field; see #8506.
1071                 C_null(type_of::type_of(ccx, t))
1072             }
1073         }
1074         _ => bug!("trans_const: cannot handle type {} repreented as {:#?}", t, l)
1075     }
1076 }
1077
1078 /// Building structs is a little complicated, because we might need to
1079 /// insert padding if a field's value is less aligned than its type.
1080 ///
1081 /// Continuing the example from `trans_const`, a value of type `(u32,
1082 /// E)` should have the `E` at offset 8, but if that field's
1083 /// initializer is 4-byte aligned then simply translating the tuple as
1084 /// a two-element struct will locate it at offset 4, and accesses to it
1085 /// will read the wrong memory.
1086 fn build_const_struct<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1087                                 st: &layout::Struct,
1088                                 vals: &[ValueRef])
1089                                 -> Vec<ValueRef> {
1090     assert_eq!(vals.len(), st.offsets.len());
1091
1092     if vals.len() == 0 {
1093         return Vec::new();
1094     }
1095
1096     // offset of current value
1097     let mut offset = 0;
1098     let mut cfields = Vec::new();
1099     cfields.reserve(st.offsets.len()*2);
1100
1101     let parts = st.field_index_by_increasing_offset().map(|i| {
1102         (&vals[i], st.offsets[i].bytes())
1103     });
1104     for (&val, target_offset) in parts {
1105         if offset < target_offset {
1106             cfields.push(padding(ccx, target_offset - offset));
1107             offset = target_offset;
1108         }
1109         assert!(!is_undef(val));
1110         cfields.push(val);
1111         offset += machine::llsize_of_alloc(ccx, val_ty(val));
1112     }
1113
1114     if offset < st.stride().bytes() {
1115         cfields.push(padding(ccx, st.stride().bytes() - offset));
1116     }
1117
1118     cfields
1119 }
1120
1121 fn build_const_union<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1122                                un: &layout::Union,
1123                                field_val: ValueRef)
1124                                -> Vec<ValueRef> {
1125     let mut cfields = vec![field_val];
1126
1127     let offset = machine::llsize_of_alloc(ccx, val_ty(field_val));
1128     let size = un.stride().bytes();
1129     if offset != size {
1130         cfields.push(padding(ccx, size - offset));
1131     }
1132
1133     cfields
1134 }
1135
1136 fn padding(ccx: &CrateContext, size: u64) -> ValueRef {
1137     C_undef(Type::array(&Type::i8(ccx), size))
1138 }