]> git.lizzy.rs Git - rust.git/blob - src/librustc_trans/trans/_match.rs
auto merge of #19628 : jbranchaud/rust/add-string-as-string-doctest, r=steveklabnik
[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(uint, uint) }
32 //!     match foo {
33 //!         A => ...,
34 //!         B(x) => ...,
35 //!         C(1u, 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 `1u`
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 back::abi;
192 use llvm::{ValueRef, BasicBlockRef};
193 use middle::check_match::StaticInliner;
194 use middle::check_match;
195 use middle::const_eval;
196 use middle::def;
197 use middle::expr_use_visitor as euv;
198 use middle::lang_items::StrEqFnLangItem;
199 use middle::mem_categorization as mc;
200 use middle::pat_util::*;
201 use middle::resolve::DefMap;
202 use trans::adt;
203 use trans::base::*;
204 use trans::build::{AddCase, And, BitCast, Br, CondBr, GEPi, InBoundsGEP, Load};
205 use trans::build::{Mul, Not, Store, Sub, add_comment};
206 use trans::build;
207 use trans::callee;
208 use trans::cleanup::{mod, CleanupMethods};
209 use trans::common::*;
210 use trans::consts;
211 use trans::datum::*;
212 use trans::expr::{mod, Dest};
213 use trans::tvec;
214 use trans::type_of;
215 use trans::debuginfo;
216 use middle::ty::{mod, Ty};
217 use session::config::FullDebugInfo;
218 use util::common::indenter;
219 use util::nodemap::FnvHashMap;
220 use util::ppaux::{Repr, vec_map_to_string};
221
222 use std;
223 use std::iter::AdditiveIterator;
224 use std::rc::Rc;
225 use syntax::ast;
226 use syntax::ast::{DUMMY_NODE_ID, Ident};
227 use syntax::codemap::Span;
228 use syntax::fold::Folder;
229 use syntax::ptr::P;
230
231 #[deriving(Show)]
232 struct ConstantExpr<'a>(&'a ast::Expr);
233
234 impl<'a> Copy for ConstantExpr<'a> {}
235
236 impl<'a> ConstantExpr<'a> {
237     fn eq(self, other: ConstantExpr<'a>, tcx: &ty::ctxt) -> bool {
238         let ConstantExpr(expr) = self;
239         let ConstantExpr(other_expr) = other;
240         match const_eval::compare_lit_exprs(tcx, expr, other_expr) {
241             Some(val1) => val1 == 0,
242             None => panic!("compare_list_exprs: type mismatch"),
243         }
244     }
245 }
246
247 // An option identifying a branch (either a literal, an enum variant or a range)
248 #[deriving(Show)]
249 enum Opt<'a, 'tcx> {
250     ConstantValue(ConstantExpr<'a>),
251     ConstantRange(ConstantExpr<'a>, ConstantExpr<'a>),
252     Variant(ty::Disr, Rc<adt::Repr<'tcx>>, ast::DefId),
253     SliceLengthEqual(uint),
254     SliceLengthGreaterOrEqual(/* prefix length */ uint, /* suffix length */ uint),
255 }
256
257 impl<'a, 'tcx> Opt<'a, 'tcx> {
258     fn eq(&self, other: &Opt<'a, 'tcx>, tcx: &ty::ctxt<'tcx>) -> bool {
259         match (self, other) {
260             (&ConstantValue(a), &ConstantValue(b)) => a.eq(b, tcx),
261             (&ConstantRange(a1, a2), &ConstantRange(b1, b2)) => {
262                 a1.eq(b1, tcx) && a2.eq(b2, tcx)
263             }
264             (&Variant(a_disr, ref a_repr, a_def), &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), &SliceLengthGreaterOrEqual(b1, b2)) => {
269                 a1 == b1 && a2 == b2
270             }
271             _ => false
272         }
273     }
274
275     fn trans<'blk>(&self, mut bcx: Block<'blk, 'tcx>) -> OptResult<'blk, 'tcx> {
276         let _icx = push_ctxt("match::trans_opt");
277         let ccx = bcx.ccx();
278         match *self {
279             ConstantValue(ConstantExpr(lit_expr)) => {
280                 let lit_ty = ty::node_id_to_type(bcx.tcx(), lit_expr.id);
281                 let (llval, _) = consts::const_expr(ccx, &*lit_expr);
282                 let lit_datum = immediate_rvalue(llval, lit_ty);
283                 let lit_datum = unpack_datum!(bcx, lit_datum.to_appropriate_datum(bcx));
284                 SingleResult(Result::new(bcx, lit_datum.val))
285             }
286             ConstantRange(ConstantExpr(ref l1), ConstantExpr(ref l2)) => {
287                 let (l1, _) = consts::const_expr(ccx, &**l1);
288                 let (l2, _) = consts::const_expr(ccx, &**l2);
289                 RangeResult(Result::new(bcx, l1), Result::new(bcx, l2))
290             }
291             Variant(disr_val, ref repr, _) => {
292                 adt::trans_case(bcx, &**repr, disr_val)
293             }
294             SliceLengthEqual(length) => {
295                 SingleResult(Result::new(bcx, C_uint(ccx, length)))
296             }
297             SliceLengthGreaterOrEqual(prefix, suffix) => {
298                 LowerBound(Result::new(bcx, C_uint(ccx, prefix + suffix)))
299             }
300         }
301     }
302 }
303
304 #[deriving(PartialEq)]
305 pub enum BranchKind {
306     NoBranch,
307     Single,
308     Switch,
309     Compare,
310     CompareSliceLength
311 }
312
313 impl Copy for BranchKind {}
314
315 pub enum OptResult<'blk, 'tcx: 'blk> {
316     SingleResult(Result<'blk, 'tcx>),
317     RangeResult(Result<'blk, 'tcx>, Result<'blk, 'tcx>),
318     LowerBound(Result<'blk, 'tcx>)
319 }
320
321 #[deriving(Clone)]
322 pub enum TransBindingMode {
323     TrByCopy(/* llbinding */ ValueRef),
324     TrByMove,
325     TrByRef,
326 }
327
328 impl Copy for TransBindingMode {}
329
330 /// Information about a pattern binding:
331 /// - `llmatch` is a pointer to a stack slot.  The stack slot contains a
332 ///   pointer into the value being matched.  Hence, llmatch has type `T**`
333 ///   where `T` is the value being matched.
334 /// - `trmode` is the trans binding mode
335 /// - `id` is the node id of the binding
336 /// - `ty` is the Rust type of the binding
337 #[deriving(Clone)]
338 pub struct BindingInfo<'tcx> {
339     pub llmatch: ValueRef,
340     pub trmode: TransBindingMode,
341     pub id: ast::NodeId,
342     pub span: Span,
343     pub ty: Ty<'tcx>,
344 }
345
346 impl<'tcx> Copy for BindingInfo<'tcx> {}
347
348 type BindingsMap<'tcx> = FnvHashMap<Ident, BindingInfo<'tcx>>;
349
350 struct ArmData<'p, 'blk, 'tcx: 'blk> {
351     bodycx: Block<'blk, 'tcx>,
352     arm: &'p ast::Arm,
353     bindings_map: BindingsMap<'tcx>
354 }
355
356 /// Info about Match.
357 /// If all `pats` are matched then arm `data` will be executed.
358 /// As we proceed `bound_ptrs` are filled with pointers to values to be bound,
359 /// these pointers are stored in llmatch variables just before executing `data` arm.
360 struct Match<'a, 'p: 'a, 'blk: 'a, 'tcx: 'blk> {
361     pats: Vec<&'p ast::Pat>,
362     data: &'a ArmData<'p, 'blk, 'tcx>,
363     bound_ptrs: Vec<(Ident, ValueRef)>,
364 }
365
366 impl<'a, 'p, 'blk, 'tcx> Repr<'tcx> for Match<'a, 'p, 'blk, 'tcx> {
367     fn repr(&self, tcx: &ty::ctxt) -> String {
368         if tcx.sess.verbose() {
369             // for many programs, this just take too long to serialize
370             self.pats.repr(tcx)
371         } else {
372             format!("{} pats", self.pats.len())
373         }
374     }
375 }
376
377 fn has_nested_bindings(m: &[Match], col: uint) -> bool {
378     for br in m.iter() {
379         match br.pats[col].node {
380             ast::PatIdent(_, _, Some(_)) => return true,
381             _ => ()
382         }
383     }
384     return false;
385 }
386
387 fn expand_nested_bindings<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
388                                               m: &[Match<'a, 'p, 'blk, 'tcx>],
389                                               col: uint,
390                                               val: ValueRef)
391                                               -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
392     debug!("expand_nested_bindings(bcx={}, m={}, col={}, val={})",
393            bcx.to_str(),
394            m.repr(bcx.tcx()),
395            col,
396            bcx.val_to_string(val));
397     let _indenter = indenter();
398
399     m.iter().map(|br| {
400         let mut bound_ptrs = br.bound_ptrs.clone();
401         let mut pat = br.pats[col];
402         loop {
403             pat = match pat.node {
404                 ast::PatIdent(_, ref path, Some(ref inner)) => {
405                     bound_ptrs.push((path.node, val));
406                     &**inner
407                 },
408                 _ => break
409             }
410         }
411
412         let mut pats = br.pats.clone();
413         pats[col] = pat;
414         Match {
415             pats: pats,
416             data: &*br.data,
417             bound_ptrs: bound_ptrs
418         }
419     }).collect()
420 }
421
422 type EnterPatterns<'a, 'p> = |&[&'p ast::Pat]|: 'a -> Option<Vec<&'p ast::Pat>>;
423
424 fn enter_match<'a, 'b, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
425                                        dm: &DefMap,
426                                        m: &[Match<'a, 'p, 'blk, 'tcx>],
427                                        col: uint,
428                                        val: ValueRef,
429                                        e: EnterPatterns<'b, 'p>)
430                                        -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
431     debug!("enter_match(bcx={}, m={}, col={}, val={})",
432            bcx.to_str(),
433            m.repr(bcx.tcx()),
434            col,
435            bcx.val_to_string(val));
436     let _indenter = indenter();
437
438     m.iter().filter_map(|br| {
439         e(br.pats.as_slice()).map(|pats| {
440             let this = br.pats[col];
441             let mut bound_ptrs = br.bound_ptrs.clone();
442             match this.node {
443                 ast::PatIdent(_, ref path, None) => {
444                     if pat_is_binding(dm, &*this) {
445                         bound_ptrs.push((path.node, val));
446                     }
447                 }
448                 ast::PatVec(ref before, Some(ref slice), ref after) => {
449                     if let ast::PatIdent(_, ref path, None) = slice.node {
450                         let subslice_val = bind_subslice_pat(
451                             bcx, this.id, val,
452                             before.len(), after.len());
453                         bound_ptrs.push((path.node, subslice_val));
454                     }
455                 }
456                 _ => {}
457             }
458             Match {
459                 pats: pats,
460                 data: br.data,
461                 bound_ptrs: bound_ptrs
462             }
463         })
464     }).collect()
465 }
466
467 fn enter_default<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
468                                      dm: &DefMap,
469                                      m: &[Match<'a, 'p, 'blk, 'tcx>],
470                                      col: uint,
471                                      val: ValueRef)
472                                      -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
473     debug!("enter_default(bcx={}, m={}, col={}, val={})",
474            bcx.to_str(),
475            m.repr(bcx.tcx()),
476            col,
477            bcx.val_to_string(val));
478     let _indenter = indenter();
479
480     // Collect all of the matches that can match against anything.
481     enter_match(bcx, dm, m, col, val, |pats| {
482         if pat_is_binding_or_wild(dm, &*pats[col]) {
483             let mut r = pats[..col].to_vec();
484             r.push_all(pats[col + 1..]);
485             Some(r)
486         } else {
487             None
488         }
489     })
490 }
491
492 // <pcwalton> nmatsakis: what does enter_opt do?
493 // <pcwalton> in trans/match
494 // <pcwalton> trans/match.rs is like stumbling around in a dark cave
495 // <nmatsakis> pcwalton: the enter family of functions adjust the set of
496 //             patterns as needed
497 // <nmatsakis> yeah, at some point I kind of achieved some level of
498 //             understanding
499 // <nmatsakis> anyhow, they adjust the patterns given that something of that
500 //             kind has been found
501 // <nmatsakis> pcwalton: ok, right, so enter_XXX() adjusts the patterns, as I
502 //             said
503 // <nmatsakis> enter_match() kind of embodies the generic code
504 // <nmatsakis> it is provided with a function that tests each pattern to see
505 //             if it might possibly apply and so forth
506 // <nmatsakis> so, if you have a pattern like {a: _, b: _, _} and one like _
507 // <nmatsakis> then _ would be expanded to (_, _)
508 // <nmatsakis> one spot for each of the sub-patterns
509 // <nmatsakis> enter_opt() is one of the more complex; it covers the fallible
510 //             cases
511 // <nmatsakis> enter_rec_or_struct() or enter_tuple() are simpler, since they
512 //             are infallible patterns
513 // <nmatsakis> so all patterns must either be records (resp. tuples) or
514 //             wildcards
515
516 /// The above is now outdated in that enter_match() now takes a function that
517 /// takes the complete row of patterns rather than just the first one.
518 /// Also, most of the enter_() family functions have been unified with
519 /// the check_match specialization step.
520 fn enter_opt<'a, 'p, 'blk, 'tcx>(
521              bcx: Block<'blk, 'tcx>,
522              _: ast::NodeId,
523              dm: &DefMap,
524              m: &[Match<'a, 'p, 'blk, 'tcx>],
525              opt: &Opt,
526              col: uint,
527              variant_size: uint,
528              val: ValueRef)
529              -> Vec<Match<'a, 'p, 'blk, 'tcx>> {
530     debug!("enter_opt(bcx={}, m={}, opt={}, col={}, val={})",
531            bcx.to_str(),
532            m.repr(bcx.tcx()),
533            *opt,
534            col,
535            bcx.val_to_string(val));
536     let _indenter = indenter();
537
538     let ctor = match opt {
539         &ConstantValue(ConstantExpr(expr)) => check_match::ConstantValue(
540             const_eval::eval_const_expr(bcx.tcx(), &*expr)
541         ),
542         &ConstantRange(ConstantExpr(lo), ConstantExpr(hi)) => check_match::ConstantRange(
543             const_eval::eval_const_expr(bcx.tcx(), &*lo),
544             const_eval::eval_const_expr(bcx.tcx(), &*hi)
545         ),
546         &SliceLengthEqual(n) =>
547             check_match::Slice(n),
548         &SliceLengthGreaterOrEqual(before, after) =>
549             check_match::SliceWithSubslice(before, after),
550         &Variant(_, _, def_id) =>
551             check_match::Constructor::Variant(def_id)
552     };
553
554     let param_env = ty::empty_parameter_environment();
555     let mcx = check_match::MatchCheckCtxt {
556         tcx: bcx.tcx(),
557         param_env: param_env,
558     };
559     enter_match(bcx, dm, m, col, val, |pats|
560         check_match::specialize(&mcx, pats.as_slice(), &ctor, col, variant_size)
561     )
562 }
563
564 // Returns the options in one column of matches. An option is something that
565 // needs to be conditionally matched at runtime; for example, the discriminant
566 // on a set of enum variants or a literal.
567 fn get_branches<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
568                                     m: &[Match<'a, 'p, 'blk, 'tcx>], col: uint)
569                                     -> Vec<Opt<'p, 'tcx>> {
570     let tcx = bcx.tcx();
571
572     let mut found: Vec<Opt> = vec![];
573     for br in m.iter() {
574         let cur = br.pats[col];
575         let opt = match cur.node {
576             ast::PatLit(ref l) => ConstantValue(ConstantExpr(&**l)),
577             ast::PatIdent(..) | ast::PatEnum(..) | ast::PatStruct(..) => {
578                 // This is either an enum variant or a variable binding.
579                 let opt_def = tcx.def_map.borrow().get(&cur.id).cloned();
580                 match opt_def {
581                     Some(def::DefVariant(enum_id, var_id, _)) => {
582                         let variant = ty::enum_variant_with_id(tcx, enum_id, var_id);
583                         Variant(variant.disr_val, adt::represent_node(bcx, cur.id), var_id)
584                     }
585                     _ => continue
586                 }
587             }
588             ast::PatRange(ref l1, ref l2) => {
589                 ConstantRange(ConstantExpr(&**l1), ConstantExpr(&**l2))
590             }
591             ast::PatVec(ref before, None, ref after) => {
592                 SliceLengthEqual(before.len() + after.len())
593             }
594             ast::PatVec(ref before, Some(_), ref after) => {
595                 SliceLengthGreaterOrEqual(before.len(), after.len())
596             }
597             _ => continue
598         };
599
600         if !found.iter().any(|x| x.eq(&opt, tcx)) {
601             found.push(opt);
602         }
603     }
604     found
605 }
606
607 struct ExtractedBlock<'blk, 'tcx: 'blk> {
608     vals: Vec<ValueRef>,
609     bcx: Block<'blk, 'tcx>,
610 }
611
612 fn extract_variant_args<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
613                                     repr: &adt::Repr<'tcx>,
614                                     disr_val: ty::Disr,
615                                     val: ValueRef)
616                                     -> ExtractedBlock<'blk, 'tcx> {
617     let _icx = push_ctxt("match::extract_variant_args");
618     let args = Vec::from_fn(adt::num_args(repr, disr_val), |i| {
619         adt::trans_field_ptr(bcx, repr, val, disr_val, i)
620     });
621
622     ExtractedBlock { vals: args, bcx: bcx }
623 }
624
625 /// Helper for converting from the ValueRef that we pass around in the match code, which is always
626 /// an lvalue, into a Datum. Eventually we should just pass around a Datum and be done with it.
627 fn match_datum<'tcx>(val: ValueRef, left_ty: Ty<'tcx>) -> Datum<'tcx, Lvalue> {
628     Datum::new(val, left_ty, Lvalue)
629 }
630
631 fn bind_subslice_pat(bcx: Block,
632                      pat_id: ast::NodeId,
633                      val: ValueRef,
634                      offset_left: uint,
635                      offset_right: uint) -> ValueRef {
636     let _icx = push_ctxt("match::bind_subslice_pat");
637     let vec_ty = node_id_type(bcx, pat_id);
638     let vt = tvec::vec_types(bcx, ty::sequence_element_type(bcx.tcx(), ty::type_content(vec_ty)));
639     let vec_datum = match_datum(val, vec_ty);
640     let (base, len) = vec_datum.get_vec_base_and_len(bcx);
641
642     let slice_byte_offset = Mul(bcx, vt.llunit_size, C_uint(bcx.ccx(), offset_left));
643     let slice_begin = tvec::pointer_add_byte(bcx, base, slice_byte_offset);
644     let slice_len_offset = C_uint(bcx.ccx(), offset_left + offset_right);
645     let slice_len = Sub(bcx, len, slice_len_offset);
646     let slice_ty = ty::mk_slice(bcx.tcx(),
647                                 ty::ReStatic,
648                                 ty::mt {ty: vt.unit_ty, mutbl: ast::MutImmutable});
649     let scratch = rvalue_scratch_datum(bcx, slice_ty, "");
650     Store(bcx, slice_begin,
651           GEPi(bcx, scratch.val, &[0u, abi::FAT_PTR_ADDR]));
652     Store(bcx, slice_len, GEPi(bcx, scratch.val, &[0u, abi::FAT_PTR_EXTRA]));
653     scratch.val
654 }
655
656 fn extract_vec_elems<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
657                                  left_ty: Ty,
658                                  before: uint,
659                                  after: uint,
660                                  val: ValueRef)
661                                  -> ExtractedBlock<'blk, 'tcx> {
662     let _icx = push_ctxt("match::extract_vec_elems");
663     let vec_datum = match_datum(val, left_ty);
664     let (base, len) = vec_datum.get_vec_base_and_len(bcx);
665     let mut elems = vec![];
666     elems.extend(range(0, before).map(|i| GEPi(bcx, base, &[i])));
667     elems.extend(range(0, after).rev().map(|i| {
668         InBoundsGEP(bcx, base, &[
669             Sub(bcx, len, C_uint(bcx.ccx(), i + 1))
670         ])
671     }));
672     ExtractedBlock { vals: elems, bcx: bcx }
673 }
674
675 // Macro for deciding whether any of the remaining matches fit a given kind of
676 // pattern.  Note that, because the macro is well-typed, either ALL of the
677 // matches should fit that sort of pattern or NONE (however, some of the
678 // matches may be wildcards like _ or identifiers).
679 macro_rules! any_pat (
680     ($m:expr, $col:expr, $pattern:pat) => (
681         ($m).iter().any(|br| {
682             match br.pats[$col].node {
683                 $pattern => true,
684                 _ => false
685             }
686         })
687     )
688 )
689
690 fn any_uniq_pat(m: &[Match], col: uint) -> bool {
691     any_pat!(m, col, ast::PatBox(_))
692 }
693
694 fn any_region_pat(m: &[Match], col: uint) -> bool {
695     any_pat!(m, col, ast::PatRegion(_))
696 }
697
698 fn any_irrefutable_adt_pat(tcx: &ty::ctxt, m: &[Match], col: uint) -> bool {
699     m.iter().any(|br| {
700         let pat = br.pats[col];
701         match pat.node {
702             ast::PatTup(_) => true,
703             ast::PatStruct(..) => {
704                 match tcx.def_map.borrow().get(&pat.id) {
705                     Some(&def::DefVariant(..)) => false,
706                     _ => true,
707                 }
708             }
709             ast::PatEnum(..) | ast::PatIdent(_, _, None) => {
710                 match tcx.def_map.borrow().get(&pat.id) {
711                     Some(&def::DefStruct(..)) => true,
712                     _ => false
713                 }
714             }
715             _ => false
716         }
717     })
718 }
719
720 /// What to do when the pattern match fails.
721 enum FailureHandler {
722     Infallible,
723     JumpToBasicBlock(BasicBlockRef),
724     Unreachable
725 }
726
727 impl FailureHandler {
728     fn is_fallible(&self) -> bool {
729         match *self {
730             Infallible => false,
731             _ => true
732         }
733     }
734
735     fn is_infallible(&self) -> bool {
736         !self.is_fallible()
737     }
738
739     fn handle_fail(&self, bcx: Block) {
740         match *self {
741             Infallible =>
742                 panic!("attempted to panic in a non-panicking panic handler!"),
743             JumpToBasicBlock(basic_block) =>
744                 Br(bcx, basic_block),
745             Unreachable =>
746                 build::Unreachable(bcx)
747         }
748     }
749 }
750
751 fn pick_column_to_specialize(def_map: &DefMap, m: &[Match]) -> Option<uint> {
752     fn pat_score(def_map: &DefMap, pat: &ast::Pat) -> uint {
753         match pat.node {
754             ast::PatIdent(_, _, Some(ref inner)) => pat_score(def_map, &**inner),
755             _ if pat_is_refutable(def_map, pat) => 1u,
756             _ => 0u
757         }
758     }
759
760     let column_score: |&[Match], uint| -> uint = |m, col| {
761         let total_score = m.iter()
762             .map(|row| row.pats[col])
763             .map(|pat| pat_score(def_map, pat))
764             .sum();
765
766         // Irrefutable columns always go first, they'd only be duplicated in the branches.
767         if total_score == 0 {
768             std::uint::MAX
769         } else {
770             total_score
771         }
772     };
773
774     let column_contains_any_nonwild_patterns: |&uint| -> bool = |&col| {
775         m.iter().any(|row| match row.pats[col].node {
776             ast::PatWild(_) => false,
777             _ => true
778         })
779     };
780
781     range(0, m[0].pats.len())
782         .filter(column_contains_any_nonwild_patterns)
783         .map(|col| (col, column_score(m, col)))
784         .max_by(|&(_, score)| score)
785         .map(|(col, _)| col)
786 }
787
788 // Compiles a comparison between two things.
789 fn compare_values<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
790                               lhs: ValueRef,
791                               rhs: ValueRef,
792                               rhs_t: Ty<'tcx>)
793                               -> Result<'blk, 'tcx> {
794     fn compare_str<'blk, 'tcx>(cx: Block<'blk, 'tcx>,
795                                lhs: ValueRef,
796                                rhs: ValueRef,
797                                rhs_t: Ty<'tcx>)
798                                -> Result<'blk, 'tcx> {
799         let did = langcall(cx,
800                            None,
801                            format!("comparison of `{}`",
802                                    cx.ty_to_string(rhs_t)).as_slice(),
803                            StrEqFnLangItem);
804         callee::trans_lang_call(cx, did, &[lhs, rhs], None)
805     }
806
807     let _icx = push_ctxt("compare_values");
808     if ty::type_is_scalar(rhs_t) {
809         let rs = compare_scalar_types(cx, lhs, rhs, rhs_t, ast::BiEq);
810         return Result::new(rs.bcx, rs.val);
811     }
812
813     match rhs_t.sty {
814         ty::ty_rptr(_, mt) => match mt.ty.sty {
815             ty::ty_str => compare_str(cx, lhs, rhs, rhs_t),
816             ty::ty_vec(ty, _) => match ty.sty {
817                 ty::ty_uint(ast::TyU8) => {
818                     // NOTE: cast &[u8] to &str and abuse the str_eq lang item,
819                     // which calls memcmp().
820                     let t = ty::mk_str_slice(cx.tcx(), ty::ReStatic, ast::MutImmutable);
821                     let lhs = BitCast(cx, lhs, type_of::type_of(cx.ccx(), t).ptr_to());
822                     let rhs = BitCast(cx, rhs, type_of::type_of(cx.ccx(), t).ptr_to());
823                     compare_str(cx, lhs, rhs, rhs_t)
824                 },
825                 _ => cx.sess().bug("only byte strings supported in compare_values"),
826             },
827             _ => cx.sess().bug("only string and byte strings supported in compare_values"),
828         },
829         _ => cx.sess().bug("only scalars, byte strings, and strings supported in compare_values"),
830     }
831 }
832
833 /// For each binding in `data.bindings_map`, adds an appropriate entry into the `fcx.lllocals` map
834 fn insert_lllocals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
835                                bindings_map: &BindingsMap<'tcx>,
836                                cs: Option<cleanup::ScopeId>)
837                                -> Block<'blk, 'tcx> {
838     for (&ident, &binding_info) in bindings_map.iter() {
839         let llval = match binding_info.trmode {
840             // By value mut binding for a copy type: load from the ptr
841             // into the matched value and copy to our alloca
842             TrByCopy(llbinding) => {
843                 let llval = Load(bcx, binding_info.llmatch);
844                 let datum = Datum::new(llval, binding_info.ty, Lvalue);
845                 call_lifetime_start(bcx, llbinding);
846                 bcx = datum.store_to(bcx, llbinding);
847                 if let Some(cs) = cs {
848                     bcx.fcx.schedule_lifetime_end(cs, llbinding);
849                 }
850
851                 llbinding
852             },
853
854             // By value move bindings: load from the ptr into the matched value
855             TrByMove => Load(bcx, binding_info.llmatch),
856
857             // By ref binding: use the ptr into the matched value
858             TrByRef => binding_info.llmatch
859         };
860
861         let datum = Datum::new(llval, binding_info.ty, Lvalue);
862         if let Some(cs) = cs {
863             bcx.fcx.schedule_drop_and_zero_mem(cs, llval, binding_info.ty);
864             bcx.fcx.schedule_lifetime_end(cs, binding_info.llmatch);
865         }
866
867         debug!("binding {} to {}",
868                binding_info.id,
869                bcx.val_to_string(llval));
870         bcx.fcx.lllocals.borrow_mut().insert(binding_info.id, datum);
871
872         if bcx.sess().opts.debuginfo == FullDebugInfo {
873             debuginfo::create_match_binding_metadata(bcx,
874                                                      ident,
875                                                      binding_info);
876         }
877     }
878     bcx
879 }
880
881 fn compile_guard<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
882                                      guard_expr: &ast::Expr,
883                                      data: &ArmData<'p, 'blk, 'tcx>,
884                                      m: &[Match<'a, 'p, 'blk, 'tcx>],
885                                      vals: &[ValueRef],
886                                      chk: &FailureHandler,
887                                      has_genuine_default: bool)
888                                      -> Block<'blk, 'tcx> {
889     debug!("compile_guard(bcx={}, guard_expr={}, m={}, vals={})",
890            bcx.to_str(),
891            bcx.expr_to_string(guard_expr),
892            m.repr(bcx.tcx()),
893            vec_map_to_string(vals, |v| bcx.val_to_string(*v)));
894     let _indenter = indenter();
895
896     let mut bcx = insert_lllocals(bcx, &data.bindings_map, None);
897
898     let val = unpack_datum!(bcx, expr::trans(bcx, guard_expr));
899     let val = val.to_llbool(bcx);
900
901     for (_, &binding_info) in data.bindings_map.iter() {
902         if let TrByCopy(llbinding) = binding_info.trmode {
903             call_lifetime_end(bcx, llbinding);
904         }
905     }
906
907     with_cond(bcx, Not(bcx, val), |bcx| {
908         // Guard does not match: remove all bindings from the lllocals table
909         for (_, &binding_info) in data.bindings_map.iter() {
910             call_lifetime_end(bcx, binding_info.llmatch);
911             bcx.fcx.lllocals.borrow_mut().remove(&binding_info.id);
912         }
913         match chk {
914             // If the default arm is the only one left, move on to the next
915             // condition explicitly rather than (possibly) falling back to
916             // the default arm.
917             &JumpToBasicBlock(_) if m.len() == 1 && has_genuine_default => {
918                 chk.handle_fail(bcx);
919             }
920             _ => {
921                 compile_submatch(bcx, m, vals, chk, has_genuine_default);
922             }
923         };
924         bcx
925     })
926 }
927
928 fn compile_submatch<'a, 'p, 'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
929                                         m: &[Match<'a, 'p, 'blk, 'tcx>],
930                                         vals: &[ValueRef],
931                                         chk: &FailureHandler,
932                                         has_genuine_default: bool) {
933     debug!("compile_submatch(bcx={}, m={}, vals={})",
934            bcx.to_str(),
935            m.repr(bcx.tcx()),
936            vec_map_to_string(vals, |v| bcx.val_to_string(*v)));
937     let _indenter = indenter();
938     let _icx = push_ctxt("match::compile_submatch");
939     let mut bcx = bcx;
940     if m.len() == 0u {
941         if chk.is_fallible() {
942             chk.handle_fail(bcx);
943         }
944         return;
945     }
946
947     let tcx = bcx.tcx();
948     let def_map = &tcx.def_map;
949     match pick_column_to_specialize(def_map, m) {
950         Some(col) => {
951             let val = vals[col];
952             if has_nested_bindings(m, col) {
953                 let expanded = expand_nested_bindings(bcx, m, col, val);
954                 compile_submatch_continue(bcx,
955                                           expanded.as_slice(),
956                                           vals,
957                                           chk,
958                                           col,
959                                           val,
960                                           has_genuine_default)
961             } else {
962                 compile_submatch_continue(bcx, m, vals, chk, col, val, has_genuine_default)
963             }
964         }
965         None => {
966             let data = &m[0].data;
967             for &(ref ident, ref value_ptr) in m[0].bound_ptrs.iter() {
968                 let llmatch = data.bindings_map[*ident].llmatch;
969                 call_lifetime_start(bcx, llmatch);
970                 Store(bcx, *value_ptr, llmatch);
971             }
972             match data.arm.guard {
973                 Some(ref guard_expr) => {
974                     bcx = compile_guard(bcx,
975                                         &**guard_expr,
976                                         m[0].data,
977                                         m[1..m.len()],
978                                         vals,
979                                         chk,
980                                         has_genuine_default);
981                 }
982                 _ => ()
983             }
984             Br(bcx, data.bodycx.llbb);
985         }
986     }
987 }
988
989 fn compile_submatch_continue<'a, 'p, 'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
990                                                  m: &[Match<'a, 'p, 'blk, 'tcx>],
991                                                  vals: &[ValueRef],
992                                                  chk: &FailureHandler,
993                                                  col: uint,
994                                                  val: ValueRef,
995                                                  has_genuine_default: bool) {
996     let fcx = bcx.fcx;
997     let tcx = bcx.tcx();
998     let dm = &tcx.def_map;
999
1000     let mut vals_left = vals[0u..col].to_vec();
1001     vals_left.push_all(vals[col + 1u..]);
1002     let ccx = bcx.fcx.ccx;
1003
1004     // Find a real id (we're adding placeholder wildcard patterns, but
1005     // each column is guaranteed to have at least one real pattern)
1006     let pat_id = m.iter().map(|br| br.pats[col].id)
1007                          .find(|&id| id != DUMMY_NODE_ID)
1008                          .unwrap_or(DUMMY_NODE_ID);
1009
1010     let left_ty = if pat_id == DUMMY_NODE_ID {
1011         ty::mk_nil(tcx)
1012     } else {
1013         node_id_type(bcx, pat_id)
1014     };
1015
1016     let mcx = check_match::MatchCheckCtxt {
1017         tcx: bcx.tcx(),
1018         param_env: ty::empty_parameter_environment(),
1019     };
1020     let adt_vals = if any_irrefutable_adt_pat(bcx.tcx(), m, col) {
1021         let repr = adt::represent_type(bcx.ccx(), left_ty);
1022         let arg_count = adt::num_args(&*repr, 0);
1023         let field_vals: Vec<ValueRef> = std::iter::range(0, arg_count).map(|ix|
1024             adt::trans_field_ptr(bcx, &*repr, val, 0, ix)
1025         ).collect();
1026         Some(field_vals)
1027     } else if any_uniq_pat(m, col) || any_region_pat(m, col) {
1028         Some(vec!(Load(bcx, val)))
1029     } else {
1030         match left_ty.sty {
1031             ty::ty_vec(_, Some(n)) => {
1032                 let args = extract_vec_elems(bcx, left_ty, n, 0, val);
1033                 Some(args.vals)
1034             }
1035             _ => None
1036         }
1037     };
1038
1039     match adt_vals {
1040         Some(field_vals) => {
1041             let pats = enter_match(bcx, dm, m, col, val, |pats|
1042                 check_match::specialize(&mcx, pats,
1043                                         &check_match::Single, col,
1044                                         field_vals.len())
1045             );
1046             let mut vals = field_vals;
1047             vals.push_all(vals_left.as_slice());
1048             compile_submatch(bcx, pats.as_slice(), vals.as_slice(), chk, has_genuine_default);
1049             return;
1050         }
1051         _ => ()
1052     }
1053
1054     // Decide what kind of branch we need
1055     let opts = get_branches(bcx, m, col);
1056     debug!("options={}", opts);
1057     let mut kind = NoBranch;
1058     let mut test_val = val;
1059     debug!("test_val={}", bcx.val_to_string(test_val));
1060     if opts.len() > 0u {
1061         match opts[0] {
1062             ConstantValue(_) | ConstantRange(_, _) => {
1063                 test_val = load_if_immediate(bcx, val, left_ty);
1064                 kind = if ty::type_is_integral(left_ty) {
1065                     Switch
1066                 } else {
1067                     Compare
1068                 };
1069             }
1070             Variant(_, ref repr, _) => {
1071                 let (the_kind, val_opt) = adt::trans_switch(bcx, &**repr, val);
1072                 kind = the_kind;
1073                 for &tval in val_opt.iter() { test_val = tval; }
1074             }
1075             SliceLengthEqual(_) | SliceLengthGreaterOrEqual(_, _) => {
1076                 let (_, len) = tvec::get_base_and_len(bcx, val, left_ty);
1077                 test_val = len;
1078                 kind = Switch;
1079             }
1080         }
1081     }
1082     for o in opts.iter() {
1083         match *o {
1084             ConstantRange(_, _) => { kind = Compare; break },
1085             SliceLengthGreaterOrEqual(_, _) => { kind = CompareSliceLength; break },
1086             _ => ()
1087         }
1088     }
1089     let else_cx = match kind {
1090         NoBranch | Single => bcx,
1091         _ => bcx.fcx.new_temp_block("match_else")
1092     };
1093     let sw = if kind == Switch {
1094         build::Switch(bcx, test_val, else_cx.llbb, opts.len())
1095     } else {
1096         C_int(ccx, 0i) // Placeholder for when not using a switch
1097     };
1098
1099     let defaults = enter_default(else_cx, dm, m, col, val);
1100     let exhaustive = chk.is_infallible() && defaults.len() == 0u;
1101     let len = opts.len();
1102
1103     // Compile subtrees for each option
1104     for (i, opt) in opts.iter().enumerate() {
1105         // In some cases of range and vector pattern matching, we need to
1106         // override the failure case so that instead of failing, it proceeds
1107         // to try more matching. branch_chk, then, is the proper failure case
1108         // for the current conditional branch.
1109         let mut branch_chk = None;
1110         let mut opt_cx = else_cx;
1111         if !exhaustive || i + 1 < len {
1112             opt_cx = bcx.fcx.new_temp_block("match_case");
1113             match kind {
1114                 Single => Br(bcx, opt_cx.llbb),
1115                 Switch => {
1116                     match opt.trans(bcx) {
1117                         SingleResult(r) => {
1118                             AddCase(sw, r.val, opt_cx.llbb);
1119                             bcx = r.bcx;
1120                         }
1121                         _ => {
1122                             bcx.sess().bug(
1123                                 "in compile_submatch, expected \
1124                                  opt.trans() to return a SingleResult")
1125                         }
1126                     }
1127                 }
1128                 Compare | CompareSliceLength => {
1129                     let t = if kind == Compare {
1130                         left_ty
1131                     } else {
1132                         ty::mk_uint() // vector length
1133                     };
1134                     let Result { bcx: after_cx, val: matches } = {
1135                         match opt.trans(bcx) {
1136                             SingleResult(Result { bcx, val }) => {
1137                                 compare_values(bcx, test_val, val, t)
1138                             }
1139                             RangeResult(Result { val: vbegin, .. },
1140                                         Result { bcx, val: vend }) => {
1141                                 let Result { bcx, val: llge } =
1142                                     compare_scalar_types(
1143                                     bcx, test_val,
1144                                     vbegin, t, ast::BiGe);
1145                                 let Result { bcx, val: llle } =
1146                                     compare_scalar_types(
1147                                     bcx, test_val, vend,
1148                                     t, ast::BiLe);
1149                                 Result::new(bcx, And(bcx, llge, llle))
1150                             }
1151                             LowerBound(Result { bcx, val }) => {
1152                                 compare_scalar_types(bcx, test_val, val, t, ast::BiGe)
1153                             }
1154                         }
1155                     };
1156                     bcx = fcx.new_temp_block("compare_next");
1157
1158                     // If none of the sub-cases match, and the current condition
1159                     // is guarded or has multiple patterns, move on to the next
1160                     // condition, if there is any, rather than falling back to
1161                     // the default.
1162                     let guarded = m[i].data.arm.guard.is_some();
1163                     let multi_pats = m[i].pats.len() > 1;
1164                     if i + 1 < len && (guarded || multi_pats || kind == CompareSliceLength) {
1165                         branch_chk = Some(JumpToBasicBlock(bcx.llbb));
1166                     }
1167                     CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb);
1168                 }
1169                 _ => ()
1170             }
1171         } else if kind == Compare || kind == CompareSliceLength {
1172             Br(bcx, else_cx.llbb);
1173         }
1174
1175         let mut size = 0u;
1176         let mut unpacked = Vec::new();
1177         match *opt {
1178             Variant(disr_val, ref repr, _) => {
1179                 let ExtractedBlock {vals: argvals, bcx: new_bcx} =
1180                     extract_variant_args(opt_cx, &**repr, disr_val, val);
1181                 size = argvals.len();
1182                 unpacked = argvals;
1183                 opt_cx = new_bcx;
1184             }
1185             SliceLengthEqual(len) => {
1186                 let args = extract_vec_elems(opt_cx, left_ty, len, 0, val);
1187                 size = args.vals.len();
1188                 unpacked = args.vals.clone();
1189                 opt_cx = args.bcx;
1190             }
1191             SliceLengthGreaterOrEqual(before, after) => {
1192                 let args = extract_vec_elems(opt_cx, left_ty, before, after, val);
1193                 size = args.vals.len();
1194                 unpacked = args.vals.clone();
1195                 opt_cx = args.bcx;
1196             }
1197             ConstantValue(_) | ConstantRange(_, _) => ()
1198         }
1199         let opt_ms = enter_opt(opt_cx, pat_id, dm, m, opt, col, size, val);
1200         let mut opt_vals = unpacked;
1201         opt_vals.push_all(vals_left.as_slice());
1202         compile_submatch(opt_cx,
1203                          opt_ms.as_slice(),
1204                          opt_vals.as_slice(),
1205                          branch_chk.as_ref().unwrap_or(chk),
1206                          has_genuine_default);
1207     }
1208
1209     // Compile the fall-through case, if any
1210     if !exhaustive && kind != Single {
1211         if kind == Compare || kind == CompareSliceLength {
1212             Br(bcx, else_cx.llbb);
1213         }
1214         match chk {
1215             // If there is only one default arm left, move on to the next
1216             // condition explicitly rather than (eventually) falling back to
1217             // the last default arm.
1218             &JumpToBasicBlock(_) if defaults.len() == 1 && has_genuine_default => {
1219                 chk.handle_fail(else_cx);
1220             }
1221             _ => {
1222                 compile_submatch(else_cx,
1223                                  defaults.as_slice(),
1224                                  vals_left.as_slice(),
1225                                  chk,
1226                                  has_genuine_default);
1227             }
1228         }
1229     }
1230 }
1231
1232 pub fn trans_match<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1233                                match_expr: &ast::Expr,
1234                                discr_expr: &ast::Expr,
1235                                arms: &[ast::Arm],
1236                                dest: Dest)
1237                                -> Block<'blk, 'tcx> {
1238     let _icx = push_ctxt("match::trans_match");
1239     trans_match_inner(bcx, match_expr.id, discr_expr, arms, dest)
1240 }
1241
1242 /// Checks whether the binding in `discr` is assigned to anywhere in the expression `body`
1243 fn is_discr_reassigned(bcx: Block, discr: &ast::Expr, body: &ast::Expr) -> bool {
1244     let (vid, field) = match discr.node {
1245         ast::ExprPath(..) => match bcx.def(discr.id) {
1246             def::DefLocal(vid) | def::DefUpvar(vid, _, _) => (vid, None),
1247             _ => return false
1248         },
1249         ast::ExprField(ref base, field) => {
1250             let vid = match bcx.tcx().def_map.borrow().get(&base.id) {
1251                 Some(&def::DefLocal(vid)) | Some(&def::DefUpvar(vid, _, _)) => vid,
1252                 _ => return false
1253             };
1254             (vid, Some(mc::NamedField(field.node.name)))
1255         },
1256         ast::ExprTupField(ref base, field) => {
1257             let vid = match bcx.tcx().def_map.borrow().get(&base.id) {
1258                 Some(&def::DefLocal(vid)) | Some(&def::DefUpvar(vid, _, _)) => vid,
1259                 _ => return false
1260             };
1261             (vid, Some(mc::PositionalField(field.node)))
1262         },
1263         _ => return false
1264     };
1265
1266     let mut rc = ReassignmentChecker {
1267         node: vid,
1268         field: field,
1269         reassigned: false
1270     };
1271     {
1272         let param_env = ty::empty_parameter_environment();
1273         let mut visitor = euv::ExprUseVisitor::new(&mut rc, bcx, param_env);
1274         visitor.walk_expr(body);
1275     }
1276     rc.reassigned
1277 }
1278
1279 struct ReassignmentChecker {
1280     node: ast::NodeId,
1281     field: Option<mc::FieldName>,
1282     reassigned: bool
1283 }
1284
1285 // Determine if the expression we're matching on is reassigned to within
1286 // the body of the match's arm.
1287 // We only care for the `mutate` callback since this check only matters
1288 // for cases where the matched value is moved.
1289 impl<'tcx> euv::Delegate<'tcx> for ReassignmentChecker {
1290     fn consume(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: euv::ConsumeMode) {}
1291     fn matched_pat(&mut self, _: &ast::Pat, _: mc::cmt, _: euv::MatchMode) {}
1292     fn consume_pat(&mut self, _: &ast::Pat, _: mc::cmt, _: euv::ConsumeMode) {}
1293     fn borrow(&mut self, _: ast::NodeId, _: Span, _: mc::cmt, _: ty::Region,
1294               _: ty::BorrowKind, _: euv::LoanCause) {}
1295     fn decl_without_init(&mut self, _: ast::NodeId, _: Span) {}
1296
1297     fn mutate(&mut self, _: ast::NodeId, _: Span, cmt: mc::cmt, _: euv::MutateMode) {
1298         match cmt.cat {
1299             mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1300             mc::cat_local(vid) => self.reassigned = self.node == vid,
1301             mc::cat_interior(ref base_cmt, mc::InteriorField(field)) => {
1302                 match base_cmt.cat {
1303                     mc::cat_upvar(mc::Upvar { id: ty::UpvarId { var_id: vid, .. }, .. }) |
1304                     mc::cat_local(vid) => {
1305                         self.reassigned = self.node == vid && Some(field) == self.field
1306                     },
1307                     _ => {}
1308                 }
1309             },
1310             _ => {}
1311         }
1312     }
1313 }
1314
1315 fn create_bindings_map<'blk, 'tcx>(bcx: Block<'blk, 'tcx>, pat: &ast::Pat,
1316                                    discr: &ast::Expr, body: &ast::Expr)
1317                                    -> BindingsMap<'tcx> {
1318     // Create the bindings map, which is a mapping from each binding name
1319     // to an alloca() that will be the value for that local variable.
1320     // Note that we use the names because each binding will have many ids
1321     // from the various alternatives.
1322     let ccx = bcx.ccx();
1323     let tcx = bcx.tcx();
1324     let reassigned = is_discr_reassigned(bcx, discr, body);
1325     let mut bindings_map = FnvHashMap::new();
1326     pat_bindings(&tcx.def_map, &*pat, |bm, p_id, span, path1| {
1327         let ident = path1.node;
1328         let variable_ty = node_id_type(bcx, p_id);
1329         let llvariable_ty = type_of::type_of(ccx, variable_ty);
1330         let tcx = bcx.tcx();
1331         let param_env = ty::empty_parameter_environment();
1332
1333         let llmatch;
1334         let trmode;
1335         match bm {
1336             ast::BindByValue(_)
1337                 if !ty::type_moves_by_default(tcx,
1338                                               variable_ty,
1339                                               &param_env) || reassigned => {
1340                 llmatch = alloca_no_lifetime(bcx,
1341                                  llvariable_ty.ptr_to(),
1342                                  "__llmatch");
1343                 trmode = TrByCopy(alloca_no_lifetime(bcx,
1344                                          llvariable_ty,
1345                                          bcx.ident(ident).as_slice()));
1346             }
1347             ast::BindByValue(_) => {
1348                 // in this case, the final type of the variable will be T,
1349                 // but during matching we need to store a *T as explained
1350                 // above
1351                 llmatch = alloca_no_lifetime(bcx,
1352                                  llvariable_ty.ptr_to(),
1353                                  bcx.ident(ident).as_slice());
1354                 trmode = TrByMove;
1355             }
1356             ast::BindByRef(_) => {
1357                 llmatch = alloca_no_lifetime(bcx,
1358                                  llvariable_ty,
1359                                  bcx.ident(ident).as_slice());
1360                 trmode = TrByRef;
1361             }
1362         };
1363         bindings_map.insert(ident, BindingInfo {
1364             llmatch: llmatch,
1365             trmode: trmode,
1366             id: p_id,
1367             span: span,
1368             ty: variable_ty
1369         });
1370     });
1371     return bindings_map;
1372 }
1373
1374 fn trans_match_inner<'blk, 'tcx>(scope_cx: Block<'blk, 'tcx>,
1375                                  match_id: ast::NodeId,
1376                                  discr_expr: &ast::Expr,
1377                                  arms: &[ast::Arm],
1378                                  dest: Dest) -> Block<'blk, 'tcx> {
1379     let _icx = push_ctxt("match::trans_match_inner");
1380     let fcx = scope_cx.fcx;
1381     let mut bcx = scope_cx;
1382     let tcx = bcx.tcx();
1383
1384     let discr_datum = unpack_datum!(bcx, expr::trans_to_lvalue(bcx, discr_expr,
1385                                                                "match"));
1386     if bcx.unreachable.get() {
1387         return bcx;
1388     }
1389
1390     let t = node_id_type(bcx, discr_expr.id);
1391     let chk = if ty::type_is_empty(tcx, t) {
1392         Unreachable
1393     } else {
1394         Infallible
1395     };
1396
1397     let arm_datas: Vec<ArmData> = arms.iter().map(|arm| ArmData {
1398         bodycx: fcx.new_id_block("case_body", arm.body.id),
1399         arm: arm,
1400         bindings_map: create_bindings_map(bcx, &*arm.pats[0], discr_expr, &*arm.body)
1401     }).collect();
1402
1403     let mut static_inliner = StaticInliner::new(scope_cx.tcx());
1404     let arm_pats: Vec<Vec<P<ast::Pat>>> = arm_datas.iter().map(|arm_data| {
1405         arm_data.arm.pats.iter().map(|p| static_inliner.fold_pat((*p).clone())).collect()
1406     }).collect();
1407     let mut matches = Vec::new();
1408     for (arm_data, pats) in arm_datas.iter().zip(arm_pats.iter()) {
1409         matches.extend(pats.iter().map(|p| Match {
1410             pats: vec![&**p],
1411             data: arm_data,
1412             bound_ptrs: Vec::new(),
1413         }));
1414     }
1415
1416     // `compile_submatch` works one column of arm patterns a time and
1417     // then peels that column off. So as we progress, it may become
1418     // impossible to tell whether we have a genuine default arm, i.e.
1419     // `_ => foo` or not. Sometimes it is important to know that in order
1420     // to decide whether moving on to the next condition or falling back
1421     // to the default arm.
1422     let has_default = arms.last().map_or(false, |arm| {
1423         arm.pats.len() == 1
1424         && arm.pats.last().unwrap().node == ast::PatWild(ast::PatWildSingle)
1425     });
1426
1427     compile_submatch(bcx, matches.as_slice(), &[discr_datum.val], &chk, has_default);
1428
1429     let mut arm_cxs = Vec::new();
1430     for arm_data in arm_datas.iter() {
1431         let mut bcx = arm_data.bodycx;
1432
1433         // insert bindings into the lllocals map and add cleanups
1434         let cs = fcx.push_custom_cleanup_scope();
1435         bcx = insert_lllocals(bcx, &arm_data.bindings_map, Some(cleanup::CustomScope(cs)));
1436         bcx = expr::trans_into(bcx, &*arm_data.arm.body, dest);
1437         bcx = fcx.pop_and_trans_custom_cleanup_scope(bcx, cs);
1438         arm_cxs.push(bcx);
1439     }
1440
1441     bcx = scope_cx.fcx.join_blocks(match_id, arm_cxs.as_slice());
1442     return bcx;
1443 }
1444
1445 /// Generates code for a local variable declaration like `let <pat>;` or `let <pat> =
1446 /// <opt_init_expr>`.
1447 pub fn store_local<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1448                                local: &ast::Local)
1449                                -> Block<'blk, 'tcx> {
1450     let _icx = push_ctxt("match::store_local");
1451     let mut bcx = bcx;
1452     let tcx = bcx.tcx();
1453     let pat = &*local.pat;
1454
1455     fn create_dummy_locals<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1456                                        pat: &ast::Pat)
1457                                        -> Block<'blk, 'tcx> {
1458         // create dummy memory for the variables if we have no
1459         // value to store into them immediately
1460         let tcx = bcx.tcx();
1461         pat_bindings(&tcx.def_map, pat, |_, p_id, _, path1| {
1462             let scope = cleanup::var_scope(tcx, p_id);
1463             bcx = mk_binding_alloca(
1464                 bcx, p_id, &path1.node, scope, (),
1465                 |(), bcx, llval, ty| { zero_mem(bcx, llval, ty); bcx });
1466         });
1467         bcx
1468     }
1469
1470     match local.init {
1471         Some(ref init_expr) => {
1472             // Optimize the "let x = expr" case. This just writes
1473             // the result of evaluating `expr` directly into the alloca
1474             // for `x`. Often the general path results in similar or the
1475             // same code post-optimization, but not always. In particular,
1476             // in unsafe code, you can have expressions like
1477             //
1478             //    let x = intrinsics::uninit();
1479             //
1480             // In such cases, the more general path is unsafe, because
1481             // it assumes it is matching against a valid value.
1482             match simple_identifier(&*pat) {
1483                 Some(ident) => {
1484                     let var_scope = cleanup::var_scope(tcx, local.id);
1485                     return mk_binding_alloca(
1486                         bcx, pat.id, ident, var_scope, (),
1487                         |(), bcx, v, _| expr::trans_into(bcx, &**init_expr,
1488                                                          expr::SaveIn(v)));
1489                 }
1490
1491                 None => {}
1492             }
1493
1494             // General path.
1495             let init_datum =
1496                 unpack_datum!(bcx, expr::trans_to_lvalue(bcx, &**init_expr, "let"));
1497             if bcx.sess().asm_comments() {
1498                 add_comment(bcx, "creating zeroable ref llval");
1499             }
1500             let var_scope = cleanup::var_scope(tcx, local.id);
1501             bind_irrefutable_pat(bcx, pat, init_datum.val, var_scope)
1502         }
1503         None => {
1504             create_dummy_locals(bcx, pat)
1505         }
1506     }
1507 }
1508
1509 /// Generates code for argument patterns like `fn foo(<pat>: T)`.
1510 /// Creates entries in the `lllocals` map for each of the bindings
1511 /// in `pat`.
1512 ///
1513 /// # Arguments
1514 ///
1515 /// - `pat` is the argument pattern
1516 /// - `llval` is a pointer to the argument value (in other words,
1517 ///   if the argument type is `T`, then `llval` is a `T*`). In some
1518 ///   cases, this code may zero out the memory `llval` points at.
1519 pub fn store_arg<'blk, 'tcx>(mut bcx: Block<'blk, 'tcx>,
1520                              pat: &ast::Pat,
1521                              arg: Datum<'tcx, Rvalue>,
1522                              arg_scope: cleanup::ScopeId)
1523                              -> Block<'blk, 'tcx> {
1524     let _icx = push_ctxt("match::store_arg");
1525
1526     match simple_identifier(&*pat) {
1527         Some(ident) => {
1528             // Generate nicer LLVM for the common case of fn a pattern
1529             // like `x: T`
1530             let arg_ty = node_id_type(bcx, pat.id);
1531             if type_of::arg_is_indirect(bcx.ccx(), arg_ty)
1532                 && bcx.sess().opts.debuginfo != FullDebugInfo {
1533                 // Don't copy an indirect argument to an alloca, the caller
1534                 // already put it in a temporary alloca and gave it up, unless
1535                 // we emit extra-debug-info, which requires local allocas :(.
1536                 let arg_val = arg.add_clean(bcx.fcx, arg_scope);
1537                 bcx.fcx.lllocals.borrow_mut()
1538                    .insert(pat.id, Datum::new(arg_val, arg_ty, Lvalue));
1539                 bcx
1540             } else {
1541                 mk_binding_alloca(
1542                     bcx, pat.id, ident, arg_scope, arg,
1543                     |arg, bcx, llval, _| arg.store_to(bcx, llval))
1544             }
1545         }
1546
1547         None => {
1548             // General path. Copy out the values that are used in the
1549             // pattern.
1550             let arg = unpack_datum!(
1551                 bcx, arg.to_lvalue_datum_in_scope(bcx, "__arg", arg_scope));
1552             bind_irrefutable_pat(bcx, pat, arg.val, arg_scope)
1553         }
1554     }
1555 }
1556
1557 /// Generates code for the pattern binding in a `for` loop like
1558 /// `for <pat> in <expr> { ... }`.
1559 pub fn store_for_loop_binding<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1560                                           pat: &ast::Pat,
1561                                           llvalue: ValueRef,
1562                                           body_scope: cleanup::ScopeId)
1563                                           -> Block<'blk, 'tcx> {
1564     let _icx = push_ctxt("match::store_for_loop_binding");
1565
1566     if simple_identifier(&*pat).is_some() {
1567         // Generate nicer LLVM for the common case of a `for` loop pattern
1568         // like `for x in blahblah { ... }`.
1569         let binding_type = node_id_type(bcx, pat.id);
1570         bcx.fcx.lllocals.borrow_mut().insert(pat.id,
1571                                              Datum::new(llvalue,
1572                                                         binding_type,
1573                                                         Lvalue));
1574         return bcx
1575     }
1576
1577     // General path. Copy out the values that are used in the pattern.
1578     bind_irrefutable_pat(bcx, pat, llvalue, body_scope)
1579 }
1580
1581 fn mk_binding_alloca<'blk, 'tcx, A>(bcx: Block<'blk, 'tcx>,
1582                                     p_id: ast::NodeId,
1583                                     ident: &ast::Ident,
1584                                     cleanup_scope: cleanup::ScopeId,
1585                                     arg: A,
1586                                     populate: |A, Block<'blk, 'tcx>, ValueRef, Ty<'tcx>|
1587                                               -> Block<'blk, 'tcx>)
1588                                     -> Block<'blk, 'tcx> {
1589     let var_ty = node_id_type(bcx, p_id);
1590
1591     // Allocate memory on stack for the binding.
1592     let llval = alloc_ty(bcx, var_ty, bcx.ident(*ident).as_slice());
1593
1594     // Subtle: be sure that we *populate* the memory *before*
1595     // we schedule the cleanup.
1596     let bcx = populate(arg, bcx, llval, var_ty);
1597     bcx.fcx.schedule_lifetime_end(cleanup_scope, llval);
1598     bcx.fcx.schedule_drop_mem(cleanup_scope, llval, var_ty);
1599
1600     // Now that memory is initialized and has cleanup scheduled,
1601     // create the datum and insert into the local variable map.
1602     let datum = Datum::new(llval, var_ty, Lvalue);
1603     bcx.fcx.lllocals.borrow_mut().insert(p_id, datum);
1604     bcx
1605 }
1606
1607 /// A simple version of the pattern matching code that only handles
1608 /// irrefutable patterns. This is used in let/argument patterns,
1609 /// not in match statements. Unifying this code with the code above
1610 /// sounds nice, but in practice it produces very inefficient code,
1611 /// since the match code is so much more general. In most cases,
1612 /// LLVM is able to optimize the code, but it causes longer compile
1613 /// times and makes the generated code nigh impossible to read.
1614 ///
1615 /// # Arguments
1616 /// - bcx: starting basic block context
1617 /// - pat: the irrefutable pattern being matched.
1618 /// - val: the value being matched -- must be an lvalue (by ref, with cleanup)
1619 fn bind_irrefutable_pat<'blk, 'tcx>(bcx: Block<'blk, 'tcx>,
1620                                     pat: &ast::Pat,
1621                                     val: ValueRef,
1622                                     cleanup_scope: cleanup::ScopeId)
1623                                     -> Block<'blk, 'tcx> {
1624     debug!("bind_irrefutable_pat(bcx={}, pat={})",
1625            bcx.to_str(),
1626            pat.repr(bcx.tcx()));
1627
1628     if bcx.sess().asm_comments() {
1629         add_comment(bcx, format!("bind_irrefutable_pat(pat={})",
1630                                  pat.repr(bcx.tcx())).as_slice());
1631     }
1632
1633     let _indenter = indenter();
1634
1635     let _icx = push_ctxt("match::bind_irrefutable_pat");
1636     let mut bcx = bcx;
1637     let tcx = bcx.tcx();
1638     let ccx = bcx.ccx();
1639     match pat.node {
1640         ast::PatIdent(pat_binding_mode, ref path1, ref inner) => {
1641             if pat_is_binding(&tcx.def_map, &*pat) {
1642                 // Allocate the stack slot where the value of this
1643                 // binding will live and place it into the appropriate
1644                 // map.
1645                 bcx = mk_binding_alloca(
1646                     bcx, pat.id, &path1.node, cleanup_scope, (),
1647                     |(), bcx, llval, ty| {
1648                         match pat_binding_mode {
1649                             ast::BindByValue(_) => {
1650                                 // By value binding: move the value that `val`
1651                                 // points at into the binding's stack slot.
1652                                 let d = Datum::new(val, ty, Lvalue);
1653                                 d.store_to(bcx, llval)
1654                             }
1655
1656                             ast::BindByRef(_) => {
1657                                 // By ref binding: the value of the variable
1658                                 // is the pointer `val` itself.
1659                                 Store(bcx, val, llval);
1660                                 bcx
1661                             }
1662                         }
1663                     });
1664             }
1665
1666             for inner_pat in inner.iter() {
1667                 bcx = bind_irrefutable_pat(bcx, &**inner_pat, val, cleanup_scope);
1668             }
1669         }
1670         ast::PatEnum(_, ref sub_pats) => {
1671             let opt_def = bcx.tcx().def_map.borrow().get(&pat.id).cloned();
1672             match opt_def {
1673                 Some(def::DefVariant(enum_id, var_id, _)) => {
1674                     let repr = adt::represent_node(bcx, pat.id);
1675                     let vinfo = ty::enum_variant_with_id(ccx.tcx(),
1676                                                          enum_id,
1677                                                          var_id);
1678                     let args = extract_variant_args(bcx,
1679                                                     &*repr,
1680                                                     vinfo.disr_val,
1681                                                     val);
1682                     for sub_pat in sub_pats.iter() {
1683                         for (i, &argval) in args.vals.iter().enumerate() {
1684                             bcx = bind_irrefutable_pat(bcx, &*sub_pat[i],
1685                                                        argval, cleanup_scope);
1686                         }
1687                     }
1688                 }
1689                 Some(def::DefStruct(..)) => {
1690                     match *sub_pats {
1691                         None => {
1692                             // This is a unit-like struct. Nothing to do here.
1693                         }
1694                         Some(ref elems) => {
1695                             // This is the tuple struct case.
1696                             let repr = adt::represent_node(bcx, pat.id);
1697                             for (i, elem) in elems.iter().enumerate() {
1698                                 let fldptr = adt::trans_field_ptr(bcx, &*repr,
1699                                                                   val, 0, i);
1700                                 bcx = bind_irrefutable_pat(bcx, &**elem,
1701                                                            fldptr, cleanup_scope);
1702                             }
1703                         }
1704                     }
1705                 }
1706                 _ => {
1707                     // Nothing to do here.
1708                 }
1709             }
1710         }
1711         ast::PatStruct(_, ref fields, _) => {
1712             let tcx = bcx.tcx();
1713             let pat_ty = node_id_type(bcx, pat.id);
1714             let pat_repr = adt::represent_type(bcx.ccx(), pat_ty);
1715             expr::with_field_tys(tcx, pat_ty, Some(pat.id), |discr, field_tys| {
1716                 for f in fields.iter() {
1717                     let ix = ty::field_idx_strict(tcx, f.node.ident.name, field_tys);
1718                     let fldptr = adt::trans_field_ptr(bcx, &*pat_repr, val,
1719                                                       discr, ix);
1720                     bcx = bind_irrefutable_pat(bcx, &*f.node.pat, fldptr, cleanup_scope);
1721                 }
1722             })
1723         }
1724         ast::PatTup(ref elems) => {
1725             let repr = adt::represent_node(bcx, pat.id);
1726             for (i, elem) in elems.iter().enumerate() {
1727                 let fldptr = adt::trans_field_ptr(bcx, &*repr, val, 0, i);
1728                 bcx = bind_irrefutable_pat(bcx, &**elem, fldptr, cleanup_scope);
1729             }
1730         }
1731         ast::PatBox(ref inner) => {
1732             let llbox = Load(bcx, val);
1733             bcx = bind_irrefutable_pat(bcx, &**inner, llbox, cleanup_scope);
1734         }
1735         ast::PatRegion(ref inner) => {
1736             let loaded_val = Load(bcx, val);
1737             bcx = bind_irrefutable_pat(bcx, &**inner, loaded_val, cleanup_scope);
1738         }
1739         ast::PatVec(ref before, ref slice, ref after) => {
1740             let pat_ty = node_id_type(bcx, pat.id);
1741             let mut extracted = extract_vec_elems(bcx, pat_ty, before.len(), after.len(), val);
1742             match slice {
1743                 &Some(_) => {
1744                     extracted.vals.insert(
1745                         before.len(),
1746                         bind_subslice_pat(bcx, pat.id, val, before.len(), after.len())
1747                     );
1748                 }
1749                 &None => ()
1750             }
1751             bcx = before
1752                 .iter()
1753                 .chain(slice.iter())
1754                 .chain(after.iter())
1755                 .zip(extracted.vals.into_iter())
1756                 .fold(bcx, |bcx, (inner, elem)|
1757                     bind_irrefutable_pat(bcx, &**inner, elem, cleanup_scope)
1758                 );
1759         }
1760         ast::PatMac(..) => {
1761             bcx.sess().span_bug(pat.span, "unexpanded macro");
1762         }
1763         ast::PatWild(_) | ast::PatLit(_) | ast::PatRange(_, _) => ()
1764     }
1765     return bcx;
1766 }