]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/glue.rs
libstd: Remove all uses of `~str` from `libstd`
[rust.git] / src / librustc / middle / trans / glue.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 //!
12 //
13 // Code relating to taking, dropping, etc as well as type descriptors.
14
15
16 use back::abi;
17 use back::link::*;
18 use lib::llvm::{llvm, ValueRef, True};
19 use lib;
20 use middle::lang_items::{FreeFnLangItem, ExchangeFreeFnLangItem};
21 use middle::trans::adt;
22 use middle::trans::base::*;
23 use middle::trans::build::*;
24 use middle::trans::callee;
25 use middle::trans::cleanup;
26 use middle::trans::cleanup::CleanupMethods;
27 use middle::trans::common::*;
28 use middle::trans::expr;
29 use middle::trans::machine::*;
30 use middle::trans::reflect;
31 use middle::trans::tvec;
32 use middle::trans::type_::Type;
33 use middle::trans::type_of::{type_of, sizing_type_of};
34 use middle::ty;
35 use util::ppaux::ty_to_short_str;
36 use util::ppaux;
37
38 use arena::TypedArena;
39 use std::c_str::ToCStr;
40 use std::cell::Cell;
41 use libc::c_uint;
42 use syntax::ast;
43 use syntax::parse::token;
44
45 pub fn trans_free<'a>(cx: &'a Block<'a>, v: ValueRef) -> &'a Block<'a> {
46     let _icx = push_ctxt("trans_free");
47     callee::trans_lang_call(cx,
48         langcall(cx, None, "", FreeFnLangItem),
49         [PointerCast(cx, v, Type::i8p(cx.ccx()))],
50         Some(expr::Ignore)).bcx
51 }
52
53 fn trans_exchange_free<'a>(cx: &'a Block<'a>, v: ValueRef, size: u64,
54                                align: u64) -> &'a Block<'a> {
55     let _icx = push_ctxt("trans_exchange_free");
56     let ccx = cx.ccx();
57     callee::trans_lang_call(cx,
58         langcall(cx, None, "", ExchangeFreeFnLangItem),
59         [PointerCast(cx, v, Type::i8p(ccx)), C_uint(ccx, size as uint), C_uint(ccx, align as uint)],
60         Some(expr::Ignore)).bcx
61 }
62
63 pub fn trans_exchange_free_ty<'a>(bcx: &'a Block<'a>, ptr: ValueRef,
64                                   content_ty: ty::t) -> &'a Block<'a> {
65     let sizing_type = sizing_type_of(bcx.ccx(), content_ty);
66     let content_size = llsize_of_alloc(bcx.ccx(), sizing_type);
67
68     // `Box<ZeroSizeType>` does not allocate.
69     if content_size != 0 {
70         let content_align = llalign_of_min(bcx.ccx(), sizing_type);
71         trans_exchange_free(bcx, ptr, content_size, content_align)
72     } else {
73         bcx
74     }
75 }
76
77 pub fn take_ty<'a>(bcx: &'a Block<'a>, v: ValueRef, t: ty::t)
78                -> &'a Block<'a> {
79     // NB: v is an *alias* of type t here, not a direct value.
80     let _icx = push_ctxt("take_ty");
81     match ty::get(t).sty {
82         ty::ty_box(_) => incr_refcnt_of_boxed(bcx, v),
83         _ if ty::type_is_structural(t)
84           && ty::type_needs_drop(bcx.tcx(), t) => {
85             iter_structural_ty(bcx, v, t, take_ty)
86         }
87         _ => bcx
88     }
89 }
90
91 fn get_drop_glue_type(ccx: &CrateContext, t: ty::t) -> ty::t {
92     let tcx = ccx.tcx();
93     if !ty::type_needs_drop(tcx, t) {
94         return ty::mk_i8();
95     }
96     match ty::get(t).sty {
97         ty::ty_box(typ) if !ty::type_needs_drop(tcx, typ) =>
98             ty::mk_box(tcx, ty::mk_i8()),
99
100         ty::ty_uniq(typ) if !ty::type_needs_drop(tcx, typ) => {
101             match ty::get(typ).sty {
102                 ty::ty_vec(_, None) | ty::ty_str => t,
103                 _ => {
104                     let llty = sizing_type_of(ccx, typ);
105                     // `Box<ZeroSizeType>` does not allocate.
106                     if llsize_of_alloc(ccx, llty) == 0 {
107                         ty::mk_i8()
108                     } else {
109                         ty::mk_uniq(tcx, ty::mk_i8())
110                     }
111                 }
112             }
113         }
114         _ => t
115     }
116 }
117
118 pub fn drop_ty<'a>(bcx: &'a Block<'a>, v: ValueRef, t: ty::t)
119                -> &'a Block<'a> {
120     // NB: v is an *alias* of type t here, not a direct value.
121     let _icx = push_ctxt("drop_ty");
122     let ccx = bcx.ccx();
123     if ty::type_needs_drop(bcx.tcx(), t) {
124         let glue = get_drop_glue(ccx, t);
125         let glue_type = get_drop_glue_type(ccx, t);
126         let ptr = if glue_type != t {
127             PointerCast(bcx, v, type_of(ccx, glue_type).ptr_to())
128         } else {
129             v
130         };
131         Call(bcx, glue, [ptr], []);
132     }
133     bcx
134 }
135
136 pub fn drop_ty_immediate<'a>(bcx: &'a Block<'a>, v: ValueRef, t: ty::t)
137                          -> &'a Block<'a> {
138     let _icx = push_ctxt("drop_ty_immediate");
139     let vp = alloca(bcx, type_of(bcx.ccx(), t), "");
140     Store(bcx, v, vp);
141     drop_ty(bcx, vp, t)
142 }
143
144 pub fn get_drop_glue(ccx: &CrateContext, t: ty::t) -> ValueRef {
145     let t = get_drop_glue_type(ccx, t);
146     match ccx.drop_glues.borrow().find(&t) {
147         Some(&glue) => return glue,
148         _ => { }
149     }
150
151     let llfnty = Type::glue_fn(ccx, type_of(ccx, t).ptr_to());
152     let glue = declare_generic_glue(ccx, t, llfnty, "drop");
153
154     ccx.drop_glues.borrow_mut().insert(t, glue);
155
156     make_generic_glue(ccx, t, glue, make_drop_glue, "drop");
157
158     glue
159 }
160
161 pub fn lazily_emit_visit_glue(ccx: &CrateContext, ti: &tydesc_info) -> ValueRef {
162     let _icx = push_ctxt("lazily_emit_visit_glue");
163
164     let llfnty = Type::glue_fn(ccx, type_of(ccx, ti.ty).ptr_to());
165
166     match ti.visit_glue.get() {
167         Some(visit_glue) => visit_glue,
168         None => {
169             debug!("+++ lazily_emit_tydesc_glue VISIT {}", ppaux::ty_to_str(ccx.tcx(), ti.ty));
170             let glue_fn = declare_generic_glue(ccx, ti.ty, llfnty, "visit");
171             ti.visit_glue.set(Some(glue_fn));
172             make_generic_glue(ccx, ti.ty, glue_fn, make_visit_glue, "visit");
173             debug!("--- lazily_emit_tydesc_glue VISIT {}", ppaux::ty_to_str(ccx.tcx(), ti.ty));
174             glue_fn
175         }
176     }
177 }
178
179 // See [Note-arg-mode]
180 pub fn call_visit_glue(bcx: &Block, v: ValueRef, tydesc: ValueRef,
181                        static_ti: Option<&tydesc_info>) {
182     let _icx = push_ctxt("call_tydesc_glue_full");
183     let ccx = bcx.ccx();
184     // NB: Don't short-circuit even if this block is unreachable because
185     // GC-based cleanup needs to the see that the roots are live.
186     if bcx.unreachable.get() && !ccx.sess().no_landing_pads() { return; }
187
188     let static_glue_fn = static_ti.map(|sti| lazily_emit_visit_glue(ccx, sti));
189
190     // When static type info is available, avoid casting to a generic pointer.
191     let llrawptr = if static_glue_fn.is_none() {
192         PointerCast(bcx, v, Type::i8p(ccx))
193     } else {
194         v
195     };
196
197     let llfn = {
198         match static_glue_fn {
199             None => {
200                 // Select out the glue function to call from the tydesc
201                 let llfnptr = GEPi(bcx, tydesc, [0u, abi::tydesc_field_visit_glue]);
202                 Load(bcx, llfnptr)
203             }
204             Some(sgf) => sgf
205         }
206     };
207
208     Call(bcx, llfn, [llrawptr], []);
209 }
210
211 fn make_visit_glue<'a>(bcx: &'a Block<'a>, v: ValueRef, t: ty::t)
212                    -> &'a Block<'a> {
213     let _icx = push_ctxt("make_visit_glue");
214     let mut bcx = bcx;
215     let (visitor_trait, object_ty) = match ty::visitor_object_ty(bcx.tcx(),
216                                                                  ty::ReStatic) {
217         Ok(pair) => pair,
218         Err(s) => {
219             bcx.tcx().sess.fatal(s.as_slice());
220         }
221     };
222     let v = PointerCast(bcx, v, type_of(bcx.ccx(), object_ty).ptr_to());
223     bcx = reflect::emit_calls_to_trait_visit_ty(bcx, t, v, visitor_trait.def_id);
224     bcx
225 }
226
227 fn trans_struct_drop_flag<'a>(bcx: &'a Block<'a>,
228                               t: ty::t,
229                               v0: ValueRef,
230                               dtor_did: ast::DefId,
231                               class_did: ast::DefId,
232                               substs: &ty::substs)
233                               -> &'a Block<'a> {
234     let repr = adt::represent_type(bcx.ccx(), t);
235     let drop_flag = adt::trans_drop_flag_ptr(bcx, &*repr, v0);
236     with_cond(bcx, IsNotNull(bcx, Load(bcx, drop_flag)), |cx| {
237         trans_struct_drop(cx, t, v0, dtor_did, class_did, substs)
238     })
239 }
240
241 fn trans_struct_drop<'a>(bcx: &'a Block<'a>,
242                          t: ty::t,
243                          v0: ValueRef,
244                          dtor_did: ast::DefId,
245                          class_did: ast::DefId,
246                          substs: &ty::substs)
247                          -> &'a Block<'a> {
248     let repr = adt::represent_type(bcx.ccx(), t);
249
250     // Find and call the actual destructor
251     let dtor_addr = get_res_dtor(bcx.ccx(), dtor_did,
252                                  class_did, substs);
253
254     // The second argument is the "self" argument for drop
255     let params = unsafe {
256         let ty = Type::from_ref(llvm::LLVMTypeOf(dtor_addr));
257         ty.element_type().func_params()
258     };
259
260     // Class dtors have no explicit args, so the params should
261     // just consist of the environment (self)
262     assert_eq!(params.len(), 1);
263
264     // Be sure to put all of the fields into a scope so we can use an invoke
265     // instruction to call the user destructor but still call the field
266     // destructors if the user destructor fails.
267     let field_scope = bcx.fcx.push_custom_cleanup_scope();
268
269     let self_arg = PointerCast(bcx, v0, *params.get(0));
270     let args = vec!(self_arg);
271
272     // Add all the fields as a value which needs to be cleaned at the end of
273     // this scope.
274     let field_tys = ty::struct_fields(bcx.tcx(), class_did, substs);
275     for (i, fld) in field_tys.iter().enumerate() {
276         let llfld_a = adt::trans_field_ptr(bcx, &*repr, v0, 0, i);
277         bcx.fcx.schedule_drop_mem(cleanup::CustomScope(field_scope),
278                                   llfld_a,
279                                   fld.mt.ty);
280     }
281
282     let (_, bcx) = invoke(bcx, dtor_addr, args, [], None);
283
284     bcx.fcx.pop_and_trans_custom_cleanup_scope(bcx, field_scope)
285 }
286
287 fn make_drop_glue<'a>(bcx: &'a Block<'a>, v0: ValueRef, t: ty::t) -> &'a Block<'a> {
288     // NB: v0 is an *alias* of type t here, not a direct value.
289     let _icx = push_ctxt("make_drop_glue");
290     match ty::get(t).sty {
291         ty::ty_box(body_ty) => {
292             decr_refcnt_maybe_free(bcx, v0, body_ty)
293         }
294         ty::ty_uniq(content_ty) => {
295             let llbox = Load(bcx, v0);
296             let not_null = IsNotNull(bcx, llbox);
297             match ty::get(content_ty).sty {
298                 ty::ty_vec(mt, None) => {
299                     with_cond(bcx, not_null, |bcx| {
300                         let bcx = tvec::make_drop_glue_unboxed(bcx, llbox, mt.ty);
301                         // FIXME: #13994: the old `Box<[T]>` will not support sized deallocation
302                         trans_exchange_free(bcx, llbox, 0, 8)
303                     })
304                 }
305                 ty::ty_str => {
306                     with_cond(bcx, not_null, |bcx| {
307                         let unit_ty = ty::sequence_element_type(bcx.tcx(), t);
308                         let bcx = tvec::make_drop_glue_unboxed(bcx, llbox, unit_ty);
309                         // FIXME: #13994: the old `Box<str>` will not support sized deallocation
310                         trans_exchange_free(bcx, llbox, 0, 8)
311                     })
312                 }
313                 _ => {
314                     with_cond(bcx, not_null, |bcx| {
315                         let bcx = drop_ty(bcx, llbox, content_ty);
316                         trans_exchange_free_ty(bcx, llbox, content_ty)
317                     })
318                 }
319             }
320         }
321         ty::ty_struct(did, ref substs) => {
322             let tcx = bcx.tcx();
323             match ty::ty_dtor(tcx, did) {
324                 ty::TraitDtor(dtor, true) => {
325                     trans_struct_drop_flag(bcx, t, v0, dtor, did, substs)
326                 }
327                 ty::TraitDtor(dtor, false) => {
328                     trans_struct_drop(bcx, t, v0, dtor, did, substs)
329                 }
330                 ty::NoDtor => {
331                     // No dtor? Just the default case
332                     iter_structural_ty(bcx, v0, t, drop_ty)
333                 }
334             }
335         }
336         ty::ty_trait(box ty::TyTrait { store: ty::UniqTraitStore, .. }) => {
337             let lluniquevalue = GEPi(bcx, v0, [0, abi::trt_field_box]);
338             // Only drop the value when it is non-null
339             with_cond(bcx, IsNotNull(bcx, Load(bcx, lluniquevalue)), |bcx| {
340                 let dtor_ptr = Load(bcx, GEPi(bcx, v0, [0, abi::trt_field_vtable]));
341                 let dtor = Load(bcx, dtor_ptr);
342                 Call(bcx, dtor, [PointerCast(bcx, lluniquevalue, Type::i8p(bcx.ccx()))], []);
343                 bcx
344             })
345         }
346         ty::ty_closure(ref f) if f.store == ty::UniqTraitStore => {
347             let box_cell_v = GEPi(bcx, v0, [0u, abi::fn_field_box]);
348             let env = Load(bcx, box_cell_v);
349             let env_ptr_ty = Type::at_box(bcx.ccx(), Type::i8(bcx.ccx())).ptr_to();
350             let env = PointerCast(bcx, env, env_ptr_ty);
351             with_cond(bcx, IsNotNull(bcx, env), |bcx| {
352                 let dtor_ptr = GEPi(bcx, env, [0u, abi::box_field_tydesc]);
353                 let dtor = Load(bcx, dtor_ptr);
354                 let cdata = GEPi(bcx, env, [0u, abi::box_field_body]);
355                 Call(bcx, dtor, [PointerCast(bcx, cdata, Type::i8p(bcx.ccx()))], []);
356
357                 // Free the environment itself
358                 // FIXME: #13994: pass align and size here
359                 trans_exchange_free(bcx, env, 0, 8)
360             })
361         }
362         _ => {
363             if ty::type_needs_drop(bcx.tcx(), t) &&
364                 ty::type_is_structural(t) {
365                 iter_structural_ty(bcx, v0, t, drop_ty)
366             } else {
367                 bcx
368             }
369         }
370     }
371 }
372
373 fn decr_refcnt_maybe_free<'a>(bcx: &'a Block<'a>,
374                               box_ptr_ptr: ValueRef,
375                               t: ty::t) -> &'a Block<'a> {
376     let _icx = push_ctxt("decr_refcnt_maybe_free");
377     let fcx = bcx.fcx;
378     let ccx = bcx.ccx();
379
380     let decr_bcx = fcx.new_temp_block("decr");
381     let free_bcx = fcx.new_temp_block("free");
382     let next_bcx = fcx.new_temp_block("next");
383
384     let box_ptr = Load(bcx, box_ptr_ptr);
385     let llnotnull = IsNotNull(bcx, box_ptr);
386     CondBr(bcx, llnotnull, decr_bcx.llbb, next_bcx.llbb);
387
388     let rc_ptr = GEPi(decr_bcx, box_ptr, [0u, abi::box_field_refcnt]);
389     let rc = Sub(decr_bcx, Load(decr_bcx, rc_ptr), C_int(ccx, 1));
390     Store(decr_bcx, rc, rc_ptr);
391     CondBr(decr_bcx, IsNull(decr_bcx, rc), free_bcx.llbb, next_bcx.llbb);
392
393     let v = Load(free_bcx, box_ptr_ptr);
394     let body = GEPi(free_bcx, v, [0u, abi::box_field_body]);
395     let free_bcx = drop_ty(free_bcx, body, t);
396     let free_bcx = trans_free(free_bcx, v);
397     Br(free_bcx, next_bcx.llbb);
398
399     next_bcx
400 }
401
402 fn incr_refcnt_of_boxed<'a>(bcx: &'a Block<'a>,
403                             box_ptr_ptr: ValueRef) -> &'a Block<'a> {
404     let _icx = push_ctxt("incr_refcnt_of_boxed");
405     let ccx = bcx.ccx();
406     let box_ptr = Load(bcx, box_ptr_ptr);
407     let rc_ptr = GEPi(bcx, box_ptr, [0u, abi::box_field_refcnt]);
408     let rc = Load(bcx, rc_ptr);
409     let rc = Add(bcx, rc, C_int(ccx, 1));
410     Store(bcx, rc, rc_ptr);
411     bcx
412 }
413
414
415 // Generates the declaration for (but doesn't emit) a type descriptor.
416 pub fn declare_tydesc(ccx: &CrateContext, t: ty::t) -> tydesc_info {
417     // If emit_tydescs already ran, then we shouldn't be creating any new
418     // tydescs.
419     assert!(!ccx.finished_tydescs.get());
420
421     let llty = type_of(ccx, t);
422
423     if ccx.sess().count_type_sizes() {
424         println!("{}\t{}", llsize_of_real(ccx, llty),
425                  ppaux::ty_to_str(ccx.tcx(), t));
426     }
427
428     let llsize = llsize_of(ccx, llty);
429     let llalign = llalign_of(ccx, llty);
430     let name = mangle_internal_name_by_type_and_seq(ccx, t, "tydesc");
431     debug!("+++ declare_tydesc {} {}", ppaux::ty_to_str(ccx.tcx(), t), name);
432     let gvar = name.as_slice().with_c_str(|buf| {
433         unsafe {
434             llvm::LLVMAddGlobal(ccx.llmod, ccx.tydesc_type().to_ref(), buf)
435         }
436     });
437     note_unique_llvm_symbol(ccx, name);
438
439     let ty_name = token::intern_and_get_ident(
440         ppaux::ty_to_str(ccx.tcx(), t).as_slice());
441     let ty_name = C_str_slice(ccx, ty_name);
442
443     debug!("--- declare_tydesc {}", ppaux::ty_to_str(ccx.tcx(), t));
444     tydesc_info {
445         ty: t,
446         tydesc: gvar,
447         size: llsize,
448         align: llalign,
449         name: ty_name,
450         visit_glue: Cell::new(None),
451     }
452 }
453
454 fn declare_generic_glue(ccx: &CrateContext, t: ty::t, llfnty: Type,
455                         name: &str) -> ValueRef {
456     let _icx = push_ctxt("declare_generic_glue");
457     let fn_nm = mangle_internal_name_by_type_and_seq(
458         ccx,
459         t,
460         format!("glue_{}", name).as_slice());
461     debug!("{} is for type {}", fn_nm, ppaux::ty_to_str(ccx.tcx(), t));
462     let llfn = decl_cdecl_fn(ccx.llmod,
463                              fn_nm.as_slice(),
464                              llfnty,
465                              ty::mk_nil());
466     note_unique_llvm_symbol(ccx, fn_nm);
467     return llfn;
468 }
469
470 fn make_generic_glue(ccx: &CrateContext,
471                      t: ty::t,
472                      llfn: ValueRef,
473                      helper: <'a> |&'a Block<'a>, ValueRef, ty::t|
474                                   -> &'a Block<'a>,
475                      name: &str)
476                      -> ValueRef {
477     let _icx = push_ctxt("make_generic_glue");
478     let glue_name = format_strbuf!("glue {} {}",
479                                    name,
480                                    ty_to_short_str(ccx.tcx(), t));
481     let _s = StatRecorder::new(ccx, glue_name);
482
483     let arena = TypedArena::new();
484     let fcx = new_fn_ctxt(ccx, llfn, -1, false, ty::mk_nil(), None, None, &arena);
485
486     init_function(&fcx, false, ty::mk_nil());
487
488     lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
489     ccx.stats.n_glues_created.set(ccx.stats.n_glues_created.get() + 1u);
490     // All glue functions take values passed *by alias*; this is a
491     // requirement since in many contexts glue is invoked indirectly and
492     // the caller has no idea if it's dealing with something that can be
493     // passed by value.
494     //
495     // llfn is expected be declared to take a parameter of the appropriate
496     // type, so we don't need to explicitly cast the function parameter.
497
498     let bcx = fcx.entry_bcx.borrow().clone().unwrap();
499     let llrawptr0 = unsafe { llvm::LLVMGetParam(llfn, fcx.arg_pos(0) as c_uint) };
500     let bcx = helper(bcx, llrawptr0, t);
501     finish_fn(&fcx, bcx);
502
503     llfn
504 }
505
506 pub fn emit_tydescs(ccx: &CrateContext) {
507     let _icx = push_ctxt("emit_tydescs");
508     // As of this point, allow no more tydescs to be created.
509     ccx.finished_tydescs.set(true);
510     let glue_fn_ty = Type::generic_glue_fn(ccx).ptr_to();
511     for (_, ti) in ccx.tydescs.borrow().iter() {
512         // Each of the glue functions needs to be cast to a generic type
513         // before being put into the tydesc because we only have a singleton
514         // tydesc type. Then we'll recast each function to its real type when
515         // calling it.
516         let drop_glue = unsafe {
517             llvm::LLVMConstPointerCast(get_drop_glue(ccx, ti.ty), glue_fn_ty.to_ref())
518         };
519         ccx.stats.n_real_glues.set(ccx.stats.n_real_glues.get() + 1);
520         let visit_glue =
521             match ti.visit_glue.get() {
522               None => {
523                   ccx.stats.n_null_glues.set(ccx.stats.n_null_glues.get() +
524                                              1u);
525                   C_null(glue_fn_ty)
526               }
527               Some(v) => {
528                 unsafe {
529                     ccx.stats.n_real_glues.set(ccx.stats.n_real_glues.get() +
530                                                1);
531                     llvm::LLVMConstPointerCast(v, glue_fn_ty.to_ref())
532                 }
533               }
534             };
535
536         let tydesc = C_named_struct(ccx.tydesc_type(),
537                                     [ti.size, // size
538                                      ti.align, // align
539                                      drop_glue, // drop_glue
540                                      visit_glue, // visit_glue
541                                      ti.name]); // name
542
543         unsafe {
544             let gvar = ti.tydesc;
545             llvm::LLVMSetInitializer(gvar, tydesc);
546             llvm::LLVMSetGlobalConstant(gvar, True);
547             lib::llvm::SetLinkage(gvar, lib::llvm::InternalLinkage);
548         }
549     };
550 }