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