]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/common.rs
core: Use raw pointers to avoid aliasing in str::split_at_mut
[rust.git] / src / librustc_trans / trans / common.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 #![allow(non_camel_case_types, non_snake_case)]
12
13 //! Code that is useful in various trans modules.
14
15 pub use self::ExprOrMethodCall::*;
16
17 use session::Session;
18 use llvm;
19 use llvm::{ValueRef, BasicBlockRef, BuilderRef, ContextRef, TypeKind};
20 use llvm::{True, False, Bool};
21 use middle::cfg;
22 use middle::def;
23 use middle::def_id::DefId;
24 use middle::infer;
25 use middle::lang_items::LangItem;
26 use middle::subst::{self, Substs};
27 use trans::base;
28 use trans::build;
29 use trans::callee;
30 use trans::cleanup;
31 use trans::consts;
32 use trans::datum;
33 use trans::debuginfo::{self, DebugLoc};
34 use trans::declare;
35 use trans::machine;
36 use trans::monomorphize;
37 use trans::type_::Type;
38 use trans::type_of;
39 use middle::traits;
40 use middle::ty::{self, Ty};
41 use middle::ty::fold::{TypeFolder, TypeFoldable};
42 use rustc_front::hir;
43 use rustc::mir::repr::Mir;
44 use util::nodemap::{FnvHashMap, NodeMap};
45
46 use arena::TypedArena;
47 use libc::{c_uint, c_char};
48 use std::ffi::CString;
49 use std::cell::{Cell, RefCell};
50 use std::vec::Vec;
51 use syntax::ast;
52 use syntax::codemap::{DUMMY_SP, Span};
53 use syntax::parse::token::InternedString;
54 use syntax::parse::token;
55
56 pub use trans::context::CrateContext;
57
58 /// Is the type's representation size known at compile time?
59 pub fn type_is_sized<'tcx>(tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
60     ty.is_sized(&tcx.empty_parameter_environment(), DUMMY_SP)
61 }
62
63 pub fn type_is_fat_ptr<'tcx>(cx: &ty::ctxt<'tcx>, ty: Ty<'tcx>) -> bool {
64     match ty.sty {
65         ty::TyRawPtr(ty::TypeAndMut{ty, ..}) |
66         ty::TyRef(_, ty::TypeAndMut{ty, ..}) |
67         ty::TyBox(ty) => {
68             !type_is_sized(cx, ty)
69         }
70         _ => {
71             false
72         }
73     }
74 }
75
76 fn type_is_newtype_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
77     match ty.sty {
78         ty::TyStruct(def, substs) => {
79             let fields = &def.struct_variant().fields;
80             fields.len() == 1 && {
81                 type_is_immediate(ccx, monomorphize::field_ty(ccx.tcx(), substs, &fields[0]))
82             }
83         }
84         _ => false
85     }
86 }
87
88 pub fn type_is_immediate<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
89     use trans::machine::llsize_of_alloc;
90     use trans::type_of::sizing_type_of;
91
92     let tcx = ccx.tcx();
93     let simple = ty.is_scalar() ||
94         ty.is_unique() || ty.is_region_ptr() ||
95         type_is_newtype_immediate(ccx, ty) ||
96         ty.is_simd();
97     if simple && !type_is_fat_ptr(tcx, ty) {
98         return true;
99     }
100     if !type_is_sized(tcx, ty) {
101         return false;
102     }
103     match ty.sty {
104         ty::TyStruct(..) | ty::TyEnum(..) | ty::TyTuple(..) | ty::TyArray(_, _) |
105         ty::TyClosure(..) => {
106             let llty = sizing_type_of(ccx, ty);
107             llsize_of_alloc(ccx, llty) <= llsize_of_alloc(ccx, ccx.int_type())
108         }
109         _ => type_is_zero_size(ccx, ty)
110     }
111 }
112
113 /// Identify types which have size zero at runtime.
114 pub fn type_is_zero_size<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
115     use trans::machine::llsize_of_alloc;
116     use trans::type_of::sizing_type_of;
117     let llty = sizing_type_of(ccx, ty);
118     llsize_of_alloc(ccx, llty) == 0
119 }
120
121 /// Identifies types which we declare to be equivalent to `void` in C for the purpose of function
122 /// return types. These are `()`, bot, uninhabited enums and all other zero-sized types.
123 pub fn return_type_is_void<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>, ty: Ty<'tcx>) -> bool {
124     ty.is_nil() || ty.is_empty(ccx.tcx()) || type_is_zero_size(ccx, ty)
125 }
126
127 /// Generates a unique symbol based off the name given. This is used to create
128 /// unique symbols for things like closures.
129 pub fn gensym_name(name: &str) -> ast::Name {
130     let num = token::gensym(name).0;
131     // use one colon which will get translated to a period by the mangler, and
132     // we're guaranteed that `num` is globally unique for this crate.
133     token::gensym(&format!("{}:{}", name, num))
134 }
135
136 /*
137 * A note on nomenclature of linking: "extern", "foreign", and "upcall".
138 *
139 * An "extern" is an LLVM symbol we wind up emitting an undefined external
140 * reference to. This means "we don't have the thing in this compilation unit,
141 * please make sure you link it in at runtime". This could be a reference to
142 * C code found in a C library, or rust code found in a rust crate.
143 *
144 * Most "externs" are implicitly declared (automatically) as a result of a
145 * user declaring an extern _module_ dependency; this causes the rust driver
146 * to locate an extern crate, scan its compilation metadata, and emit extern
147 * declarations for any symbols used by the declaring crate.
148 *
149 * A "foreign" is an extern that references C (or other non-rust ABI) code.
150 * There is no metadata to scan for extern references so in these cases either
151 * a header-digester like bindgen, or manual function prototypes, have to
152 * serve as declarators. So these are usually given explicitly as prototype
153 * declarations, in rust code, with ABI attributes on them noting which ABI to
154 * link via.
155 *
156 * An "upcall" is a foreign call generated by the compiler (not corresponding
157 * to any user-written call in the code) into the runtime library, to perform
158 * some helper task such as bringing a task to life, allocating memory, etc.
159 *
160 */
161
162 use trans::Disr;
163
164 #[derive(Copy, Clone)]
165 pub struct NodeIdAndSpan {
166     pub id: ast::NodeId,
167     pub span: Span,
168 }
169
170 pub fn expr_info(expr: &hir::Expr) -> NodeIdAndSpan {
171     NodeIdAndSpan { id: expr.id, span: expr.span }
172 }
173
174 /// The concrete version of ty::FieldDef. The name is the field index if
175 /// the field is numeric.
176 pub struct Field<'tcx>(pub ast::Name, pub Ty<'tcx>);
177
178 /// The concrete version of ty::VariantDef
179 pub struct VariantInfo<'tcx> {
180     pub discr: Disr,
181     pub fields: Vec<Field<'tcx>>
182 }
183
184 impl<'tcx> VariantInfo<'tcx> {
185     pub fn from_ty(tcx: &ty::ctxt<'tcx>,
186                    ty: Ty<'tcx>,
187                    opt_def: Option<def::Def>)
188                    -> Self
189     {
190         match ty.sty {
191             ty::TyStruct(adt, substs) | ty::TyEnum(adt, substs) => {
192                 let variant = match opt_def {
193                     None => adt.struct_variant(),
194                     Some(def) => adt.variant_of_def(def)
195                 };
196
197                 VariantInfo {
198                     discr: Disr::from(variant.disr_val),
199                     fields: variant.fields.iter().map(|f| {
200                         Field(f.name, monomorphize::field_ty(tcx, substs, f))
201                     }).collect()
202                 }
203             }
204
205             ty::TyTuple(ref v) => {
206                 VariantInfo {
207                     discr: Disr(0),
208                     fields: v.iter().enumerate().map(|(i, &t)| {
209                         Field(token::intern(&i.to_string()), t)
210                     }).collect()
211                 }
212             }
213
214             _ => {
215                 tcx.sess.bug(&format!(
216                     "cannot get field types from the type {:?}",
217                     ty));
218             }
219         }
220     }
221
222     /// Return the variant corresponding to a given node (e.g. expr)
223     pub fn of_node(tcx: &ty::ctxt<'tcx>, ty: Ty<'tcx>, id: ast::NodeId) -> Self {
224         let node_def = tcx.def_map.borrow().get(&id).map(|v| v.full_def());
225         Self::from_ty(tcx, ty, node_def)
226     }
227
228     pub fn field_index(&self, name: ast::Name) -> usize {
229         self.fields.iter().position(|&Field(n,_)| n == name).unwrap_or_else(|| {
230             panic!("unknown field `{}`", name)
231         })
232     }
233 }
234
235 pub struct BuilderRef_res {
236     pub b: BuilderRef,
237 }
238
239 impl Drop for BuilderRef_res {
240     fn drop(&mut self) {
241         unsafe {
242             llvm::LLVMDisposeBuilder(self.b);
243         }
244     }
245 }
246
247 pub fn BuilderRef_res(b: BuilderRef) -> BuilderRef_res {
248     BuilderRef_res {
249         b: b
250     }
251 }
252
253 pub type ExternMap = FnvHashMap<String, ValueRef>;
254
255 pub fn validate_substs(substs: &Substs) {
256     assert!(!substs.types.needs_infer());
257 }
258
259 // work around bizarre resolve errors
260 type RvalueDatum<'tcx> = datum::Datum<'tcx, datum::Rvalue>;
261 pub type LvalueDatum<'tcx> = datum::Datum<'tcx, datum::Lvalue>;
262
263 #[derive(Clone, Debug)]
264 struct HintEntry<'tcx> {
265     // The datum for the dropflag-hint itself; note that many
266     // source-level Lvalues will be associated with the same
267     // dropflag-hint datum.
268     datum: cleanup::DropHintDatum<'tcx>,
269 }
270
271 pub struct DropFlagHintsMap<'tcx> {
272     // Maps NodeId for expressions that read/write unfragmented state
273     // to that state's drop-flag "hint."  (A stack-local hint
274     // indicates either that (1.) it is certain that no-drop is
275     // needed, or (2.)  inline drop-flag must be consulted.)
276     node_map: NodeMap<HintEntry<'tcx>>,
277 }
278
279 impl<'tcx> DropFlagHintsMap<'tcx> {
280     pub fn new() -> DropFlagHintsMap<'tcx> { DropFlagHintsMap { node_map: NodeMap() } }
281     pub fn has_hint(&self, id: ast::NodeId) -> bool { self.node_map.contains_key(&id) }
282     pub fn insert(&mut self, id: ast::NodeId, datum: cleanup::DropHintDatum<'tcx>) {
283         self.node_map.insert(id, HintEntry { datum: datum });
284     }
285     pub fn hint_datum(&self, id: ast::NodeId) -> Option<cleanup::DropHintDatum<'tcx>> {
286         self.node_map.get(&id).map(|t|t.datum)
287     }
288 }
289
290 // Function context.  Every LLVM function we create will have one of
291 // these.
292 pub struct FunctionContext<'a, 'tcx: 'a> {
293     // The MIR for this function. At present, this is optional because
294     // we only have MIR available for things that are local to the
295     // crate.
296     pub mir: Option<&'a Mir<'tcx>>,
297
298     // The ValueRef returned from a call to llvm::LLVMAddFunction; the
299     // address of the first instruction in the sequence of
300     // instructions for this function that will go in the .text
301     // section of the executable we're generating.
302     pub llfn: ValueRef,
303
304     // always an empty parameter-environment NOTE: @jroesch another use of ParamEnv
305     pub param_env: ty::ParameterEnvironment<'a, 'tcx>,
306
307     // The environment argument in a closure.
308     pub llenv: Option<ValueRef>,
309
310     // A pointer to where to store the return value. If the return type is
311     // immediate, this points to an alloca in the function. Otherwise, it's a
312     // pointer to the hidden first parameter of the function. After function
313     // construction, this should always be Some.
314     pub llretslotptr: Cell<Option<ValueRef>>,
315
316     // These pub elements: "hoisted basic blocks" containing
317     // administrative activities that have to happen in only one place in
318     // the function, due to LLVM's quirks.
319     // A marker for the place where we want to insert the function's static
320     // allocas, so that LLVM will coalesce them into a single alloca call.
321     pub alloca_insert_pt: Cell<Option<ValueRef>>,
322     pub llreturn: Cell<Option<BasicBlockRef>>,
323
324     // If the function has any nested return's, including something like:
325     // fn foo() -> Option<Foo> { Some(Foo { x: return None }) }, then
326     // we use a separate alloca for each return
327     pub needs_ret_allocas: bool,
328
329     // The a value alloca'd for calls to upcalls.rust_personality. Used when
330     // outputting the resume instruction.
331     pub personality: Cell<Option<ValueRef>>,
332
333     // True if the caller expects this fn to use the out pointer to
334     // return. Either way, your code should write into the slot llretslotptr
335     // points to, but if this value is false, that slot will be a local alloca.
336     pub caller_expects_out_pointer: bool,
337
338     // Maps the DefId's for local variables to the allocas created for
339     // them in llallocas.
340     pub lllocals: RefCell<NodeMap<LvalueDatum<'tcx>>>,
341
342     // Same as above, but for closure upvars
343     pub llupvars: RefCell<NodeMap<ValueRef>>,
344
345     // Carries info about drop-flags for local bindings (longer term,
346     // paths) for the code being compiled.
347     pub lldropflag_hints: RefCell<DropFlagHintsMap<'tcx>>,
348
349     // The NodeId of the function, or -1 if it doesn't correspond to
350     // a user-defined function.
351     pub id: ast::NodeId,
352
353     // If this function is being monomorphized, this contains the type
354     // substitutions used.
355     pub param_substs: &'tcx Substs<'tcx>,
356
357     // The source span and nesting context where this function comes from, for
358     // error reporting and symbol generation.
359     pub span: Option<Span>,
360
361     // The arena that blocks are allocated from.
362     pub block_arena: &'a TypedArena<BlockS<'a, 'tcx>>,
363
364     // This function's enclosing crate context.
365     pub ccx: &'a CrateContext<'a, 'tcx>,
366
367     // Used and maintained by the debuginfo module.
368     pub debug_context: debuginfo::FunctionDebugContext,
369
370     // Cleanup scopes.
371     pub scopes: RefCell<Vec<cleanup::CleanupScope<'a, 'tcx>>>,
372
373     pub cfg: Option<cfg::CFG>,
374 }
375
376 impl<'a, 'tcx> FunctionContext<'a, 'tcx> {
377     pub fn mir(&self) -> &'a Mir<'tcx> {
378         self.mir.unwrap()
379     }
380
381     pub fn arg_offset(&self) -> usize {
382         self.env_arg_pos() + if self.llenv.is_some() { 1 } else { 0 }
383     }
384
385     pub fn env_arg_pos(&self) -> usize {
386         if self.caller_expects_out_pointer {
387             1
388         } else {
389             0
390         }
391     }
392
393     pub fn cleanup(&self) {
394         unsafe {
395             llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt
396                                                      .get()
397                                                      .unwrap());
398         }
399     }
400
401     pub fn get_llreturn(&self) -> BasicBlockRef {
402         if self.llreturn.get().is_none() {
403
404             self.llreturn.set(Some(unsafe {
405                 llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(), self.llfn,
406                                                     "return\0".as_ptr() as *const _)
407             }))
408         }
409
410         self.llreturn.get().unwrap()
411     }
412
413     pub fn get_ret_slot(&self, bcx: Block<'a, 'tcx>,
414                         output: ty::FnOutput<'tcx>,
415                         name: &str) -> ValueRef {
416         if self.needs_ret_allocas {
417             base::alloca(bcx, match output {
418                 ty::FnConverging(output_type) => type_of::type_of(bcx.ccx(), output_type),
419                 ty::FnDiverging => Type::void(bcx.ccx())
420             }, name)
421         } else {
422             self.llretslotptr.get().unwrap()
423         }
424     }
425
426     pub fn new_block(&'a self,
427                      is_lpad: bool,
428                      name: &str,
429                      opt_node_id: Option<ast::NodeId>)
430                      -> Block<'a, 'tcx> {
431         unsafe {
432             let name = CString::new(name).unwrap();
433             let llbb = llvm::LLVMAppendBasicBlockInContext(self.ccx.llcx(),
434                                                            self.llfn,
435                                                            name.as_ptr());
436             BlockS::new(llbb, is_lpad, opt_node_id, self)
437         }
438     }
439
440     pub fn new_id_block(&'a self,
441                         name: &str,
442                         node_id: ast::NodeId)
443                         -> Block<'a, 'tcx> {
444         self.new_block(false, name, Some(node_id))
445     }
446
447     pub fn new_temp_block(&'a self,
448                           name: &str)
449                           -> Block<'a, 'tcx> {
450         self.new_block(false, name, None)
451     }
452
453     pub fn join_blocks(&'a self,
454                        id: ast::NodeId,
455                        in_cxs: &[Block<'a, 'tcx>])
456                        -> Block<'a, 'tcx> {
457         let out = self.new_id_block("join", id);
458         let mut reachable = false;
459         for bcx in in_cxs {
460             if !bcx.unreachable.get() {
461                 build::Br(*bcx, out.llbb, DebugLoc::None);
462                 reachable = true;
463             }
464         }
465         if !reachable {
466             build::Unreachable(out);
467         }
468         return out;
469     }
470
471     pub fn monomorphize<T>(&self, value: &T) -> T
472         where T : TypeFoldable<'tcx>
473     {
474         monomorphize::apply_param_substs(self.ccx.tcx(),
475                                          self.param_substs,
476                                          value)
477     }
478
479     /// This is the same as `common::type_needs_drop`, except that it
480     /// may use or update caches within this `FunctionContext`.
481     pub fn type_needs_drop(&self, ty: Ty<'tcx>) -> bool {
482         self.ccx.tcx().type_needs_drop_given_env(ty, &self.param_env)
483     }
484
485     pub fn eh_personality(&self) -> ValueRef {
486         // The exception handling personality function.
487         //
488         // If our compilation unit has the `eh_personality` lang item somewhere
489         // within it, then we just need to translate that. Otherwise, we're
490         // building an rlib which will depend on some upstream implementation of
491         // this function, so we just codegen a generic reference to it. We don't
492         // specify any of the types for the function, we just make it a symbol
493         // that LLVM can later use.
494         //
495         // Note that MSVC is a little special here in that we don't use the
496         // `eh_personality` lang item at all. Currently LLVM has support for
497         // both Dwarf and SEH unwind mechanisms for MSVC targets and uses the
498         // *name of the personality function* to decide what kind of unwind side
499         // tables/landing pads to emit. It looks like Dwarf is used by default,
500         // injecting a dependency on the `_Unwind_Resume` symbol for resuming
501         // an "exception", but for MSVC we want to force SEH. This means that we
502         // can't actually have the personality function be our standard
503         // `rust_eh_personality` function, but rather we wired it up to the
504         // CRT's custom personality function, which forces LLVM to consider
505         // landing pads as "landing pads for SEH".
506         let target = &self.ccx.sess().target.target;
507         match self.ccx.tcx().lang_items.eh_personality() {
508             Some(def_id) if !base::wants_msvc_seh(self.ccx.sess()) => {
509                 callee::trans_fn_ref(self.ccx, def_id, ExprId(0),
510                                      self.param_substs).val
511             }
512             _ => {
513                 let mut personality = self.ccx.eh_personality().borrow_mut();
514                 match *personality {
515                     Some(llpersonality) => llpersonality,
516                     None => {
517                         let name = if !base::wants_msvc_seh(self.ccx.sess()) {
518                             "rust_eh_personality"
519                         } else if target.arch == "x86" {
520                             "_except_handler3"
521                         } else {
522                             "__C_specific_handler"
523                         };
524                         let fty = Type::variadic_func(&[], &Type::i32(self.ccx));
525                         let f = declare::declare_cfn(self.ccx, name, fty,
526                                                      self.ccx.tcx().types.i32);
527                         *personality = Some(f);
528                         f
529                     }
530                 }
531             }
532         }
533     }
534
535     // Returns a ValueRef of the "eh_unwind_resume" lang item if one is defined,
536     // otherwise declares it as an external funtion.
537     pub fn eh_unwind_resume(&self) -> ValueRef {
538         use trans::attributes;
539         assert!(self.ccx.sess().target.target.options.custom_unwind_resume);
540         match self.ccx.tcx().lang_items.eh_unwind_resume() {
541             Some(def_id) => {
542                 callee::trans_fn_ref(self.ccx, def_id, ExprId(0),
543                                      self.param_substs).val
544             }
545             None => {
546                 let mut unwresume = self.ccx.eh_unwind_resume().borrow_mut();
547                 match *unwresume {
548                     Some(llfn) => llfn,
549                     None => {
550                         let fty = Type::func(&[Type::i8p(self.ccx)], &Type::void(self.ccx));
551                         let llfn = declare::declare_fn(self.ccx,
552                                                        "rust_eh_unwind_resume",
553                                                        llvm::CCallConv,
554                                                        fty, ty::FnDiverging);
555                         attributes::unwind(llfn, true);
556                         *unwresume = Some(llfn);
557                         llfn
558                     }
559                 }
560             }
561         }
562     }
563 }
564
565 // Basic block context.  We create a block context for each basic block
566 // (single-entry, single-exit sequence of instructions) we generate from Rust
567 // code.  Each basic block we generate is attached to a function, typically
568 // with many basic blocks per function.  All the basic blocks attached to a
569 // function are organized as a directed graph.
570 pub struct BlockS<'blk, 'tcx: 'blk> {
571     // The BasicBlockRef returned from a call to
572     // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
573     // block to the function pointed to by llfn.  We insert
574     // instructions into that block by way of this block context.
575     // The block pointing to this one in the function's digraph.
576     pub llbb: BasicBlockRef,
577     pub terminated: Cell<bool>,
578     pub unreachable: Cell<bool>,
579
580     // Is this block part of a landing pad?
581     pub is_lpad: bool,
582
583     // AST node-id associated with this block, if any. Used for
584     // debugging purposes only.
585     pub opt_node_id: Option<ast::NodeId>,
586
587     // The function context for the function to which this block is
588     // attached.
589     pub fcx: &'blk FunctionContext<'blk, 'tcx>,
590 }
591
592 pub type Block<'blk, 'tcx> = &'blk BlockS<'blk, 'tcx>;
593
594 impl<'blk, 'tcx> BlockS<'blk, 'tcx> {
595     pub fn new(llbb: BasicBlockRef,
596                is_lpad: bool,
597                opt_node_id: Option<ast::NodeId>,
598                fcx: &'blk FunctionContext<'blk, 'tcx>)
599                -> Block<'blk, 'tcx> {
600         fcx.block_arena.alloc(BlockS {
601             llbb: llbb,
602             terminated: Cell::new(false),
603             unreachable: Cell::new(false),
604             is_lpad: is_lpad,
605             opt_node_id: opt_node_id,
606             fcx: fcx
607         })
608     }
609
610     pub fn ccx(&self) -> &'blk CrateContext<'blk, 'tcx> {
611         self.fcx.ccx
612     }
613     pub fn tcx(&self) -> &'blk ty::ctxt<'tcx> {
614         self.fcx.ccx.tcx()
615     }
616     pub fn sess(&self) -> &'blk Session { self.fcx.ccx.sess() }
617
618     pub fn mir(&self) -> &'blk Mir<'tcx> {
619         self.fcx.mir()
620     }
621
622     pub fn name(&self, name: ast::Name) -> String {
623         name.to_string()
624     }
625
626     pub fn node_id_to_string(&self, id: ast::NodeId) -> String {
627         self.tcx().map.node_to_string(id).to_string()
628     }
629
630     pub fn def(&self, nid: ast::NodeId) -> def::Def {
631         match self.tcx().def_map.borrow().get(&nid) {
632             Some(v) => v.full_def(),
633             None => {
634                 self.tcx().sess.bug(&format!(
635                     "no def associated with node id {}", nid));
636             }
637         }
638     }
639
640     pub fn val_to_string(&self, val: ValueRef) -> String {
641         self.ccx().tn().val_to_string(val)
642     }
643
644     pub fn llty_str(&self, ty: Type) -> String {
645         self.ccx().tn().type_to_string(ty)
646     }
647
648     pub fn to_str(&self) -> String {
649         format!("[block {:p}]", self)
650     }
651
652     pub fn monomorphize<T>(&self, value: &T) -> T
653         where T : TypeFoldable<'tcx>
654     {
655         monomorphize::apply_param_substs(self.tcx(),
656                                          self.fcx.param_substs,
657                                          value)
658     }
659 }
660
661 pub struct Result<'blk, 'tcx: 'blk> {
662     pub bcx: Block<'blk, 'tcx>,
663     pub val: ValueRef
664 }
665
666 impl<'b, 'tcx> Result<'b, 'tcx> {
667     pub fn new(bcx: Block<'b, 'tcx>, val: ValueRef) -> Result<'b, 'tcx> {
668         Result {
669             bcx: bcx,
670             val: val,
671         }
672     }
673 }
674
675 pub fn val_ty(v: ValueRef) -> Type {
676     unsafe {
677         Type::from_ref(llvm::LLVMTypeOf(v))
678     }
679 }
680
681 // LLVM constant constructors.
682 pub fn C_null(t: Type) -> ValueRef {
683     unsafe {
684         llvm::LLVMConstNull(t.to_ref())
685     }
686 }
687
688 pub fn C_undef(t: Type) -> ValueRef {
689     unsafe {
690         llvm::LLVMGetUndef(t.to_ref())
691     }
692 }
693
694 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
695     unsafe {
696         llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
697     }
698 }
699
700 pub fn C_floating(s: &str, t: Type) -> ValueRef {
701     unsafe {
702         let s = CString::new(s).unwrap();
703         llvm::LLVMConstRealOfString(t.to_ref(), s.as_ptr())
704     }
705 }
706
707 pub fn C_floating_f64(f: f64, t: Type) -> ValueRef {
708     unsafe {
709         llvm::LLVMConstReal(t.to_ref(), f)
710     }
711 }
712
713 pub fn C_nil(ccx: &CrateContext) -> ValueRef {
714     C_struct(ccx, &[], false)
715 }
716
717 pub fn C_bool(ccx: &CrateContext, val: bool) -> ValueRef {
718     C_integral(Type::i1(ccx), val as u64, false)
719 }
720
721 pub fn C_i32(ccx: &CrateContext, i: i32) -> ValueRef {
722     C_integral(Type::i32(ccx), i as u64, true)
723 }
724
725 pub fn C_u32(ccx: &CrateContext, i: u32) -> ValueRef {
726     C_integral(Type::i32(ccx), i as u64, false)
727 }
728
729 pub fn C_u64(ccx: &CrateContext, i: u64) -> ValueRef {
730     C_integral(Type::i64(ccx), i, false)
731 }
732
733 pub fn C_int<I: AsI64>(ccx: &CrateContext, i: I) -> ValueRef {
734     let v = i.as_i64();
735
736     let bit_size = machine::llbitsize_of_real(ccx, ccx.int_type());
737
738     if bit_size < 64 {
739         // make sure it doesn't overflow
740         assert!(v < (1<<(bit_size-1)) && v >= -(1<<(bit_size-1)));
741     }
742
743     C_integral(ccx.int_type(), v as u64, true)
744 }
745
746 pub fn C_uint<I: AsU64>(ccx: &CrateContext, i: I) -> ValueRef {
747     let v = i.as_u64();
748
749     let bit_size = machine::llbitsize_of_real(ccx, ccx.int_type());
750
751     if bit_size < 64 {
752         // make sure it doesn't overflow
753         assert!(v < (1<<bit_size));
754     }
755
756     C_integral(ccx.int_type(), v, false)
757 }
758
759 pub trait AsI64 { fn as_i64(self) -> i64; }
760 pub trait AsU64 { fn as_u64(self) -> u64; }
761
762 // FIXME: remove the intptr conversions, because they
763 // are host-architecture-dependent
764 impl AsI64 for i64 { fn as_i64(self) -> i64 { self as i64 }}
765 impl AsI64 for i32 { fn as_i64(self) -> i64 { self as i64 }}
766 impl AsI64 for isize { fn as_i64(self) -> i64 { self as i64 }}
767
768 impl AsU64 for u64  { fn as_u64(self) -> u64 { self as u64 }}
769 impl AsU64 for u32  { fn as_u64(self) -> u64 { self as u64 }}
770 impl AsU64 for usize { fn as_u64(self) -> u64 { self as u64 }}
771
772 pub fn C_u8(ccx: &CrateContext, i: u8) -> ValueRef {
773     C_integral(Type::i8(ccx), i as u64, false)
774 }
775
776
777 // This is a 'c-like' raw string, which differs from
778 // our boxed-and-length-annotated strings.
779 pub fn C_cstr(cx: &CrateContext, s: InternedString, null_terminated: bool) -> ValueRef {
780     unsafe {
781         match cx.const_cstr_cache().borrow().get(&s) {
782             Some(&llval) => return llval,
783             None => ()
784         }
785
786         let sc = llvm::LLVMConstStringInContext(cx.llcx(),
787                                                 s.as_ptr() as *const c_char,
788                                                 s.len() as c_uint,
789                                                 !null_terminated as Bool);
790
791         let gsym = token::gensym("str");
792         let sym = format!("str{}", gsym.0);
793         let g = declare::define_global(cx, &sym[..], val_ty(sc)).unwrap_or_else(||{
794             cx.sess().bug(&format!("symbol `{}` is already defined", sym));
795         });
796         llvm::LLVMSetInitializer(g, sc);
797         llvm::LLVMSetGlobalConstant(g, True);
798         llvm::SetLinkage(g, llvm::InternalLinkage);
799
800         cx.const_cstr_cache().borrow_mut().insert(s, g);
801         g
802     }
803 }
804
805 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
806 // you will be kicked off fast isel. See issue #4352 for an example of this.
807 pub fn C_str_slice(cx: &CrateContext, s: InternedString) -> ValueRef {
808     let len = s.len();
809     let cs = consts::ptrcast(C_cstr(cx, s, false), Type::i8p(cx));
810     C_named_struct(cx.tn().find_type("str_slice").unwrap(), &[cs, C_uint(cx, len)])
811 }
812
813 pub fn C_struct(cx: &CrateContext, elts: &[ValueRef], packed: bool) -> ValueRef {
814     C_struct_in_context(cx.llcx(), elts, packed)
815 }
816
817 pub fn C_struct_in_context(llcx: ContextRef, elts: &[ValueRef], packed: bool) -> ValueRef {
818     unsafe {
819         llvm::LLVMConstStructInContext(llcx,
820                                        elts.as_ptr(), elts.len() as c_uint,
821                                        packed as Bool)
822     }
823 }
824
825 pub fn C_named_struct(t: Type, elts: &[ValueRef]) -> ValueRef {
826     unsafe {
827         llvm::LLVMConstNamedStruct(t.to_ref(), elts.as_ptr(), elts.len() as c_uint)
828     }
829 }
830
831 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
832     unsafe {
833         return llvm::LLVMConstArray(ty.to_ref(), elts.as_ptr(), elts.len() as c_uint);
834     }
835 }
836
837 pub fn C_vector(elts: &[ValueRef]) -> ValueRef {
838     unsafe {
839         return llvm::LLVMConstVector(elts.as_ptr(), elts.len() as c_uint);
840     }
841 }
842
843 pub fn C_bytes(cx: &CrateContext, bytes: &[u8]) -> ValueRef {
844     C_bytes_in_context(cx.llcx(), bytes)
845 }
846
847 pub fn C_bytes_in_context(llcx: ContextRef, bytes: &[u8]) -> ValueRef {
848     unsafe {
849         let ptr = bytes.as_ptr() as *const c_char;
850         return llvm::LLVMConstStringInContext(llcx, ptr, bytes.len() as c_uint, True);
851     }
852 }
853
854 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
855               -> ValueRef {
856     unsafe {
857         let r = llvm::LLVMConstExtractValue(v, us.as_ptr(), us.len() as c_uint);
858
859         debug!("const_get_elt(v={}, us={:?}, r={})",
860                cx.tn().val_to_string(v), us, cx.tn().val_to_string(r));
861
862         return r;
863     }
864 }
865
866 pub fn const_to_int(v: ValueRef) -> i64 {
867     unsafe {
868         llvm::LLVMConstIntGetSExtValue(v)
869     }
870 }
871
872 pub fn const_to_uint(v: ValueRef) -> u64 {
873     unsafe {
874         llvm::LLVMConstIntGetZExtValue(v)
875     }
876 }
877
878 fn is_const_integral(v: ValueRef) -> bool {
879     unsafe {
880         !llvm::LLVMIsAConstantInt(v).is_null()
881     }
882 }
883
884 pub fn const_to_opt_int(v: ValueRef) -> Option<i64> {
885     unsafe {
886         if is_const_integral(v) {
887             Some(llvm::LLVMConstIntGetSExtValue(v))
888         } else {
889             None
890         }
891     }
892 }
893
894 pub fn const_to_opt_uint(v: ValueRef) -> Option<u64> {
895     unsafe {
896         if is_const_integral(v) {
897             Some(llvm::LLVMConstIntGetZExtValue(v))
898         } else {
899             None
900         }
901     }
902 }
903
904 pub fn is_undef(val: ValueRef) -> bool {
905     unsafe {
906         llvm::LLVMIsUndef(val) != False
907     }
908 }
909
910 #[allow(dead_code)] // potentially useful
911 pub fn is_null(val: ValueRef) -> bool {
912     unsafe {
913         llvm::LLVMIsNull(val) != False
914     }
915 }
916
917 pub fn monomorphize_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, t: Ty<'tcx>) -> Ty<'tcx> {
918     bcx.fcx.monomorphize(&t)
919 }
920
921 pub fn node_id_type<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, id: ast::NodeId) -> Ty<'tcx> {
922     let tcx = bcx.tcx();
923     let t = tcx.node_id_to_type(id);
924     monomorphize_type(bcx, t)
925 }
926
927 pub fn expr_ty<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &hir::Expr) -> Ty<'tcx> {
928     node_id_type(bcx, ex.id)
929 }
930
931 pub fn expr_ty_adjusted<'blk, 'tcx>(bcx: &BlockS<'blk, 'tcx>, ex: &hir::Expr) -> Ty<'tcx> {
932     monomorphize_type(bcx, bcx.tcx().expr_ty_adjusted(ex))
933 }
934
935 /// Attempts to resolve an obligation. The result is a shallow vtable resolution -- meaning that we
936 /// do not (necessarily) resolve all nested obligations on the impl. Note that type check should
937 /// guarantee to us that all nested obligations *could be* resolved if we wanted to.
938 pub fn fulfill_obligation<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
939                                     span: Span,
940                                     trait_ref: ty::PolyTraitRef<'tcx>)
941                                     -> traits::Vtable<'tcx, ()>
942 {
943     let tcx = ccx.tcx();
944
945     // Remove any references to regions; this helps improve caching.
946     let trait_ref = tcx.erase_regions(&trait_ref);
947
948     // First check the cache.
949     match ccx.trait_cache().borrow().get(&trait_ref) {
950         Some(vtable) => {
951             info!("Cache hit: {:?}", trait_ref);
952             return (*vtable).clone();
953         }
954         None => { }
955     }
956
957     debug!("trans fulfill_obligation: trait_ref={:?} def_id={:?}",
958            trait_ref, trait_ref.def_id());
959
960
961     // Do the initial selection for the obligation. This yields the
962     // shallow result we are looking for -- that is, what specific impl.
963     let infcx = infer::normalizing_infer_ctxt(tcx, &tcx.tables);
964     let mut selcx = traits::SelectionContext::new(&infcx);
965
966     let obligation =
967         traits::Obligation::new(traits::ObligationCause::misc(span, ast::DUMMY_NODE_ID),
968                                 trait_ref.to_poly_trait_predicate());
969     let selection = match selcx.select(&obligation) {
970         Ok(Some(selection)) => selection,
971         Ok(None) => {
972             // Ambiguity can happen when monomorphizing during trans
973             // expands to some humongo type that never occurred
974             // statically -- this humongo type can then overflow,
975             // leading to an ambiguous result. So report this as an
976             // overflow bug, since I believe this is the only case
977             // where ambiguity can result.
978             debug!("Encountered ambiguity selecting `{:?}` during trans, \
979                     presuming due to overflow",
980                    trait_ref);
981             ccx.sess().span_fatal(
982                 span,
983                 "reached the recursion limit during monomorphization (selection ambiguity)");
984         }
985         Err(e) => {
986             tcx.sess.span_bug(
987                 span,
988                 &format!("Encountered error `{:?}` selecting `{:?}` during trans",
989                         e,
990                         trait_ref))
991         }
992     };
993
994     // Currently, we use a fulfillment context to completely resolve
995     // all nested obligations. This is because they can inform the
996     // inference of the impl's type parameters.
997     let mut fulfill_cx = infcx.fulfillment_cx.borrow_mut();
998     let vtable = selection.map(|predicate| {
999         fulfill_cx.register_predicate_obligation(&infcx, predicate);
1000     });
1001     let vtable = infer::drain_fulfillment_cx_or_panic(
1002         span, &infcx, &mut fulfill_cx, &vtable
1003     );
1004
1005     info!("Cache miss: {:?} => {:?}", trait_ref, vtable);
1006
1007     ccx.trait_cache().borrow_mut().insert(trait_ref, vtable.clone());
1008
1009     vtable
1010 }
1011
1012 /// Normalizes the predicates and checks whether they hold.  If this
1013 /// returns false, then either normalize encountered an error or one
1014 /// of the predicates did not hold. Used when creating vtables to
1015 /// check for unsatisfiable methods.
1016 pub fn normalize_and_test_predicates<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1017                                                predicates: Vec<ty::Predicate<'tcx>>)
1018                                                -> bool
1019 {
1020     debug!("normalize_and_test_predicates(predicates={:?})",
1021            predicates);
1022
1023     let tcx = ccx.tcx();
1024     let infcx = infer::normalizing_infer_ctxt(tcx, &tcx.tables);
1025     let mut selcx = traits::SelectionContext::new(&infcx);
1026     let mut fulfill_cx = infcx.fulfillment_cx.borrow_mut();
1027     let cause = traits::ObligationCause::dummy();
1028     let traits::Normalized { value: predicates, obligations } =
1029         traits::normalize(&mut selcx, cause.clone(), &predicates);
1030     for obligation in obligations {
1031         fulfill_cx.register_predicate_obligation(&infcx, obligation);
1032     }
1033     for predicate in predicates {
1034         let obligation = traits::Obligation::new(cause.clone(), predicate);
1035         fulfill_cx.register_predicate_obligation(&infcx, obligation);
1036     }
1037
1038     infer::drain_fulfillment_cx(&infcx, &mut fulfill_cx, &()).is_ok()
1039 }
1040
1041 // Key used to lookup values supplied for type parameters in an expr.
1042 #[derive(Copy, Clone, PartialEq, Debug)]
1043 pub enum ExprOrMethodCall {
1044     // Type parameters for a path like `None::<int>`
1045     ExprId(ast::NodeId),
1046
1047     // Type parameters for a method call like `a.foo::<int>()`
1048     MethodCallKey(ty::MethodCall)
1049 }
1050
1051 pub fn node_id_substs<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1052                             node: ExprOrMethodCall,
1053                             param_substs: &subst::Substs<'tcx>)
1054                             -> subst::Substs<'tcx> {
1055     let tcx = ccx.tcx();
1056
1057     let substs = match node {
1058         ExprId(id) => {
1059             tcx.node_id_item_substs(id).substs
1060         }
1061         MethodCallKey(method_call) => {
1062             tcx.tables.borrow().method_map[&method_call].substs.clone()
1063         }
1064     };
1065
1066     if substs.types.needs_infer() {
1067             tcx.sess.bug(&format!("type parameters for node {:?} include inference types: {:?}",
1068                                  node, substs));
1069         }
1070
1071         monomorphize::apply_param_substs(tcx,
1072                                          param_substs,
1073                                          &substs.erase_regions())
1074 }
1075
1076 pub fn langcall(bcx: Block,
1077                 span: Option<Span>,
1078                 msg: &str,
1079                 li: LangItem)
1080                 -> DefId {
1081     match bcx.tcx().lang_items.require(li) {
1082         Ok(id) => id,
1083         Err(s) => {
1084             let msg = format!("{} {}", msg, s);
1085             match span {
1086                 Some(span) => bcx.tcx().sess.span_fatal(span, &msg[..]),
1087                 None => bcx.tcx().sess.fatal(&msg[..]),
1088             }
1089         }
1090     }
1091 }
1092
1093 /// Return the VariantDef corresponding to an inlined variant node
1094 pub fn inlined_variant_def<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1095                                      inlined_vid: ast::NodeId)
1096                                      -> ty::VariantDef<'tcx>
1097 {
1098
1099     let ctor_ty = ccx.tcx().node_id_to_type(inlined_vid);
1100     debug!("inlined_variant_def: ctor_ty={:?} inlined_vid={:?}", ctor_ty,
1101            inlined_vid);
1102     let adt_def = match ctor_ty.sty {
1103         ty::TyBareFn(_, &ty::BareFnTy { sig: ty::Binder(ty::FnSig {
1104             output: ty::FnConverging(ty), ..
1105         }), ..}) => ty,
1106         _ => ctor_ty
1107     }.ty_adt_def().unwrap();
1108     let inlined_vid_def_id = ccx.tcx().map.local_def_id(inlined_vid);
1109     adt_def.variants.iter().find(|v| {
1110         inlined_vid_def_id == v.did ||
1111             ccx.external().borrow().get(&v.did) == Some(&Some(inlined_vid))
1112     }).unwrap_or_else(|| {
1113         ccx.sess().bug(&format!("no variant for {:?}::{}", adt_def, inlined_vid))
1114     })
1115 }
1116
1117 // To avoid UB from LLVM, these two functions mask RHS with an
1118 // appropriate mask unconditionally (i.e. the fallback behavior for
1119 // all shifts). For 32- and 64-bit types, this matches the semantics
1120 // of Java. (See related discussion on #1877 and #10183.)
1121
1122 pub fn build_unchecked_lshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1123                                           lhs: ValueRef,
1124                                           rhs: ValueRef,
1125                                           binop_debug_loc: DebugLoc) -> ValueRef {
1126     let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShl, lhs, rhs);
1127     // #1877, #10183: Ensure that input is always valid
1128     let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
1129     build::Shl(bcx, lhs, rhs, binop_debug_loc)
1130 }
1131
1132 pub fn build_unchecked_rshift<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1133                                           lhs_t: Ty<'tcx>,
1134                                           lhs: ValueRef,
1135                                           rhs: ValueRef,
1136                                           binop_debug_loc: DebugLoc) -> ValueRef {
1137     let rhs = base::cast_shift_expr_rhs(bcx, hir::BinOp_::BiShr, lhs, rhs);
1138     // #1877, #10183: Ensure that input is always valid
1139     let rhs = shift_mask_rhs(bcx, rhs, binop_debug_loc);
1140     let is_signed = lhs_t.is_signed();
1141     if is_signed {
1142         build::AShr(bcx, lhs, rhs, binop_debug_loc)
1143     } else {
1144         build::LShr(bcx, lhs, rhs, binop_debug_loc)
1145     }
1146 }
1147
1148 fn shift_mask_rhs<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1149                               rhs: ValueRef,
1150                               debug_loc: DebugLoc) -> ValueRef {
1151     let rhs_llty = val_ty(rhs);
1152     build::And(bcx, rhs, shift_mask_val(bcx, rhs_llty, rhs_llty, false), debug_loc)
1153 }
1154
1155 pub fn shift_mask_val<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1156                               llty: Type,
1157                               mask_llty: Type,
1158                               invert: bool) -> ValueRef {
1159     let kind = llty.kind();
1160     match kind {
1161         TypeKind::Integer => {
1162             // i8/u8 can shift by at most 7, i16/u16 by at most 15, etc.
1163             let val = llty.int_width() - 1;
1164             if invert {
1165                 C_integral(mask_llty, !val, true)
1166             } else {
1167                 C_integral(mask_llty, val, false)
1168             }
1169         },
1170         TypeKind::Vector => {
1171             let mask = shift_mask_val(bcx, llty.element_type(), mask_llty.element_type(), invert);
1172             build::VectorSplat(bcx, mask_llty.vector_length(), mask)
1173         },
1174         _ => panic!("shift_mask_val: expected Integer or Vector, found {:?}", kind),
1175     }
1176 }
1177
1178 pub fn get_static_val<'a, 'tcx>(ccx: &CrateContext<'a, 'tcx>,
1179                             did: DefId,
1180                             ty: Ty<'tcx>)
1181                             -> ValueRef {
1182     if let Some(node_id) = ccx.tcx().map.as_local_node_id(did) {
1183         base::get_item_val(ccx, node_id)
1184     } else {
1185         base::get_extern_const(ccx, did, ty)
1186     }
1187 }