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