1 // Copyright 2012-2014 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.
11 //! An analysis to determine which locals require allocas and
14 use rustc_data_structures::bitvec::BitVector;
15 use rustc_data_structures::indexed_vec::{Idx, IndexVec};
16 use rustc::mir::repr as mir;
17 use rustc::mir::repr::TerminatorKind;
18 use rustc::mir::visit::{Visitor, LvalueContext};
19 use rustc::mir::traversal;
20 use common::{self, Block, BlockAndBuilder};
25 pub fn lvalue_locals<'bcx, 'tcx>(bcx: Block<'bcx,'tcx>,
26 mir: &mir::Mir<'tcx>) -> BitVector {
27 let bcx = bcx.build();
28 let mut analyzer = LocalAnalyzer::new(mir, &bcx);
30 analyzer.visit_mir(mir);
32 let local_types = mir.arg_decls.iter().map(|a| a.ty)
33 .chain(mir.var_decls.iter().map(|v| v.ty))
34 .chain(mir.temp_decls.iter().map(|t| t.ty))
35 .chain(iter::once(mir.return_ty));
36 for (index, ty) in local_types.enumerate() {
37 let ty = bcx.monomorphize(&ty);
38 debug!("local {} has type {:?}", index, ty);
43 common::type_is_zero_size(bcx.ccx(), ty)
45 // These sorts of types are immediates that we can store
46 // in an ValueRef without an alloca.
47 assert!(common::type_is_immediate(bcx.ccx(), ty) ||
48 common::type_is_fat_ptr(bcx.tcx(), ty));
49 } else if common::type_is_imm_pair(bcx.ccx(), ty) {
50 // We allow pairs and uses of any of their 2 fields.
52 // These sorts of types require an alloca. Note that
53 // type_is_immediate() may *still* be true, particularly
54 // for newtypes, but we currently force some types
55 // (e.g. structs) into an alloca unconditionally, just so
56 // that we don't have to deal with having two pathways
57 // (gep vs extractvalue etc).
58 analyzer.mark_as_lvalue(mir::Local::new(index));
62 analyzer.lvalue_locals
65 struct LocalAnalyzer<'mir, 'bcx: 'mir, 'tcx: 'bcx> {
66 mir: &'mir mir::Mir<'tcx>,
67 bcx: &'mir BlockAndBuilder<'bcx, 'tcx>,
68 lvalue_locals: BitVector,
69 seen_assigned: BitVector
72 impl<'mir, 'bcx, 'tcx> LocalAnalyzer<'mir, 'bcx, 'tcx> {
73 fn new(mir: &'mir mir::Mir<'tcx>,
74 bcx: &'mir BlockAndBuilder<'bcx, 'tcx>)
75 -> LocalAnalyzer<'mir, 'bcx, 'tcx> {
76 let local_count = mir.count_locals();
80 lvalue_locals: BitVector::new(local_count),
81 seen_assigned: BitVector::new(local_count)
85 fn mark_as_lvalue(&mut self, local: mir::Local) {
86 debug!("marking {:?} as lvalue", local);
87 self.lvalue_locals.insert(local.index());
90 fn mark_assigned(&mut self, local: mir::Local) {
91 if !self.seen_assigned.insert(local.index()) {
92 self.mark_as_lvalue(local);
97 impl<'mir, 'bcx, 'tcx> Visitor<'tcx> for LocalAnalyzer<'mir, 'bcx, 'tcx> {
98 fn visit_assign(&mut self,
99 block: mir::BasicBlock,
100 lvalue: &mir::Lvalue<'tcx>,
101 rvalue: &mir::Rvalue<'tcx>) {
102 debug!("visit_assign(block={:?}, lvalue={:?}, rvalue={:?})", block, lvalue, rvalue);
104 if let Some(index) = self.mir.local_index(lvalue) {
105 self.mark_assigned(index);
106 if !rvalue::rvalue_creates_operand(self.mir, self.bcx, rvalue) {
107 self.mark_as_lvalue(index);
110 self.visit_lvalue(lvalue, LvalueContext::Store);
113 self.visit_rvalue(rvalue);
116 fn visit_terminator_kind(&mut self,
117 block: mir::BasicBlock,
118 kind: &mir::TerminatorKind<'tcx>) {
120 mir::TerminatorKind::Call {
121 func: mir::Operand::Constant(mir::Constant {
122 literal: mir::Literal::Item { def_id, .. }, ..
125 } if Some(def_id) == self.bcx.tcx().lang_items.box_free_fn() => {
126 // box_free(x) shares with `drop x` the property that it
127 // is not guaranteed to be statically dominated by the
128 // definition of x, so x must always be in an alloca.
129 if let mir::Operand::Consume(ref lvalue) = args[0] {
130 self.visit_lvalue(lvalue, LvalueContext::Drop);
136 self.super_terminator_kind(block, kind);
139 fn visit_lvalue(&mut self,
140 lvalue: &mir::Lvalue<'tcx>,
141 context: LvalueContext) {
142 debug!("visit_lvalue(lvalue={:?}, context={:?})", lvalue, context);
144 // Allow uses of projections of immediate pair fields.
145 if let mir::Lvalue::Projection(ref proj) = *lvalue {
146 if self.mir.local_index(&proj.base).is_some() {
147 let ty = proj.base.ty(self.mir, self.bcx.tcx());
149 let ty = self.bcx.monomorphize(&ty.to_ty(self.bcx.tcx()));
150 if common::type_is_imm_pair(self.bcx.ccx(), ty) {
151 if let mir::ProjectionElem::Field(..) = proj.elem {
152 if let LvalueContext::Consume = context {
160 if let Some(index) = self.mir.local_index(lvalue) {
162 LvalueContext::Call => {
163 self.mark_assigned(index);
166 LvalueContext::StorageLive |
167 LvalueContext::StorageDead |
168 LvalueContext::Consume => {}
170 LvalueContext::Store |
171 LvalueContext::Inspect |
172 LvalueContext::Borrow { .. } |
173 LvalueContext::Slice { .. } |
174 LvalueContext::Projection => {
175 self.mark_as_lvalue(index);
178 LvalueContext::Drop => {
179 let ty = lvalue.ty(self.mir, self.bcx.tcx());
180 let ty = self.bcx.monomorphize(&ty.to_ty(self.bcx.tcx()));
182 // Only need the lvalue if we're actually dropping it.
183 if glue::type_needs_drop(self.bcx.tcx(), ty) {
184 self.mark_as_lvalue(index);
190 // A deref projection only reads the pointer, never needs the lvalue.
191 if let mir::Lvalue::Projection(ref proj) = *lvalue {
192 if let mir::ProjectionElem::Deref = proj.elem {
193 return self.visit_lvalue(&proj.base, LvalueContext::Consume);
197 self.super_lvalue(lvalue, context);
201 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
202 pub enum CleanupKind {
205 Internal { funclet: mir::BasicBlock }
208 pub fn cleanup_kinds<'bcx,'tcx>(_bcx: Block<'bcx,'tcx>,
209 mir: &mir::Mir<'tcx>)
210 -> IndexVec<mir::BasicBlock, CleanupKind>
212 fn discover_masters<'tcx>(result: &mut IndexVec<mir::BasicBlock, CleanupKind>,
213 mir: &mir::Mir<'tcx>) {
214 for (bb, data) in mir.basic_blocks().iter_enumerated() {
215 match data.terminator().kind {
216 TerminatorKind::Goto { .. } |
217 TerminatorKind::Resume |
218 TerminatorKind::Return |
219 TerminatorKind::Unreachable |
220 TerminatorKind::If { .. } |
221 TerminatorKind::Switch { .. } |
222 TerminatorKind::SwitchInt { .. } => {
225 TerminatorKind::Call { cleanup: unwind, .. } |
226 TerminatorKind::Assert { cleanup: unwind, .. } |
227 TerminatorKind::DropAndReplace { unwind, .. } |
228 TerminatorKind::Drop { unwind, .. } => {
229 if let Some(unwind) = unwind {
230 debug!("cleanup_kinds: {:?}/{:?} registering {:?} as funclet",
232 result[unwind] = CleanupKind::Funclet;
239 fn propagate<'tcx>(result: &mut IndexVec<mir::BasicBlock, CleanupKind>,
240 mir: &mir::Mir<'tcx>) {
241 let mut funclet_succs = IndexVec::from_elem(None, mir.basic_blocks());
243 let mut set_successor = |funclet: mir::BasicBlock, succ| {
244 match funclet_succs[funclet] {
245 ref mut s @ None => {
246 debug!("set_successor: updating successor of {:?} to {:?}",
250 Some(s) => if s != succ {
251 span_bug!(mir.span, "funclet {:?} has 2 parents - {:?} and {:?}",
257 for (bb, data) in traversal::reverse_postorder(mir) {
258 let funclet = match result[bb] {
259 CleanupKind::NotCleanup => continue,
260 CleanupKind::Funclet => bb,
261 CleanupKind::Internal { funclet } => funclet,
264 debug!("cleanup_kinds: {:?}/{:?}/{:?} propagating funclet {:?}",
265 bb, data, result[bb], funclet);
267 for &succ in data.terminator().successors().iter() {
268 let kind = result[succ];
269 debug!("cleanup_kinds: propagating {:?} to {:?}/{:?}",
270 funclet, succ, kind);
272 CleanupKind::NotCleanup => {
273 result[succ] = CleanupKind::Internal { funclet: funclet };
275 CleanupKind::Funclet => {
276 set_successor(funclet, succ);
278 CleanupKind::Internal { funclet: succ_funclet } => {
279 if funclet != succ_funclet {
280 // `succ` has 2 different funclet going into it, so it must
281 // be a funclet by itself.
283 debug!("promoting {:?} to a funclet and updating {:?}", succ,
285 result[succ] = CleanupKind::Funclet;
286 set_successor(succ_funclet, succ);
287 set_successor(funclet, succ);
295 let mut result = IndexVec::from_elem(CleanupKind::NotCleanup, mir.basic_blocks());
297 discover_masters(&mut result, mir);
298 propagate(&mut result, mir);
299 debug!("cleanup_kinds: result={:?}", result);