]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/context.rs
std: move StrUtil::as_c_str into StrSlice
[rust.git] / src / librustc / middle / trans / context.rs
1 // Copyright 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
12 use back::{upcall};
13 use driver::session;
14 use lib::llvm::{ContextRef, ModuleRef, ValueRef};
15 use lib::llvm::{llvm, TargetData, TypeNames};
16 use lib::llvm::{mk_target_data};
17 use metadata::common::LinkMeta;
18 use middle::astencode;
19 use middle::resolve;
20 use middle::trans::adt;
21 use middle::trans::base;
22 use middle::trans::builder::Builder;
23 use middle::trans::debuginfo;
24 use middle::trans::type_use;
25 use middle::ty;
26
27 use middle::trans::type_::Type;
28
29 use std::hash;
30 use std::hashmap::{HashMap, HashSet};
31 use std::local_data;
32 use syntax::ast;
33
34 use middle::trans::common::{mono_id,ExternMap,tydesc_info,BuilderRef_res,Stats};
35
36 use middle::trans::base::{decl_crate_map};
37
38 pub struct CrateContext {
39      sess: session::Session,
40      llmod: ModuleRef,
41      llcx: ContextRef,
42      td: TargetData,
43      tn: TypeNames,
44      externs: ExternMap,
45      intrinsics: HashMap<&'static str, ValueRef>,
46      item_vals: HashMap<ast::node_id, ValueRef>,
47      exp_map2: resolve::ExportMap2,
48      reachable: @mut HashSet<ast::node_id>,
49      item_symbols: HashMap<ast::node_id, ~str>,
50      link_meta: LinkMeta,
51      enum_sizes: HashMap<ty::t, uint>,
52      discrims: HashMap<ast::def_id, ValueRef>,
53      discrim_symbols: HashMap<ast::node_id, @str>,
54      tydescs: HashMap<ty::t, @mut tydesc_info>,
55      // Set when running emit_tydescs to enforce that no more tydescs are
56      // created.
57      finished_tydescs: bool,
58      // Track mapping of external ids to local items imported for inlining
59      external: HashMap<ast::def_id, Option<ast::node_id>>,
60      // Cache instances of monomorphized functions
61      monomorphized: HashMap<mono_id, ValueRef>,
62      monomorphizing: HashMap<ast::def_id, uint>,
63      // Cache computed type parameter uses (see type_use.rs)
64      type_use_cache: HashMap<ast::def_id, @~[type_use::type_uses]>,
65      // Cache generated vtables
66      vtables: HashMap<mono_id, ValueRef>,
67      // Cache of constant strings,
68      const_cstr_cache: HashMap<@str, ValueRef>,
69
70      // Reverse-direction for const ptrs cast from globals.
71      // Key is an int, cast from a ValueRef holding a *T,
72      // Val is a ValueRef holding a *[T].
73      //
74      // Needed because LLVM loses pointer->pointee association
75      // when we ptrcast, and we have to ptrcast during translation
76      // of a [T] const because we form a slice, a [*T,int] pair, not
77      // a pointer to an LLVM array type.
78      const_globals: HashMap<int, ValueRef>,
79
80      // Cache of emitted const values
81      const_values: HashMap<ast::node_id, ValueRef>,
82
83      // Cache of external const values
84      extern_const_values: HashMap<ast::def_id, ValueRef>,
85
86      impl_method_cache: HashMap<(ast::def_id, ast::ident), ast::def_id>,
87
88      module_data: HashMap<~str, ValueRef>,
89      lltypes: HashMap<ty::t, Type>,
90      llsizingtypes: HashMap<ty::t, Type>,
91      adt_reprs: HashMap<ty::t, @adt::Repr>,
92      symbol_hasher: hash::State,
93      type_hashcodes: HashMap<ty::t, @str>,
94      type_short_names: HashMap<ty::t, ~str>,
95      all_llvm_symbols: HashSet<@str>,
96      tcx: ty::ctxt,
97      maps: astencode::Maps,
98      stats: @mut Stats,
99      upcalls: @upcall::Upcalls,
100      tydesc_type: Type,
101      int_type: Type,
102      float_type: Type,
103      opaque_vec_type: Type,
104      builder: BuilderRef_res,
105      crate_map: ValueRef,
106      // Set when at least one function uses GC. Needed so that
107      // decl_gc_metadata knows whether to link to the module metadata, which
108      // is not emitted by LLVM's GC pass when no functions use GC.
109      uses_gc: bool,
110      dbg_cx: Option<debuginfo::DebugContext>,
111      do_not_commit_warning_issued: bool
112 }
113
114 impl CrateContext {
115     pub fn new(sess: session::Session,
116                name: &str,
117                tcx: ty::ctxt,
118                emap2: resolve::ExportMap2,
119                maps: astencode::Maps,
120                symbol_hasher: hash::State,
121                link_meta: LinkMeta,
122                reachable: @mut HashSet<ast::node_id>)
123                -> CrateContext {
124         unsafe {
125             let llcx = llvm::LLVMContextCreate();
126             set_task_llcx(llcx);
127             let llmod = name.as_c_str(|buf| llvm::LLVMModuleCreateWithNameInContext(buf, llcx));
128             let data_layout: &str = sess.targ_cfg.target_strs.data_layout;
129             let targ_triple: &str = sess.targ_cfg.target_strs.target_triple;
130             data_layout.as_c_str(|buf| llvm::LLVMSetDataLayout(llmod, buf));
131             targ_triple.as_c_str(|buf| llvm::LLVMSetTarget(llmod, buf));
132             let targ_cfg = sess.targ_cfg;
133
134             let td = mk_target_data(sess.targ_cfg.target_strs.data_layout);
135             let mut tn = TypeNames::new();
136
137             let mut intrinsics = base::declare_intrinsics(llmod);
138             if sess.opts.extra_debuginfo {
139                 base::declare_dbg_intrinsics(llmod, &mut intrinsics);
140             }
141             let int_type = Type::int(targ_cfg.arch);
142             let float_type = Type::float(targ_cfg.arch);
143             let tydesc_type = Type::tydesc(targ_cfg.arch);
144             let opaque_vec_type = Type::opaque_vec(targ_cfg.arch);
145
146             let mut str_slice_ty = Type::named_struct("str_slice");
147             str_slice_ty.set_struct_body([Type::i8p(), int_type], false);
148
149             tn.associate_type("tydesc", &tydesc_type);
150             tn.associate_type("str_slice", &str_slice_ty);
151
152             let crate_map = decl_crate_map(sess, link_meta, llmod);
153             let dbg_cx = if sess.opts.debuginfo {
154                 Some(debuginfo::DebugContext::new(llmod, name.to_owned()))
155             } else {
156                 None
157             };
158
159             if sess.count_llvm_insns() {
160                 base::init_insn_ctxt()
161             }
162
163             CrateContext {
164                   sess: sess,
165                   llmod: llmod,
166                   llcx: llcx,
167                   td: td,
168                   tn: tn,
169                   externs: HashMap::new(),
170                   intrinsics: intrinsics,
171                   item_vals: HashMap::new(),
172                   exp_map2: emap2,
173                   reachable: reachable,
174                   item_symbols: HashMap::new(),
175                   link_meta: link_meta,
176                   enum_sizes: HashMap::new(),
177                   discrims: HashMap::new(),
178                   discrim_symbols: HashMap::new(),
179                   tydescs: HashMap::new(),
180                   finished_tydescs: false,
181                   external: HashMap::new(),
182                   monomorphized: HashMap::new(),
183                   monomorphizing: HashMap::new(),
184                   type_use_cache: HashMap::new(),
185                   vtables: HashMap::new(),
186                   const_cstr_cache: HashMap::new(),
187                   const_globals: HashMap::new(),
188                   const_values: HashMap::new(),
189                   extern_const_values: HashMap::new(),
190                   impl_method_cache: HashMap::new(),
191                   module_data: HashMap::new(),
192                   lltypes: HashMap::new(),
193                   llsizingtypes: HashMap::new(),
194                   adt_reprs: HashMap::new(),
195                   symbol_hasher: symbol_hasher,
196                   type_hashcodes: HashMap::new(),
197                   type_short_names: HashMap::new(),
198                   all_llvm_symbols: HashSet::new(),
199                   tcx: tcx,
200                   maps: maps,
201                   stats: @mut Stats {
202                     n_static_tydescs: 0u,
203                     n_glues_created: 0u,
204                     n_null_glues: 0u,
205                     n_real_glues: 0u,
206                     n_fns: 0u,
207                     n_monos: 0u,
208                     n_inlines: 0u,
209                     n_closures: 0u,
210                     n_llvm_insns: 0u,
211                     llvm_insn_ctxt: ~[],
212                     llvm_insns: HashMap::new(),
213                     fn_stats: ~[]
214                   },
215                   upcalls: upcall::declare_upcalls(targ_cfg, llmod),
216                   tydesc_type: tydesc_type,
217                   int_type: int_type,
218                   float_type: float_type,
219                   opaque_vec_type: opaque_vec_type,
220                   builder: BuilderRef_res(llvm::LLVMCreateBuilderInContext(llcx)),
221                   crate_map: crate_map,
222                   uses_gc: false,
223                   dbg_cx: dbg_cx,
224                   do_not_commit_warning_issued: false
225             }
226         }
227     }
228
229     pub fn builder(@mut self) -> Builder {
230         Builder::new(self)
231     }
232 }
233
234 #[unsafe_destructor]
235 impl Drop for CrateContext {
236     fn drop(&self) {
237         unset_task_llcx();
238     }
239 }
240
241 static task_local_llcx_key: local_data::Key<@ContextRef> = &local_data::Key;
242
243 pub fn task_llcx() -> ContextRef {
244     let opt = local_data::get(task_local_llcx_key, |k| k.map(|&k| *k));
245     *opt.expect("task-local LLVMContextRef wasn't ever set!")
246 }
247
248 fn set_task_llcx(c: ContextRef) {
249     local_data::set(task_local_llcx_key, @c);
250 }
251
252 fn unset_task_llcx() {
253     local_data::pop(task_local_llcx_key);
254 }