]> git.lizzy.rs Git - rust.git/blob - src/librustc_codegen_llvm/mir/mod.rs
Reduced line length to pass tidy
[rust.git] / src / librustc_codegen_llvm / mir / mod.rs
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.
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 use common::{C_i32, C_null};
12 use libc::c_uint;
13 use llvm::{self, BasicBlock};
14 use llvm::debuginfo::DIScope;
15 use llvm_util;
16 use rustc::ty::{self, Ty, TypeFoldable, UpvarSubsts};
17 use rustc::ty::layout::{LayoutOf, TyLayout};
18 use rustc::mir::{self, Mir};
19 use rustc::ty::subst::Substs;
20 use rustc::session::config::DebugInfo;
21 use base;
22 use builder::Builder;
23 use common::{CodegenCx, Funclet};
24 use debuginfo::{self, declare_local, VariableAccess, VariableKind, FunctionDebugContext};
25 use monomorphize::Instance;
26 use abi::{ArgTypeExt, FnType, FnTypeExt, PassMode};
27 use type_::Type;
28 use value::Value;
29
30 use syntax_pos::{DUMMY_SP, NO_EXPANSION, BytePos, Span};
31 use syntax::symbol::keywords;
32
33 use std::iter;
34
35 use rustc_data_structures::bit_set::BitSet;
36 use rustc_data_structures::indexed_vec::IndexVec;
37
38 pub use self::constant::codegen_static_initializer;
39
40 use self::analyze::CleanupKind;
41 use self::place::PlaceRef;
42 use rustc::mir::traversal;
43
44 use self::operand::{OperandRef, OperandValue};
45
46 /// Master context for codegenning from MIR.
47 pub struct FunctionCx<'a, 'll: 'a, 'tcx: 'll, V> {
48     instance: Instance<'tcx>,
49
50     mir: &'a mir::Mir<'tcx>,
51
52     debug_context: FunctionDebugContext<'ll>,
53
54     llfn: V,
55
56     cx: &'a CodegenCx<'ll, 'tcx>,
57
58     fn_ty: FnType<'tcx, Ty<'tcx>>,
59
60     /// When unwinding is initiated, we have to store this personality
61     /// value somewhere so that we can load it and re-use it in the
62     /// resume instruction. The personality is (afaik) some kind of
63     /// value used for C++ unwinding, which must filter by type: we
64     /// don't really care about it very much. Anyway, this value
65     /// contains an alloca into which the personality is stored and
66     /// then later loaded when generating the DIVERGE_BLOCK.
67     personality_slot: Option<PlaceRef<'tcx, V>>,
68
69     /// A `Block` for each MIR `BasicBlock`
70     blocks: IndexVec<mir::BasicBlock, &'ll BasicBlock>,
71
72     /// The funclet status of each basic block
73     cleanup_kinds: IndexVec<mir::BasicBlock, analyze::CleanupKind>,
74
75     /// When targeting MSVC, this stores the cleanup info for each funclet
76     /// BB. Thisrustup component add rustfmt-preview is initialized as we compute the funclets'
77     /// head block in RPO.
78     funclets: &'a IndexVec<mir::BasicBlock, Option<Funclet<'ll>>>,
79
80     /// This stores the landing-pad block for a given BB, computed lazily on GNU
81     /// and eagerly on MSVC.
82     landing_pads: IndexVec<mir::BasicBlock, Option<&'ll BasicBlock>>,
83
84     /// Cached unreachable block
85     unreachable_block: Option<&'ll BasicBlock>,
86
87     /// The location where each MIR arg/var/tmp/ret is stored. This is
88     /// usually an `PlaceRef` representing an alloca, but not always:
89     /// sometimes we can skip the alloca and just store the value
90     /// directly using an `OperandRef`, which makes for tighter LLVM
91     /// IR. The conditions for using an `OperandRef` are as follows:
92     ///
93     /// - the type of the local must be judged "immediate" by `is_llvm_immediate`
94     /// - the operand must never be referenced indirectly
95     ///     - we should not take its address using the `&` operator
96     ///     - nor should it appear in a place path like `tmp.a`
97     /// - the operand must be defined by an rvalue that can generate immediate
98     ///   values
99     ///
100     /// Avoiding allocs can also be important for certain intrinsics,
101     /// notably `expect`.
102     locals: IndexVec<mir::Local, LocalRef<'tcx, V>>,
103
104     /// Debug information for MIR scopes.
105     scopes: IndexVec<mir::SourceScope, debuginfo::MirDebugScope<'ll>>,
106
107     /// If this function is being monomorphized, this contains the type substitutions used.
108     param_substs: &'tcx Substs<'tcx>,
109 }
110
111 impl FunctionCx<'a, 'll, 'tcx, &'ll Value> {
112     pub fn monomorphize<T>(&self, value: &T) -> T
113         where T: TypeFoldable<'tcx>
114     {
115         self.cx.tcx.subst_and_normalize_erasing_regions(
116             self.param_substs,
117             ty::ParamEnv::reveal_all(),
118             value,
119         )
120     }
121
122     pub fn set_debug_loc(&mut self, bx: &Builder<'_, 'll, '_>, source_info: mir::SourceInfo) {
123         let (scope, span) = self.debug_loc(source_info);
124         debuginfo::set_source_location(&self.debug_context, bx, scope, span);
125     }
126
127     pub fn debug_loc(&mut self, source_info: mir::SourceInfo) -> (Option<&'ll DIScope>, Span) {
128         // Bail out if debug info emission is not enabled.
129         match self.debug_context {
130             FunctionDebugContext::DebugInfoDisabled |
131             FunctionDebugContext::FunctionWithoutDebugInfo => {
132                 return (self.scopes[source_info.scope].scope_metadata, source_info.span);
133             }
134             FunctionDebugContext::RegularContext(_) =>{}
135         }
136
137         // In order to have a good line stepping behavior in debugger, we overwrite debug
138         // locations of macro expansions with that of the outermost expansion site
139         // (unless the crate is being compiled with `-Z debug-macros`).
140         if source_info.span.ctxt() == NO_EXPANSION ||
141            self.cx.sess().opts.debugging_opts.debug_macros {
142             let scope = self.scope_metadata_for_loc(source_info.scope, source_info.span.lo());
143             (scope, source_info.span)
144         } else {
145             // Walk up the macro expansion chain until we reach a non-expanded span.
146             // We also stop at the function body level because no line stepping can occur
147             // at the level above that.
148             let mut span = source_info.span;
149             while span.ctxt() != NO_EXPANSION && span.ctxt() != self.mir.span.ctxt() {
150                 if let Some(info) = span.ctxt().outer().expn_info() {
151                     span = info.call_site;
152                 } else {
153                     break;
154                 }
155             }
156             let scope = self.scope_metadata_for_loc(source_info.scope, span.lo());
157             // Use span of the outermost expansion site, while keeping the original lexical scope.
158             (scope, span)
159         }
160     }
161
162     // DILocations inherit source file name from the parent DIScope.  Due to macro expansions
163     // it may so happen that the current span belongs to a different file than the DIScope
164     // corresponding to span's containing source scope.  If so, we need to create a DIScope
165     // "extension" into that file.
166     fn scope_metadata_for_loc(&self, scope_id: mir::SourceScope, pos: BytePos)
167                               -> Option<&'ll DIScope> {
168         let scope_metadata = self.scopes[scope_id].scope_metadata;
169         if pos < self.scopes[scope_id].file_start_pos ||
170            pos >= self.scopes[scope_id].file_end_pos {
171             let cm = self.cx.sess().source_map();
172             let defining_crate = self.debug_context.get_ref(DUMMY_SP).defining_crate;
173             Some(debuginfo::extend_scope_to_file(self.cx,
174                                                  scope_metadata.unwrap(),
175                                                  &cm.lookup_char_pos(pos).file,
176                                                  defining_crate))
177         } else {
178             scope_metadata
179         }
180     }
181 }
182
183 enum LocalRef<'tcx, V> {
184     Place(PlaceRef<'tcx, V>),
185     /// `UnsizedPlace(p)`: `p` itself is a thin pointer (indirect place).
186     /// `*p` is the fat pointer that references the actual unsized place.
187     /// Every time it is initialized, we have to reallocate the place
188     /// and update the fat pointer. That's the reason why it is indirect.
189     UnsizedPlace(PlaceRef<'tcx, V>),
190     Operand(Option<OperandRef<'tcx, V>>),
191 }
192
193 impl LocalRef<'tcx, &'ll Value> {
194     fn new_operand(
195         cx: &CodegenCx<'ll, 'tcx>,
196         layout: TyLayout<'tcx>,
197     ) -> LocalRef<'tcx, &'ll Value> {
198         if layout.is_zst() {
199             // Zero-size temporaries aren't always initialized, which
200             // doesn't matter because they don't contain data, but
201             // we need something in the operand.
202             LocalRef::Operand(Some(OperandRef::new_zst(cx, layout)))
203         } else {
204             LocalRef::Operand(None)
205         }
206     }
207 }
208
209 ///////////////////////////////////////////////////////////////////////////
210
211 pub fn codegen_mir(
212     cx: &'a CodegenCx<'ll, 'tcx>,
213     llfn: &'ll Value,
214     mir: &'a Mir<'tcx>,
215     instance: Instance<'tcx>,
216     sig: ty::FnSig<'tcx>,
217 ) {
218     let fn_ty = FnType::new(cx, sig, &[]);
219     debug!("fn_ty: {:?}", fn_ty);
220     let debug_context =
221         debuginfo::create_function_debug_context(cx, instance, sig, llfn, mir);
222     let bx = Builder::new_block(cx, llfn, "start");
223
224     if mir.basic_blocks().iter().any(|bb| bb.is_cleanup) {
225         bx.set_personality_fn(cx.eh_personality());
226     }
227
228     let cleanup_kinds = analyze::cleanup_kinds(&mir);
229     // Allocate a `Block` for every basic block, except
230     // the start block, if nothing loops back to it.
231     let reentrant_start_block = !mir.predecessors_for(mir::START_BLOCK).is_empty();
232     let block_bxs: IndexVec<mir::BasicBlock, &'ll BasicBlock> =
233         mir.basic_blocks().indices().map(|bb| {
234             if bb == mir::START_BLOCK && !reentrant_start_block {
235                 bx.llbb()
236             } else {
237                 bx.build_sibling_block(&format!("{:?}", bb)).llbb()
238             }
239         }).collect();
240
241     // Compute debuginfo scopes from MIR scopes.
242     let scopes = debuginfo::create_mir_scopes(cx, mir, &debug_context);
243     let (landing_pads, funclets) = create_funclets(mir, &bx, &cleanup_kinds, &block_bxs);
244
245     let mut fx = FunctionCx {
246         instance,
247         mir,
248         llfn,
249         fn_ty,
250         cx,
251         personality_slot: None,
252         blocks: block_bxs,
253         unreachable_block: None,
254         cleanup_kinds,
255         landing_pads,
256         funclets: &funclets,
257         scopes,
258         locals: IndexVec::new(),
259         debug_context,
260         param_substs: {
261             assert!(!instance.substs.needs_infer());
262             instance.substs
263         },
264     };
265
266     let memory_locals = analyze::non_ssa_locals(&fx);
267
268     // Allocate variable and temp allocas
269     fx.locals = {
270         let args = arg_local_refs(&bx, &fx, &fx.scopes, &memory_locals);
271
272         let mut allocate_local = |local| {
273             let decl = &mir.local_decls[local];
274             let layout = bx.cx.layout_of(fx.monomorphize(&decl.ty));
275             assert!(!layout.ty.has_erasable_regions());
276
277             if let Some(name) = decl.name {
278                 // User variable
279                 let debug_scope = fx.scopes[decl.visibility_scope];
280                 let dbg = debug_scope.is_valid() && bx.sess().opts.debuginfo == DebugInfo::Full;
281
282                 if !memory_locals.contains(local) && !dbg {
283                     debug!("alloc: {:?} ({}) -> operand", local, name);
284                     return LocalRef::new_operand(bx.cx, layout);
285                 }
286
287                 debug!("alloc: {:?} ({}) -> place", local, name);
288                 if layout.is_unsized() {
289                     let indirect_place =
290                         PlaceRef::alloca_unsized_indirect(&bx, layout, &name.as_str());
291                     // FIXME: add an appropriate debuginfo
292                     LocalRef::UnsizedPlace(indirect_place)
293                 } else {
294                     let place = PlaceRef::alloca(&bx, layout, &name.as_str());
295                     if dbg {
296                         let (scope, span) = fx.debug_loc(mir::SourceInfo {
297                             span: decl.source_info.span,
298                             scope: decl.visibility_scope,
299                         });
300                         declare_local(&bx, &fx.debug_context, name, layout.ty, scope.unwrap(),
301                             VariableAccess::DirectVariable { alloca: place.llval },
302                             VariableKind::LocalVariable, span);
303                     }
304                     LocalRef::Place(place)
305                 }
306             } else {
307                 // Temporary or return place
308                 if local == mir::RETURN_PLACE && fx.fn_ty.ret.is_indirect() {
309                     debug!("alloc: {:?} (return place) -> place", local);
310                     let llretptr = llvm::get_param(llfn, 0);
311                     LocalRef::Place(PlaceRef::new_sized(llretptr, layout, layout.align))
312                 } else if memory_locals.contains(local) {
313                     debug!("alloc: {:?} -> place", local);
314                     if layout.is_unsized() {
315                         let indirect_place =
316                             PlaceRef::alloca_unsized_indirect(&bx, layout, &format!("{:?}", local));
317                         LocalRef::UnsizedPlace(indirect_place)
318                     } else {
319                         LocalRef::Place(PlaceRef::alloca(&bx, layout, &format!("{:?}", local)))
320                     }
321                 } else {
322                     // If this is an immediate local, we do not create an
323                     // alloca in advance. Instead we wait until we see the
324                     // definition and update the operand there.
325                     debug!("alloc: {:?} -> operand", local);
326                     LocalRef::new_operand(bx.cx, layout)
327                 }
328             }
329         };
330
331         let retptr = allocate_local(mir::RETURN_PLACE);
332         iter::once(retptr)
333             .chain(args.into_iter())
334             .chain(mir.vars_and_temps_iter().map(allocate_local))
335             .collect()
336     };
337
338     // Branch to the START block, if it's not the entry block.
339     if reentrant_start_block {
340         bx.br(fx.blocks[mir::START_BLOCK]);
341     }
342
343     // Up until here, IR instructions for this function have explicitly not been annotated with
344     // source code location, so we don't step into call setup code. From here on, source location
345     // emitting should be enabled.
346     debuginfo::start_emitting_source_locations(&fx.debug_context);
347
348     let rpo = traversal::reverse_postorder(&mir);
349     let mut visited = BitSet::new_empty(mir.basic_blocks().len());
350
351     // Codegen the body of each block using reverse postorder
352     for (bb, _) in rpo {
353         visited.insert(bb.index());
354         fx.codegen_block(bb);
355     }
356
357     // Remove blocks that haven't been visited, or have no
358     // predecessors.
359     for bb in mir.basic_blocks().indices() {
360         // Unreachable block
361         if !visited.contains(bb.index()) {
362             debug!("codegen_mir: block {:?} was not visited", bb);
363             unsafe {
364                 llvm::LLVMDeleteBasicBlock(fx.blocks[bb]);
365             }
366         }
367     }
368 }
369
370 fn create_funclets(
371     mir: &'a Mir<'tcx>,
372     bx: &Builder<'a, 'll, 'tcx>,
373     cleanup_kinds: &IndexVec<mir::BasicBlock, CleanupKind>,
374     block_bxs: &IndexVec<mir::BasicBlock, &'ll BasicBlock>)
375     -> (IndexVec<mir::BasicBlock, Option<&'ll BasicBlock>>,
376         IndexVec<mir::BasicBlock, Option<Funclet<'ll>>>)
377 {
378     block_bxs.iter_enumerated().zip(cleanup_kinds).map(|((bb, &llbb), cleanup_kind)| {
379         match *cleanup_kind {
380             CleanupKind::Funclet if base::wants_msvc_seh(bx.sess()) => {}
381             _ => return (None, None)
382         }
383
384         let cleanup;
385         let ret_llbb;
386         match mir[bb].terminator.as_ref().map(|t| &t.kind) {
387             // This is a basic block that we're aborting the program for,
388             // notably in an `extern` function. These basic blocks are inserted
389             // so that we assert that `extern` functions do indeed not panic,
390             // and if they do we abort the process.
391             //
392             // On MSVC these are tricky though (where we're doing funclets). If
393             // we were to do a cleanuppad (like below) the normal functions like
394             // `longjmp` would trigger the abort logic, terminating the
395             // program. Instead we insert the equivalent of `catch(...)` for C++
396             // which magically doesn't trigger when `longjmp` files over this
397             // frame.
398             //
399             // Lots more discussion can be found on #48251 but this codegen is
400             // modeled after clang's for:
401             //
402             //      try {
403             //          foo();
404             //      } catch (...) {
405             //          bar();
406             //      }
407             Some(&mir::TerminatorKind::Abort) => {
408                 let cs_bx = bx.build_sibling_block(&format!("cs_funclet{:?}", bb));
409                 let cp_bx = bx.build_sibling_block(&format!("cp_funclet{:?}", bb));
410                 ret_llbb = cs_bx.llbb();
411
412                 let cs = cs_bx.catch_switch(None, None, 1);
413                 cs_bx.add_handler(cs, cp_bx.llbb());
414
415                 // The "null" here is actually a RTTI type descriptor for the
416                 // C++ personality function, but `catch (...)` has no type so
417                 // it's null. The 64 here is actually a bitfield which
418                 // represents that this is a catch-all block.
419                 let null = C_null(Type::i8p(bx.cx));
420                 let sixty_four = C_i32(bx.cx, 64);
421                 cleanup = cp_bx.catch_pad(cs, &[null, sixty_four, null]);
422                 cp_bx.br(llbb);
423             }
424             _ => {
425                 let cleanup_bx = bx.build_sibling_block(&format!("funclet_{:?}", bb));
426                 ret_llbb = cleanup_bx.llbb();
427                 cleanup = cleanup_bx.cleanup_pad(None, &[]);
428                 cleanup_bx.br(llbb);
429             }
430         };
431
432         (Some(ret_llbb), Some(Funclet::new(cleanup)))
433     }).unzip()
434 }
435
436 /// Produce, for each argument, a `Value` pointing at the
437 /// argument's value. As arguments are places, these are always
438 /// indirect.
439 fn arg_local_refs(
440     bx: &Builder<'a, 'll, 'tcx>,
441     fx: &FunctionCx<'a, 'll, 'tcx, &'ll Value>,
442     scopes: &IndexVec<mir::SourceScope, debuginfo::MirDebugScope<'ll>>,
443     memory_locals: &BitSet<mir::Local>,
444 ) -> Vec<LocalRef<'tcx, &'ll Value>> {
445     let mir = fx.mir;
446     let tcx = bx.tcx();
447     let mut idx = 0;
448     let mut llarg_idx = fx.fn_ty.ret.is_indirect() as usize;
449
450     // Get the argument scope, if it exists and if we need it.
451     let arg_scope = scopes[mir::OUTERMOST_SOURCE_SCOPE];
452     let arg_scope = if bx.sess().opts.debuginfo == DebugInfo::Full {
453         arg_scope.scope_metadata
454     } else {
455         None
456     };
457
458     mir.args_iter().enumerate().map(|(arg_index, local)| {
459         let arg_decl = &mir.local_decls[local];
460
461         let name = if let Some(name) = arg_decl.name {
462             name.as_str().to_string()
463         } else {
464             format!("arg{}", arg_index)
465         };
466
467         if Some(local) == mir.spread_arg {
468             // This argument (e.g. the last argument in the "rust-call" ABI)
469             // is a tuple that was spread at the ABI level and now we have
470             // to reconstruct it into a tuple local variable, from multiple
471             // individual LLVM function arguments.
472
473             let arg_ty = fx.monomorphize(&arg_decl.ty);
474             let tupled_arg_tys = match arg_ty.sty {
475                 ty::Tuple(ref tys) => tys,
476                 _ => bug!("spread argument isn't a tuple?!")
477             };
478
479             let place = PlaceRef::alloca(bx, bx.cx.layout_of(arg_ty), &name);
480             for i in 0..tupled_arg_tys.len() {
481                 let arg = &fx.fn_ty.args[idx];
482                 idx += 1;
483                 if arg.pad.is_some() {
484                     llarg_idx += 1;
485                 }
486                 arg.store_fn_arg(bx, &mut llarg_idx, place.project_field(bx, i));
487             }
488
489             // Now that we have one alloca that contains the aggregate value,
490             // we can create one debuginfo entry for the argument.
491             arg_scope.map(|scope| {
492                 let variable_access = VariableAccess::DirectVariable {
493                     alloca: place.llval
494                 };
495                 declare_local(
496                     bx,
497                     &fx.debug_context,
498                     arg_decl.name.unwrap_or(keywords::Invalid.name()),
499                     arg_ty, scope,
500                     variable_access,
501                     VariableKind::ArgumentVariable(arg_index + 1),
502                     DUMMY_SP
503                 );
504             });
505
506             return LocalRef::Place(place);
507         }
508
509         let arg = &fx.fn_ty.args[idx];
510         idx += 1;
511         if arg.pad.is_some() {
512             llarg_idx += 1;
513         }
514
515         if arg_scope.is_none() && !memory_locals.contains(local) {
516             // We don't have to cast or keep the argument in the alloca.
517             // FIXME(eddyb): We should figure out how to use llvm.dbg.value instead
518             // of putting everything in allocas just so we can use llvm.dbg.declare.
519             let local = |op| LocalRef::Operand(Some(op));
520             match arg.mode {
521                 PassMode::Ignore => {
522                     return local(OperandRef::new_zst(bx.cx, arg.layout));
523                 }
524                 PassMode::Direct(_) => {
525                     let llarg = llvm::get_param(bx.llfn(), llarg_idx as c_uint);
526                     bx.set_value_name(llarg, &name);
527                     llarg_idx += 1;
528                     return local(
529                         OperandRef::from_immediate_or_packed_pair(bx, llarg, arg.layout));
530                 }
531                 PassMode::Pair(..) => {
532                     let a = llvm::get_param(bx.llfn(), llarg_idx as c_uint);
533                     bx.set_value_name(a, &(name.clone() + ".0"));
534                     llarg_idx += 1;
535
536                     let b = llvm::get_param(bx.llfn(), llarg_idx as c_uint);
537                     bx.set_value_name(b, &(name + ".1"));
538                     llarg_idx += 1;
539
540                     return local(OperandRef {
541                         val: OperandValue::Pair(a, b),
542                         layout: arg.layout
543                     });
544                 }
545                 _ => {}
546             }
547         }
548
549         let place = if arg.is_sized_indirect() {
550             // Don't copy an indirect argument to an alloca, the caller
551             // already put it in a temporary alloca and gave it up.
552             // FIXME: lifetimes
553             let llarg = llvm::get_param(bx.llfn(), llarg_idx as c_uint);
554             bx.set_value_name(llarg, &name);
555             llarg_idx += 1;
556             PlaceRef::new_sized(llarg, arg.layout, arg.layout.align)
557         } else if arg.is_unsized_indirect() {
558             // As the storage for the indirect argument lives during
559             // the whole function call, we just copy the fat pointer.
560             let llarg = llvm::get_param(bx.llfn(), llarg_idx as c_uint);
561             llarg_idx += 1;
562             let llextra = llvm::get_param(bx.llfn(), llarg_idx as c_uint);
563             llarg_idx += 1;
564             let indirect_operand = OperandValue::Pair(llarg, llextra);
565
566             let tmp = PlaceRef::alloca_unsized_indirect(bx, arg.layout, &name);
567             indirect_operand.store(&bx, tmp);
568             tmp
569         } else {
570             let tmp = PlaceRef::alloca(bx, arg.layout, &name);
571             arg.store_fn_arg(bx, &mut llarg_idx, tmp);
572             tmp
573         };
574         arg_scope.map(|scope| {
575             // Is this a regular argument?
576             if arg_index > 0 || mir.upvar_decls.is_empty() {
577                 // The Rust ABI passes indirect variables using a pointer and a manual copy, so we
578                 // need to insert a deref here, but the C ABI uses a pointer and a copy using the
579                 // byval attribute, for which LLVM always does the deref itself,
580                 // so we must not add it.
581                 let variable_access = VariableAccess::DirectVariable {
582                     alloca: place.llval
583                 };
584
585                 declare_local(
586                     bx,
587                     &fx.debug_context,
588                     arg_decl.name.unwrap_or(keywords::Invalid.name()),
589                     arg.layout.ty,
590                     scope,
591                     variable_access,
592                     VariableKind::ArgumentVariable(arg_index + 1),
593                     DUMMY_SP
594                 );
595                 return;
596             }
597
598             // Or is it the closure environment?
599             let (closure_layout, env_ref) = match arg.layout.ty.sty {
600                 ty::RawPtr(ty::TypeAndMut { ty, .. }) |
601                 ty::Ref(_, ty, _)  => (bx.cx.layout_of(ty), true),
602                 _ => (arg.layout, false)
603             };
604
605             let (def_id, upvar_substs) = match closure_layout.ty.sty {
606                 ty::Closure(def_id, substs) => (def_id, UpvarSubsts::Closure(substs)),
607                 ty::Generator(def_id, substs, _) => (def_id, UpvarSubsts::Generator(substs)),
608                 _ => bug!("upvar_decls with non-closure arg0 type `{}`", closure_layout.ty)
609             };
610             let upvar_tys = upvar_substs.upvar_tys(def_id, tcx);
611
612             // Store the pointer to closure data in an alloca for debuginfo
613             // because that's what the llvm.dbg.declare intrinsic expects.
614
615             // FIXME(eddyb) this shouldn't be necessary but SROA seems to
616             // mishandle DW_OP_plus not preceded by DW_OP_deref, i.e. it
617             // doesn't actually strip the offset when splitting the closure
618             // environment into its components so it ends up out of bounds.
619             // (cuviper) It seems to be fine without the alloca on LLVM 6 and later.
620             let env_alloca = !env_ref && llvm_util::get_major_version() < 6;
621             let env_ptr = if env_alloca {
622                 let scratch = PlaceRef::alloca(bx,
623                     bx.cx.layout_of(tcx.mk_mut_ptr(arg.layout.ty)),
624                     "__debuginfo_env_ptr");
625                 bx.store(place.llval, scratch.llval, scratch.align);
626                 scratch.llval
627             } else {
628                 place.llval
629             };
630
631             for (i, (decl, ty)) in mir.upvar_decls.iter().zip(upvar_tys).enumerate() {
632                 let byte_offset_of_var_in_env = closure_layout.fields.offset(i).bytes();
633
634                 let ops = unsafe {
635                     [llvm::LLVMRustDIBuilderCreateOpDeref(),
636                      llvm::LLVMRustDIBuilderCreateOpPlusUconst(),
637                      byte_offset_of_var_in_env as i64,
638                      llvm::LLVMRustDIBuilderCreateOpDeref()]
639                 };
640
641                 // The environment and the capture can each be indirect.
642
643                 // FIXME(eddyb) see above why we sometimes have to keep
644                 // a pointer in an alloca for debuginfo atm.
645                 let mut ops = if env_ref || env_alloca { &ops[..] } else { &ops[1..] };
646
647                 let ty = if let (true, &ty::Ref(_, ty, _)) = (decl.by_ref, &ty.sty) {
648                     ty
649                 } else {
650                     ops = &ops[..ops.len() - 1];
651                     ty
652                 };
653
654                 let variable_access = VariableAccess::IndirectVariable {
655                     alloca: env_ptr,
656                     address_operations: &ops
657                 };
658                 declare_local(
659                     bx,
660                     &fx.debug_context,
661                     decl.debug_name,
662                     ty,
663                     scope,
664                     variable_access,
665                     VariableKind::LocalVariable,
666                     DUMMY_SP
667                 );
668             }
669         });
670         if arg.is_unsized_indirect() {
671             LocalRef::UnsizedPlace(place)
672         } else {
673             LocalRef::Place(place)
674         }
675     }).collect()
676 }
677
678 mod analyze;
679 mod block;
680 mod constant;
681 pub mod place;
682 pub mod operand;
683 mod rvalue;
684 mod statement;