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