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