]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/_match.rs
Use get_dataptr() and get_meta() where appropriate
[rust.git] / src / librustc_trans / trans / _match.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 //! # Compilation of match statements
12 //!
13 //! I will endeavor to explain the code as best I can.  I have only a loose
14 //! understanding of some parts of it.
15 //!
16 //! ## Matching
17 //!
18 //! The basic state of the code is maintained in an array `m` of `Match`
19 //! objects.  Each `Match` describes some list of patterns, all of which must
20 //! match against the current list of values.  If those patterns match, then
21 //! the arm listed in the match is the correct arm.  A given arm may have
22 //! multiple corresponding match entries, one for each alternative that
23 //! remains.  As we proceed these sets of matches are adjusted by the various
24 //! `enter_XXX()` functions, each of which adjusts the set of options given
25 //! some information about the value which has been matched.
26 //!
27 //! So, initially, there is one value and N matches, each of which have one
28 //! constituent pattern.  N here is usually the number of arms but may be
29 //! greater, if some arms have multiple alternatives.  For example, here:
30 //!
31 //!     enum Foo { A, B(int), C(usize, usize) }
32 //!     match foo {
33 //!         A => ...,
34 //!         B(x) => ...,
35 //!         C(1, 2) => ...,
36 //!         C(_) => ...
37 //!     }
38 //!
39 //! The value would be `foo`.  There would be four matches, each of which
40 //! contains one pattern (and, in one case, a guard).  We could collect the
41 //! various options and then compile the code for the case where `foo` is an
42 //! `A`, a `B`, and a `C`.  When we generate the code for `C`, we would (1)
43 //! drop the two matches that do not match a `C` and (2) expand the other two
44 //! into two patterns each.  In the first case, the two patterns would be `1`
45 //! and `2`, and the in the second case the _ pattern would be expanded into
46 //! `_` and `_`.  The two values are of course the arguments to `C`.
47 //!
48 //! Here is a quick guide to the various functions:
49 //!
50 //! - `compile_submatch()`: The main workhouse.  It takes a list of values and
51 //!   a list of matches and finds the various possibilities that could occur.
52 //!
53 //! - `enter_XXX()`: modifies the list of matches based on some information
54 //!   about the value that has been matched.  For example,
55 //!   `enter_rec_or_struct()` adjusts the values given that a record or struct
56 //!   has been matched.  This is an infallible pattern, so *all* of the matches
57 //!   must be either wildcards or record/struct patterns.  `enter_opt()`
58 //!   handles the fallible cases, and it is correspondingly more complex.
59 //!
60 //! ## Bindings
61 //!
62 //! We store information about the bound variables for each arm as part of the
63 //! per-arm `ArmData` struct.  There is a mapping from identifiers to
64 //! `BindingInfo` structs.  These structs contain the mode/id/type of the
65 //! binding, but they also contain an LLVM value which points at an alloca
66 //! called `llmatch`. For by value bindings that are Copy, we also create
67 //! an extra alloca that we copy the matched value to so that any changes
68 //! we do to our copy is not reflected in the original and vice-versa.
69 //! We don't do this if it's a move since the original value can't be used
70 //! and thus allowing us to cheat in not creating an extra alloca.
71 //!
72 //! The `llmatch` binding always stores a pointer into the value being matched
73 //! which points at the data for the binding.  If the value being matched has
74 //! type `T`, then, `llmatch` will point at an alloca of type `T*` (and hence
75 //! `llmatch` has type `T**`).  So, if you have a pattern like:
76 //!
77 //!    let a: A = ...;
78 //!    let b: B = ...;
79 //!    match (a, b) { (ref c, d) => { ... } }
80 //!
81 //! For `c` and `d`, we would generate allocas of type `C*` and `D*`
82 //! respectively.  These are called the `llmatch`.  As we match, when we come
83 //! up against an identifier, we store the current pointer into the
84 //! corresponding alloca.
85 //!
86 //! Once a pattern is completely matched, and assuming that there is no guard
87 //! pattern, we will branch to a block that leads to the body itself.  For any
88 //! by-value bindings, this block will first load the ptr from `llmatch` (the
89 //! one of type `D*`) and then load a second time to get the actual value (the
90 //! one of type `D`). For by ref bindings, the value of the local variable is
91 //! simply the first alloca.
92 //!
93 //! So, for the example above, we would generate a setup kind of like this:
94 //!
95 //!        +-------+
96 //!        | Entry |
97 //!        +-------+
98 //!            |
99 //!        +--------------------------------------------+
100 //!        | llmatch_c = (addr of first half of tuple)  |
101 //!        | llmatch_d = (addr of second half of tuple) |
102 //!        +--------------------------------------------+
103 //!            |
104 //!        +--------------------------------------+
105 //!        | *llbinding_d = **llmatch_d           |
106 //!        +--------------------------------------+
107 //!
108 //! If there is a guard, the situation is slightly different, because we must
109 //! execute the guard code.  Moreover, we need to do so once for each of the
110 //! alternatives that lead to the arm, because if the guard fails, they may
111 //! have different points from which to continue the search. Therefore, in that
112 //! case, we generate code that looks more like:
113 //!
114 //!        +-------+
115 //!        | Entry |
116 //!        +-------+
117 //!            |
118 //!        +-------------------------------------------+
119 //!        | llmatch_c = (addr of first half of tuple) |
120 //!        | llmatch_d = (addr of first half of tuple) |
121 //!        +-------------------------------------------+
122 //!            |
123 //!        +-------------------------------------------------+
124 //!        | *llbinding_d = **llmatch_d                      |
125 //!        | check condition                                 |
126 //!        | if false { goto next case }                     |
127 //!        | if true { goto body }                           |
128 //!        +-------------------------------------------------+
129 //!
130 //! The handling for the cleanups is a bit... sensitive.  Basically, the body
131 //! is the one that invokes `add_clean()` for each binding.  During the guard
132 //! evaluation, we add temporary cleanups and revoke them after the guard is
133 //! evaluated (it could fail, after all). Note that guards and moves are
134 //! just plain incompatible.
135 //!
136 //! Some relevant helper functions that manage bindings:
137 //! - `create_bindings_map()`
138 //! - `insert_lllocals()`
139 //!
140 //!
141 //! ## Notes on vector pattern matching.
142 //!
143 //! Vector pattern matching is surprisingly tricky. The problem is that
144 //! the structure of the vector isn't fully known, and slice matches
145 //! can be done on subparts of it.
146 //!
147 //! The way that vector pattern matches are dealt with, then, is as
148 //! follows. First, we make the actual condition associated with a
149 //! vector pattern simply a vector length comparison. So the pattern
150 //! [1, .. x] gets the condition "vec len >= 1", and the pattern
151 //! [.. x] gets the condition "vec len >= 0". The problem here is that
152 //! having the condition "vec len >= 1" hold clearly does not mean that
153 //! only a pattern that has exactly that condition will match. This
154 //! means that it may well be the case that a condition holds, but none
155 //! of the patterns matching that condition match; to deal with this,
156 //! when doing vector length matches, we have match failures proceed to
157 //! the next condition to check.
158 //!
159 //! There are a couple more subtleties to deal with. While the "actual"
160 //! condition associated with vector length tests is simply a test on
161 //! the vector length, the actual vec_len Opt entry contains more
162 //! information used to restrict which matches are associated with it.
163 //! So that all matches in a submatch are matching against the same
164 //! values from inside the vector, they are split up by how many
165 //! elements they match at the front and at the back of the vector. In
166 //! order to make sure that arms are properly checked in order, even
167 //! with the overmatching conditions, each vec_len Opt entry is
168 //! associated with a range of matches.
169 //! Consider the following:
170 //!
171 //!   match &[1, 2, 3] {
172 //!       [1, 1, .. _] => 0,
173 //!       [1, 2, 2, .. _] => 1,
174 //!       [1, 2, 3, .. _] => 2,
175 //!       [1, 2, .. _] => 3,
176 //!       _ => 4
177 //!   }
178 //! The proper arm to match is arm 2, but arms 0 and 3 both have the
179 //! condition "len >= 2". If arm 3 was lumped in with arm 0, then the
180 //! wrong branch would be taken. Instead, vec_len Opts are associated
181 //! with a contiguous range of matches that have the same "shape".
182 //! This is sort of ugly and requires a bunch of special handling of
183 //! vec_len options.
184
185 pub use self::BranchKind::*;
186 pub use self::OptResult::*;
187 pub use self::TransBindingMode::*;
188 use self::Opt::*;
189 use self::FailureHandler::*;
190
191 use llvm::{ValueRef, BasicBlockRef};
192 use middle::check_match::StaticInliner;
193 use middle::check_match;
194 use middle::const_eval;
195 use middle::def::{self, DefMap};
196 use middle::expr_use_visitor as euv;
197 use middle::infer;
198 use middle::lang_items::StrEqFnLangItem;
199 use middle::mem_categorization as mc;
200 use middle::pat_util::*;
201 use trans::adt;
202 use trans::base::*;
203 use trans::build::{AddCase, And, Br, CondBr, GEPi, InBoundsGEP, Load, PointerCast};
204 use trans::build::{Not, Store, Sub, add_comment};
205 use trans::build;
206 use trans::callee;
207 use trans::cleanup::{self, CleanupMethods, DropHintMethods};
208 use trans::common::*;
209 use trans::consts;
210 use trans::datum::*;
211 use trans::debuginfo::{self, DebugLoc, ToDebugLoc};
212 use trans::expr::{self, Dest};
213 use trans::monomorphize;
214 use trans::tvec;
215 use trans::type_of;
216 use middle::ty::{self, Ty};
217 use session::config::NoDebugInfo;
218 use util::common::indenter;
219 use util::nodemap::FnvHashMap;
220 use util::ppaux;
221
222 use std;
223 use std::cmp::Ordering;
224 use std::fmt;
225 use std::rc::Rc;
226 use syntax::ast;
227 use syntax::ast::{DUMMY_NODE_ID, NodeId};
228 use syntax::codemap::Span;
229 use syntax::fold::Folder;
230 use syntax::ptr::P;
231
232 #[derive(Copy, Clone, Debug)]
233 struct ConstantExpr<'a>(&'a ast::Expr);
234
235 impl<'a> ConstantExpr<'a> {
236     fn eq(self, other: ConstantExpr<'a>, tcx: &ty::ctxt) -> bool {
237         match const_eval::compare_lit_exprs(tcx, self.0, other.0) {
238             Some(result) => result == Ordering::Equal,
239             None => panic!("compare_list_exprs: type mismatch"),
240         }
241     }
242 }
243
244 // An option identifying a branch (either a literal, an enum variant or a range)
245 #[derive(Debug)]
246 enum Opt<'a, 'tcx> {
247     ConstantValue(ConstantExpr<'a>, DebugLoc),
248     ConstantRange(ConstantExpr<'a>, ConstantExpr<'a>, DebugLoc),
249     Variant(ty::Disr, Rc<adt::Repr<'tcx>>, ast::DefId, DebugLoc),
250     SliceLengthEqual(usize, DebugLoc),
251     SliceLengthGreaterOrEqual(/* prefix length */ usize,
252                               /* suffix length */ usize,
253                               DebugLoc),
254 }
255
256 impl<'a, 'tcx> Opt<'a, 'tcx> {
257     fn eq(&self, other: &Opt<'a, 'tcx>, tcx: &ty::ctxt<'tcx>) -> bool {
258         match (self, other) {
259             (&ConstantValue(a, _), &ConstantValue(b, _)) => a.eq(b, tcx),
260             (&ConstantRange(a1, a2, _), &ConstantRange(b1, b2, _)) => {
261                 a1.eq(b1, tcx) && a2.eq(b2, tcx)
262             }
263             (&Variant(a_disr, ref a_repr, a_def, _),
264              &Variant(b_disr, ref b_repr, b_def, _)) => {
265                 a_disr == b_disr && *a_repr == *b_repr && a_def == b_def
266             }
267             (&SliceLengthEqual(a, _), &SliceLengthEqual(b, _)) => a == b,
268             (&SliceLengthGreaterOrEqual(a1, a2, _),
269              &SliceLengthGreaterOrEqual(b1, b2, _)) => {
270                 a1 == b1 && a2 == b2
271             }
272             _ => false
273         }
274     }
275
276     fn trans<'blk>(&self, mut bcx: Block<'blk, 'tcx>) -> OptResult<'blk, 'tcx> {
277         let _icx = push_ctxt("match::trans_opt");
278         let ccx = bcx.ccx();
279         match *self {
280             ConstantValue(ConstantExpr(lit_expr), _) => {
281                 let lit_ty = bcx.tcx().node_id_to_type(lit_expr.id);
282                 let (llval, _) = consts::const_expr(ccx, &*lit_expr, bcx.fcx.param_substs, None);
283                 let lit_datum = immediate_rvalue(llval, lit_ty);
284                 let lit_datum = unpack_datum!(bcx, lit_datum.to_appropriate_datum(bcx));
285                 SingleResult(Result::new(bcx, lit_datum.val))
286             }
287             ConstantRange(ConstantExpr(ref l1), ConstantExpr(ref l2), _) => {
288                 let (l1, _) = consts::const_expr(ccx, &**l1, bcx.fcx.param_substs, None);
289                 let (l2, _) = consts::const_expr(ccx, &**l2, bcx.fcx.param_substs, None);
290                 RangeResult(Result::new(bcx, l1), Result::new(bcx, l2))
291             }
292             Variant(disr_val, ref repr, _, _) => {
293                 adt::trans_case(bcx, &**repr, disr_val)
294             }
295             SliceLengthEqual(length, _) => {
296                 SingleResult(Result::new(bcx, C_uint(ccx, length)))
297             }
298             SliceLengthGreaterOrEqual(prefix, suffix, _) => {
299                 LowerBound(Result::new(bcx, C_uint(ccx, prefix + suffix)))
300             }
301         }
302     }
303
304     fn debug_loc(&self) -> DebugLoc {
305         match *self {
306             ConstantValue(_,debug_loc)                 |
307             ConstantRange(_, _, debug_loc)             |
308             Variant(_, _, _, debug_loc)                |
309             SliceLengthEqual(_, debug_loc)             |
310             SliceLengthGreaterOrEqual(_, _, debug_loc) => debug_loc
311         }
312     }
313 }
314
315 #[derive(Copy, Clone, PartialEq)]
316 pub enum BranchKind {
317     NoBranch,
318     Single,
319     Switch,
320     Compare,
321     CompareSliceLength
322 }
323
324 pub enum OptResult<'blk, 'tcx: 'blk> {
325     SingleResult(Result<'blk, 'tcx>),
326     RangeResult(Result<'blk, 'tcx>, Result<'blk, 'tcx>),
327     LowerBound(Result<'blk, 'tcx>)
328 }
329
330 #[derive(Clone, Copy, PartialEq)]
331 pub enum TransBindingMode {
332     /// By-value binding for a copy type: copies from matched data
333     /// into a fresh LLVM alloca.
334     TrByCopy(/* llbinding */ ValueRef),
335
336     /// By-value binding for a non-copy type where we copy into a
337     /// fresh LLVM alloca; this most accurately reflects the language
338     /// semantics (e.g. it properly handles overwrites of the matched
339     /// input), but potentially injects an unwanted copy.
340     TrByMoveIntoCopy(/* llbinding */ ValueRef),
341
342     /// Binding a non-copy type by reference under the hood; this is
343     /// a codegen optimization to avoid unnecessary memory traffic.
344     TrByMoveRef,
345
346     /// By-ref binding exposed in the original source input.
347     TrByRef,
348 }
349
350 impl TransBindingMode {
351     /// if binding by making a fresh copy; returns the alloca that it
352     /// will copy into; otherwise None.
353     fn alloca_if_copy(&self) -> Option<ValueRef> {
354         match *self {
355             TrByCopy(llbinding) | TrByMoveIntoCopy(llbinding) => Some(llbinding),
356             TrByMoveRef | TrByRef => None,
357         }
358     }
359 }
360
361 /// Information about a pattern binding:
362 /// - `llmatch` is a pointer to a stack slot.  The stack slot contains a
363 ///   pointer into the value being matched.  Hence, llmatch has type `T**`
364 ///   where `T` is the value being matched.
365 /// - `trmode` is the trans binding mode
366 /// - `id` is the node id of the binding
367 /// - `ty` is the Rust type of the binding
368 #[derive(Clone, Copy)]
369 pub struct BindingInfo<'tcx> {
370     pub llmatch: ValueRef,
371     pub trmode: TransBindingMode,
372     pub id: ast::NodeId,
373     pub span: Span,
374     pub ty: Ty<'tcx>,
375 }
376
377 type BindingsMap<'tcx> = FnvHashMap<ast::Ident, BindingInfo<'tcx>>;
378
379 struct ArmData<'p, 'blk, 'tcx: 'blk> {
380     bodycx: Block<'blk, 'tcx>,
381     arm: &'p ast::Arm,
382     bindings_map: BindingsMap<'tcx>
383 }
384
385 /// Info about Match.
386 /// If all `pats` are matched then arm `data` will be executed.
387 /// As we proceed `bound_ptrs` are filled with pointers to values to be bound,
388 /// these pointers are stored in llmatch variables just before executing `data` arm.
389 struct Match<'a, 'p: 'a, 'blk: 'a, 'tcx: 'blk> {
390     pats: Vec<&'p ast::Pat>,
391     data: &'a ArmData<'p, 'blk, 'tcx>,
392     bound_ptrs: Vec<(ast::Ident, ValueRef)>,
393     // Thread along renamings done by the check_match::StaticInliner, so we can
394     // map back to original NodeIds
395     pat_renaming_map: Option<&'a FnvHashMap<(NodeId, Span), NodeId>>
396 }
397
398 impl<'a, 'p, 'blk, 'tcx> fmt::Debug for Match<'a, 'p, 'blk, 'tcx> {
399     fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
400         if ppaux::verbose() {
401             // for many programs, this just take too long to serialize
402             write!(f, "{:?}", self.pats)
403         } else {
404             write!(f, "{} pats", self.pats.len())
405         }
406     }
407 }
408
409 fn has_nested_bindings(m: &[Match], col: usize) -> bool {
410     for br in m {
411         match br.pats[col].node {
412             ast::PatIdent(_, _, Some(_)) => return true,
413             _ => ()
414         }
415     }
416     return false;
417 }
418
419 // As noted in `fn match_datum`, we should eventually pass around a
420 // `Datum<Lvalue>` for the `val`; but until we get to that point, this
421 // `MatchInput` struct will serve -- it has everything `Datum<Lvalue>`
422 // does except for the type field.
423 #[derive(Copy, Clone)]
424 pub struct MatchInput { val: ValueRef, lval: Lvalue }
425
426 impl<'tcx> Datum<'tcx, Lvalue> {
427     pub fn match_input(&self) -> MatchInput {
428         MatchInput {
429             val: self.val,
430             lval: self.kind,
431         }
432     }
433 }
434
435 impl MatchInput {
436     fn from_val(val: ValueRef) -> MatchInput {
437         MatchInput {
438             val: val,
439             lval: Lvalue::new("MatchInput::from_val"),
440         }
441     }
442
443     fn to_datum<'tcx>(self, ty: Ty<'tcx>) -> Datum<'tcx, Lvalue> {
444         Datum::new(self.val, ty, self.lval)
445     }
446 }
447
448 fn expand_nested_bindings<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
449                                               m: &[Match<'a, 'p, 'blk, 'tcx>],
450                                               col: usize,
451                                               val: MatchInput)
452                                               -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
453     debug!("expand_nested_bindings(bcx={}, m={:?}, col={}, val={})",
454            bcx.to_str(),
455            m,
456            col,
457            bcx.val_to_string(val.val));
458     let _indenter = indenter();
459
460     m.iter().map(|br| {
461         let mut bound_ptrs = br.bound_ptrs.clone();
462         let mut pat = br.pats[col];
463         loop {
464             pat = match pat.node {
465                 ast::PatIdent(_, ref path, Some(ref inner)) => {
466                     bound_ptrs.push((path.node, val.val));
467                     &**inner
468                 },
469                 _ => break
470             }
471         }
472
473         let mut pats = br.pats.clone();
474         pats[col] = pat;
475         Match {
476             pats: pats,
477             data: &*br.data,
478             bound_ptrs: bound_ptrs,
479             pat_renaming_map: br.pat_renaming_map,
480         }
481     }).collect()
482 }
483
484 fn enter_match<'a, 'b, 'p, 'blk, 'tcx, F>(bcx: Block<'blk, 'tcx>,
485                                           dm: &DefMap,
486                                           m: &[Match<'a, 'p, 'blk, 'tcx>],
487                                           col: usize,
488                                           val: MatchInput,
489                                           mut e: F)
490                                           -> Vec<Match<'a, 'p, 'blk, 'tcx>> where
491     F: FnMut(&[&'p ast::Pat]) -> Option<Vec<&'p ast::Pat>>,
492 {
493     debug!("enter_match(bcx={}, m={:?}, col={}, val={})",
494            bcx.to_str(),
495            m,
496            col,
497            bcx.val_to_string(val.val));
498     let _indenter = indenter();
499
500     m.iter().filter_map(|br| {
501         e(&br.pats).map(|pats| {
502             let this = br.pats[col];
503             let mut bound_ptrs = br.bound_ptrs.clone();
504             match this.node {
505                 ast::PatIdent(_, ref path, None) => {
506                     if pat_is_binding(dm, &*this) {
507                         bound_ptrs.push((path.node, val.val));
508                     }
509                 }
510                 ast::PatVec(ref before, Some(ref slice), ref after) => {
511                     if let ast::PatIdent(_, ref path, None) = slice.node {
512                         let subslice_val = bind_subslice_pat(
513                             bcx, this.id, val,
514                             before.len(), after.len());
515                         bound_ptrs.push((path.node, subslice_val));
516                     }
517                 }
518                 _ => {}
519             }
520             Match {
521                 pats: pats,
522                 data: br.data,
523                 bound_ptrs: bound_ptrs,
524                 pat_renaming_map: br.pat_renaming_map,
525             }
526         })
527     }).collect()
528 }
529
530 fn enter_default<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
531                                      dm: &DefMap,
532                                      m: &[Match<'a, 'p, 'blk, 'tcx>],
533                                      col: usize,
534                                      val: MatchInput)
535                                      -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
536     debug!("enter_default(bcx={}, m={:?}, col={}, val={})",
537            bcx.to_str(),
538            m,
539            col,
540            bcx.val_to_string(val.val));
541     let _indenter = indenter();
542
543     // Collect all of the matches that can match against anything.
544     enter_match(bcx, dm, m, col, val, |pats| {
545         if pat_is_binding_or_wild(dm, &*pats[col]) {
546             let mut r = pats[..col].to_vec();
547             r.push_all(&pats[col + 1..]);
548             Some(r)
549         } else {
550             None
551         }
552     })
553 }
554
555 // <pcwalton> nmatsakis: what does enter_opt do?
556 // <pcwalton> in trans/match
557 // <pcwalton> trans/match.rs is like stumbling around in a dark cave
558 // <nmatsakis> pcwalton: the enter family of functions adjust the set of
559 //             patterns as needed
560 // <nmatsakis> yeah, at some point I kind of achieved some level of
561 //             understanding
562 // <nmatsakis> anyhow, they adjust the patterns given that something of that
563 //             kind has been found
564 // <nmatsakis> pcwalton: ok, right, so enter_XXX() adjusts the patterns, as I
565 //             said
566 // <nmatsakis> enter_match() kind of embodies the generic code
567 // <nmatsakis> it is provided with a function that tests each pattern to see
568 //             if it might possibly apply and so forth
569 // <nmatsakis> so, if you have a pattern like {a: _, b: _, _} and one like _
570 // <nmatsakis> then _ would be expanded to (_, _)
571 // <nmatsakis> one spot for each of the sub-patterns
572 // <nmatsakis> enter_opt() is one of the more complex; it covers the fallible
573 //             cases
574 // <nmatsakis> enter_rec_or_struct() or enter_tuple() are simpler, since they
575 //             are infallible patterns
576 // <nmatsakis> so all patterns must either be records (resp. tuples) or
577 //             wildcards
578
579 /// The above is now outdated in that enter_match() now takes a function that
580 /// takes the complete row of patterns rather than just the first one.
581 /// Also, most of the enter_() family functions have been unified with
582 /// the check_match specialization step.
583 fn enter_opt<'a, 'p, 'blk, 'tcx>(
584              bcx: Block<'blk, 'tcx>,
585              _: ast::NodeId,
586              dm: &DefMap,
587              m: &[Match<'a, 'p, 'blk, 'tcx>],
588              opt: &Opt,
589              col: usize,
590              variant_size: usize,
591              val: MatchInput)
592              -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
593     debug!("enter_opt(bcx={}, m={:?}, opt={:?}, col={}, val={})",
594            bcx.to_str(),
595            m,
596            *opt,
597            col,
598            bcx.val_to_string(val.val));
599     let _indenter = indenter();
600
601     let ctor = match opt {
602         &ConstantValue(ConstantExpr(expr), _) => check_match::ConstantValue(
603             const_eval::eval_const_expr(bcx.tcx(), &*expr)
604         ),
605         &ConstantRange(ConstantExpr(lo), ConstantExpr(hi), _) => check_match::ConstantRange(
606             const_eval::eval_const_expr(bcx.tcx(), &*lo),
607             const_eval::eval_const_expr(bcx.tcx(), &*hi)
608         ),
609         &SliceLengthEqual(n, _) =>
610             check_match::Slice(n),
611         &SliceLengthGreaterOrEqual(before, after, _) =>
612             check_match::SliceWithSubslice(before, after),
613         &Variant(_, _, def_id, _) =>
614             check_match::Constructor::Variant(def_id)
615     };
616
617     let param_env = bcx.tcx().empty_parameter_environment();
618     let mcx = check_match::MatchCheckCtxt {
619         tcx: bcx.tcx(),
620         param_env: param_env,
621     };
622     enter_match(bcx, dm, m, col, val, |pats|
623         check_match::specialize(&mcx, &pats[..], &ctor, col, variant_size)
624     )
625 }
626
627 // Returns the options in one column of matches. An option is something that
628 // needs to be conditionally matched at runtime; for example, the discriminant
629 // on a set of enum variants or a literal.
630 fn get_branches<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
631                                     m: &[Match<'a, 'p, 'blk, 'tcx>],
632                                     col: usize)
633                                     -> Vec<Opt<'p, 'tcx>> {
634     let tcx = bcx.tcx();
635
636     let mut found: Vec<Opt> = vec![];
637     for br in m {
638         let cur = br.pats[col];
639         let debug_loc = match br.pat_renaming_map {
640             Some(pat_renaming_map) => {
641                 match pat_renaming_map.get(&(cur.id, cur.span)) {
642                     Some(&id) => DebugLoc::At(id, cur.span),
643                     None => DebugLoc::At(cur.id, cur.span),
644                 }
645             }
646             None => DebugLoc::None
647         };
648
649         let opt = match cur.node {
650             ast::PatLit(ref l) => {
651                 ConstantValue(ConstantExpr(&**l), debug_loc)
652             }
653             ast::PatIdent(..) | ast::PatEnum(..) | ast::PatStruct(..) => {
654                 // This is either an enum variant or a variable binding.
655                 let opt_def = tcx.def_map.borrow().get(&cur.id).map(|d| d.full_def());
656                 match opt_def {
657                     Some(def::DefVariant(enum_id, var_id, _)) => {
658                         let variant = tcx.lookup_adt_def(enum_id).variant_with_id(var_id);
659                         Variant(variant.disr_val,
660                                 adt::represent_node(bcx, cur.id),
661                                 var_id,
662                                 debug_loc)
663                     }
664                     _ => continue
665                 }
666             }
667             ast::PatRange(ref l1, ref l2) => {
668                 ConstantRange(ConstantExpr(&**l1), ConstantExpr(&**l2), debug_loc)
669             }
670             ast::PatVec(ref before, None, ref after) => {
671                 SliceLengthEqual(before.len() + after.len(), debug_loc)
672             }
673             ast::PatVec(ref before, Some(_), ref after) => {
674                 SliceLengthGreaterOrEqual(before.len(), after.len(), debug_loc)
675             }
676             _ => continue
677         };
678
679         if !found.iter().any(|x| x.eq(&opt, tcx)) {
680             found.push(opt);
681         }
682     }
683     found
684 }
685
686 struct ExtractedBlock<'blk, 'tcx: 'blk> {
687     vals: Vec<ValueRef>,
688     bcx: Block<'blk, 'tcx>,
689 }
690
691 fn extract_variant_args<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
692                                     repr: &adt::Repr<'tcx>,
693                                     disr_val: ty::Disr,
694                                     val: MatchInput)
695                                     -> ExtractedBlock<'blk, 'tcx> {
696     let _icx = push_ctxt("match::extract_variant_args");
697     let args = (0..adt::num_args(repr, disr_val)).map(|i| {
698         adt::trans_field_ptr(bcx, repr, val.val, disr_val, i)
699     }).collect();
700
701     ExtractedBlock { vals: args, bcx: bcx }
702 }
703
704 /// Helper for converting from the ValueRef that we pass around in the match code, which is always
705 /// an lvalue, into a Datum. Eventually we should just pass around a Datum and be done with it.
706 fn match_datum<'tcx>(val: MatchInput, left_ty: Ty<'tcx>) -> Datum<'tcx, Lvalue> {
707     val.to_datum(left_ty)
708 }
709
710 fn bind_subslice_pat(bcx: Block,
711                      pat_id: ast::NodeId,
712                      val: MatchInput,
713                      offset_left: usize,
714                      offset_right: usize) -> ValueRef {
715     let _icx = push_ctxt("match::bind_subslice_pat");
716     let vec_ty = node_id_type(bcx, pat_id);
717     let vec_ty_contents = match vec_ty.sty {
718         ty::TyBox(ty) => ty,
719         ty::TyRef(_, mt) | ty::TyRawPtr(mt) => mt.ty,
720         _ => vec_ty
721     };
722     let unit_ty = vec_ty_contents.sequence_element_type(bcx.tcx());
723     let vec_datum = match_datum(val, vec_ty);
724     let (base, len) = vec_datum.get_vec_base_and_len(bcx);
725
726     let slice_begin = InBoundsGEP(bcx, base, &[C_uint(bcx.ccx(), offset_left)]);
727     let slice_len_offset = C_uint(bcx.ccx(), offset_left + offset_right);
728     let slice_len = Sub(bcx, len, slice_len_offset, DebugLoc::None);
729     let slice_ty = bcx.tcx().mk_imm_ref(bcx.tcx().mk_region(ty::ReStatic),
730                                          bcx.tcx().mk_slice(unit_ty));
731     let scratch = rvalue_scratch_datum(bcx, slice_ty, "");
732     Store(bcx, slice_begin, expr::get_dataptr(bcx, scratch.val));
733     Store(bcx, slice_len, expr::get_meta(bcx, scratch.val));
734     scratch.val
735 }
736
737 fn extract_vec_elems<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
738                                  left_ty: Ty<'tcx>,
739                                  before: usize,
740                                  after: usize,
741                                  val: MatchInput)
742                                  -> ExtractedBlock<'blk, 'tcx> {
743     let _icx = push_ctxt("match::extract_vec_elems");
744     let vec_datum = match_datum(val, left_ty);
745     let (base, len) = vec_datum.get_vec_base_and_len(bcx);
746     let mut elems = vec![];
747     elems.extend((0..before).map(|i| GEPi(bcx, base, &[i])));
748     elems.extend((0..after).rev().map(|i| {
749         InBoundsGEP(bcx, base, &[
750             Sub(bcx, len, C_uint(bcx.ccx(), i + 1), DebugLoc::None)
751         ])
752     }));
753     ExtractedBlock { vals: elems, bcx: bcx }
754 }
755
756 // Macro for deciding whether any of the remaining matches fit a given kind of
757 // pattern.  Note that, because the macro is well-typed, either ALL of the
758 // matches should fit that sort of pattern or NONE (however, some of the
759 // matches may be wildcards like _ or identifiers).
760 macro_rules! any_pat {
761     ($m:expr, $col:expr, $pattern:pat) => (
762         ($m).iter().any(|br| {
763             match br.pats[$col].node {
764                 $pattern => true,
765                 _ => false
766             }
767         })
768     )
769 }
770
771 fn any_uniq_pat(m: &[Match], col: usize) -> bool {
772     any_pat!(m, col, ast::PatBox(_))
773 }
774
775 fn any_region_pat(m: &[Match], col: usize) -> bool {
776     any_pat!(m, col, ast::PatRegion(..))
777 }
778
779 fn any_irrefutable_adt_pat(tcx: &ty::ctxt, m: &[Match], col: usize) -> bool {
780     m.iter().any(|br| {
781         let pat = br.pats[col];
782         match pat.node {
783             ast::PatTup(_) => true,
784             ast::PatStruct(..) => {
785                 match tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
786                     Some(def::DefVariant(..)) => false,
787                     _ => true,
788                 }
789             }
790             ast::PatEnum(..) | ast::PatIdent(_, _, None) => {
791                 match tcx.def_map.borrow().get(&pat.id).map(|d| d.full_def()) {
792                     Some(def::DefStruct(..)) => true,
793                     _ => false
794                 }
795             }
796             _ => false
797         }
798     })
799 }
800
801 /// What to do when the pattern match fails.
802 enum FailureHandler {
803     Infallible,
804     JumpToBasicBlock(BasicBlockRef),
805     Unreachable
806 }
807
808 impl FailureHandler {
809     fn is_fallible(&self) -> bool {
810         match *self {
811             Infallible => false,
812             _ => true
813         }
814     }
815
816     fn is_infallible(&self) -> bool {
817         !self.is_fallible()
818     }
819
820     fn handle_fail(&self, bcx: Block) {
821         match *self {
822             Infallible =>
823                 panic!("attempted to panic in a non-panicking panic handler!"),
824             JumpToBasicBlock(basic_block) =>
825                 Br(bcx, basic_block, DebugLoc::None),
826             Unreachable =>
827                 build::Unreachable(bcx)
828         }
829     }
830 }
831
832 fn pick_column_to_specialize(def_map: &DefMap, m: &[Match]) -> Option<usize> {
833     fn pat_score(def_map: &DefMap, pat: &ast::Pat) -> usize {
834         match pat.node {
835             ast::PatIdent(_, _, Some(ref inner)) => pat_score(def_map, &**inner),
836             _ if pat_is_refutable(def_map, pat) => 1,
837             _ => 0
838         }
839     }
840
841     let column_score = |m: &[Match], col: usize| -> usize {
842         let total_score = m.iter()
843             .map(|row| row.pats[col])
844             .map(|pat| pat_score(def_map, pat))
845             .sum();
846
847         // Irrefutable columns always go first, they'd only be duplicated in the branches.
848         if total_score == 0 {
849             std::usize::MAX
850         } else {
851             total_score
852         }
853     };
854
855     let column_contains_any_nonwild_patterns = |&col: &usize| -> bool {
856         m.iter().any(|row| match row.pats[col].node {
857             ast::PatWild(_) => false,
858             _ => true
859         })
860     };
861
862     (0..m[0].pats.len())
863         .filter(column_contains_any_nonwild_patterns)
864         .map(|col| (col, column_score(m, col)))
865         .max_by(|&(_, score)| score)
866         .map(|(col, _)| col)
867 }
868
869 // Compiles a comparison between two things.
870 fn compare_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
871                               lhs: ValueRef,
872                               rhs: ValueRef,
873                               rhs_t: Ty<'tcx>,
874                               debug_loc: DebugLoc)
875                               -> Result<'blk, 'tcx> {
876     fn compare_str<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
877                                lhs: ValueRef,
878                                rhs: ValueRef,
879                                rhs_t: Ty<'tcx>,
880                                debug_loc: DebugLoc)
881                                -> Result<'blk, 'tcx> {
882         let did = langcall(cx,
883                            None,
884                            &format!("comparison of `{}`", rhs_t),
885                            StrEqFnLangItem);
886         let lhs_data = Load(cx, expr::get_dataptr(cx, lhs));
887         let lhs_len = Load(cx, expr::get_meta(cx, lhs));
888         let rhs_data = Load(cx, expr::get_dataptr(cx, rhs));
889         let rhs_len = Load(cx, expr::get_meta(cx, rhs));
890         callee::trans_lang_call(cx, did, &[lhs_data, lhs_len, rhs_data, rhs_len], None, debug_loc)
891     }
892
893     let _icx = push_ctxt("compare_values");
894     if rhs_t.is_scalar() {
895         let cmp = compare_scalar_types(cx, lhs, rhs, rhs_t, ast::BiEq, debug_loc);
896         return Result::new(cx, cmp);
897     }
898
899     match rhs_t.sty {
900         ty::TyRef(_, mt) => match mt.ty.sty {
901             ty::TyStr => compare_str(cx, lhs, rhs, rhs_t, debug_loc),
902             ty::TyArray(ty, _) | ty::TySlice(ty) => match ty.sty {
903                 ty::TyUint(ast::TyU8) => {
904                     // NOTE: cast &[u8] and &[u8; N] to &str and abuse the str_eq lang item,
905                     // which calls memcmp().
906                     let pat_len = val_ty(rhs).element_type().array_length();
907                     let ty_str_slice = cx.tcx().mk_static_str();
908
909                     let rhs_str = alloc_ty(cx, ty_str_slice, "rhs_str");
910                     Store(cx, expr::get_dataptr(cx, rhs), expr::get_dataptr(cx, rhs_str));
911                     Store(cx, C_uint(cx.ccx(), pat_len), expr::get_meta(cx, rhs_str));
912
913                     let lhs_str;
914                     if val_ty(lhs) == val_ty(rhs) {
915                         // Both the discriminant and the pattern are thin pointers
916                         lhs_str = alloc_ty(cx, ty_str_slice, "lhs_str");
917                         Store(cx, expr::get_dataptr(cx, lhs), expr::get_dataptr(cx, lhs_str));
918                         Store(cx, C_uint(cx.ccx(), pat_len), expr::get_meta(cx, lhs_str));
919                     }
920                     else {
921                         // The discriminant is a fat pointer
922                         let llty_str_slice = type_of::type_of(cx.ccx(), ty_str_slice).ptr_to();
923                         lhs_str = PointerCast(cx, lhs, llty_str_slice);
924                     }
925
926                     compare_str(cx, lhs_str, rhs_str, rhs_t, debug_loc)
927                 },
928                 _ => cx.sess().bug("only byte strings supported in compare_values"),
929             },
930             _ => cx.sess().bug("only string and byte strings supported in compare_values"),
931         },
932         _ => cx.sess().bug("only scalars, byte strings, and strings supported in compare_values"),
933     }
934 }
935
936 /// For each binding in `data.bindings_map`, adds an appropriate entry into the `fcx.lllocals` map
937 fn insert_lllocals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
938                                bindings_map: &BindingsMap<'tcx>,
939                                cs: Option<cleanup::ScopeId>)
940                                -> Block<'blk, 'tcx> {
941     for (&ident, &binding_info) in bindings_map {
942         let (llval, aliases_other_state) = match binding_info.trmode {
943             // By value mut binding for a copy type: load from the ptr
944             // into the matched value and copy to our alloca
945             TrByCopy(llbinding) |
946             TrByMoveIntoCopy(llbinding) => {
947                 let llval = Load(bcx, binding_info.llmatch);
948                 let lvalue = match binding_info.trmode {
949                     TrByCopy(..) =>
950                         Lvalue::new("_match::insert_lllocals"),
951                     TrByMoveIntoCopy(..) => {
952                         // match_input moves from the input into a
953                         // separate stack slot.
954                         //
955                         // E.g. consider moving the value `D(A)` out
956                         // of the tuple `(D(A), D(B))` and into the
957                         // local variable `x` via the pattern `(x,_)`,
958                         // leaving the remainder of the tuple `(_,
959                         // D(B))` still to be dropped in the future.
960                         //
961                         // Thus, here we must must zero the place that
962                         // we are moving *from*, because we do not yet
963                         // track drop flags for a fragmented parent
964                         // match input expression.
965                         //
966                         // Longer term we will be able to map the move
967                         // into `(x, _)` up to the parent path that
968                         // owns the whole tuple, and mark the
969                         // corresponding stack-local drop-flag
970                         // tracking the first component of the tuple.
971                         let hint_kind = HintKind::ZeroAndMaintain;
972                         Lvalue::new_with_hint("_match::insert_lllocals (match_input)",
973                                               bcx, binding_info.id, hint_kind)
974                     }
975                     _ => unreachable!(),
976                 };
977                 let datum = Datum::new(llval, binding_info.ty, lvalue);
978                 call_lifetime_start(bcx, llbinding);
979                 bcx = datum.store_to(bcx, llbinding);
980                 if let Some(cs) = cs {
981                     bcx.fcx.schedule_lifetime_end(cs, llbinding);
982                 }
983
984                 (llbinding, false)
985             },
986
987             // By value move bindings: load from the ptr into the matched value
988             TrByMoveRef => (Load(bcx, binding_info.llmatch), true),
989
990             // By ref binding: use the ptr into the matched value
991             TrByRef => (binding_info.llmatch, true),
992         };
993
994
995         // A local that aliases some other state must be zeroed, since
996         // the other state (e.g. some parent data that we matched
997         // into) will still have its subcomponents (such as this
998         // local) destructed at the end of the parent's scope. Longer
999         // term, we will properly map such parents to the set of
1000         // unique drop flags for its fragments.
1001         let hint_kind = if aliases_other_state {
1002             HintKind::ZeroAndMaintain
1003         } else {
1004             HintKind::DontZeroJustUse
1005         };
1006         let lvalue = Lvalue::new_with_hint("_match::insert_lllocals (local)",
1007                                            bcx,
1008                                            binding_info.id,
1009                                            hint_kind);
1010         let datum = Datum::new(llval, binding_info.ty, lvalue);
1011         if let Some(cs) = cs {
1012             let opt_datum = lvalue.dropflag_hint(bcx);
1013             bcx.fcx.schedule_lifetime_end(cs, binding_info.llmatch);
1014             bcx.fcx.schedule_drop_and_fill_mem(cs, llval, binding_info.ty, opt_datum);
1015         }
1016
1017         debug!("binding {} to {}", binding_info.id, bcx.val_to_string(llval));
1018         bcx.fcx.lllocals.borrow_mut().insert(binding_info.id, datum);
1019         debuginfo::create_match_binding_metadata(bcx, ident.name, binding_info);
1020     }
1021     bcx
1022 }
1023
1024 fn compile_guard<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1025                                      guard_expr: &ast::Expr,
1026                                      data: &ArmData<'p, 'blk, 'tcx>,
1027                                      m: &[Match<'a, 'p, 'blk, 'tcx>],
1028                                      vals: &[MatchInput],
1029                                      chk: &FailureHandler,
1030                                      has_genuine_default: bool)
1031                                      -> Block<'blk, 'tcx> {
1032     debug!("compile_guard(bcx={}, guard_expr={:?}, m={:?}, vals=[{}])",
1033            bcx.to_str(),
1034            guard_expr,
1035            m,
1036            vals.iter().map(|v| bcx.val_to_string(v.val)).collect::<Vec<_>>().join(", "));
1037     let _indenter = indenter();
1038
1039     let mut bcx = insert_lllocals(bcx, &data.bindings_map, None);
1040
1041     let val = unpack_datum!(bcx, expr::trans(bcx, guard_expr));
1042     let val = val.to_llbool(bcx);
1043
1044     for (_, &binding_info) in &data.bindings_map {
1045         if let Some(llbinding) = binding_info.trmode.alloca_if_copy() {
1046             call_lifetime_end(bcx, llbinding)
1047         }
1048     }
1049
1050     for (_, &binding_info) in &data.bindings_map {
1051         bcx.fcx.lllocals.borrow_mut().remove(&binding_info.id);
1052     }
1053
1054     with_cond(bcx, Not(bcx, val, guard_expr.debug_loc()), |bcx| {
1055         for (_, &binding_info) in &data.bindings_map {
1056             call_lifetime_end(bcx, binding_info.llmatch);
1057         }
1058         match chk {
1059             // If the default arm is the only one left, move on to the next
1060             // condition explicitly rather than (possibly) falling back to
1061             // the default arm.
1062             &JumpToBasicBlock(_) if m.len() == 1 && has_genuine_default => {
1063                 chk.handle_fail(bcx);
1064             }
1065             _ => {
1066                 compile_submatch(bcx, m, vals, chk, has_genuine_default);
1067             }
1068         };
1069         bcx
1070     })
1071 }
1072
1073 fn compile_submatch<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1074                                         m: &[Match<'a, 'p, 'blk, 'tcx>],
1075                                         vals: &[MatchInput],
1076                                         chk: &FailureHandler,
1077                                         has_genuine_default: bool) {
1078     debug!("compile_submatch(bcx={}, m={:?}, vals=[{}])",
1079            bcx.to_str(),
1080            m,
1081            vals.iter().map(|v| bcx.val_to_string(v.val)).collect::<Vec<_>>().join(", "));
1082     let _indenter = indenter();
1083     let _icx = push_ctxt("match::compile_submatch");
1084     let mut bcx = bcx;
1085     if m.is_empty() {
1086         if chk.is_fallible() {
1087             chk.handle_fail(bcx);
1088         }
1089         return;
1090     }
1091
1092     let tcx = bcx.tcx();
1093     let def_map = &tcx.def_map;
1094     match pick_column_to_specialize(def_map, m) {
1095         Some(col) => {
1096             let val = vals[col];
1097             if has_nested_bindings(m, col) {
1098                 let expanded = expand_nested_bindings(bcx, m, col, val);
1099                 compile_submatch_continue(bcx,
1100                                           &expanded[..],
1101                                           vals,
1102                                           chk,
1103                                           col,
1104                                           val,
1105                                           has_genuine_default)
1106             } else {
1107                 compile_submatch_continue(bcx, m, vals, chk, col, val, has_genuine_default)
1108             }
1109         }
1110         None => {
1111             let data = &m[0].data;
1112             for &(ref ident, ref value_ptr) in &m[0].bound_ptrs {
1113                 let binfo = *data.bindings_map.get(ident).unwrap();
1114                 call_lifetime_start(bcx, binfo.llmatch);
1115                 if binfo.trmode == TrByRef && type_is_fat_ptr(bcx.tcx(), binfo.ty) {
1116                     expr::copy_fat_ptr(bcx, *value_ptr, binfo.llmatch);
1117                 }
1118                 else {
1119                     Store(bcx, *value_ptr, binfo.llmatch);
1120                 }
1121             }
1122             match data.arm.guard {
1123                 Some(ref guard_expr) => {
1124                     bcx = compile_guard(bcx,
1125                                         &**guard_expr,
1126                                         m[0].data,
1127                                         &m[1..m.len()],
1128                                         vals,
1129                                         chk,
1130                                         has_genuine_default);
1131                 }
1132                 _ => ()
1133             }
1134             Br(bcx, data.bodycx.llbb, DebugLoc::None);
1135         }
1136     }
1137 }
1138
1139 fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1140                                                  m: &[Match<'a, 'p, 'blk, 'tcx>],
1141                                                  vals: &[MatchInput],
1142                                                  chk: &FailureHandler,
1143                                                  col: usize,
1144                                                  val: MatchInput,
1145                                                  has_genuine_default: bool) {
1146     let fcx = bcx.fcx;
1147     let tcx = bcx.tcx();
1148     let dm = &tcx.def_map;
1149
1150     let mut vals_left = vals[0..col].to_vec();
1151     vals_left.push_all(&vals[col + 1..]);
1152     let ccx = bcx.fcx.ccx;
1153
1154     // Find a real id (we're adding placeholder wildcard patterns, but
1155     // each column is guaranteed to have at least one real pattern)
1156     let pat_id = m.iter().map(|br| br.pats[col].id)
1157                          .find(|&id| id != DUMMY_NODE_ID)
1158                          .unwrap_or(DUMMY_NODE_ID);
1159
1160     let left_ty = if pat_id == DUMMY_NODE_ID {
1161         tcx.mk_nil()
1162     } else {
1163         node_id_type(bcx, pat_id)
1164     };
1165
1166     let mcx = check_match::MatchCheckCtxt {
1167         tcx: bcx.tcx(),
1168         param_env: bcx.tcx().empty_parameter_environment(),
1169     };
1170     let adt_vals = if any_irrefutable_adt_pat(bcx.tcx(), m, col) {
1171         let repr = adt::represent_type(bcx.ccx(), left_ty);
1172         let arg_count = adt::num_args(&*repr, 0);
1173         let (arg_count, struct_val) = if type_is_sized(bcx.tcx(), left_ty) {
1174             (arg_count, val.val)
1175         } else {
1176             // For an unsized ADT (i.e. DST struct), we need to treat
1177             // the last field specially: instead of simply passing a
1178             // ValueRef pointing to that field, as with all the others,
1179             // we skip it and instead construct a 'fat ptr' below.
1180             (arg_count - 1, Load(bcx, expr::get_dataptr(bcx, val.val)))
1181         };
1182         let mut field_vals: Vec<ValueRef> = (0..arg_count).map(|ix|
1183             adt::trans_field_ptr(bcx, &*repr, struct_val, 0, ix)
1184         ).collect();
1185
1186         match left_ty.sty {
1187             ty::TyStruct(def, substs) if !type_is_sized(bcx.tcx(), left_ty) => {
1188                 // The last field is technically unsized but
1189                 // since we can only ever match that field behind
1190                 // a reference we construct a fat ptr here.
1191                 let unsized_ty = def.struct_variant().fields.last().map(|field| {
1192                     monomorphize::field_ty(bcx.tcx(), substs, field)
1193                 }).unwrap();
1194                 let llty = type_of::type_of(bcx.ccx(), unsized_ty);
1195                 let scratch = alloca_no_lifetime(bcx, llty, "__struct_field_fat_ptr");
1196                 let data = adt::trans_field_ptr(bcx, &*repr, struct_val, 0, arg_count);
1197                 let len = Load(bcx, expr::get_meta(bcx, val.val));
1198                 Store(bcx, data, expr::get_dataptr(bcx, scratch));
1199                 Store(bcx, len, expr::get_meta(bcx, scratch));
1200                 field_vals.push(scratch);
1201             }
1202             _ => {}
1203         }
1204         Some(field_vals)
1205     } else if any_uniq_pat(m, col) || any_region_pat(m, col) {
1206         Some(vec!(Load(bcx, val.val)))
1207     } else {
1208         match left_ty.sty {
1209             ty::TyArray(_, n) => {
1210                 let args = extract_vec_elems(bcx, left_ty, n, 0, val);
1211                 Some(args.vals)
1212             }
1213             _ => None
1214         }
1215     };
1216     match adt_vals {
1217         Some(field_vals) => {
1218             let pats = enter_match(bcx, dm, m, col, val, |pats|
1219                 check_match::specialize(&mcx, pats,
1220                                         &check_match::Single, col,
1221                                         field_vals.len())
1222             );
1223             let mut vals: Vec<_> = field_vals.into_iter()
1224                 .map(|v|MatchInput::from_val(v))
1225                 .collect();
1226             vals.push_all(&vals_left);
1227             compile_submatch(bcx, &pats, &vals, chk, has_genuine_default);
1228             return;
1229         }
1230         _ => ()
1231     }
1232
1233     // Decide what kind of branch we need
1234     let opts = get_branches(bcx, m, col);
1235     debug!("options={:?}", opts);
1236     let mut kind = NoBranch;
1237     let mut test_val = val.val;
1238     debug!("test_val={}", bcx.val_to_string(test_val));
1239     if !opts.is_empty() {
1240         match opts[0] {
1241             ConstantValue(..) | ConstantRange(..) => {
1242                 test_val = load_if_immediate(bcx, val.val, left_ty);
1243                 kind = if left_ty.is_integral() {
1244                     Switch
1245                 } else {
1246                     Compare
1247                 };
1248             }
1249             Variant(_, ref repr, _, _) => {
1250                 let (the_kind, val_opt) = adt::trans_switch(bcx, &**repr, val.val);
1251                 kind = the_kind;
1252                 if let Some(tval) = val_opt { test_val = tval; }
1253             }
1254             SliceLengthEqual(..) | SliceLengthGreaterOrEqual(..) => {
1255                 let (_, len) = tvec::get_base_and_len(bcx, val.val, left_ty);
1256                 test_val = len;
1257                 kind = Switch;
1258             }
1259         }
1260     }
1261     for o in &opts {
1262         match *o {
1263             ConstantRange(..) => { kind = Compare; break },
1264             SliceLengthGreaterOrEqual(..) => { kind = CompareSliceLength; break },
1265             _ => ()
1266         }
1267     }
1268     let else_cx = match kind {
1269         NoBranch | Single => bcx,
1270         _ => bcx.fcx.new_temp_block("match_else")
1271     };
1272     let sw = if kind == Switch {
1273         build::Switch(bcx, test_val, else_cx.llbb, opts.len())
1274     } else {
1275         C_int(ccx, 0) // Placeholder for when not using a switch
1276     };
1277
1278     let defaults = enter_default(else_cx, dm, m, col, val);
1279     let exhaustive = chk.is_infallible() && defaults.is_empty();
1280     let len = opts.len();
1281
1282     // Compile subtrees for each option
1283     for (i, opt) in opts.iter().enumerate() {
1284         // In some cases of range and vector pattern matching, we need to
1285         // override the failure case so that instead of failing, it proceeds
1286         // to try more matching. branch_chk, then, is the proper failure case
1287         // for the current conditional branch.
1288         let mut branch_chk = None;
1289         let mut opt_cx = else_cx;
1290         let debug_loc = opt.debug_loc();
1291
1292         if !exhaustive || i + 1 < len {
1293             opt_cx = bcx.fcx.new_temp_block("match_case");
1294             match kind {
1295                 Single => Br(bcx, opt_cx.llbb, debug_loc),
1296                 Switch => {
1297                     match opt.trans(bcx) {
1298                         SingleResult(r) => {
1299                             AddCase(sw, r.val, opt_cx.llbb);
1300                             bcx = r.bcx;
1301                         }
1302                         _ => {
1303                             bcx.sess().bug(
1304                                 "in compile_submatch, expected \
1305                                  opt.trans() to return a SingleResult")
1306                         }
1307                     }
1308                 }
1309                 Compare | CompareSliceLength => {
1310                     let t = if kind == Compare {
1311                         left_ty
1312                     } else {
1313                         tcx.types.usize // vector length
1314                     };
1315                     let Result { bcx: after_cx, val: matches } = {
1316                         match opt.trans(bcx) {
1317                             SingleResult(Result { bcx, val }) => {
1318                                 compare_values(bcx, test_val, val, t, debug_loc)
1319                             }
1320                             RangeResult(Result { val: vbegin, .. },
1321                                         Result { bcx, val: vend }) => {
1322                                 let llge = compare_scalar_types(bcx, test_val, vbegin,
1323                                                                 t, ast::BiGe, debug_loc);
1324                                 let llle = compare_scalar_types(bcx, test_val, vend,
1325                                                                 t, ast::BiLe, debug_loc);
1326                                 Result::new(bcx, And(bcx, llge, llle, DebugLoc::None))
1327                             }
1328                             LowerBound(Result { bcx, val }) => {
1329                                 Result::new(bcx, compare_scalar_types(bcx, test_val,
1330                                                                       val, t, ast::BiGe,
1331                                                                       debug_loc))
1332                             }
1333                         }
1334                     };
1335                     bcx = fcx.new_temp_block("compare_next");
1336
1337                     // If none of the sub-cases match, and the current condition
1338                     // is guarded or has multiple patterns, move on to the next
1339                     // condition, if there is any, rather than falling back to
1340                     // the default.
1341                     let guarded = m[i].data.arm.guard.is_some();
1342                     let multi_pats = m[i].pats.len() > 1;
1343                     if i + 1 < len && (guarded || multi_pats || kind == CompareSliceLength) {
1344                         branch_chk = Some(JumpToBasicBlock(bcx.llbb));
1345                     }
1346                     CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb, debug_loc);
1347                 }
1348                 _ => ()
1349             }
1350         } else if kind == Compare || kind == CompareSliceLength {
1351             Br(bcx, else_cx.llbb, debug_loc);
1352         }
1353
1354         let mut size = 0;
1355         let mut unpacked = Vec::new();
1356         match *opt {
1357             Variant(disr_val, ref repr, _, _) => {
1358                 let ExtractedBlock {vals: argvals, bcx: new_bcx} =
1359                     extract_variant_args(opt_cx, &**repr, disr_val, val);
1360                 size = argvals.len();
1361                 unpacked = argvals;
1362                 opt_cx = new_bcx;
1363             }
1364             SliceLengthEqual(len, _) => {
1365                 let args = extract_vec_elems(opt_cx, left_ty, len, 0, val);
1366                 size = args.vals.len();
1367                 unpacked = args.vals.clone();
1368                 opt_cx = args.bcx;
1369             }
1370             SliceLengthGreaterOrEqual(before, after, _) => {
1371                 let args = extract_vec_elems(opt_cx, left_ty, before, after, val);
1372                 size = args.vals.len();
1373                 unpacked = args.vals.clone();
1374                 opt_cx = args.bcx;
1375             }
1376             ConstantValue(..) | ConstantRange(..) => ()
1377         }
1378         let opt_ms = enter_opt(opt_cx, pat_id, dm, m, opt, col, size, val);
1379         let mut opt_vals: Vec<_> = unpacked.into_iter()
1380             .map(|v|MatchInput::from_val(v))
1381             .collect();
1382         opt_vals.push_all(&vals_left[..]);
1383         compile_submatch(opt_cx,
1384                          &opt_ms[..],
1385                          &opt_vals[..],
1386                          branch_chk.as_ref().unwrap_or(chk),
1387                          has_genuine_default);
1388     }
1389
1390     // Compile the fall-through case, if any
1391     if !exhaustive && kind != Single {
1392         if kind == Compare || kind == CompareSliceLength {
1393             Br(bcx, else_cx.llbb, DebugLoc::None);
1394         }
1395         match chk {
1396             // If there is only one default arm left, move on to the next
1397             // condition explicitly rather than (eventually) falling back to
1398             // the last default arm.
1399             &JumpToBasicBlock(_) if defaults.len() == 1 && has_genuine_default => {
1400                 chk.handle_fail(else_cx);
1401             }
1402             _ => {
1403                 compile_submatch(else_cx,
1404                                  &defaults[..],
1405                                  &vals_left[..],
1406                                  chk,
1407                                  has_genuine_default);
1408             }
1409         }
1410     }
1411 }
1412
1413 pub fn trans_match<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1414                                match_expr: &ast::Expr,
1415                                discr_expr: &ast::Expr,
1416                                arms: &[ast::Arm],
1417                                dest: Dest)
1418                                -> Block<'blk, 'tcx> {
1419     let _icx = push_ctxt("match::trans_match");
1420     trans_match_inner(bcx, match_expr.id, discr_expr, arms, dest)
1421 }
1422
1423 /// Checks whether the binding in `discr` is assigned to anywhere in the expression `body`
1424 fn is_discr_reassigned(bcx: Block, discr: &ast::Expr, body: &ast::Expr) -> bool {
1425     let (vid, field) = match discr.node {
1426         ast::ExprPath(..) => match bcx.def(discr.id) {
1427             def::DefLocal(vid) | def::DefUpvar(vid, _) => (vid, None),
1428             _ => return false
1429         },
1430         ast::ExprField(ref base, field) => {
1431             let vid = match bcx.tcx().def_map.borrow().get(&base.id).map(|d| d.full_def()) {
1432                 Some(def::DefLocal(vid)) | Some(def::DefUpvar(vid, _)) => vid,
1433                 _ => return false
1434             };
1435             (vid, Some(mc::NamedField(field.node.name)))
1436         },
1437         ast::ExprTupField(ref base, field) => {
1438             let vid = match bcx.tcx().def_map.borrow().get(&base.id).map(|d| d.full_def()) {
1439                 Some(def::DefLocal(vid)) | Some(def::DefUpvar(vid, _)) => vid,
1440                 _ => return false
1441             };
1442             (vid, Some(mc::PositionalField(field.node)))
1443         },
1444         _ => return false
1445     };
1446
1447     let mut rc = ReassignmentChecker {
1448         node: vid,
1449         field: field,
1450         reassigned: false
1451     };
1452     {
1453         let infcx = infer::normalizing_infer_ctxt(bcx.tcx(), &bcx.tcx().tables);
1454         let mut visitor = euv::ExprUseVisitor::new(&mut rc, &infcx);
1455         visitor.walk_expr(body);
1456     }
1457     rc.reassigned
1458 }
1459
1460 struct ReassignmentChecker {
1461     node: ast::NodeId,
1462     field: Option<mc::FieldName>,
1463     reassigned: bool
1464 }
1465
1466 // Determine if the expression we're matching on is reassigned to within
1467 // the body of the match's arm.
1468 // We only care for the `mutate` callback since this check only matters
1469 // for cases where the matched value is moved.
1470 impl<'tcx> euv::Delegate<'tcx> for ReassignmentChecker {
1471     fn consume(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: euv::ConsumeMode) {}
1472     fn matched_pat(&mut self, _: &ast::Pat, _: mc::cmt, _: euv::MatchMode) {}
1473     fn consume_pat(&mut self, _: &ast::Pat, _: mc::cmt, _: euv::ConsumeMode) {}
1474     fn borrow(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: ty::Region,
1475               _: ty::BorrowKind, _: euv::LoanCause) {}
1476     fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
1477
1478     fn mutate(&mut self, _: ast::NodeId, _: Span, cmt: mc::cmt, _: euv::MutateMode) {
1479         match cmt.cat {
1480             mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1481             mc::cat_local(vid) => self.reassigned |= self.node == vid,
1482             mc::cat_interior(ref base_cmt, mc::InteriorField(field)) => {
1483                 match base_cmt.cat {
1484                     mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1485                     mc::cat_local(vid) => {
1486                         self.reassigned |= self.node == vid &&
1487                             (self.field.is_none() || Some(field) == self.field)
1488                     },
1489                     _ => {}
1490                 }
1491             },
1492             _ => {}
1493         }
1494     }
1495 }
1496
1497 fn create_bindings_map<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, pat: &ast::Pat,
1498                                    discr: &ast::Expr, body: &ast::Expr)
1499                                    -> BindingsMap<'tcx> {
1500     // Create the bindings map, which is a mapping from each binding name
1501     // to an alloca() that will be the value for that local variable.
1502     // Note that we use the names because each binding will have many ids
1503     // from the various alternatives.
1504     let ccx = bcx.ccx();
1505     let tcx = bcx.tcx();
1506     let reassigned = is_discr_reassigned(bcx, discr, body);
1507     let mut bindings_map = FnvHashMap();
1508     pat_bindings(&tcx.def_map, &*pat, |bm, p_id, span, path1| {
1509         let ident = path1.node;
1510         let name = ident.name;
1511         let variable_ty = node_id_type(bcx, p_id);
1512         let llvariable_ty = type_of::type_of(ccx, variable_ty);
1513         let tcx = bcx.tcx();
1514         let param_env = tcx.empty_parameter_environment();
1515
1516         let llmatch;
1517         let trmode;
1518         let moves_by_default = variable_ty.moves_by_default(&param_env, span);
1519         match bm {
1520             ast::BindByValue(_) if !moves_by_default || reassigned =>
1521             {
1522                 llmatch = alloca_no_lifetime(bcx,
1523                                              llvariable_ty.ptr_to(),
1524                                              "__llmatch");
1525                 let llcopy = alloca_no_lifetime(bcx,
1526                                                 llvariable_ty,
1527                                                 &bcx.name(name));
1528                 trmode = if moves_by_default {
1529                     TrByMoveIntoCopy(llcopy)
1530                 } else {
1531                     TrByCopy(llcopy)
1532                 };
1533             }
1534             ast::BindByValue(_) => {
1535                 // in this case, the final type of the variable will be T,
1536                 // but during matching we need to store a *T as explained
1537                 // above
1538                 llmatch = alloca_no_lifetime(bcx,
1539                                              llvariable_ty.ptr_to(),
1540                                              &bcx.name(name));
1541                 trmode = TrByMoveRef;
1542             }
1543             ast::BindByRef(_) => {
1544                 llmatch = alloca_no_lifetime(bcx,
1545                                  llvariable_ty,
1546                                  &bcx.name(name));
1547                 trmode = TrByRef;
1548             }
1549         };
1550         bindings_map.insert(ident, BindingInfo {
1551             llmatch: llmatch,
1552             trmode: trmode,
1553             id: p_id,
1554             span: span,
1555             ty: variable_ty
1556         });
1557     });
1558     return bindings_map;
1559 }
1560
1561 fn trans_match_inner<'blk, 'tcx>(scope_cx: Block<'blk, 'tcx>,
1562                                  match_id: ast::NodeId,
1563                                  discr_expr: &ast::Expr,
1564                                  arms: &[ast::Arm],
1565                                  dest: Dest) -> Block<'blk, 'tcx> {
1566     let _icx = push_ctxt("match::trans_match_inner");
1567     let fcx = scope_cx.fcx;
1568     let mut bcx = scope_cx;
1569     let tcx = bcx.tcx();
1570
1571     let discr_datum = unpack_datum!(bcx, expr::trans_to_lvalue(bcx, discr_expr,
1572                                                                "match"));
1573     if bcx.unreachable.get() {
1574         return bcx;
1575     }
1576
1577     let t = node_id_type(bcx, discr_expr.id);
1578     let chk = if t.is_empty(tcx) {
1579         Unreachable
1580     } else {
1581         Infallible
1582     };
1583
1584     let arm_datas: Vec<ArmData> = arms.iter().map(|arm| ArmData {
1585         bodycx: fcx.new_id_block("case_body", arm.body.id),
1586         arm: arm,
1587         bindings_map: create_bindings_map(bcx, &*arm.pats[0], discr_expr, &*arm.body)
1588     }).collect();
1589
1590     let mut pat_renaming_map = if scope_cx.sess().opts.debuginfo != NoDebugInfo {
1591         Some(FnvHashMap())
1592     } else {
1593         None
1594     };
1595
1596     let arm_pats: Vec<Vec<P<ast::Pat>>> = {
1597         let mut static_inliner = StaticInliner::new(scope_cx.tcx(),
1598                                                     pat_renaming_map.as_mut());
1599         arm_datas.iter().map(|arm_data| {
1600             arm_data.arm.pats.iter().map(|p| static_inliner.fold_pat((*p).clone())).collect()
1601         }).collect()
1602     };
1603
1604     let mut matches = Vec::new();
1605     for (arm_data, pats) in arm_datas.iter().zip(&arm_pats) {
1606         matches.extend(pats.iter().map(|p| Match {
1607             pats: vec![&**p],
1608             data: arm_data,
1609             bound_ptrs: Vec::new(),
1610             pat_renaming_map: pat_renaming_map.as_ref()
1611         }));
1612     }
1613
1614     // `compile_submatch` works one column of arm patterns a time and
1615     // then peels that column off. So as we progress, it may become
1616     // impossible to tell whether we have a genuine default arm, i.e.
1617     // `_ => foo` or not. Sometimes it is important to know that in order
1618     // to decide whether moving on to the next condition or falling back
1619     // to the default arm.
1620     let has_default = arms.last().map_or(false, |arm| {
1621         arm.pats.len() == 1
1622         && arm.pats.last().unwrap().node == ast::PatWild(ast::PatWildSingle)
1623     });
1624
1625     compile_submatch(bcx, &matches[..], &[discr_datum.match_input()], &chk, has_default);
1626
1627     let mut arm_cxs = Vec::new();
1628     for arm_data in &arm_datas {
1629         let mut bcx = arm_data.bodycx;
1630
1631         // insert bindings into the lllocals map and add cleanups
1632         let cs = fcx.push_custom_cleanup_scope();
1633         bcx = insert_lllocals(bcx, &arm_data.bindings_map, Some(cleanup::CustomScope(cs)));
1634         bcx = expr::trans_into(bcx, &*arm_data.arm.body, dest);
1635         bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, cs);
1636         arm_cxs.push(bcx);
1637     }
1638
1639     bcx = scope_cx.fcx.join_blocks(match_id, &arm_cxs[..]);
1640     return bcx;
1641 }
1642
1643 /// Generates code for a local variable declaration like `let <pat>;` or `let <pat> =
1644 /// <opt_init_expr>`.
1645 pub fn store_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1646                                local: &ast::Local)
1647                                -> Block<'blk, 'tcx> {
1648     let _icx = push_ctxt("match::store_local");
1649     let mut bcx = bcx;
1650     let tcx = bcx.tcx();
1651     let pat = &*local.pat;
1652
1653     fn create_dummy_locals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1654                                        pat: &ast::Pat)
1655                                        -> Block<'blk, 'tcx> {
1656         let _icx = push_ctxt("create_dummy_locals");
1657         // create dummy memory for the variables if we have no
1658         // value to store into them immediately
1659         let tcx = bcx.tcx();
1660         pat_bindings(&tcx.def_map, pat, |_, p_id, _, path1| {
1661             let scope = cleanup::var_scope(tcx, p_id);
1662             bcx = mk_binding_alloca(
1663                 bcx, p_id, path1.node.name, scope, (),
1664                 "_match::store_local::create_dummy_locals",
1665                 |(), bcx, Datum { val: llval, ty, kind }| {
1666                     // Dummy-locals start out uninitialized, so set their
1667                     // drop-flag hints (if any) to "moved."
1668                     if let Some(hint) = kind.dropflag_hint(bcx) {
1669                         let moved_hint = adt::DTOR_MOVED_HINT;
1670                         debug!("store moved_hint={} for hint={:?}, uninitialized dummy",
1671                                moved_hint, hint);
1672                         Store(bcx, C_u8(bcx.fcx.ccx, moved_hint), hint.to_value().value());
1673                     }
1674
1675                     if kind.drop_flag_info.must_zero() {
1676                         // if no drop-flag hint, or the hint requires
1677                         // we maintain the embedded drop-flag, then
1678                         // mark embedded drop-flag(s) as moved
1679                         // (i.e. "already dropped").
1680                         drop_done_fill_mem(bcx, llval, ty);
1681                     }
1682                     bcx
1683                 });
1684         });
1685         bcx
1686     }
1687
1688     match local.init {
1689         Some(ref init_expr) => {
1690             // Optimize the "let x = expr" case. This just writes
1691             // the result of evaluating `expr` directly into the alloca
1692             // for `x`. Often the general path results in similar or the
1693             // same code post-optimization, but not always. In particular,
1694             // in unsafe code, you can have expressions like
1695             //
1696             //    let x = intrinsics::uninit();
1697             //
1698             // In such cases, the more general path is unsafe, because
1699             // it assumes it is matching against a valid value.
1700             match simple_identifier(&*pat) {
1701                 Some(ident) => {
1702                     let var_scope = cleanup::var_scope(tcx, local.id);
1703                     return mk_binding_alloca(
1704                         bcx, pat.id, ident.name, var_scope, (),
1705                         "_match::store_local",
1706                         |(), bcx, Datum { val: v, .. }| expr::trans_into(bcx, &**init_expr,
1707                                                                          expr::SaveIn(v)));
1708                 }
1709
1710                 None => {}
1711             }
1712
1713             // General path.
1714             let init_datum =
1715                 unpack_datum!(bcx, expr::trans_to_lvalue(bcx, &**init_expr, "let"));
1716             if bcx.sess().asm_comments() {
1717                 add_comment(bcx, "creating zeroable ref llval");
1718             }
1719             let var_scope = cleanup::var_scope(tcx, local.id);
1720             bind_irrefutable_pat(bcx, pat, init_datum.match_input(), var_scope)
1721         }
1722         None => {
1723             create_dummy_locals(bcx, pat)
1724         }
1725     }
1726 }
1727
1728 fn mk_binding_alloca<'blk, 'tcx, A, F>(bcx: Block<'blk, 'tcx>,
1729                                        p_id: ast::NodeId,
1730                                        name: ast::Name,
1731                                        cleanup_scope: cleanup::ScopeId,
1732                                        arg: A,
1733                                        caller_name: &'static str,
1734                                        populate: F)
1735                                        -> Block<'blk, 'tcx> where
1736     F: FnOnce(A, Block<'blk, 'tcx>, Datum<'tcx, Lvalue>) -> Block<'blk, 'tcx>,
1737 {
1738     let var_ty = node_id_type(bcx, p_id);
1739
1740     // Allocate memory on stack for the binding.
1741     let llval = alloc_ty(bcx, var_ty, &bcx.name(name));
1742     let lvalue = Lvalue::new_with_hint(caller_name, bcx, p_id, HintKind::DontZeroJustUse);
1743     let datum = Datum::new(llval, var_ty, lvalue);
1744
1745     // Subtle: be sure that we *populate* the memory *before*
1746     // we schedule the cleanup.
1747     let bcx = populate(arg, bcx, datum);
1748     bcx.fcx.schedule_lifetime_end(cleanup_scope, llval);
1749     bcx.fcx.schedule_drop_mem(cleanup_scope, llval, var_ty, lvalue.dropflag_hint(bcx));
1750
1751     // Now that memory is initialized and has cleanup scheduled,
1752     // insert datum into the local variable map.
1753     bcx.fcx.lllocals.borrow_mut().insert(p_id, datum);
1754     bcx
1755 }
1756
1757 /// A simple version of the pattern matching code that only handles
1758 /// irrefutable patterns. This is used in let/argument patterns,
1759 /// not in match statements. Unifying this code with the code above
1760 /// sounds nice, but in practice it produces very inefficient code,
1761 /// since the match code is so much more general. In most cases,
1762 /// LLVM is able to optimize the code, but it causes longer compile
1763 /// times and makes the generated code nigh impossible to read.
1764 ///
1765 /// # Arguments
1766 /// - bcx: starting basic block context
1767 /// - pat: the irrefutable pattern being matched.
1768 /// - val: the value being matched -- must be an lvalue (by ref, with cleanup)
1769 pub fn bind_irrefutable_pat<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1770                                     pat: &ast::Pat,
1771                                     val: MatchInput,
1772                                     cleanup_scope: cleanup::ScopeId)
1773                                     -> Block<'blk, 'tcx> {
1774     debug!("bind_irrefutable_pat(bcx={}, pat={:?})",
1775            bcx.to_str(),
1776            pat);
1777
1778     if bcx.sess().asm_comments() {
1779         add_comment(bcx, &format!("bind_irrefutable_pat(pat={:?})",
1780                                  pat));
1781     }
1782
1783     let _indenter = indenter();
1784
1785     let _icx = push_ctxt("match::bind_irrefutable_pat");
1786     let mut bcx = bcx;
1787     let tcx = bcx.tcx();
1788     let ccx = bcx.ccx();
1789     match pat.node {
1790         ast::PatIdent(pat_binding_mode, ref path1, ref inner) => {
1791             if pat_is_binding(&tcx.def_map, &*pat) {
1792                 // Allocate the stack slot where the value of this
1793                 // binding will live and place it into the appropriate
1794                 // map.
1795                 bcx = mk_binding_alloca(
1796                     bcx, pat.id, path1.node.name, cleanup_scope, (),
1797                     "_match::bind_irrefutable_pat",
1798                     |(), bcx, Datum { val: llval, ty, kind: _ }| {
1799                         match pat_binding_mode {
1800                             ast::BindByValue(_) => {
1801                                 // By value binding: move the value that `val`
1802                                 // points at into the binding's stack slot.
1803                                 let d = val.to_datum(ty);
1804                                 d.store_to(bcx, llval)
1805                             }
1806
1807                             ast::BindByRef(_) => {
1808                                 // By ref binding: the value of the variable
1809                                 // is the pointer `val` itself or fat pointer referenced by `val`
1810                                 if type_is_fat_ptr(bcx.tcx(), ty) {
1811                                     expr::copy_fat_ptr(bcx, val.val, llval);
1812                                 }
1813                                 else {
1814                                     Store(bcx, val.val, llval);
1815                                 }
1816
1817                                 bcx
1818                             }
1819                         }
1820                     });
1821             }
1822
1823             if let Some(ref inner_pat) = *inner {
1824                 bcx = bind_irrefutable_pat(bcx, &**inner_pat, val, cleanup_scope);
1825             }
1826         }
1827         ast::PatEnum(_, ref sub_pats) => {
1828             let opt_def = bcx.tcx().def_map.borrow().get(&pat.id).map(|d| d.full_def());
1829             match opt_def {
1830                 Some(def::DefVariant(enum_id, var_id, _)) => {
1831                     let repr = adt::represent_node(bcx, pat.id);
1832                     let vinfo = ccx.tcx().lookup_adt_def(enum_id).variant_with_id(var_id);
1833                     let args = extract_variant_args(bcx,
1834                                                     &*repr,
1835                                                     vinfo.disr_val,
1836                                                     val);
1837                     if let Some(ref sub_pat) = *sub_pats {
1838                         for (i, &argval) in args.vals.iter().enumerate() {
1839                             bcx = bind_irrefutable_pat(
1840                                 bcx,
1841                                 &*sub_pat[i],
1842                                 MatchInput::from_val(argval),
1843                                 cleanup_scope);
1844                         }
1845                     }
1846                 }
1847                 Some(def::DefStruct(..)) => {
1848                     match *sub_pats {
1849                         None => {
1850                             // This is a unit-like struct. Nothing to do here.
1851                         }
1852                         Some(ref elems) => {
1853                             // This is the tuple struct case.
1854                             let repr = adt::represent_node(bcx, pat.id);
1855                             for (i, elem) in elems.iter().enumerate() {
1856                                 let fldptr = adt::trans_field_ptr(bcx, &*repr,
1857                                                                   val.val, 0, i);
1858                                 bcx = bind_irrefutable_pat(
1859                                     bcx,
1860                                     &**elem,
1861                                     MatchInput::from_val(fldptr),
1862                                     cleanup_scope);
1863                             }
1864                         }
1865                     }
1866                 }
1867                 _ => {
1868                     // Nothing to do here.
1869                 }
1870             }
1871         }
1872         ast::PatStruct(_, ref fields, _) => {
1873             let tcx = bcx.tcx();
1874             let pat_ty = node_id_type(bcx, pat.id);
1875             let pat_repr = adt::represent_type(bcx.ccx(), pat_ty);
1876             let pat_v = VariantInfo::of_node(tcx, pat_ty, pat.id);
1877             for f in fields {
1878                 let name = f.node.ident.name;
1879                 let fldptr = adt::trans_field_ptr(
1880                     bcx,
1881                     &*pat_repr,
1882                     val.val,
1883                     pat_v.discr,
1884                     pat_v.field_index(name));
1885                 bcx = bind_irrefutable_pat(bcx,
1886                                            &*f.node.pat,
1887                                            MatchInput::from_val(fldptr),
1888                                            cleanup_scope);
1889             }
1890         }
1891         ast::PatTup(ref elems) => {
1892             let repr = adt::represent_node(bcx, pat.id);
1893             for (i, elem) in elems.iter().enumerate() {
1894                 let fldptr = adt::trans_field_ptr(bcx, &*repr, val.val, 0, i);
1895                 bcx = bind_irrefutable_pat(
1896                     bcx,
1897                     &**elem,
1898                     MatchInput::from_val(fldptr),
1899                     cleanup_scope);
1900             }
1901         }
1902         ast::PatBox(ref inner) => {
1903             let llbox = Load(bcx, val.val);
1904             bcx = bind_irrefutable_pat(
1905                 bcx, &**inner, MatchInput::from_val(llbox), cleanup_scope);
1906         }
1907         ast::PatRegion(ref inner, _) => {
1908             let loaded_val = Load(bcx, val.val);
1909             bcx = bind_irrefutable_pat(
1910                 bcx,
1911                 &**inner,
1912                 MatchInput::from_val(loaded_val),
1913                 cleanup_scope);
1914         }
1915         ast::PatVec(ref before, ref slice, ref after) => {
1916             let pat_ty = node_id_type(bcx, pat.id);
1917             let mut extracted = extract_vec_elems(bcx, pat_ty, before.len(), after.len(), val);
1918             match slice {
1919                 &Some(_) => {
1920                     extracted.vals.insert(
1921                         before.len(),
1922                         bind_subslice_pat(bcx, pat.id, val, before.len(), after.len())
1923                     );
1924                 }
1925                 &None => ()
1926             }
1927             bcx = before
1928                 .iter()
1929                 .chain(slice.iter())
1930                 .chain(after.iter())
1931                 .zip(extracted.vals)
1932                 .fold(bcx, |bcx, (inner, elem)| {
1933                     bind_irrefutable_pat(
1934                         bcx,
1935                         &**inner,
1936                         MatchInput::from_val(elem),
1937                         cleanup_scope)
1938                 });
1939         }
1940         ast::PatMac(..) => {
1941             bcx.sess().span_bug(pat.span, "unexpanded macro");
1942         }
1943         ast::PatQPath(..) | ast::PatWild(_) | ast::PatLit(_) |
1944         ast::PatRange(_, _) => ()
1945     }
1946     return bcx;
1947 }