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