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.
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.
14 use lib::llvm::{ContextRef, ModuleRef, ValueRef};
15 use lib::llvm::{llvm, TargetData, TypeNames};
16 use lib::llvm::{mk_target_data, False};
17 use metadata::common::LinkMeta;
18 use middle::astencode;
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::trans::common::{C_i32, C_null};
28 use middle::trans::type_::Type;
30 use std::c_str::ToCStr;
32 use std::hashmap::{HashMap, HashSet};
35 use std::libc::c_uint;
38 use middle::trans::common::{mono_id,ExternMap,tydesc_info,BuilderRef_res,Stats};
40 use middle::trans::base::{decl_crate_map};
42 pub struct CrateContext {
43 sess: session::Session,
49 intrinsics: HashMap<&'static str, ValueRef>,
50 item_vals: HashMap<ast::NodeId, ValueRef>,
51 exp_map2: resolve::ExportMap2,
52 reachable: @mut HashSet<ast::NodeId>,
53 item_symbols: HashMap<ast::NodeId, ~str>,
55 enum_sizes: HashMap<ty::t, uint>,
56 discrims: HashMap<ast::def_id, ValueRef>,
57 discrim_symbols: HashMap<ast::NodeId, @str>,
58 tydescs: HashMap<ty::t, @mut tydesc_info>,
59 // Set when running emit_tydescs to enforce that no more tydescs are
61 finished_tydescs: bool,
62 // Track mapping of external ids to local items imported for inlining
63 external: HashMap<ast::def_id, Option<ast::NodeId>>,
64 // Cache instances of monomorphized functions
65 monomorphized: HashMap<mono_id, ValueRef>,
66 monomorphizing: HashMap<ast::def_id, uint>,
67 // Cache computed type parameter uses (see type_use.rs)
68 type_use_cache: HashMap<ast::def_id, @~[type_use::type_uses]>,
69 // Cache generated vtables
70 vtables: HashMap<mono_id, ValueRef>,
71 // Cache of constant strings,
72 const_cstr_cache: HashMap<@str, ValueRef>,
74 // Reverse-direction for const ptrs cast from globals.
75 // Key is an int, cast from a ValueRef holding a *T,
76 // Val is a ValueRef holding a *[T].
78 // Needed because LLVM loses pointer->pointee association
79 // when we ptrcast, and we have to ptrcast during translation
80 // of a [T] const because we form a slice, a [*T,int] pair, not
81 // a pointer to an LLVM array type.
82 const_globals: HashMap<int, ValueRef>,
84 // Cache of emitted const values
85 const_values: HashMap<ast::NodeId, ValueRef>,
87 // Cache of external const values
88 extern_const_values: HashMap<ast::def_id, ValueRef>,
90 impl_method_cache: HashMap<(ast::def_id, ast::ident), ast::def_id>,
92 module_data: HashMap<~str, ValueRef>,
93 lltypes: HashMap<ty::t, Type>,
94 llsizingtypes: HashMap<ty::t, Type>,
95 adt_reprs: HashMap<ty::t, @adt::Repr>,
96 symbol_hasher: hash::State,
97 type_hashcodes: HashMap<ty::t, @str>,
98 type_short_names: HashMap<ty::t, ~str>,
99 all_llvm_symbols: HashSet<@str>,
101 maps: astencode::Maps,
103 upcalls: @upcall::Upcalls,
107 opaque_vec_type: Type,
108 builder: BuilderRef_res,
110 // Set when at least one function uses GC. Needed so that
111 // decl_gc_metadata knows whether to link to the module metadata, which
112 // is not emitted by LLVM's GC pass when no functions use GC.
114 dbg_cx: Option<debuginfo::DebugContext>,
115 do_not_commit_warning_issued: bool
119 pub fn new(sess: session::Session,
122 emap2: resolve::ExportMap2,
123 maps: astencode::Maps,
124 symbol_hasher: hash::State,
126 reachable: @mut HashSet<ast::NodeId>)
129 let llcx = llvm::LLVMContextCreate();
131 let llmod = do name.with_c_str |buf| {
132 llvm::LLVMModuleCreateWithNameInContext(buf, llcx)
134 let data_layout: &str = sess.targ_cfg.target_strs.data_layout;
135 let targ_triple: &str = sess.targ_cfg.target_strs.target_triple;
136 do data_layout.with_c_str |buf| {
137 llvm::LLVMSetDataLayout(llmod, buf)
139 do targ_triple.with_c_str |buf| {
140 llvm::LLVMSetTarget(llmod, buf)
142 let targ_cfg = sess.targ_cfg;
144 let td = mk_target_data(sess.targ_cfg.target_strs.data_layout);
145 let mut tn = TypeNames::new();
147 let mut intrinsics = base::declare_intrinsics(llmod);
148 if sess.opts.extra_debuginfo {
149 base::declare_dbg_intrinsics(llmod, &mut intrinsics);
151 let int_type = Type::int(targ_cfg.arch);
152 let float_type = Type::float(targ_cfg.arch);
153 let tydesc_type = Type::tydesc(targ_cfg.arch);
154 let opaque_vec_type = Type::opaque_vec(targ_cfg.arch);
156 let mut str_slice_ty = Type::named_struct("str_slice");
157 str_slice_ty.set_struct_body([Type::i8p(), int_type], false);
159 tn.associate_type("tydesc", &tydesc_type);
160 tn.associate_type("str_slice", &str_slice_ty);
162 let crate_map = decl_crate_map(sess, link_meta, llmod);
163 let dbg_cx = if sess.opts.debuginfo {
164 Some(debuginfo::DebugContext::new(llmod, name.to_owned()))
169 if sess.count_llvm_insns() {
170 base::init_insn_ctxt()
179 externs: HashMap::new(),
180 intrinsics: intrinsics,
181 item_vals: HashMap::new(),
183 reachable: reachable,
184 item_symbols: HashMap::new(),
185 link_meta: link_meta,
186 enum_sizes: HashMap::new(),
187 discrims: HashMap::new(),
188 discrim_symbols: HashMap::new(),
189 tydescs: HashMap::new(),
190 finished_tydescs: false,
191 external: HashMap::new(),
192 monomorphized: HashMap::new(),
193 monomorphizing: HashMap::new(),
194 type_use_cache: HashMap::new(),
195 vtables: HashMap::new(),
196 const_cstr_cache: HashMap::new(),
197 const_globals: HashMap::new(),
198 const_values: HashMap::new(),
199 extern_const_values: HashMap::new(),
200 impl_method_cache: HashMap::new(),
201 module_data: HashMap::new(),
202 lltypes: HashMap::new(),
203 llsizingtypes: HashMap::new(),
204 adt_reprs: HashMap::new(),
205 symbol_hasher: symbol_hasher,
206 type_hashcodes: HashMap::new(),
207 type_short_names: HashMap::new(),
208 all_llvm_symbols: HashSet::new(),
212 n_static_tydescs: 0u,
222 llvm_insns: HashMap::new(),
225 upcalls: upcall::declare_upcalls(targ_cfg, llmod),
226 tydesc_type: tydesc_type,
228 float_type: float_type,
229 opaque_vec_type: opaque_vec_type,
230 builder: BuilderRef_res(llvm::LLVMCreateBuilderInContext(llcx)),
231 crate_map: crate_map,
234 do_not_commit_warning_issued: false
239 pub fn builder(@mut self) -> Builder {
243 pub fn const_inbounds_gepi(&self,
245 indices: &[uint]) -> ValueRef {
246 debug!("const_inbounds_gepi: pointer=%s indices=%?",
247 self.tn.val_to_str(pointer), indices);
249 indices.iter().map(|i| C_i32(*i as i32)).collect();
251 llvm::LLVMConstInBoundsGEP(pointer,
253 indices.len() as c_uint)
257 pub fn offsetof_gep(&self,
259 indices: &[uint]) -> ValueRef {
261 * Returns the offset of applying the given GEP indices
262 * to an instance of `llptr_ty`. Similar to `offsetof` in C,
263 * except that `llptr_ty` must be a pointer type.
267 let null = C_null(llptr_ty);
268 llvm::LLVMConstPtrToInt(self.const_inbounds_gepi(null, indices),
269 self.int_type.to_ref())
275 impl Drop for CrateContext {
281 static task_local_llcx_key: local_data::Key<@ContextRef> = &local_data::Key;
283 pub fn task_llcx() -> ContextRef {
284 let opt = local_data::get(task_local_llcx_key, |k| k.map_move(|k| *k));
285 *opt.expect("task-local LLVMContextRef wasn't ever set!")
288 fn set_task_llcx(c: ContextRef) {
289 local_data::set(task_local_llcx_key, @c);
292 fn unset_task_llcx() {
293 local_data::pop(task_local_llcx_key);