]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/common.rs
auto merge of #7996 : erickt/rust/cleanup-strs, r=erickt
[rust.git] / src / librustc / middle / trans / common.rs
1 // Copyright 2012-2013 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 //! Code that is useful in various trans modules.
12
13
14 use driver::session;
15 use driver::session::Session;
16 use lib::llvm::{ValueRef, BasicBlockRef, BuilderRef};
17 use lib::llvm::{True, False, Bool};
18 use lib::llvm::{llvm};
19 use lib;
20 use middle::lang_items::LangItem;
21 use middle::trans::base;
22 use middle::trans::build;
23 use middle::trans::datum;
24 use middle::trans::glue;
25 use middle::trans::write_guard;
26 use middle::ty::substs;
27 use middle::ty;
28 use middle::typeck;
29 use middle::borrowck::root_map_key;
30 use util::ppaux::{Repr};
31
32 use middle::trans::type_::Type;
33
34 use std::cast::transmute;
35 use std::cast;
36 use std::hashmap::{HashMap};
37 use std::libc::{c_uint, c_longlong, c_ulonglong};
38 use std::vec;
39 use syntax::ast::ident;
40 use syntax::ast_map::{path, path_elt};
41 use syntax::codemap::span;
42 use syntax::parse::token;
43 use syntax::{ast, ast_map};
44
45 pub use middle::trans::context::CrateContext;
46
47 pub fn gensym_name(name: &str) -> ident {
48     token::str_to_ident(fmt!("%s_%u", name, token::gensym(name)))
49 }
50
51 pub struct tydesc_info {
52     ty: ty::t,
53     tydesc: ValueRef,
54     size: ValueRef,
55     align: ValueRef,
56     take_glue: Option<ValueRef>,
57     drop_glue: Option<ValueRef>,
58     free_glue: Option<ValueRef>,
59     visit_glue: Option<ValueRef>
60 }
61
62 /*
63  * A note on nomenclature of linking: "extern", "foreign", and "upcall".
64  *
65  * An "extern" is an LLVM symbol we wind up emitting an undefined external
66  * reference to. This means "we don't have the thing in this compilation unit,
67  * please make sure you link it in at runtime". This could be a reference to
68  * C code found in a C library, or rust code found in a rust crate.
69  *
70  * Most "externs" are implicitly declared (automatically) as a result of a
71  * user declaring an extern _module_ dependency; this causes the rust driver
72  * to locate an extern crate, scan its compilation metadata, and emit extern
73  * declarations for any symbols used by the declaring crate.
74  *
75  * A "foreign" is an extern that references C (or other non-rust ABI) code.
76  * There is no metadata to scan for extern references so in these cases either
77  * a header-digester like bindgen, or manual function prototypes, have to
78  * serve as declarators. So these are usually given explicitly as prototype
79  * declarations, in rust code, with ABI attributes on them noting which ABI to
80  * link via.
81  *
82  * An "upcall" is a foreign call generated by the compiler (not corresponding
83  * to any user-written call in the code) into the runtime library, to perform
84  * some helper task such as bringing a task to life, allocating memory, etc.
85  *
86  */
87
88 pub struct Stats {
89     n_static_tydescs: uint,
90     n_glues_created: uint,
91     n_null_glues: uint,
92     n_real_glues: uint,
93     n_fns: uint,
94     n_monos: uint,
95     n_inlines: uint,
96     n_closures: uint,
97     n_llvm_insns: uint,
98     llvm_insn_ctxt: ~[~str],
99     llvm_insns: HashMap<~str, uint>,
100     fn_stats: ~[(~str, uint, uint)] // (ident, time-in-ms, llvm-instructions)
101 }
102
103 pub struct BuilderRef_res {
104     B: BuilderRef,
105 }
106
107 impl Drop for BuilderRef_res {
108     fn drop(&self) {
109         unsafe {
110             llvm::LLVMDisposeBuilder(self.B);
111         }
112     }
113 }
114
115 pub fn BuilderRef_res(B: BuilderRef) -> BuilderRef_res {
116     BuilderRef_res {
117         B: B
118     }
119 }
120
121 pub type ExternMap = HashMap<@str, ValueRef>;
122
123 // Types used for llself.
124 pub struct ValSelfData {
125     v: ValueRef,
126     t: ty::t,
127     is_copy: bool,
128 }
129
130 // Here `self_ty` is the real type of the self parameter to this method. It
131 // will only be set in the case of default methods.
132 pub struct param_substs {
133     tys: ~[ty::t],
134     self_ty: Option<ty::t>,
135     vtables: Option<typeck::vtable_res>,
136     self_vtable: Option<typeck::vtable_origin>
137 }
138
139 impl param_substs {
140     pub fn validate(&self) {
141         for self.tys.iter().advance |t| { assert!(!ty::type_needs_infer(*t)); }
142         for self.self_ty.iter().advance |t| { assert!(!ty::type_needs_infer(*t)); }
143     }
144 }
145
146 fn param_substs_to_str(this: &param_substs, tcx: ty::ctxt) -> ~str {
147     fmt!("param_substs {tys:%s, vtables:%s}",
148          this.tys.repr(tcx),
149          this.vtables.repr(tcx))
150 }
151
152 impl Repr for param_substs {
153     fn repr(&self, tcx: ty::ctxt) -> ~str {
154         param_substs_to_str(self, tcx)
155     }
156 }
157
158 // Function context.  Every LLVM function we create will have one of
159 // these.
160 pub struct FunctionContext {
161     // The ValueRef returned from a call to llvm::LLVMAddFunction; the
162     // address of the first instruction in the sequence of
163     // instructions for this function that will go in the .text
164     // section of the executable we're generating.
165     llfn: ValueRef,
166
167     // The implicit environment argument that arrives in the function we're
168     // creating.
169     llenv: ValueRef,
170
171     // The place to store the return value. If the return type is immediate,
172     // this is an alloca in the function. Otherwise, it's the hidden first
173     // parameter to the function. After function construction, this should
174     // always be Some.
175     llretptr: Option<ValueRef>,
176
177     entry_bcx: Option<@mut Block>,
178
179     // These elements: "hoisted basic blocks" containing
180     // administrative activities that have to happen in only one place in
181     // the function, due to LLVM's quirks.
182     // A marker for the place where we want to insert the function's static
183     // allocas, so that LLVM will coalesce them into a single alloca call.
184     alloca_insert_pt: Option<ValueRef>,
185     llreturn: Option<BasicBlockRef>,
186     // The 'self' value currently in use in this function, if there
187     // is one.
188     //
189     // NB: This is the type of the self *variable*, not the self *type*. The
190     // self type is set only for default methods, while the self variable is
191     // set for all methods.
192     llself: Option<ValSelfData>,
193     // The a value alloca'd for calls to upcalls.rust_personality. Used when
194     // outputting the resume instruction.
195     personality: Option<ValueRef>,
196     // If this is a for-loop body that returns, this holds the pointers needed
197     // for that (flagptr, retptr)
198     loop_ret: Option<(ValueRef, ValueRef)>,
199
200     // True if this function has an immediate return value, false otherwise.
201     // If this is false, the llretptr will alias the first argument of the
202     // function.
203     has_immediate_return_value: bool,
204
205     // Maps arguments to allocas created for them in llallocas.
206     llargs: @mut HashMap<ast::node_id, ValueRef>,
207     // Maps the def_ids for local variables to the allocas created for
208     // them in llallocas.
209     lllocals: @mut HashMap<ast::node_id, ValueRef>,
210     // Same as above, but for closure upvars
211     llupvars: @mut HashMap<ast::node_id, ValueRef>,
212
213     // The node_id of the function, or -1 if it doesn't correspond to
214     // a user-defined function.
215     id: ast::node_id,
216
217     // If this function is being monomorphized, this contains the type
218     // substitutions used.
219     param_substs: Option<@param_substs>,
220
221     // The source span and nesting context where this function comes from, for
222     // error reporting and symbol generation.
223     span: Option<span>,
224     path: path,
225
226     // This function's enclosing crate context.
227     ccx: @mut CrateContext
228 }
229
230 impl FunctionContext {
231     pub fn arg_pos(&self, arg: uint) -> uint {
232         if self.has_immediate_return_value {
233             arg + 1u
234         } else {
235             arg + 2u
236         }
237     }
238
239     pub fn out_arg_pos(&self) -> uint {
240         assert!(self.has_immediate_return_value);
241         0u
242     }
243
244     pub fn env_arg_pos(&self) -> uint {
245         if !self.has_immediate_return_value {
246             1u
247         } else {
248             0u
249         }
250     }
251
252     pub fn cleanup(&mut self) {
253         unsafe {
254             llvm::LLVMInstructionEraseFromParent(self.alloca_insert_pt.get());
255         }
256         // Remove the cycle between fcx and bcx, so memory can be freed
257         self.entry_bcx = None;
258     }
259
260     pub fn get_llreturn(&mut self) -> BasicBlockRef {
261         if self.llreturn.is_none() {
262             self.llreturn = Some(base::mk_return_basic_block(self.llfn));
263         }
264
265         self.llreturn.get()
266     }
267 }
268
269 pub fn warn_not_to_commit(ccx: &mut CrateContext, msg: &str) {
270     if !ccx.do_not_commit_warning_issued {
271         ccx.do_not_commit_warning_issued = true;
272         ccx.sess.warn(msg.to_str() + " -- do not commit like this!");
273     }
274 }
275
276 // Heap selectors. Indicate which heap something should go on.
277 #[deriving(Eq)]
278 pub enum heap {
279     heap_managed,
280     heap_managed_unique,
281     heap_exchange,
282     heap_exchange_closure
283 }
284
285 #[deriving(Clone, Eq)]
286 pub enum cleantype {
287     normal_exit_only,
288     normal_exit_and_unwind
289 }
290
291 pub enum cleanup {
292     clean(@fn(@mut Block) -> @mut Block, cleantype),
293     clean_temp(ValueRef, @fn(@mut Block) -> @mut Block, cleantype),
294 }
295
296 // Can't use deriving(Clone) because of the managed closure.
297 impl Clone for cleanup {
298     fn clone(&self) -> cleanup {
299         match *self {
300             clean(f, ct) => clean(f, ct),
301             clean_temp(v, f, ct) => clean_temp(v, f, ct),
302         }
303     }
304 }
305
306 // Used to remember and reuse existing cleanup paths
307 // target: none means the path ends in an resume instruction
308 #[deriving(Clone)]
309 pub struct cleanup_path {
310     target: Option<BasicBlockRef>,
311     size: uint,
312     dest: BasicBlockRef
313 }
314
315 pub fn shrink_scope_clean(scope_info: &mut ScopeInfo, size: uint) {
316     scope_info.landing_pad = None;
317     scope_info.cleanup_paths = scope_info.cleanup_paths.iter()
318             .take_while(|&cu| cu.size <= size).transform(|&x|x).collect();
319 }
320
321 pub fn grow_scope_clean(scope_info: &mut ScopeInfo) {
322     scope_info.landing_pad = None;
323 }
324
325 pub fn cleanup_type(cx: ty::ctxt, ty: ty::t) -> cleantype {
326     if ty::type_needs_unwind_cleanup(cx, ty) {
327         normal_exit_and_unwind
328     } else {
329         normal_exit_only
330     }
331 }
332
333 pub fn add_clean(bcx: @mut Block, val: ValueRef, t: ty::t) {
334     if !ty::type_needs_drop(bcx.tcx(), t) { return; }
335
336     debug!("add_clean(%s, %s, %s)", bcx.to_str(), bcx.val_to_str(val), t.repr(bcx.tcx()));
337
338     let cleanup_type = cleanup_type(bcx.tcx(), t);
339     do in_scope_cx(bcx, None) |scope_info| {
340         scope_info.cleanups.push(clean(|a| glue::drop_ty(a, val, t), cleanup_type));
341         grow_scope_clean(scope_info);
342     }
343 }
344
345 pub fn add_clean_temp_immediate(cx: @mut Block, val: ValueRef, ty: ty::t) {
346     if !ty::type_needs_drop(cx.tcx(), ty) { return; }
347     debug!("add_clean_temp_immediate(%s, %s, %s)",
348            cx.to_str(), cx.val_to_str(val),
349            ty.repr(cx.tcx()));
350     let cleanup_type = cleanup_type(cx.tcx(), ty);
351     do in_scope_cx(cx, None) |scope_info| {
352         scope_info.cleanups.push(
353             clean_temp(val, |a| glue::drop_ty_immediate(a, val, ty),
354                        cleanup_type));
355         grow_scope_clean(scope_info);
356     }
357 }
358
359 pub fn add_clean_temp_mem(bcx: @mut Block, val: ValueRef, t: ty::t) {
360     add_clean_temp_mem_in_scope_(bcx, None, val, t);
361 }
362
363 pub fn add_clean_temp_mem_in_scope(bcx: @mut Block,
364                                    scope_id: ast::node_id,
365                                    val: ValueRef,
366                                    t: ty::t) {
367     add_clean_temp_mem_in_scope_(bcx, Some(scope_id), val, t);
368 }
369
370 pub fn add_clean_temp_mem_in_scope_(bcx: @mut Block, scope_id: Option<ast::node_id>,
371                                     val: ValueRef, t: ty::t) {
372     if !ty::type_needs_drop(bcx.tcx(), t) { return; }
373     debug!("add_clean_temp_mem(%s, %s, %s)",
374            bcx.to_str(), bcx.val_to_str(val),
375            t.repr(bcx.tcx()));
376     let cleanup_type = cleanup_type(bcx.tcx(), t);
377     do in_scope_cx(bcx, scope_id) |scope_info| {
378         scope_info.cleanups.push(clean_temp(val, |a| glue::drop_ty(a, val, t), cleanup_type));
379         grow_scope_clean(scope_info);
380     }
381 }
382 pub fn add_clean_return_to_mut(bcx: @mut Block,
383                                scope_id: ast::node_id,
384                                root_key: root_map_key,
385                                frozen_val_ref: ValueRef,
386                                bits_val_ref: ValueRef,
387                                filename_val: ValueRef,
388                                line_val: ValueRef) {
389     //! When an `@mut` has been frozen, we have to
390     //! call the lang-item `return_to_mut` when the
391     //! freeze goes out of scope. We need to pass
392     //! in both the value which was frozen (`frozen_val`) and
393     //! the value (`bits_val_ref`) which was returned when the
394     //! box was frozen initially. Here, both `frozen_val_ref` and
395     //! `bits_val_ref` are in fact pointers to stack slots.
396
397     debug!("add_clean_return_to_mut(%s, %s, %s)",
398            bcx.to_str(),
399            bcx.val_to_str(frozen_val_ref),
400            bcx.val_to_str(bits_val_ref));
401     do in_scope_cx(bcx, Some(scope_id)) |scope_info| {
402         scope_info.cleanups.push(
403             clean_temp(
404                 frozen_val_ref,
405                 |bcx| write_guard::return_to_mut(bcx, root_key, frozen_val_ref, bits_val_ref,
406                                                  filename_val, line_val),
407                 normal_exit_only));
408         grow_scope_clean(scope_info);
409     }
410 }
411 pub fn add_clean_free(cx: @mut Block, ptr: ValueRef, heap: heap) {
412     let free_fn = match heap {
413       heap_managed | heap_managed_unique => {
414         let f: @fn(@mut Block) -> @mut Block = |a| glue::trans_free(a, ptr);
415         f
416       }
417       heap_exchange | heap_exchange_closure => {
418         let f: @fn(@mut Block) -> @mut Block = |a| glue::trans_exchange_free(a, ptr);
419         f
420       }
421     };
422     do in_scope_cx(cx, None) |scope_info| {
423         scope_info.cleanups.push(clean_temp(ptr, free_fn,
424                                       normal_exit_and_unwind));
425         grow_scope_clean(scope_info);
426     }
427 }
428
429 // Note that this only works for temporaries. We should, at some point, move
430 // to a system where we can also cancel the cleanup on local variables, but
431 // this will be more involved. For now, we simply zero out the local, and the
432 // drop glue checks whether it is zero.
433 pub fn revoke_clean(cx: @mut Block, val: ValueRef) {
434     do in_scope_cx(cx, None) |scope_info| {
435         let cleanup_pos = scope_info.cleanups.iter().position(
436             |cu| match *cu {
437                 clean_temp(v, _, _) if v == val => true,
438                 _ => false
439             });
440         for cleanup_pos.iter().advance |i| {
441             scope_info.cleanups =
442                 vec::append(scope_info.cleanups.slice(0u, *i).to_owned(),
443                             scope_info.cleanups.slice(*i + 1u,
444                                                       scope_info.cleanups.len()));
445             shrink_scope_clean(scope_info, *i);
446         }
447     }
448 }
449
450 pub fn block_cleanups(bcx: @mut Block) -> ~[cleanup] {
451     match bcx.scope {
452        None  => ~[],
453        Some(inf) => inf.cleanups.clone(),
454     }
455 }
456
457 pub struct ScopeInfo {
458     parent: Option<@mut ScopeInfo>,
459     loop_break: Option<@mut Block>,
460     loop_label: Option<ident>,
461     // A list of functions that must be run at when leaving this
462     // block, cleaning up any variables that were introduced in the
463     // block.
464     cleanups: ~[cleanup],
465     // Existing cleanup paths that may be reused, indexed by destination and
466     // cleared when the set of cleanups changes.
467     cleanup_paths: ~[cleanup_path],
468     // Unwinding landing pad. Also cleared when cleanups change.
469     landing_pad: Option<BasicBlockRef>,
470     // info about the AST node this scope originated from, if any
471     node_info: Option<NodeInfo>,
472 }
473
474 impl ScopeInfo {
475     pub fn empty_cleanups(&mut self) -> bool {
476         self.cleanups.is_empty()
477     }
478 }
479
480 pub trait get_node_info {
481     fn info(&self) -> Option<NodeInfo>;
482 }
483
484 impl get_node_info for ast::expr {
485     fn info(&self) -> Option<NodeInfo> {
486         Some(NodeInfo {id: self.id,
487                        callee_id: self.get_callee_id(),
488                        span: self.span})
489     }
490 }
491
492 impl get_node_info for ast::Block {
493     fn info(&self) -> Option<NodeInfo> {
494         Some(NodeInfo {id: self.id,
495                        callee_id: None,
496                        span: self.span})
497     }
498 }
499
500 impl get_node_info for Option<@ast::expr> {
501     fn info(&self) -> Option<NodeInfo> {
502         self.chain_ref(|s| s.info())
503     }
504 }
505
506 pub struct NodeInfo {
507     id: ast::node_id,
508     callee_id: Option<ast::node_id>,
509     span: span
510 }
511
512 // Basic block context.  We create a block context for each basic block
513 // (single-entry, single-exit sequence of instructions) we generate from Rust
514 // code.  Each basic block we generate is attached to a function, typically
515 // with many basic blocks per function.  All the basic blocks attached to a
516 // function are organized as a directed graph.
517 pub struct Block {
518     // The BasicBlockRef returned from a call to
519     // llvm::LLVMAppendBasicBlock(llfn, name), which adds a basic
520     // block to the function pointed to by llfn.  We insert
521     // instructions into that block by way of this block context.
522     // The block pointing to this one in the function's digraph.
523     llbb: BasicBlockRef,
524     terminated: bool,
525     unreachable: bool,
526     parent: Option<@mut Block>,
527     // The current scope within this basic block
528     scope: Option<@mut ScopeInfo>,
529     // Is this block part of a landing pad?
530     is_lpad: bool,
531     // info about the AST node this block originated from, if any
532     node_info: Option<NodeInfo>,
533     // The function context for the function to which this block is
534     // attached.
535     fcx: @mut FunctionContext
536 }
537
538 impl Block {
539
540     pub fn new(llbb: BasicBlockRef,
541                parent: Option<@mut Block>,
542                is_lpad: bool,
543                node_info: Option<NodeInfo>,
544                fcx: @mut FunctionContext)
545             -> Block {
546         Block {
547             llbb: llbb,
548             terminated: false,
549             unreachable: false,
550             parent: parent,
551             scope: None,
552             is_lpad: is_lpad,
553             node_info: node_info,
554             fcx: fcx
555         }
556     }
557
558     pub fn ccx(&self) -> @mut CrateContext { self.fcx.ccx }
559     pub fn tcx(&self) -> ty::ctxt { self.fcx.ccx.tcx }
560     pub fn sess(&self) -> Session { self.fcx.ccx.sess }
561
562     pub fn ident(&self, ident: ident) -> @str {
563         token::ident_to_str(&ident)
564     }
565
566     pub fn node_id_to_str(&self, id: ast::node_id) -> ~str {
567         ast_map::node_id_to_str(self.tcx().items, id, self.sess().intr())
568     }
569
570     pub fn expr_to_str(&self, e: @ast::expr) -> ~str {
571         e.repr(self.tcx())
572     }
573
574     pub fn expr_is_lval(&self, e: &ast::expr) -> bool {
575         ty::expr_is_lval(self.tcx(), self.ccx().maps.method_map, e)
576     }
577
578     pub fn expr_kind(&self, e: &ast::expr) -> ty::ExprKind {
579         ty::expr_kind(self.tcx(), self.ccx().maps.method_map, e)
580     }
581
582     pub fn def(&self, nid: ast::node_id) -> ast::def {
583         match self.tcx().def_map.find(&nid) {
584             Some(&v) => v,
585             None => {
586                 self.tcx().sess.bug(fmt!(
587                     "No def associated with node id %?", nid));
588             }
589         }
590     }
591
592     pub fn val_to_str(&self, val: ValueRef) -> ~str {
593         self.ccx().tn.val_to_str(val)
594     }
595
596     pub fn llty_str(&self, ty: Type) -> ~str {
597         self.ccx().tn.type_to_str(ty)
598     }
599
600     pub fn ty_to_str(&self, t: ty::t) -> ~str {
601         t.repr(self.tcx())
602     }
603
604     pub fn to_str(&self) -> ~str {
605         unsafe {
606             match self.node_info {
607                 Some(node_info) => fmt!("[block %d]", node_info.id),
608                 None => fmt!("[block %x]", transmute(&*self)),
609             }
610         }
611     }
612 }
613
614 pub struct Result {
615     bcx: @mut Block,
616     val: ValueRef
617 }
618
619 pub fn rslt(bcx: @mut Block, val: ValueRef) -> Result {
620     Result {bcx: bcx, val: val}
621 }
622
623 impl Result {
624     pub fn unpack(&self, bcx: &mut @mut Block) -> ValueRef {
625         *bcx = self.bcx;
626         return self.val;
627     }
628 }
629
630 pub fn val_ty(v: ValueRef) -> Type {
631     unsafe {
632         Type::from_ref(llvm::LLVMTypeOf(v))
633     }
634 }
635
636 pub fn in_scope_cx(cx: @mut Block, scope_id: Option<ast::node_id>, f: &fn(si: &mut ScopeInfo)) {
637     let mut cur = cx;
638     let mut cur_scope = cur.scope;
639     loop {
640         cur_scope = match cur_scope {
641             Some(inf) => match scope_id {
642                 Some(wanted) => match inf.node_info {
643                     Some(NodeInfo { id: actual, _ }) if wanted == actual => {
644                         debug!("in_scope_cx: selected cur=%s (cx=%s)",
645                                cur.to_str(), cx.to_str());
646                         f(inf);
647                         return;
648                     },
649                     _ => inf.parent,
650                 },
651                 None => {
652                     debug!("in_scope_cx: selected cur=%s (cx=%s)",
653                            cur.to_str(), cx.to_str());
654                     f(inf);
655                     return;
656                 }
657             },
658             None => {
659                 cur = block_parent(cur);
660                 cur.scope
661             }
662         }
663     }
664 }
665
666 pub fn block_parent(cx: @mut Block) -> @mut Block {
667     match cx.parent {
668       Some(b) => b,
669       None    => cx.sess().bug(fmt!("block_parent called on root block %?",
670                                    cx))
671     }
672 }
673
674
675 // Let T be the content of a box @T.  tuplify_box_ty(t) returns the
676 // representation of @T as a tuple (i.e., the ty::t version of what T_box()
677 // returns).
678 pub fn tuplify_box_ty(tcx: ty::ctxt, t: ty::t) -> ty::t {
679     let ptr = ty::mk_ptr(
680         tcx,
681         ty::mt {ty: ty::mk_i8(), mutbl: ast::m_imm}
682     );
683     return ty::mk_tup(tcx, ~[ty::mk_uint(), ty::mk_type(tcx),
684                          ptr, ptr,
685                          t]);
686 }
687
688
689 // LLVM constant constructors.
690 pub fn C_null(t: Type) -> ValueRef {
691     unsafe {
692         llvm::LLVMConstNull(t.to_ref())
693     }
694 }
695
696 pub fn C_undef(t: Type) -> ValueRef {
697     unsafe {
698         llvm::LLVMGetUndef(t.to_ref())
699     }
700 }
701
702 pub fn C_integral(t: Type, u: u64, sign_extend: bool) -> ValueRef {
703     unsafe {
704         llvm::LLVMConstInt(t.to_ref(), u, sign_extend as Bool)
705     }
706 }
707
708 pub fn C_floating(s: &str, t: Type) -> ValueRef {
709     unsafe {
710         do s.as_c_str |buf| {
711             llvm::LLVMConstRealOfString(t.to_ref(), buf)
712         }
713     }
714 }
715
716 pub fn C_nil() -> ValueRef {
717     return C_struct([]);
718 }
719
720 pub fn C_bool(val: bool) -> ValueRef {
721     C_integral(Type::bool(), val as u64, false)
722 }
723
724 pub fn C_i1(val: bool) -> ValueRef {
725     C_integral(Type::i1(), val as u64, false)
726 }
727
728 pub fn C_i32(i: i32) -> ValueRef {
729     return C_integral(Type::i32(), i as u64, true);
730 }
731
732 pub fn C_i64(i: i64) -> ValueRef {
733     return C_integral(Type::i64(), i as u64, true);
734 }
735
736 pub fn C_int(cx: &CrateContext, i: int) -> ValueRef {
737     return C_integral(cx.int_type, i as u64, true);
738 }
739
740 pub fn C_uint(cx: &CrateContext, i: uint) -> ValueRef {
741     return C_integral(cx.int_type, i as u64, false);
742 }
743
744 pub fn C_u8(i: uint) -> ValueRef {
745     return C_integral(Type::i8(), i as u64, false);
746 }
747
748
749 // This is a 'c-like' raw string, which differs from
750 // our boxed-and-length-annotated strings.
751 pub fn C_cstr(cx: &mut CrateContext, s: @str) -> ValueRef {
752     unsafe {
753         match cx.const_cstr_cache.find_equiv(&s) {
754             Some(&llval) => return llval,
755             None => ()
756         }
757
758         let sc = do s.as_c_str |buf| {
759             llvm::LLVMConstStringInContext(cx.llcx, buf, s.len() as c_uint, False)
760         };
761
762         let gsym = token::gensym("str");
763         let g = do fmt!("str%u", gsym).as_c_str |buf| {
764             llvm::LLVMAddGlobal(cx.llmod, val_ty(sc).to_ref(), buf)
765         };
766         llvm::LLVMSetInitializer(g, sc);
767         llvm::LLVMSetGlobalConstant(g, True);
768         lib::llvm::SetLinkage(g, lib::llvm::InternalLinkage);
769
770         cx.const_cstr_cache.insert(s, g);
771
772         return g;
773     }
774 }
775
776 // NB: Do not use `do_spill_noroot` to make this into a constant string, or
777 // you will be kicked off fast isel. See issue #4352 for an example of this.
778 pub fn C_estr_slice(cx: &mut CrateContext, s: @str) -> ValueRef {
779     unsafe {
780         let len = s.len();
781         let cs = llvm::LLVMConstPointerCast(C_cstr(cx, s), Type::i8p().to_ref());
782         C_struct([cs, C_uint(cx, len + 1u /* +1 for null */)])
783     }
784 }
785
786 pub fn C_zero_byte_arr(size: uint) -> ValueRef {
787     unsafe {
788         let mut i = 0u;
789         let mut elts: ~[ValueRef] = ~[];
790         while i < size { elts.push(C_u8(0u)); i += 1u; }
791         return llvm::LLVMConstArray(Type::i8().to_ref(),
792                                     vec::raw::to_ptr(elts), elts.len() as c_uint);
793     }
794 }
795
796 pub fn C_struct(elts: &[ValueRef]) -> ValueRef {
797     unsafe {
798         do elts.as_imm_buf |ptr, len| {
799             llvm::LLVMConstStructInContext(base::task_llcx(), ptr, len as c_uint, False)
800         }
801     }
802 }
803
804 pub fn C_packed_struct(elts: &[ValueRef]) -> ValueRef {
805     unsafe {
806         do elts.as_imm_buf |ptr, len| {
807             llvm::LLVMConstStructInContext(base::task_llcx(), ptr, len as c_uint, True)
808         }
809     }
810 }
811
812 pub fn C_named_struct(T: Type, elts: &[ValueRef]) -> ValueRef {
813     unsafe {
814         do elts.as_imm_buf |ptr, len| {
815             llvm::LLVMConstNamedStruct(T.to_ref(), ptr, len as c_uint)
816         }
817     }
818 }
819
820 pub fn C_array(ty: Type, elts: &[ValueRef]) -> ValueRef {
821     unsafe {
822         return llvm::LLVMConstArray(ty.to_ref(), vec::raw::to_ptr(elts), elts.len() as c_uint);
823     }
824 }
825
826 pub fn C_bytes(bytes: &[u8]) -> ValueRef {
827     unsafe {
828         let ptr = cast::transmute(vec::raw::to_ptr(bytes));
829         return llvm::LLVMConstStringInContext(base::task_llcx(), ptr, bytes.len() as c_uint, True);
830     }
831 }
832
833 pub fn get_param(fndecl: ValueRef, param: uint) -> ValueRef {
834     unsafe {
835         llvm::LLVMGetParam(fndecl, param as c_uint)
836     }
837 }
838
839 pub fn const_get_elt(cx: &CrateContext, v: ValueRef, us: &[c_uint])
840                   -> ValueRef {
841     unsafe {
842         let r = do us.as_imm_buf |p, len| {
843             llvm::LLVMConstExtractValue(v, p, len as c_uint)
844         };
845
846         debug!("const_get_elt(v=%s, us=%?, r=%s)",
847                cx.tn.val_to_str(v), us, cx.tn.val_to_str(r));
848
849         return r;
850     }
851 }
852
853 pub fn const_to_int(v: ValueRef) -> c_longlong {
854     unsafe {
855         llvm::LLVMConstIntGetSExtValue(v)
856     }
857 }
858
859 pub fn const_to_uint(v: ValueRef) -> c_ulonglong {
860     unsafe {
861         llvm::LLVMConstIntGetZExtValue(v)
862     }
863 }
864
865 pub fn is_undef(val: ValueRef) -> bool {
866     unsafe {
867         llvm::LLVMIsUndef(val) != False
868     }
869 }
870
871 pub fn is_null(val: ValueRef) -> bool {
872     unsafe {
873         llvm::LLVMIsNull(val) != False
874     }
875 }
876
877 // Used to identify cached monomorphized functions and vtables
878 #[deriving(Eq,IterBytes)]
879 pub enum mono_param_id {
880     mono_precise(ty::t, Option<@~[mono_id]>),
881     mono_any,
882     mono_repr(uint /* size */,
883               uint /* align */,
884               MonoDataClass,
885               datum::DatumMode),
886 }
887
888 #[deriving(Eq,IterBytes)]
889 pub enum MonoDataClass {
890     MonoBits,    // Anything not treated differently from arbitrary integer data
891     MonoNonNull, // Non-null pointers (used for optional-pointer optimization)
892     // FIXME(#3547)---scalars and floats are
893     // treated differently in most ABIs.  But we
894     // should be doing something more detailed
895     // here.
896     MonoFloat
897 }
898
899 pub fn mono_data_classify(t: ty::t) -> MonoDataClass {
900     match ty::get(t).sty {
901         ty::ty_float(_) => MonoFloat,
902         ty::ty_rptr(*) | ty::ty_uniq(*) |
903         ty::ty_box(*) | ty::ty_opaque_box(*) |
904         ty::ty_estr(ty::vstore_uniq) | ty::ty_evec(_, ty::vstore_uniq) |
905         ty::ty_estr(ty::vstore_box) | ty::ty_evec(_, ty::vstore_box) |
906         ty::ty_bare_fn(*) => MonoNonNull,
907         // Is that everything?  Would closures or slices qualify?
908         _ => MonoBits
909     }
910 }
911
912
913 #[deriving(Eq,IterBytes)]
914 pub struct mono_id_ {
915     def: ast::def_id,
916     params: ~[mono_param_id]
917 }
918
919 pub type mono_id = @mono_id_;
920
921 pub fn umax(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
922     let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
923     return build::Select(cx, cond, b, a);
924 }
925
926 pub fn umin(cx: @mut Block, a: ValueRef, b: ValueRef) -> ValueRef {
927     let cond = build::ICmp(cx, lib::llvm::IntULT, a, b);
928     return build::Select(cx, cond, a, b);
929 }
930
931 pub fn align_to(cx: @mut Block, off: ValueRef, align: ValueRef) -> ValueRef {
932     let mask = build::Sub(cx, align, C_int(cx.ccx(), 1));
933     let bumped = build::Add(cx, off, mask);
934     return build::And(cx, bumped, build::Not(cx, mask));
935 }
936
937 pub fn path_str(sess: session::Session, p: &[path_elt]) -> ~str {
938     let mut r = ~"";
939     let mut first = true;
940     for p.iter().advance |e| {
941         match *e {
942             ast_map::path_name(s) | ast_map::path_mod(s) => {
943                 if first {
944                     first = false
945                 } else {
946                     r.push_str("::")
947                 }
948                 r.push_str(sess.str_of(s));
949             }
950         }
951     }
952     r
953 }
954
955 pub fn monomorphize_type(bcx: @mut Block, t: ty::t) -> ty::t {
956     match bcx.fcx.param_substs {
957         Some(substs) => {
958             ty::subst_tps(bcx.tcx(), substs.tys, substs.self_ty, t)
959         }
960         _ => {
961             assert!(!ty::type_has_params(t));
962             assert!(!ty::type_has_self(t));
963             t
964         }
965     }
966 }
967
968 pub fn node_id_type(bcx: @mut Block, id: ast::node_id) -> ty::t {
969     let tcx = bcx.tcx();
970     let t = ty::node_id_to_type(tcx, id);
971     monomorphize_type(bcx, t)
972 }
973
974 pub fn expr_ty(bcx: @mut Block, ex: &ast::expr) -> ty::t {
975     node_id_type(bcx, ex.id)
976 }
977
978 pub fn expr_ty_adjusted(bcx: @mut Block, ex: &ast::expr) -> ty::t {
979     let tcx = bcx.tcx();
980     let t = ty::expr_ty_adjusted(tcx, ex);
981     monomorphize_type(bcx, t)
982 }
983
984 pub fn node_id_type_params(bcx: @mut Block, id: ast::node_id) -> ~[ty::t] {
985     let tcx = bcx.tcx();
986     let params = ty::node_id_to_type_params(tcx, id);
987
988     if !params.iter().all(|t| !ty::type_needs_infer(*t)) {
989         bcx.sess().bug(
990             fmt!("Type parameters for node %d include inference types: %s",
991                  id, params.map(|t| bcx.ty_to_str(*t)).connect(",")));
992     }
993
994     match bcx.fcx.param_substs {
995       Some(substs) => {
996         do params.iter().transform |t| {
997             ty::subst_tps(tcx, substs.tys, substs.self_ty, *t)
998         }.collect()
999       }
1000       _ => params
1001     }
1002 }
1003
1004 pub fn node_vtables(bcx: @mut Block, id: ast::node_id)
1005                  -> Option<typeck::vtable_res> {
1006     let raw_vtables = bcx.ccx().maps.vtable_map.find(&id);
1007     raw_vtables.map(
1008         |&vts| resolve_vtables_in_fn_ctxt(bcx.fcx, *vts))
1009 }
1010
1011 pub fn resolve_vtables_in_fn_ctxt(fcx: &FunctionContext, vts: typeck::vtable_res)
1012     -> typeck::vtable_res {
1013     resolve_vtables_under_param_substs(fcx.ccx.tcx,
1014                                        fcx.param_substs,
1015                                        vts)
1016 }
1017
1018 pub fn resolve_vtables_under_param_substs(tcx: ty::ctxt,
1019                                           param_substs: Option<@param_substs>,
1020                                           vts: typeck::vtable_res)
1021     -> typeck::vtable_res {
1022     @vts.iter().transform(|ds|
1023       @ds.iter().transform(
1024           |d| resolve_vtable_under_param_substs(tcx,
1025                                                 param_substs,
1026                                                 d))
1027                           .collect::<~[typeck::vtable_origin]>())
1028         .collect::<~[typeck::vtable_param_res]>()
1029 }
1030
1031
1032 // Apply the typaram substitutions in the FunctionContext to a vtable. This should
1033 // eliminate any vtable_params.
1034 pub fn resolve_vtable_in_fn_ctxt(fcx: &FunctionContext, vt: &typeck::vtable_origin)
1035     -> typeck::vtable_origin {
1036     resolve_vtable_under_param_substs(fcx.ccx.tcx,
1037                                       fcx.param_substs,
1038                                       vt)
1039 }
1040
1041 pub fn resolve_vtable_under_param_substs(tcx: ty::ctxt,
1042                                          param_substs: Option<@param_substs>,
1043                                          vt: &typeck::vtable_origin)
1044                                          -> typeck::vtable_origin {
1045     match *vt {
1046         typeck::vtable_static(trait_id, ref tys, sub) => {
1047             let tys = match param_substs {
1048                 Some(substs) => {
1049                     do tys.iter().transform |t| {
1050                         ty::subst_tps(tcx, substs.tys, substs.self_ty, *t)
1051                     }.collect()
1052                 }
1053                 _ => tys.to_owned()
1054             };
1055             typeck::vtable_static(
1056                 trait_id, tys,
1057                 resolve_vtables_under_param_substs(tcx, param_substs, sub))
1058         }
1059         typeck::vtable_param(n_param, n_bound) => {
1060             match param_substs {
1061                 Some(substs) => {
1062                     find_vtable(tcx, substs, n_param, n_bound)
1063                 }
1064                 _ => {
1065                     tcx.sess.bug(fmt!(
1066                         "resolve_vtable_in_fn_ctxt: asked to lookup but \
1067                          no vtables in the fn_ctxt!"))
1068                 }
1069             }
1070         }
1071         typeck::vtable_self(_trait_id) => {
1072             match param_substs {
1073                 Some(@param_substs
1074                      {self_vtable: Some(ref self_vtable), _}) => {
1075                     (*self_vtable).clone()
1076                 }
1077                 _ => {
1078                     tcx.sess.bug(fmt!(
1079                         "resolve_vtable_in_fn_ctxt: asked to lookup but \
1080                          no self_vtable in the fn_ctxt!"))
1081                 }
1082             }
1083         }
1084     }
1085 }
1086
1087 pub fn find_vtable(tcx: ty::ctxt,
1088                    ps: &param_substs,
1089                    n_param: uint,
1090                    n_bound: uint)
1091                    -> typeck::vtable_origin {
1092     debug!("find_vtable(n_param=%u, n_bound=%u, ps=%s)",
1093            n_param, n_bound, ps.repr(tcx));
1094
1095     ps.vtables.get()[n_param][n_bound].clone()
1096 }
1097
1098 pub fn dummy_substs(tps: ~[ty::t]) -> ty::substs {
1099     substs {
1100         self_r: Some(ty::re_bound(ty::br_self)),
1101         self_ty: None,
1102         tps: tps
1103     }
1104 }
1105
1106 pub fn filename_and_line_num_from_span(bcx: @mut Block,
1107                                        span: span) -> (ValueRef, ValueRef) {
1108     let loc = bcx.sess().parse_sess.cm.lookup_char_pos(span.lo);
1109     let filename_cstr = C_cstr(bcx.ccx(), loc.file.name);
1110     let filename = build::PointerCast(bcx, filename_cstr, Type::i8p());
1111     let line = C_int(bcx.ccx(), loc.line as int);
1112     (filename, line)
1113 }
1114
1115 // Casts a Rust bool value to an i1.
1116 pub fn bool_to_i1(bcx: @mut Block, llval: ValueRef) -> ValueRef {
1117     build::ICmp(bcx, lib::llvm::IntNE, llval, C_bool(false))
1118 }
1119
1120 pub fn langcall(bcx: @mut Block, span: Option<span>, msg: &str,
1121                 li: LangItem) -> ast::def_id {
1122     match bcx.tcx().lang_items.require(li) {
1123         Ok(id) => id,
1124         Err(s) => {
1125             let msg = fmt!("%s %s", msg, s);
1126             match span {
1127                 Some(span) => { bcx.tcx().sess.span_fatal(span, msg); }
1128                 None => { bcx.tcx().sess.fatal(msg); }
1129             }
1130         }
1131     }
1132 }