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