]> git.lizzy.rs Git - rust.git/blob - src/librustc/middle/trans/_match.rs
introduce `base_and_len` fns for element length
[rust.git] / src / librustc / middle / trans / _match.rs
1 // Copyright 2012 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 up to two LLVM values, called `llmatch` and
68  * `llbinding` respectively (the `llbinding`, as will be described shortly, is
69  * optional and only present for by-value bindings---therefore it is bundled
70  * up as part of the `TransBindingMode` type).  Both point at allocas.
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  * In addition, for each by-value binding (copy or move), we will create a
87  * second alloca (`llbinding`) that will hold the final value.  In this
88  * example, that means that `d` would have this second alloca of type `D` (and
89  * hence `llbinding` has type `D*`).
90  *
91  * Once a pattern is completely matched, and assuming that there is no guard
92  * pattern, we will branch to a block that leads to the body itself.  For any
93  * by-value bindings, this block will first load the ptr from `llmatch` (the
94  * one of type `D*`) and copy/move the value into `llbinding` (the one of type
95  * `D`).  The second alloca then becomes the value of the local variable.  For
96  * by ref bindings, the value of the local variable is simply the first
97  * alloca.
98  *
99  * So, for the example above, we would generate a setup kind of like this:
100  *
101  *        +-------+
102  *        | Entry |
103  *        +-------+
104  *            |
105  *        +-------------------------------------------+
106  *        | llmatch_c = (addr of first half of tuple) |
107  *        | llmatch_d = (addr of first half of tuple) |
108  *        +-------------------------------------------+
109  *            |
110  *        +--------------------------------------+
111  *        | *llbinding_d = **llmatch_dlbinding_d |
112  *        +--------------------------------------+
113  *
114  * If there is a guard, the situation is slightly different, because we must
115  * execute the guard code.  Moreover, we need to do so once for each of the
116  * alternatives that lead to the arm, because if the guard fails, they may
117  * have different points from which to continue the search. Therefore, in that
118  * case, we generate code that looks more like:
119  *
120  *        +-------+
121  *        | Entry |
122  *        +-------+
123  *            |
124  *        +-------------------------------------------+
125  *        | llmatch_c = (addr of first half of tuple) |
126  *        | llmatch_d = (addr of first half of tuple) |
127  *        +-------------------------------------------+
128  *            |
129  *        +-------------------------------------------------+
130  *        | *llbinding_d = **llmatch_dlbinding_d            |
131  *        | check condition                                 |
132  *        | if false { free *llbinding_d, goto next case }  |
133  *        | if true { goto body }                           |
134  *        +-------------------------------------------------+
135  *
136  * The handling for the cleanups is a bit... sensitive.  Basically, the body
137  * is the one that invokes `add_clean()` for each binding.  During the guard
138  * evaluation, we add temporary cleanups and revoke them after the guard is
139  * evaluated (it could fail, after all).  Presuming the guard fails, we drop
140  * the various values we copied explicitly.  Note that guards and moves are
141  * just plain incompatible.
142  *
143  * Some relevant helper functions that manage bindings:
144  * - `create_bindings_map()`
145  * - `store_non_ref_bindings()`
146  * - `insert_lllocals()`
147  *
148  *
149  * ## Notes on vector pattern matching.
150  *
151  * Vector pattern matching is surprisingly tricky. The problem is that
152  * the structure of the vector isn't fully known, and slice matches
153  * can be done on subparts of it.
154  *
155  * The way that vector pattern matches are dealt with, then, is as
156  * follows. First, we make the actual condition associated with a
157  * vector pattern simply a vector length comparison. So the pattern
158  * [1, .. x] gets the condition "vec len >= 1", and the pattern
159  * [.. x] gets the condition "vec len >= 0". The problem here is that
160  * having the condition "vec len >= 1" hold clearly does not mean that
161  * only a pattern that has exactly that condition will match. This
162  * means that it may well be the case that a condition holds, but none
163  * of the patterns matching that condition match; to deal with this,
164  * when doing vector length matches, we have match failures proceed to
165  * the next condition to check.
166  *
167  * There are a couple more subtleties to deal with. While the "actual"
168  * condition associated with vector length tests is simply a test on
169  * the vector length, the actual vec_len Opt entry contains more
170  * information used to restrict which matches are associated with it.
171  * So that all matches in a submatch are matching against the same
172  * values from inside the vector, they are split up by how many
173  * elements they match at the front and at the back of the vector. In
174  * order to make sure that arms are properly checked in order, even
175  * with the overmatching conditions, each vec_len Opt entry is
176  * associated with a range of matches.
177  * Consider the following:
178  *
179  *   match &[1, 2, 3] {
180  *       [1, 1, .. _] => 0,
181  *       [1, 2, 2, .. _] => 1,
182  *       [1, 2, 3, .. _] => 2,
183  *       [1, 2, .. _] => 3,
184  *       _ => 4
185  *   }
186  * The proper arm to match is arm 2, but arms 0 and 3 both have the
187  * condition "len >= 2". If arm 3 was lumped in with arm 0, then the
188  * wrong branch would be taken. Instead, vec_len Opts are associated
189  * with a contiguous range of matches that have the same "shape".
190  * This is sort of ugly and requires a bunch of special handling of
191  * vec_len options.
192  *
193  */
194
195
196 use back::abi;
197 use lib::llvm::{llvm, ValueRef, BasicBlockRef};
198 use middle::const_eval;
199 use middle::borrowck::root_map_key;
200 use middle::lang_items::{UniqStrEqFnLangItem, StrEqFnLangItem};
201 use middle::pat_util::*;
202 use middle::resolve::DefMap;
203 use middle::trans::adt;
204 use middle::trans::base::*;
205 use middle::trans::build::*;
206 use middle::trans::callee;
207 use middle::trans::common::*;
208 use middle::trans::consts;
209 use middle::trans::controlflow;
210 use middle::trans::datum;
211 use middle::trans::datum::*;
212 use middle::trans::expr::Dest;
213 use middle::trans::expr;
214 use middle::trans::glue;
215 use middle::trans::tvec;
216 use middle::trans::type_of;
217 use middle::trans::debuginfo;
218 use middle::ty;
219 use util::common::indenter;
220 use util::ppaux::{Repr, vec_map_to_str};
221
222 use std::hashmap::HashMap;
223 use std::vec;
224 use syntax::ast;
225 use syntax::ast::Ident;
226 use syntax::ast_util::path_to_ident;
227 use syntax::ast_util;
228 use syntax::codemap::{Span, dummy_sp};
229
230 // An option identifying a literal: either a unit-like struct or an
231 // expression.
232 enum Lit {
233     UnitLikeStructLit(ast::NodeId),    // the node ID of the pattern
234     ExprLit(@ast::Expr),
235     ConstLit(ast::DefId),              // the def ID of the constant
236 }
237
238 #[deriving(Eq)]
239 pub enum VecLenOpt {
240     vec_len_eq,
241     vec_len_ge(/* length of prefix */uint)
242 }
243
244 // An option identifying a branch (either a literal, a enum variant or a
245 // range)
246 enum Opt {
247     lit(Lit),
248     var(ty::Disr, @adt::Repr),
249     range(@ast::Expr, @ast::Expr),
250     vec_len(/* length */ uint, VecLenOpt, /*range of matches*/(uint, uint))
251 }
252
253 fn opt_eq(tcx: ty::ctxt, a: &Opt, b: &Opt) -> bool {
254     match (a, b) {
255         (&lit(a), &lit(b)) => {
256             match (a, b) {
257                 (UnitLikeStructLit(a), UnitLikeStructLit(b)) => a == b,
258                 _ => {
259                     let a_expr;
260                     match a {
261                         ExprLit(existing_a_expr) => a_expr = existing_a_expr,
262                             ConstLit(a_const) => {
263                                 let e = const_eval::lookup_const_by_id(tcx, a_const);
264                                 a_expr = e.unwrap();
265                             }
266                         UnitLikeStructLit(_) => {
267                             fail2!("UnitLikeStructLit should have been handled \
268                                     above")
269                         }
270                     }
271
272                     let b_expr;
273                     match b {
274                         ExprLit(existing_b_expr) => b_expr = existing_b_expr,
275                             ConstLit(b_const) => {
276                                 let e = const_eval::lookup_const_by_id(tcx, b_const);
277                                 b_expr = e.unwrap();
278                             }
279                         UnitLikeStructLit(_) => {
280                             fail2!("UnitLikeStructLit should have been handled \
281                                     above")
282                         }
283                     }
284
285                     match const_eval::compare_lit_exprs(tcx, a_expr, b_expr) {
286                         Some(val1) => val1 == 0,
287                         None => fail2!("compare_list_exprs: type mismatch"),
288                     }
289                 }
290             }
291         }
292         (&range(a1, a2), &range(b1, b2)) => {
293             let m1 = const_eval::compare_lit_exprs(tcx, a1, b1);
294             let m2 = const_eval::compare_lit_exprs(tcx, a2, b2);
295             match (m1, m2) {
296                 (Some(val1), Some(val2)) => (val1 == 0 && val2 == 0),
297                 _ => fail2!("compare_list_exprs: type mismatch"),
298             }
299         }
300         (&var(a, _), &var(b, _)) => a == b,
301         (&vec_len(a1, a2, _), &vec_len(b1, b2, _)) =>
302             a1 == b1 && a2 == b2,
303         _ => false
304     }
305 }
306
307 pub enum opt_result {
308     single_result(Result),
309     lower_bound(Result),
310     range_result(Result, Result),
311 }
312 fn trans_opt(bcx: @mut Block, o: &Opt) -> opt_result {
313     let _icx = push_ctxt("match::trans_opt");
314     let ccx = bcx.ccx();
315     let bcx = bcx;
316     match *o {
317         lit(ExprLit(lit_expr)) => {
318             let datumblock = expr::trans_to_datum(bcx, lit_expr);
319             return single_result(datumblock.to_result());
320         }
321         lit(UnitLikeStructLit(pat_id)) => {
322             let struct_ty = ty::node_id_to_type(bcx.tcx(), pat_id);
323             let datumblock = datum::scratch_datum(bcx, struct_ty, "", true);
324             return single_result(datumblock.to_result(bcx));
325         }
326         lit(ConstLit(lit_id)) => {
327             let (llval, _) = consts::get_const_val(bcx.ccx(), lit_id);
328             return single_result(rslt(bcx, llval));
329         }
330         var(disr_val, repr) => {
331             return adt::trans_case(bcx, repr, disr_val);
332         }
333         range(l1, l2) => {
334             let (l1, _) = consts::const_expr(ccx, l1);
335             let (l2, _) = consts::const_expr(ccx, l2);
336             return range_result(rslt(bcx, l1), rslt(bcx, l2));
337         }
338         vec_len(n, vec_len_eq, _) => {
339             return single_result(rslt(bcx, C_int(ccx, n as int)));
340         }
341         vec_len(n, vec_len_ge(_), _) => {
342             return lower_bound(rslt(bcx, C_int(ccx, n as int)));
343         }
344     }
345 }
346
347 fn variant_opt(bcx: @mut Block, pat_id: ast::NodeId)
348     -> Opt {
349     let ccx = bcx.ccx();
350     match ccx.tcx.def_map.get_copy(&pat_id) {
351         ast::DefVariant(enum_id, var_id, _) => {
352             let variants = ty::enum_variants(ccx.tcx, enum_id);
353             for v in (*variants).iter() {
354                 if var_id == v.id {
355                     return var(v.disr_val,
356                                adt::represent_node(bcx, pat_id))
357                 }
358             }
359             unreachable!();
360         }
361         ast::DefFn(*) |
362         ast::DefStruct(_) => {
363             return lit(UnitLikeStructLit(pat_id));
364         }
365         _ => {
366             ccx.sess.bug("non-variant or struct in variant_opt()");
367         }
368     }
369 }
370
371 #[deriving(Clone)]
372 enum TransBindingMode {
373     TrByValue(/*llbinding:*/ ValueRef),
374     TrByRef,
375 }
376
377 /**
378  * Information about a pattern binding:
379  * - `llmatch` is a pointer to a stack slot.  The stack slot contains a
380  *   pointer into the value being matched.  Hence, llmatch has type `T**`
381  *   where `T` is the value being matched.
382  * - `trmode` is the trans binding mode
383  * - `id` is the node id of the binding
384  * - `ty` is the Rust type of the binding */
385  #[deriving(Clone)]
386 struct BindingInfo {
387     llmatch: ValueRef,
388     trmode: TransBindingMode,
389     id: ast::NodeId,
390     span: Span,
391     ty: ty::t,
392 }
393
394 type BindingsMap = HashMap<Ident, BindingInfo>;
395
396 #[deriving(Clone)]
397 struct ArmData<'self> {
398     bodycx: @mut Block,
399     arm: &'self ast::Arm,
400     bindings_map: @BindingsMap
401 }
402
403 /**
404  * Info about Match.
405  * If all `pats` are matched then arm `data` will be executed.
406  * As we proceed `bound_ptrs` are filled with pointers to values to be bound,
407  * these pointers are stored in llmatch variables just before executing `data` arm.
408  */
409 #[deriving(Clone)]
410 struct Match<'self> {
411     pats: ~[@ast::Pat],
412     data: ArmData<'self>,
413     bound_ptrs: ~[(Ident, ValueRef)]
414 }
415
416 impl<'self> Repr for Match<'self> {
417     fn repr(&self, tcx: ty::ctxt) -> ~str {
418         if tcx.sess.verbose() {
419             // for many programs, this just take too long to serialize
420             self.pats.repr(tcx)
421         } else {
422             format!("{} pats", self.pats.len())
423         }
424     }
425 }
426
427 fn has_nested_bindings(m: &[Match], col: uint) -> bool {
428     for br in m.iter() {
429         match br.pats[col].node {
430           ast::PatIdent(_, _, Some(_)) => return true,
431           _ => ()
432         }
433     }
434     return false;
435 }
436
437 fn expand_nested_bindings<'r>(bcx: @mut Block,
438                                   m: &[Match<'r>],
439                                   col: uint,
440                                   val: ValueRef)
441                               -> ~[Match<'r>] {
442     debug2!("expand_nested_bindings(bcx={}, m={}, col={}, val={})",
443            bcx.to_str(),
444            m.repr(bcx.tcx()),
445            col,
446            bcx.val_to_str(val));
447     let _indenter = indenter();
448
449     do m.map |br| {
450         match br.pats[col].node {
451             ast::PatIdent(_, ref path, Some(inner)) => {
452                 let pats = vec::append(
453                     br.pats.slice(0u, col).to_owned(),
454                     vec::append(~[inner],
455                                 br.pats.slice(col + 1u,
456                                            br.pats.len())));
457
458                 let mut res = Match {
459                     pats: pats,
460                     data: br.data.clone(),
461                     bound_ptrs: br.bound_ptrs.clone()
462                 };
463                 res.bound_ptrs.push((path_to_ident(path), val));
464                 res
465             }
466             _ => (*br).clone(),
467         }
468     }
469 }
470
471 fn assert_is_binding_or_wild(bcx: @mut Block, p: @ast::Pat) {
472     if !pat_is_binding_or_wild(bcx.tcx().def_map, p) {
473         bcx.sess().span_bug(
474             p.span,
475             format!("Expected an identifier pattern but found p: {}",
476                  p.repr(bcx.tcx())));
477     }
478 }
479
480 type enter_pat<'self> = &'self fn(@ast::Pat) -> Option<~[@ast::Pat]>;
481
482 fn enter_match<'r>(bcx: @mut Block,
483                        dm: DefMap,
484                        m: &[Match<'r>],
485                        col: uint,
486                        val: ValueRef,
487                        e: enter_pat)
488                     -> ~[Match<'r>] {
489     debug2!("enter_match(bcx={}, m={}, col={}, val={})",
490            bcx.to_str(),
491            m.repr(bcx.tcx()),
492            col,
493            bcx.val_to_str(val));
494     let _indenter = indenter();
495
496     let mut result = ~[];
497     for br in m.iter() {
498         match e(br.pats[col]) {
499             Some(sub) => {
500                 let pats =
501                     vec::append(
502                         vec::append(sub, br.pats.slice(0u, col)),
503                         br.pats.slice(col + 1u, br.pats.len()));
504
505                 let this = br.pats[col];
506                 let mut bound_ptrs = br.bound_ptrs.clone();
507                 match this.node {
508                     ast::PatIdent(_, ref path, None) => {
509                         if pat_is_binding(dm, this) {
510                             bound_ptrs.push((path_to_ident(path), val));
511                         }
512                     }
513                     _ => {}
514                 }
515
516                 result.push(Match {
517                     pats: pats,
518                     data: br.data.clone(),
519                     bound_ptrs: bound_ptrs
520                 });
521             }
522             None => ()
523         }
524     }
525
526     debug2!("result={}", result.repr(bcx.tcx()));
527
528     return result;
529 }
530
531 fn enter_default<'r>(bcx: @mut Block,
532                      dm: DefMap,
533                      m: &[Match<'r>],
534                      col: uint,
535                      val: ValueRef,
536                      chk: FailureHandler)
537                       -> ~[Match<'r>] {
538     debug2!("enter_default(bcx={}, m={}, col={}, val={})",
539            bcx.to_str(),
540            m.repr(bcx.tcx()),
541            col,
542            bcx.val_to_str(val));
543     let _indenter = indenter();
544
545     // Collect all of the matches that can match against anything.
546     let matches = do enter_match(bcx, dm, m, col, val) |p| {
547         match p.node {
548           ast::PatWild | ast::PatTup(_) => Some(~[]),
549           ast::PatIdent(_, _, None) if pat_is_binding(dm, p) => Some(~[]),
550           _ => None
551         }
552     };
553
554     // Ok, now, this is pretty subtle. A "default" match is a match
555     // that needs to be considered if none of the actual checks on the
556     // value being considered succeed. The subtlety lies in that sometimes
557     // identifier/wildcard matches are *not* default matches. Consider:
558     // "match x { _ if something => foo, true => bar, false => baz }".
559     // There is a wildcard match, but it is *not* a default case. The boolean
560     // case on the value being considered is exhaustive. If the case is
561     // exhaustive, then there are no defaults.
562     //
563     // We detect whether the case is exhaustive in the following
564     // somewhat kludgy way: if the last wildcard/binding match has a
565     // guard, then by non-redundancy, we know that there aren't any
566     // non guarded matches, and thus by exhaustiveness, we know that
567     // we don't need any default cases. If the check *isn't* nonexhaustive
568     // (because chk is Some), then we need the defaults anyways.
569     let is_exhaustive = match matches.last_opt() {
570         Some(m) if m.data.arm.guard.is_some() && chk.is_infallible() => true,
571         _ => false
572     };
573
574     if is_exhaustive { ~[] } else { matches }
575 }
576
577 // <pcwalton> nmatsakis: what does enter_opt do?
578 // <pcwalton> in trans/match
579 // <pcwalton> trans/match.rs is like stumbling around in a dark cave
580 // <nmatsakis> pcwalton: the enter family of functions adjust the set of
581 //             patterns as needed
582 // <nmatsakis> yeah, at some point I kind of achieved some level of
583 //             understanding
584 // <nmatsakis> anyhow, they adjust the patterns given that something of that
585 //             kind has been found
586 // <nmatsakis> pcwalton: ok, right, so enter_XXX() adjusts the patterns, as I
587 //             said
588 // <nmatsakis> enter_match() kind of embodies the generic code
589 // <nmatsakis> it is provided with a function that tests each pattern to see
590 //             if it might possibly apply and so forth
591 // <nmatsakis> so, if you have a pattern like {a: _, b: _, _} and one like _
592 // <nmatsakis> then _ would be expanded to (_, _)
593 // <nmatsakis> one spot for each of the sub-patterns
594 // <nmatsakis> enter_opt() is one of the more complex; it covers the fallible
595 //             cases
596 // <nmatsakis> enter_rec_or_struct() or enter_tuple() are simpler, since they
597 //             are infallible patterns
598 // <nmatsakis> so all patterns must either be records (resp. tuples) or
599 //             wildcards
600
601 fn enter_opt<'r>(bcx: @mut Block,
602                      m: &[Match<'r>],
603                      opt: &Opt,
604                      col: uint,
605                      variant_size: uint,
606                      val: ValueRef)
607                   -> ~[Match<'r>] {
608     debug2!("enter_opt(bcx={}, m={}, opt={:?}, col={}, val={})",
609            bcx.to_str(),
610            m.repr(bcx.tcx()),
611            *opt,
612            col,
613            bcx.val_to_str(val));
614     let _indenter = indenter();
615
616     let tcx = bcx.tcx();
617     let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()};
618     let mut i = 0;
619     do enter_match(bcx, tcx.def_map, m, col, val) |p| {
620         let answer = match p.node {
621             ast::PatEnum(*) |
622             ast::PatIdent(_, _, None) if pat_is_const(tcx.def_map, p) => {
623                 let const_def = tcx.def_map.get_copy(&p.id);
624                 let const_def_id = ast_util::def_id_of_def(const_def);
625                 if opt_eq(tcx, &lit(ConstLit(const_def_id)), opt) {
626                     Some(~[])
627                 } else {
628                     None
629                 }
630             }
631             ast::PatEnum(_, ref subpats) => {
632                 if opt_eq(tcx, &variant_opt(bcx, p.id), opt) {
633                     // XXX: Must we clone?
634                     match *subpats {
635                         None => Some(vec::from_elem(variant_size, dummy)),
636                         _ => (*subpats).clone(),
637                     }
638                 } else {
639                     None
640                 }
641             }
642             ast::PatIdent(_, _, None)
643                     if pat_is_variant_or_struct(tcx.def_map, p) => {
644                 if opt_eq(tcx, &variant_opt(bcx, p.id), opt) {
645                     Some(~[])
646                 } else {
647                     None
648                 }
649             }
650             ast::PatLit(l) => {
651                 if opt_eq(tcx, &lit(ExprLit(l)), opt) {Some(~[])} else {None}
652             }
653             ast::PatRange(l1, l2) => {
654                 if opt_eq(tcx, &range(l1, l2), opt) {Some(~[])} else {None}
655             }
656             ast::PatStruct(_, ref field_pats, _) => {
657                 if opt_eq(tcx, &variant_opt(bcx, p.id), opt) {
658                     // Look up the struct variant ID.
659                     let struct_id;
660                     match tcx.def_map.get_copy(&p.id) {
661                         ast::DefVariant(_, found_struct_id, _) => {
662                             struct_id = found_struct_id;
663                         }
664                         _ => {
665                             tcx.sess.span_bug(p.span, "expected enum variant def");
666                         }
667                     }
668
669                     // Reorder the patterns into the same order they were
670                     // specified in the struct definition. Also fill in
671                     // unspecified fields with dummy.
672                     let mut reordered_patterns = ~[];
673                     let r = ty::lookup_struct_fields(tcx, struct_id);
674                     for field in r.iter() {
675                             match field_pats.iter().find(|p| p.ident.name
676                                                          == field.name) {
677                                 None => reordered_patterns.push(dummy),
678                                 Some(fp) => reordered_patterns.push(fp.pat)
679                             }
680                     }
681                     Some(reordered_patterns)
682                 } else {
683                     None
684                 }
685             }
686             ast::PatVec(ref before, slice, ref after) => {
687                 let (lo, hi) = match *opt {
688                     vec_len(_, _, (lo, hi)) => (lo, hi),
689                     _ => tcx.sess.span_bug(p.span,
690                                            "vec pattern but not vec opt")
691                 };
692
693                 match slice {
694                     Some(slice) if i >= lo && i <= hi => {
695                         let n = before.len() + after.len();
696                         let this_opt = vec_len(n, vec_len_ge(before.len()),
697                                                (lo, hi));
698                         if opt_eq(tcx, &this_opt, opt) {
699                             Some(vec::append_one((*before).clone(), slice) +
700                                     *after)
701                         } else {
702                             None
703                         }
704                     }
705                     None if i >= lo && i <= hi => {
706                         let n = before.len();
707                         if opt_eq(tcx, &vec_len(n, vec_len_eq, (lo,hi)), opt) {
708                             Some((*before).clone())
709                         } else {
710                             None
711                         }
712                     }
713                     _ => None
714                 }
715             }
716             _ => {
717                 assert_is_binding_or_wild(bcx, p);
718                 // In most cases, a binding/wildcard match be
719                 // considered to match against any Opt. However, when
720                 // doing vector pattern matching, submatches are
721                 // considered even if the eventual match might be from
722                 // a different submatch. Thus, when a submatch fails
723                 // when doing a vector match, we proceed to the next
724                 // submatch. Thus, including a default match would
725                 // cause the default match to fire spuriously.
726                 match *opt {
727                     vec_len(*) => None,
728                     _ => Some(vec::from_elem(variant_size, dummy))
729                 }
730             }
731         };
732         i += 1;
733         answer
734     }
735 }
736
737 fn enter_rec_or_struct<'r>(bcx: @mut Block,
738                                dm: DefMap,
739                                m: &[Match<'r>],
740                                col: uint,
741                                fields: &[ast::Ident],
742                                val: ValueRef)
743                             -> ~[Match<'r>] {
744     debug2!("enter_rec_or_struct(bcx={}, m={}, col={}, val={})",
745            bcx.to_str(),
746            m.repr(bcx.tcx()),
747            col,
748            bcx.val_to_str(val));
749     let _indenter = indenter();
750
751     let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()};
752     do enter_match(bcx, dm, m, col, val) |p| {
753         match p.node {
754             ast::PatStruct(_, ref fpats, _) => {
755                 let mut pats = ~[];
756                 for fname in fields.iter() {
757                     match fpats.iter().find(|p| p.ident.name == fname.name) {
758                         None => pats.push(dummy),
759                         Some(pat) => pats.push(pat.pat)
760                     }
761                 }
762                 Some(pats)
763             }
764             _ => {
765                 assert_is_binding_or_wild(bcx, p);
766                 Some(vec::from_elem(fields.len(), dummy))
767             }
768         }
769     }
770 }
771
772 fn enter_tup<'r>(bcx: @mut Block,
773                      dm: DefMap,
774                      m: &[Match<'r>],
775                      col: uint,
776                      val: ValueRef,
777                      n_elts: uint)
778                   -> ~[Match<'r>] {
779     debug2!("enter_tup(bcx={}, m={}, col={}, val={})",
780            bcx.to_str(),
781            m.repr(bcx.tcx()),
782            col,
783            bcx.val_to_str(val));
784     let _indenter = indenter();
785
786     let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()};
787     do enter_match(bcx, dm, m, col, val) |p| {
788         match p.node {
789             ast::PatTup(ref elts) => Some((*elts).clone()),
790             _ => {
791                 assert_is_binding_or_wild(bcx, p);
792                 Some(vec::from_elem(n_elts, dummy))
793             }
794         }
795     }
796 }
797
798 fn enter_tuple_struct<'r>(bcx: @mut Block,
799                               dm: DefMap,
800                               m: &[Match<'r>],
801                               col: uint,
802                               val: ValueRef,
803                               n_elts: uint)
804                           -> ~[Match<'r>] {
805     debug2!("enter_tuple_struct(bcx={}, m={}, col={}, val={})",
806            bcx.to_str(),
807            m.repr(bcx.tcx()),
808            col,
809            bcx.val_to_str(val));
810     let _indenter = indenter();
811
812     let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()};
813     do enter_match(bcx, dm, m, col, val) |p| {
814         match p.node {
815             ast::PatEnum(_, Some(ref elts)) => Some((*elts).clone()),
816             _ => {
817                 assert_is_binding_or_wild(bcx, p);
818                 Some(vec::from_elem(n_elts, dummy))
819             }
820         }
821     }
822 }
823
824 fn enter_box<'r>(bcx: @mut Block,
825                      dm: DefMap,
826                      m: &[Match<'r>],
827                      col: uint,
828                      val: ValueRef)
829                  -> ~[Match<'r>] {
830     debug2!("enter_box(bcx={}, m={}, col={}, val={})",
831            bcx.to_str(),
832            m.repr(bcx.tcx()),
833            col,
834            bcx.val_to_str(val));
835     let _indenter = indenter();
836
837     let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()};
838     do enter_match(bcx, dm, m, col, val) |p| {
839         match p.node {
840             ast::PatBox(sub) => {
841                 Some(~[sub])
842             }
843             _ => {
844                 assert_is_binding_or_wild(bcx, p);
845                 Some(~[dummy])
846             }
847         }
848     }
849 }
850
851 fn enter_uniq<'r>(bcx: @mut Block,
852                       dm: DefMap,
853                       m: &[Match<'r>],
854                       col: uint,
855                       val: ValueRef)
856                   -> ~[Match<'r>] {
857     debug2!("enter_uniq(bcx={}, m={}, col={}, val={})",
858            bcx.to_str(),
859            m.repr(bcx.tcx()),
860            col,
861            bcx.val_to_str(val));
862     let _indenter = indenter();
863
864     let dummy = @ast::Pat {id: 0, node: ast::PatWild, span: dummy_sp()};
865     do enter_match(bcx, dm, m, col, val) |p| {
866         match p.node {
867             ast::PatUniq(sub) => {
868                 Some(~[sub])
869             }
870             _ => {
871                 assert_is_binding_or_wild(bcx, p);
872                 Some(~[dummy])
873             }
874         }
875     }
876 }
877
878 fn enter_region<'r>(bcx: @mut Block,
879                         dm: DefMap,
880                         m: &[Match<'r>],
881                         col: uint,
882                         val: ValueRef)
883                     -> ~[Match<'r>] {
884     debug2!("enter_region(bcx={}, m={}, col={}, val={})",
885            bcx.to_str(),
886            m.repr(bcx.tcx()),
887            col,
888            bcx.val_to_str(val));
889     let _indenter = indenter();
890
891     let dummy = @ast::Pat { id: 0, node: ast::PatWild, span: dummy_sp() };
892     do enter_match(bcx, dm, m, col, val) |p| {
893         match p.node {
894             ast::PatRegion(sub) => {
895                 Some(~[sub])
896             }
897             _ => {
898                 assert_is_binding_or_wild(bcx, p);
899                 Some(~[dummy])
900             }
901         }
902     }
903 }
904
905 // Returns the options in one column of matches. An option is something that
906 // needs to be conditionally matched at runtime; for example, the discriminant
907 // on a set of enum variants or a literal.
908 fn get_options(bcx: @mut Block, m: &[Match], col: uint) -> ~[Opt] {
909     let ccx = bcx.ccx();
910     fn add_to_set(tcx: ty::ctxt, set: &mut ~[Opt], val: Opt) {
911         if set.iter().any(|l| opt_eq(tcx, l, &val)) {return;}
912         set.push(val);
913     }
914     // Vector comparisions are special in that since the actual
915     // conditions over-match, we need to be careful about them. This
916     // means that in order to properly handle things in order, we need
917     // to not always merge conditions.
918     fn add_veclen_to_set(set: &mut ~[Opt], i: uint,
919                          len: uint, vlo: VecLenOpt) {
920         match set.last_opt() {
921             // If the last condition in the list matches the one we want
922             // to add, then extend its range. Otherwise, make a new
923             // vec_len with a range just covering the new entry.
924             Some(&vec_len(len2, vlo2, (start, end)))
925                  if len == len2 && vlo == vlo2 =>
926                  set[set.len() - 1] = vec_len(len, vlo, (start, end+1)),
927             _ => set.push(vec_len(len, vlo, (i, i)))
928         }
929     }
930
931     let mut found = ~[];
932     for (i, br) in m.iter().enumerate() {
933         let cur = br.pats[col];
934         match cur.node {
935             ast::PatLit(l) => {
936                 add_to_set(ccx.tcx, &mut found, lit(ExprLit(l)));
937             }
938             ast::PatIdent(*) => {
939                 // This is one of: an enum variant, a unit-like struct, or a
940                 // variable binding.
941                 match ccx.tcx.def_map.find(&cur.id) {
942                     Some(&ast::DefVariant(*)) => {
943                         add_to_set(ccx.tcx, &mut found,
944                                    variant_opt(bcx, cur.id));
945                     }
946                     Some(&ast::DefStruct(*)) => {
947                         add_to_set(ccx.tcx, &mut found,
948                                    lit(UnitLikeStructLit(cur.id)));
949                     }
950                     Some(&ast::DefStatic(const_did, false)) => {
951                         add_to_set(ccx.tcx, &mut found,
952                                    lit(ConstLit(const_did)));
953                     }
954                     _ => {}
955                 }
956             }
957             ast::PatEnum(*) | ast::PatStruct(*) => {
958                 // This could be one of: a tuple-like enum variant, a
959                 // struct-like enum variant, or a struct.
960                 match ccx.tcx.def_map.find(&cur.id) {
961                     Some(&ast::DefFn(*)) |
962                     Some(&ast::DefVariant(*)) => {
963                         add_to_set(ccx.tcx, &mut found,
964                                    variant_opt(bcx, cur.id));
965                     }
966                     Some(&ast::DefStatic(const_did, false)) => {
967                         add_to_set(ccx.tcx, &mut found,
968                                    lit(ConstLit(const_did)));
969                     }
970                     _ => {}
971                 }
972             }
973             ast::PatRange(l1, l2) => {
974                 add_to_set(ccx.tcx, &mut found, range(l1, l2));
975             }
976             ast::PatVec(ref before, slice, ref after) => {
977                 let (len, vec_opt) = match slice {
978                     None => (before.len(), vec_len_eq),
979                     Some(_) => (before.len() + after.len(),
980                                 vec_len_ge(before.len()))
981                 };
982                 add_veclen_to_set(&mut found, i, len, vec_opt);
983             }
984             _ => {}
985         }
986     }
987     return found;
988 }
989
990 struct ExtractedBlock {
991     vals: ~[ValueRef],
992     bcx: @mut Block
993 }
994
995 fn extract_variant_args(bcx: @mut Block,
996                             repr: &adt::Repr,
997                             disr_val: ty::Disr,
998                             val: ValueRef)
999     -> ExtractedBlock {
1000     let _icx = push_ctxt("match::extract_variant_args");
1001     let args = do vec::from_fn(adt::num_args(repr, disr_val)) |i| {
1002         adt::trans_field_ptr(bcx, repr, val, disr_val, i)
1003     };
1004
1005     ExtractedBlock { vals: args, bcx: bcx }
1006 }
1007
1008 fn match_datum(bcx: @mut Block, val: ValueRef, pat_id: ast::NodeId) -> Datum {
1009     //! Helper for converting from the ValueRef that we pass around in
1010     //! the match code, which is always by ref, into a Datum. Eventually
1011     //! we should just pass around a Datum and be done with it.
1012
1013     let ty = node_id_type(bcx, pat_id);
1014     Datum {val: val, ty: ty, mode: datum::ByRef(RevokeClean)}
1015 }
1016
1017
1018 fn extract_vec_elems(bcx: @mut Block,
1019                          pat_span: Span,
1020                          pat_id: ast::NodeId,
1021                          elem_count: uint,
1022                          slice: Option<uint>,
1023                          val: ValueRef,
1024                          count: ValueRef)
1025                       -> ExtractedBlock {
1026     let _icx = push_ctxt("match::extract_vec_elems");
1027     let vec_datum = match_datum(bcx, val, pat_id);
1028     let (bcx, base, len) = vec_datum.get_vec_base_and_len(bcx, pat_span, pat_id, 0);
1029     let vt = tvec::vec_types(bcx, node_id_type(bcx, pat_id));
1030
1031     let mut elems = do vec::from_fn(elem_count) |i| {
1032         match slice {
1033             None => GEPi(bcx, base, [i]),
1034             Some(n) if i < n => GEPi(bcx, base, [i]),
1035             Some(n) if i > n => {
1036                 InBoundsGEP(bcx, base, [
1037                     Sub(bcx, count,
1038                         C_int(bcx.ccx(), (elem_count - i) as int))])
1039             }
1040             _ => unsafe { llvm::LLVMGetUndef(vt.llunit_ty.to_ref()) }
1041         }
1042     };
1043     if slice.is_some() {
1044         let n = slice.unwrap();
1045         let slice_byte_offset = Mul(bcx, vt.llunit_size, C_uint(bcx.ccx(), n));
1046         let slice_begin = tvec::pointer_add_byte(bcx, base, slice_byte_offset);
1047         let slice_len_offset = C_uint(bcx.ccx(), elem_count - 1u);
1048         let slice_len = Sub(bcx, len, slice_len_offset);
1049         let slice_ty = ty::mk_evec(bcx.tcx(),
1050             ty::mt {ty: vt.unit_ty, mutbl: ast::MutImmutable},
1051             ty::vstore_slice(ty::re_static)
1052         );
1053         let scratch = scratch_datum(bcx, slice_ty, "", false);
1054         Store(bcx, slice_begin,
1055             GEPi(bcx, scratch.val, [0u, abi::slice_elt_base])
1056         );
1057         Store(bcx, slice_len, GEPi(bcx, scratch.val, [0u, abi::slice_elt_len]));
1058         elems[n] = scratch.val;
1059         scratch.add_clean(bcx);
1060     }
1061
1062     ExtractedBlock { vals: elems, bcx: bcx }
1063 }
1064
1065 /// Checks every pattern in `m` at `col` column.
1066 /// If there are a struct pattern among them function
1067 /// returns list of all fields that are matched in these patterns.
1068 /// Function returns None if there is no struct pattern.
1069 /// Function doesn't collect fields from struct-like enum variants.
1070 /// Function can return empty list if there is only wildcard struct pattern.
1071 fn collect_record_or_struct_fields(bcx: @mut Block,
1072                                        m: &[Match],
1073                                        col: uint)
1074                                     -> Option<~[ast::Ident]> {
1075     let mut fields: ~[ast::Ident] = ~[];
1076     let mut found = false;
1077     for br in m.iter() {
1078         match br.pats[col].node {
1079           ast::PatStruct(_, ref fs, _) => {
1080             match ty::get(node_id_type(bcx, br.pats[col].id)).sty {
1081               ty::ty_struct(*) => {
1082                    extend(&mut fields, *fs);
1083                    found = true;
1084               }
1085               _ => ()
1086             }
1087           }
1088           _ => ()
1089         }
1090     }
1091     if found {
1092         return Some(fields);
1093     } else {
1094         return None;
1095     }
1096
1097     fn extend(idents: &mut ~[ast::Ident], field_pats: &[ast::FieldPat]) {
1098         for field_pat in field_pats.iter() {
1099             let field_ident = field_pat.ident;
1100             if !idents.iter().any(|x| x.name == field_ident.name) {
1101                 idents.push(field_ident);
1102             }
1103         }
1104     }
1105 }
1106
1107 fn pats_require_rooting(bcx: @mut Block,
1108                             m: &[Match],
1109                             col: uint)
1110                          -> bool {
1111     do m.iter().any |br| {
1112         let pat_id = br.pats[col].id;
1113         let key = root_map_key {id: pat_id, derefs: 0u };
1114         bcx.ccx().maps.root_map.contains_key(&key)
1115     }
1116 }
1117
1118 fn root_pats_as_necessary(mut bcx: @mut Block,
1119                               m: &[Match],
1120                               col: uint,
1121                               val: ValueRef)
1122                            -> @mut Block {
1123     for br in m.iter() {
1124         let pat_id = br.pats[col].id;
1125         if pat_id != 0 {
1126             let datum = Datum {val: val, ty: node_id_type(bcx, pat_id),
1127                                mode: ByRef(ZeroMem)};
1128             bcx = datum.root_and_write_guard(bcx, br.pats[col].span, pat_id, 0);
1129         }
1130     }
1131     return bcx;
1132 }
1133
1134 // Macro for deciding whether any of the remaining matches fit a given kind of
1135 // pattern.  Note that, because the macro is well-typed, either ALL of the
1136 // matches should fit that sort of pattern or NONE (however, some of the
1137 // matches may be wildcards like _ or identifiers).
1138 macro_rules! any_pat (
1139     ($m:expr, $pattern:pat) => (
1140         do ($m).iter().any |br| {
1141             match br.pats[col].node {
1142                 $pattern => true,
1143                 _ => false
1144             }
1145         }
1146     )
1147 )
1148
1149 fn any_box_pat(m: &[Match], col: uint) -> bool {
1150     any_pat!(m, ast::PatBox(_))
1151 }
1152
1153 fn any_uniq_pat(m: &[Match], col: uint) -> bool {
1154     any_pat!(m, ast::PatUniq(_))
1155 }
1156
1157 fn any_region_pat(m: &[Match], col: uint) -> bool {
1158     any_pat!(m, ast::PatRegion(_))
1159 }
1160
1161 fn any_tup_pat(m: &[Match], col: uint) -> bool {
1162     any_pat!(m, ast::PatTup(_))
1163 }
1164
1165 fn any_tuple_struct_pat(bcx: @mut Block, m: &[Match], col: uint) -> bool {
1166     do m.iter().any |br| {
1167         let pat = br.pats[col];
1168         match pat.node {
1169             ast::PatEnum(_, Some(_)) => {
1170                 match bcx.tcx().def_map.find(&pat.id) {
1171                     Some(&ast::DefFn(*)) |
1172                     Some(&ast::DefStruct(*)) => true,
1173                     _ => false
1174                 }
1175             }
1176             _ => false
1177         }
1178     }
1179 }
1180
1181 trait CustomFailureHandler {
1182     fn handle_fail(&self) -> BasicBlockRef;
1183 }
1184
1185 struct DynamicFailureHandler {
1186     bcx: @mut Block,
1187     sp: Span,
1188     msg: @str,
1189     finished: @mut Option<BasicBlockRef>,
1190 }
1191
1192 impl CustomFailureHandler for DynamicFailureHandler {
1193     fn handle_fail(&self) -> BasicBlockRef {
1194         match *self.finished {
1195             Some(bb) => return bb,
1196             _ => (),
1197         }
1198
1199         let fail_cx = sub_block(self.bcx, "case_fallthrough");
1200         controlflow::trans_fail(fail_cx, Some(self.sp), self.msg);
1201         *self.finished = Some(fail_cx.llbb);
1202         fail_cx.llbb
1203     }
1204 }
1205
1206 /// What to do when the pattern match fails.
1207 enum FailureHandler {
1208     Infallible,
1209     JumpToBasicBlock(BasicBlockRef),
1210     CustomFailureHandlerClass(@CustomFailureHandler),
1211 }
1212
1213 impl FailureHandler {
1214     fn is_infallible(&self) -> bool {
1215         match *self {
1216             Infallible => true,
1217             _ => false,
1218         }
1219     }
1220
1221     fn is_fallible(&self) -> bool {
1222         !self.is_infallible()
1223     }
1224
1225     fn handle_fail(&self) -> BasicBlockRef {
1226         match *self {
1227             Infallible => {
1228                 fail2!("attempted to fail in infallible failure handler!")
1229             }
1230             JumpToBasicBlock(basic_block) => basic_block,
1231             CustomFailureHandlerClass(custom_failure_handler) => {
1232                 custom_failure_handler.handle_fail()
1233             }
1234         }
1235     }
1236 }
1237
1238 fn pick_col(m: &[Match]) -> uint {
1239     fn score(p: &ast::Pat) -> uint {
1240         match p.node {
1241           ast::PatLit(_) | ast::PatEnum(_, _) | ast::PatRange(_, _) => 1u,
1242           ast::PatIdent(_, _, Some(p)) => score(p),
1243           _ => 0u
1244         }
1245     }
1246     let mut scores = vec::from_elem(m[0].pats.len(), 0u);
1247     for br in m.iter() {
1248         for (i, p) in br.pats.iter().enumerate() {
1249             scores[i] += score(*p);
1250         }
1251     }
1252     let mut max_score = 0u;
1253     let mut best_col = 0u;
1254     for (i, score) in scores.iter().enumerate() {
1255         let score = *score;
1256
1257         // Irrefutable columns always go first, they'd only be duplicated in
1258         // the branches.
1259         if score == 0u { return i; }
1260         // If no irrefutable ones are found, we pick the one with the biggest
1261         // branching factor.
1262         if score > max_score { max_score = score; best_col = i; }
1263     }
1264     return best_col;
1265 }
1266
1267 #[deriving(Eq)]
1268 pub enum branch_kind { no_branch, single, switch, compare, compare_vec_len, }
1269
1270 // Compiles a comparison between two things.
1271 //
1272 // NB: This must produce an i1, not a Rust bool (i8).
1273 fn compare_values(cx: @mut Block,
1274                       lhs: ValueRef,
1275                       rhs: ValueRef,
1276                       rhs_t: ty::t)
1277                    -> Result {
1278     let _icx = push_ctxt("compare_values");
1279     if ty::type_is_scalar(rhs_t) {
1280       let rs = compare_scalar_types(cx, lhs, rhs, rhs_t, ast::BiEq);
1281       return rslt(rs.bcx, rs.val);
1282     }
1283
1284     match ty::get(rhs_t).sty {
1285         ty::ty_estr(ty::vstore_uniq) => {
1286             let scratch_lhs = alloca(cx, val_ty(lhs), "__lhs");
1287             Store(cx, lhs, scratch_lhs);
1288             let scratch_rhs = alloca(cx, val_ty(rhs), "__rhs");
1289             Store(cx, rhs, scratch_rhs);
1290             let did = langcall(cx, None,
1291                                format!("comparison of `{}`", cx.ty_to_str(rhs_t)),
1292                                UniqStrEqFnLangItem);
1293             let result = callee::trans_lang_call(cx, did, [scratch_lhs, scratch_rhs], None);
1294             Result {
1295                 bcx: result.bcx,
1296                 val: bool_to_i1(result.bcx, result.val)
1297             }
1298         }
1299         ty::ty_estr(_) => {
1300             let did = langcall(cx, None,
1301                                format!("comparison of `{}`", cx.ty_to_str(rhs_t)),
1302                                StrEqFnLangItem);
1303             let result = callee::trans_lang_call(cx, did, [lhs, rhs], None);
1304             Result {
1305                 bcx: result.bcx,
1306                 val: bool_to_i1(result.bcx, result.val)
1307             }
1308         }
1309         _ => {
1310             cx.tcx().sess.bug("only scalars and strings supported in \
1311                                 compare_values");
1312         }
1313     }
1314 }
1315
1316 fn store_non_ref_bindings(bcx: @mut Block,
1317                           bindings_map: &BindingsMap,
1318                           mut opt_temp_cleanups: Option<&mut ~[ValueRef]>)
1319                           -> @mut Block
1320 {
1321     /*!
1322      *
1323      * For each copy/move binding, copy the value from the value
1324      * being matched into its final home.  This code executes once
1325      * one of the patterns for a given arm has completely matched.
1326      * It adds temporary cleanups to the `temp_cleanups` array,
1327      * if one is provided.
1328      */
1329
1330     let mut bcx = bcx;
1331     for (_, &binding_info) in bindings_map.iter() {
1332         match binding_info.trmode {
1333             TrByValue(lldest) => {
1334                 let llval = Load(bcx, binding_info.llmatch); // get a T*
1335                 let datum = Datum {val: llval, ty: binding_info.ty,
1336                                    mode: ByRef(ZeroMem)};
1337                 bcx = datum.store_to(bcx, INIT, lldest);
1338                 do opt_temp_cleanups.mutate |temp_cleanups| {
1339                     add_clean_temp_mem(bcx, lldest, binding_info.ty);
1340                     temp_cleanups.push(lldest);
1341                     temp_cleanups
1342                 };
1343             }
1344             TrByRef => {}
1345         }
1346     }
1347     return bcx;
1348 }
1349
1350 fn insert_lllocals(bcx: @mut Block,
1351                    bindings_map: &BindingsMap,
1352                    add_cleans: bool) -> @mut Block {
1353     /*!
1354      * For each binding in `data.bindings_map`, adds an appropriate entry into
1355      * the `fcx.lllocals` map.  If add_cleans is true, then adds cleanups for
1356      * the bindings.
1357      */
1358
1359     let llmap = bcx.fcx.lllocals;
1360
1361     for (&ident, &binding_info) in bindings_map.iter() {
1362         let llval = match binding_info.trmode {
1363             // By value bindings: use the stack slot that we
1364             // copied/moved the value into
1365             TrByValue(lldest) => {
1366                 if add_cleans {
1367                     add_clean(bcx, lldest, binding_info.ty);
1368                 }
1369
1370                 lldest
1371             }
1372
1373             // By ref binding: use the ptr into the matched value
1374             TrByRef => {
1375                 binding_info.llmatch
1376             }
1377         };
1378
1379         debug2!("binding {:?} to {}", binding_info.id, bcx.val_to_str(llval));
1380         llmap.insert(binding_info.id, llval);
1381
1382         if bcx.sess().opts.extra_debuginfo {
1383             debuginfo::create_match_binding_metadata(bcx,
1384                                                      ident,
1385                                                      binding_info.id,
1386                                                      binding_info.ty,
1387                                                      binding_info.span);
1388         }
1389     }
1390     return bcx;
1391 }
1392
1393 fn compile_guard(bcx: @mut Block,
1394                      guard_expr: &ast::Expr,
1395                      data: &ArmData,
1396                      m: &[Match],
1397                      vals: &[ValueRef],
1398                      chk: FailureHandler)
1399                   -> @mut Block {
1400     debug2!("compile_guard(bcx={}, guard_expr={}, m={}, vals={})",
1401            bcx.to_str(),
1402            bcx.expr_to_str(guard_expr),
1403            m.repr(bcx.tcx()),
1404            vec_map_to_str(vals, |v| bcx.val_to_str(*v)));
1405     let _indenter = indenter();
1406
1407     let mut bcx = bcx;
1408     let mut temp_cleanups = ~[];
1409     bcx = store_non_ref_bindings(bcx,
1410                                  data.bindings_map,
1411                                  Some(&mut temp_cleanups));
1412     bcx = insert_lllocals(bcx, data.bindings_map, false);
1413
1414     let val = unpack_result!(bcx, {
1415         do with_scope_result(bcx, guard_expr.info(),
1416                              "guard") |bcx| {
1417             expr::trans_to_datum(bcx, guard_expr).to_result()
1418         }
1419     });
1420     let val = bool_to_i1(bcx, val);
1421
1422     // Revoke the temp cleanups now that the guard successfully executed.
1423     for llval in temp_cleanups.iter() {
1424         revoke_clean(bcx, *llval);
1425     }
1426
1427     return do with_cond(bcx, Not(bcx, val)) |bcx| {
1428         // Guard does not match: free the values we copied,
1429         // and remove all bindings from the lllocals table
1430         let bcx = drop_bindings(bcx, data);
1431         compile_submatch(bcx, m, vals, chk);
1432         bcx
1433     };
1434
1435     fn drop_bindings(bcx: @mut Block, data: &ArmData) -> @mut Block {
1436         let mut bcx = bcx;
1437         for (_, &binding_info) in data.bindings_map.iter() {
1438             match binding_info.trmode {
1439                 TrByValue(llval) => {
1440                     bcx = glue::drop_ty(bcx, llval, binding_info.ty);
1441                 }
1442                 TrByRef => {}
1443             }
1444             bcx.fcx.lllocals.remove(&binding_info.id);
1445         }
1446         return bcx;
1447     }
1448 }
1449
1450 fn compile_submatch(bcx: @mut Block,
1451                     m: &[Match],
1452                     vals: &[ValueRef],
1453                     chk: FailureHandler) {
1454     debug2!("compile_submatch(bcx={}, m={}, vals={})",
1455            bcx.to_str(),
1456            m.repr(bcx.tcx()),
1457            vec_map_to_str(vals, |v| bcx.val_to_str(*v)));
1458     let _indenter = indenter();
1459
1460     /*
1461       For an empty match, a fall-through case must exist
1462      */
1463     assert!((m.len() > 0u || chk.is_fallible()));
1464     let _icx = push_ctxt("match::compile_submatch");
1465     let mut bcx = bcx;
1466     if m.len() == 0u {
1467         Br(bcx, chk.handle_fail());
1468         return;
1469     }
1470     if m[0].pats.len() == 0u {
1471         let data = &m[0].data;
1472         for &(ref ident, ref value_ptr) in m[0].bound_ptrs.iter() {
1473             let llmatch = data.bindings_map.get(ident).llmatch;
1474             Store(bcx, *value_ptr, llmatch);
1475         }
1476         match data.arm.guard {
1477             Some(guard_expr) => {
1478                 bcx = compile_guard(bcx,
1479                                     guard_expr,
1480                                     &m[0].data,
1481                                     m.slice(1, m.len()),
1482                                     vals,
1483                                     chk);
1484             }
1485             _ => ()
1486         }
1487         Br(bcx, data.bodycx.llbb);
1488         return;
1489     }
1490
1491     let col = pick_col(m);
1492     let val = vals[col];
1493
1494     if has_nested_bindings(m, col) {
1495         let expanded = expand_nested_bindings(bcx, m, col, val);
1496         compile_submatch_continue(bcx, expanded, vals, chk, col, val)
1497     } else {
1498         compile_submatch_continue(bcx, m, vals, chk, col, val)
1499     }
1500 }
1501
1502 fn compile_submatch_continue(mut bcx: @mut Block,
1503                              m: &[Match],
1504                              vals: &[ValueRef],
1505                              chk: FailureHandler,
1506                              col: uint,
1507                              val: ValueRef) {
1508     let tcx = bcx.tcx();
1509     let dm = tcx.def_map;
1510
1511     let vals_left = vec::append(vals.slice(0u, col).to_owned(),
1512                                 vals.slice(col + 1u, vals.len()));
1513     let ccx = bcx.fcx.ccx;
1514     let mut pat_id = 0;
1515     let mut pat_span = dummy_sp();
1516     for br in m.iter() {
1517         // Find a real id (we're adding placeholder wildcard patterns, but
1518         // each column is guaranteed to have at least one real pattern)
1519         if pat_id == 0 {
1520             pat_id = br.pats[col].id;
1521             pat_span = br.pats[col].span;
1522         }
1523     }
1524
1525     // If we are not matching against an `@T`, we should not be
1526     // required to root any values.
1527     assert!(any_box_pat(m, col) || !pats_require_rooting(bcx, m, col));
1528
1529     match collect_record_or_struct_fields(bcx, m, col) {
1530         Some(ref rec_fields) => {
1531             let pat_ty = node_id_type(bcx, pat_id);
1532             let pat_repr = adt::represent_type(bcx.ccx(), pat_ty);
1533             do expr::with_field_tys(tcx, pat_ty, None) |discr, field_tys| {
1534                 let rec_vals = rec_fields.map(|field_name| {
1535                         let ix = ty::field_idx_strict(tcx, field_name.name, field_tys);
1536                         adt::trans_field_ptr(bcx, pat_repr, val, discr, ix)
1537                         });
1538                 compile_submatch(
1539                         bcx,
1540                         enter_rec_or_struct(bcx, dm, m, col, *rec_fields, val),
1541                         vec::append(rec_vals, vals_left),
1542                         chk);
1543             }
1544             return;
1545         }
1546         None => {}
1547     }
1548
1549     if any_tup_pat(m, col) {
1550         let tup_ty = node_id_type(bcx, pat_id);
1551         let tup_repr = adt::represent_type(bcx.ccx(), tup_ty);
1552         let n_tup_elts = match ty::get(tup_ty).sty {
1553           ty::ty_tup(ref elts) => elts.len(),
1554           _ => ccx.sess.bug("non-tuple type in tuple pattern")
1555         };
1556         let tup_vals = do vec::from_fn(n_tup_elts) |i| {
1557             adt::trans_field_ptr(bcx, tup_repr, val, 0, i)
1558         };
1559         compile_submatch(bcx, enter_tup(bcx, dm, m, col, val, n_tup_elts),
1560                          vec::append(tup_vals, vals_left), chk);
1561         return;
1562     }
1563
1564     if any_tuple_struct_pat(bcx, m, col) {
1565         let struct_ty = node_id_type(bcx, pat_id);
1566         let struct_element_count;
1567         match ty::get(struct_ty).sty {
1568             ty::ty_struct(struct_id, _) => {
1569                 struct_element_count =
1570                     ty::lookup_struct_fields(tcx, struct_id).len();
1571             }
1572             _ => {
1573                 ccx.sess.bug("non-struct type in tuple struct pattern");
1574             }
1575         }
1576
1577         let struct_repr = adt::represent_type(bcx.ccx(), struct_ty);
1578         let llstructvals = do vec::from_fn(struct_element_count) |i| {
1579             adt::trans_field_ptr(bcx, struct_repr, val, 0, i)
1580         };
1581         compile_submatch(bcx,
1582                          enter_tuple_struct(bcx, dm, m, col, val,
1583                                             struct_element_count),
1584                          vec::append(llstructvals, vals_left),
1585                          chk);
1586         return;
1587     }
1588
1589     // Unbox in case of a box field
1590     if any_box_pat(m, col) {
1591         bcx = root_pats_as_necessary(bcx, m, col, val);
1592         let llbox = Load(bcx, val);
1593         let unboxed = GEPi(bcx, llbox, [0u, abi::box_field_body]);
1594         compile_submatch(bcx, enter_box(bcx, dm, m, col, val),
1595                          vec::append(~[unboxed], vals_left), chk);
1596         return;
1597     }
1598
1599     if any_uniq_pat(m, col) {
1600         let pat_ty = node_id_type(bcx, pat_id);
1601         let llbox = Load(bcx, val);
1602         let unboxed = match ty::get(pat_ty).sty {
1603             ty::ty_uniq(*) if !ty::type_contents(bcx.tcx(), pat_ty).contains_managed() => llbox,
1604             _ => GEPi(bcx, llbox, [0u, abi::box_field_body])
1605         };
1606         compile_submatch(bcx, enter_uniq(bcx, dm, m, col, val),
1607                          vec::append(~[unboxed], vals_left), chk);
1608         return;
1609     }
1610
1611     if any_region_pat(m, col) {
1612         let loaded_val = Load(bcx, val);
1613         compile_submatch(bcx, enter_region(bcx, dm, m, col, val),
1614                          vec::append(~[loaded_val], vals_left), chk);
1615         return;
1616     }
1617
1618     // Decide what kind of branch we need
1619     let opts = get_options(bcx, m, col);
1620     debug2!("options={:?}", opts);
1621     let mut kind = no_branch;
1622     let mut test_val = val;
1623     if opts.len() > 0u {
1624         match opts[0] {
1625             var(_, repr) => {
1626                 let (the_kind, val_opt) = adt::trans_switch(bcx, repr, val);
1627                 kind = the_kind;
1628                 for &tval in val_opt.iter() { test_val = tval; }
1629             }
1630             lit(_) => {
1631                 let pty = node_id_type(bcx, pat_id);
1632                 test_val = load_if_immediate(bcx, val, pty);
1633                 kind = if ty::type_is_integral(pty) { switch }
1634                 else { compare };
1635             }
1636             range(_, _) => {
1637                 test_val = Load(bcx, val);
1638                 kind = compare;
1639             },
1640             vec_len(*) => {
1641                 let vt = tvec::vec_types(bcx, node_id_type(bcx, pat_id));
1642                 let unboxed = load_if_immediate(bcx, val, vt.vec_ty);
1643                 let (_, len) = tvec::get_base_and_len(bcx, unboxed, vt.vec_ty);
1644                 test_val = len;
1645                 kind = compare_vec_len;
1646             }
1647         }
1648     }
1649     for o in opts.iter() {
1650         match *o {
1651             range(_, _) => { kind = compare; break }
1652             _ => ()
1653         }
1654     }
1655     let else_cx = match kind {
1656         no_branch | single => bcx,
1657         _ => sub_block(bcx, "match_else")
1658     };
1659     let sw = if kind == switch {
1660         Switch(bcx, test_val, else_cx.llbb, opts.len())
1661     } else {
1662         C_int(ccx, 0) // Placeholder for when not using a switch
1663     };
1664
1665     let defaults = enter_default(else_cx, dm, m, col, val, chk);
1666     let exhaustive = chk.is_infallible() && defaults.len() == 0u;
1667     let len = opts.len();
1668
1669     // Compile subtrees for each option
1670     for (i, opt) in opts.iter().enumerate() {
1671         // In some cases in vector pattern matching, we need to override
1672         // the failure case so that instead of failing, it proceeds to
1673         // try more matching. branch_chk, then, is the proper failure case
1674         // for the current conditional branch.
1675         let mut branch_chk = chk;
1676         let mut opt_cx = else_cx;
1677         if !exhaustive || i+1 < len {
1678             opt_cx = sub_block(bcx, "match_case");
1679             match kind {
1680               single => Br(bcx, opt_cx.llbb),
1681               switch => {
1682                   match trans_opt(bcx, opt) {
1683                       single_result(r) => {
1684                         unsafe {
1685                           llvm::LLVMAddCase(sw, r.val, opt_cx.llbb);
1686                           bcx = r.bcx;
1687                         }
1688                       }
1689                       _ => {
1690                           bcx.sess().bug(
1691                               "in compile_submatch, expected \
1692                                trans_opt to return a single_result")
1693                       }
1694                   }
1695               }
1696               compare => {
1697                   let t = node_id_type(bcx, pat_id);
1698                   let Result {bcx: after_cx, val: matches} = {
1699                       do with_scope_result(bcx, None,
1700                                            "compare_scope") |bcx| {
1701                           match trans_opt(bcx, opt) {
1702                               single_result(
1703                                   Result {bcx, val}) => {
1704                                   compare_values(bcx, test_val, val, t)
1705                               }
1706                               lower_bound(
1707                                   Result {bcx, val}) => {
1708                                   compare_scalar_types(
1709                                           bcx, test_val, val,
1710                                           t, ast::BiGe)
1711                               }
1712                               range_result(
1713                                   Result {val: vbegin, _},
1714                                   Result {bcx, val: vend}) => {
1715                                   let Result {bcx, val: llge} =
1716                                       compare_scalar_types(
1717                                           bcx, test_val,
1718                                           vbegin, t, ast::BiGe);
1719                                   let Result {bcx, val: llle} =
1720                                       compare_scalar_types(
1721                                           bcx, test_val, vend,
1722                                           t, ast::BiLe);
1723                                   rslt(bcx, And(bcx, llge, llle))
1724                               }
1725                           }
1726                       }
1727                   };
1728                   bcx = sub_block(after_cx, "compare_next");
1729                   CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb);
1730               }
1731               compare_vec_len => {
1732                   let Result {bcx: after_cx, val: matches} = {
1733                       do with_scope_result(bcx, None,
1734                                            "compare_vec_len_scope") |bcx| {
1735                           match trans_opt(bcx, opt) {
1736                               single_result(
1737                                   Result {bcx, val}) => {
1738                                   let value = compare_scalar_values(
1739                                       bcx, test_val, val,
1740                                       signed_int, ast::BiEq);
1741                                   rslt(bcx, value)
1742                               }
1743                               lower_bound(
1744                                   Result {bcx, val: val}) => {
1745                                   let value = compare_scalar_values(
1746                                       bcx, test_val, val,
1747                                       signed_int, ast::BiGe);
1748                                   rslt(bcx, value)
1749                               }
1750                               range_result(
1751                                   Result {val: vbegin, _},
1752                                   Result {bcx, val: vend}) => {
1753                                   let llge =
1754                                       compare_scalar_values(
1755                                           bcx, test_val,
1756                                           vbegin, signed_int, ast::BiGe);
1757                                   let llle =
1758                                       compare_scalar_values(
1759                                           bcx, test_val, vend,
1760                                           signed_int, ast::BiLe);
1761                                   rslt(bcx, And(bcx, llge, llle))
1762                               }
1763                           }
1764                       }
1765                   };
1766                   bcx = sub_block(after_cx, "compare_vec_len_next");
1767
1768                   // If none of these subcases match, move on to the
1769                   // next condition.
1770                   branch_chk = JumpToBasicBlock(bcx.llbb);
1771                   CondBr(after_cx, matches, opt_cx.llbb, bcx.llbb);
1772               }
1773               _ => ()
1774             }
1775         } else if kind == compare || kind == compare_vec_len {
1776             Br(bcx, else_cx.llbb);
1777         }
1778
1779         let mut size = 0u;
1780         let mut unpacked = ~[];
1781         match *opt {
1782             var(disr_val, repr) => {
1783                 let ExtractedBlock {vals: argvals, bcx: new_bcx} =
1784                     extract_variant_args(opt_cx, repr, disr_val, val);
1785                 size = argvals.len();
1786                 unpacked = argvals;
1787                 opt_cx = new_bcx;
1788             }
1789             vec_len(n, vt, _) => {
1790                 let (n, slice) = match vt {
1791                     vec_len_ge(i) => (n + 1u, Some(i)),
1792                     vec_len_eq => (n, None)
1793                 };
1794                 let args = extract_vec_elems(opt_cx, pat_span, pat_id, n,
1795                                              slice, val, test_val);
1796                 size = args.vals.len();
1797                 unpacked = args.vals.clone();
1798                 opt_cx = args.bcx;
1799             }
1800             lit(_) | range(_, _) => ()
1801         }
1802         let opt_ms = enter_opt(opt_cx, m, opt, col, size, val);
1803         let opt_vals = vec::append(unpacked, vals_left);
1804         compile_submatch(opt_cx, opt_ms, opt_vals, branch_chk);
1805     }
1806
1807     // Compile the fall-through case, if any
1808     if !exhaustive {
1809         if kind == compare || kind == compare_vec_len {
1810             Br(bcx, else_cx.llbb);
1811         }
1812         if kind != single {
1813             compile_submatch(else_cx, defaults, vals_left, chk);
1814         }
1815     }
1816 }
1817
1818 pub fn trans_match(bcx: @mut Block,
1819                    match_expr: &ast::Expr,
1820                    discr_expr: &ast::Expr,
1821                    arms: &[ast::Arm],
1822                    dest: Dest) -> @mut Block {
1823     let _icx = push_ctxt("match::trans_match");
1824     do with_scope(bcx, match_expr.info(), "match") |bcx| {
1825         trans_match_inner(bcx, discr_expr, arms, dest)
1826     }
1827 }
1828
1829 fn create_bindings_map(bcx: @mut Block, pat: @ast::Pat) -> BindingsMap {
1830     // Create the bindings map, which is a mapping from each binding name
1831     // to an alloca() that will be the value for that local variable.
1832     // Note that we use the names because each binding will have many ids
1833     // from the various alternatives.
1834     let ccx = bcx.ccx();
1835     let tcx = bcx.tcx();
1836     let mut bindings_map = HashMap::new();
1837     do pat_bindings(tcx.def_map, pat) |bm, p_id, span, path| {
1838         let ident = path_to_ident(path);
1839         let variable_ty = node_id_type(bcx, p_id);
1840         let llvariable_ty = type_of::type_of(ccx, variable_ty);
1841
1842         let llmatch;
1843         let trmode;
1844         match bm {
1845             ast::BindInfer => {
1846                 // in this case, the final type of the variable will be T,
1847                 // but during matching we need to store a *T as explained
1848                 // above
1849                 llmatch = alloca(bcx, llvariable_ty.ptr_to(), "__llmatch");
1850                 trmode = TrByValue(alloca(bcx, llvariable_ty,
1851                                           bcx.ident(ident)));
1852             }
1853             ast::BindByRef(_) => {
1854                 llmatch = alloca(bcx, llvariable_ty, bcx.ident(ident));
1855                 trmode = TrByRef;
1856             }
1857         };
1858         bindings_map.insert(ident, BindingInfo {
1859             llmatch: llmatch,
1860             trmode: trmode,
1861             id: p_id,
1862             span: span,
1863             ty: variable_ty
1864         });
1865     }
1866     return bindings_map;
1867 }
1868
1869 fn trans_match_inner(scope_cx: @mut Block,
1870                          discr_expr: &ast::Expr,
1871                          arms: &[ast::Arm],
1872                          dest: Dest) -> @mut Block {
1873     let _icx = push_ctxt("match::trans_match_inner");
1874     let mut bcx = scope_cx;
1875     let tcx = bcx.tcx();
1876
1877     let discr_datum = unpack_datum!(bcx, {
1878         expr::trans_to_datum(bcx, discr_expr)
1879     });
1880     if bcx.unreachable {
1881         return bcx;
1882     }
1883
1884     let mut arm_datas = ~[];
1885     let mut matches = ~[];
1886     for arm in arms.iter() {
1887         let body = scope_block(bcx, arm.body.info(), "case_body");
1888         let bindings_map = create_bindings_map(bcx, arm.pats[0]);
1889         let arm_data = ArmData {
1890             bodycx: body,
1891             arm: arm,
1892             bindings_map: @bindings_map
1893         };
1894         arm_datas.push(arm_data.clone());
1895         for p in arm.pats.iter() {
1896             matches.push(Match {
1897                 pats: ~[*p],
1898                 data: arm_data.clone(),
1899                 bound_ptrs: ~[],
1900             });
1901         }
1902     }
1903
1904     let t = node_id_type(bcx, discr_expr.id);
1905     let chk = {
1906         if ty::type_is_empty(tcx, t) {
1907             // Special case for empty types
1908             let fail_cx = @mut None;
1909             let fail_handler = @DynamicFailureHandler {
1910                 bcx: scope_cx,
1911                 sp: discr_expr.span,
1912                 msg: @"scrutinizing value that can't exist",
1913                 finished: fail_cx,
1914             } as @CustomFailureHandler;
1915             CustomFailureHandlerClass(fail_handler)
1916         } else {
1917             Infallible
1918         }
1919     };
1920     let lldiscr = discr_datum.to_zeroable_ref_llval(bcx);
1921     compile_submatch(bcx, matches, [lldiscr], chk);
1922
1923     let mut arm_cxs = ~[];
1924     for arm_data in arm_datas.iter() {
1925         let mut bcx = arm_data.bodycx;
1926
1927         // If this arm has a guard, then the various by-value bindings have
1928         // already been copied into their homes.  If not, we do it here.  This
1929         // is just to reduce code space.  See extensive comment at the start
1930         // of the file for more details.
1931         if arm_data.arm.guard.is_none() {
1932             bcx = store_non_ref_bindings(bcx, arm_data.bindings_map, None);
1933         }
1934
1935         // insert bindings into the lllocals map and add cleanups
1936         bcx = insert_lllocals(bcx, arm_data.bindings_map, true);
1937
1938         bcx = controlflow::trans_block(bcx, &arm_data.arm.body, dest);
1939         bcx = trans_block_cleanups(bcx, block_cleanups(arm_data.bodycx));
1940         arm_cxs.push(bcx);
1941     }
1942
1943     bcx = controlflow::join_blocks(scope_cx, arm_cxs);
1944     return bcx;
1945 }
1946
1947 enum IrrefutablePatternBindingMode {
1948     // Stores the association between node ID and LLVM value in `lllocals`.
1949     BindLocal,
1950     // Stores the association between node ID and LLVM value in `llargs`.
1951     BindArgument
1952 }
1953
1954 pub fn store_local(bcx: @mut Block,
1955                    pat: @ast::Pat,
1956                    opt_init_expr: Option<@ast::Expr>)
1957                    -> @mut Block {
1958     /*!
1959      * Generates code for a local variable declaration like
1960      * `let <pat>;` or `let <pat> = <opt_init_expr>`.
1961      */
1962     let _icx = push_ctxt("match::store_local");
1963     let mut bcx = bcx;
1964
1965     return match opt_init_expr {
1966         Some(init_expr) => {
1967             // Optimize the "let x = expr" case. This just writes
1968             // the result of evaluating `expr` directly into the alloca
1969             // for `x`. Often the general path results in similar or the
1970             // same code post-optimization, but not always. In particular,
1971             // in unsafe code, you can have expressions like
1972             //
1973             //    let x = intrinsics::uninit();
1974             //
1975             // In such cases, the more general path is unsafe, because
1976             // it assumes it is matching against a valid value.
1977             match simple_identifier(pat) {
1978                 Some(path) => {
1979                     return mk_binding_alloca(
1980                         bcx, pat.id, path, BindLocal,
1981                         |bcx, _, llval| expr::trans_into(bcx, init_expr,
1982                                                          expr::SaveIn(llval)));
1983                 }
1984
1985                 None => {}
1986             }
1987
1988             // General path.
1989             let init_datum =
1990                 unpack_datum!(
1991                     bcx,
1992                     expr::trans_to_datum(bcx, init_expr));
1993             if ty::type_is_bot(expr_ty(bcx, init_expr)) {
1994                 create_dummy_locals(bcx, pat)
1995             } else {
1996                 if bcx.sess().asm_comments() {
1997                     add_comment(bcx, "creating zeroable ref llval");
1998                 }
1999                 let llptr = init_datum.to_zeroable_ref_llval(bcx);
2000                 return bind_irrefutable_pat(bcx, pat, llptr, BindLocal);
2001             }
2002         }
2003         None => {
2004             create_dummy_locals(bcx, pat)
2005         }
2006     };
2007
2008     fn create_dummy_locals(mut bcx: @mut Block, pat: @ast::Pat) -> @mut Block {
2009         // create dummy memory for the variables if we have no
2010         // value to store into them immediately
2011         let tcx = bcx.tcx();
2012         do pat_bindings(tcx.def_map, pat) |_, p_id, _, path| {
2013             bcx = mk_binding_alloca(
2014                 bcx, p_id, path, BindLocal,
2015                 |bcx, var_ty, llval| { zero_mem(bcx, llval, var_ty); bcx });
2016         }
2017         bcx
2018     }
2019 }
2020
2021 pub fn store_arg(mut bcx: @mut Block,
2022                  pat: @ast::Pat,
2023                  llval: ValueRef)
2024                  -> @mut Block {
2025     /*!
2026      * Generates code for argument patterns like `fn foo(<pat>: T)`.
2027      * Creates entries in the `llargs` map for each of the bindings
2028      * in `pat`.
2029      *
2030      * # Arguments
2031      *
2032      * - `pat` is the argument pattern
2033      * - `llval` is a pointer to the argument value (in other words,
2034      *   if the argument type is `T`, then `llval` is a `T*`). In some
2035      *   cases, this code may zero out the memory `llval` points at.
2036      */
2037     let _icx = push_ctxt("match::store_arg");
2038
2039     // We always need to cleanup the argument as we exit the fn scope.
2040     // Note that we cannot do it before for fear of a fn like
2041     //    fn getaddr(~ref x: ~uint) -> *uint {....}
2042     // (From test `run-pass/func-arg-ref-pattern.rs`)
2043     let arg_ty = node_id_type(bcx, pat.id);
2044     add_clean(bcx, llval, arg_ty);
2045
2046     // Debug information (the llvm.dbg.declare intrinsic to be precise) always expects to get an
2047     // alloca, which only is the case on the general path, so lets disable the optimized path when
2048     // debug info is enabled.
2049     let fast_path = !bcx.ccx().sess.opts.extra_debuginfo && simple_identifier(pat).is_some();
2050
2051     if fast_path {
2052         // Optimized path for `x: T` case. This just adopts
2053         // `llval` wholesale as the pointer for `x`, avoiding the
2054         // general logic which may copy out of `llval`.
2055         bcx.fcx.llargs.insert(pat.id, llval);
2056     } else {
2057         // General path. Copy out the values that are used in the
2058         // pattern.
2059         bcx = bind_irrefutable_pat(bcx, pat, llval, BindArgument);
2060     }
2061
2062     return bcx;
2063 }
2064
2065 fn mk_binding_alloca(mut bcx: @mut Block,
2066                      p_id: ast::NodeId,
2067                      path: &ast::Path,
2068                      binding_mode: IrrefutablePatternBindingMode,
2069                      populate: &fn(@mut Block, ty::t, ValueRef) -> @mut Block) -> @mut Block {
2070     let var_ty = node_id_type(bcx, p_id);
2071     let ident = ast_util::path_to_ident(path);
2072     let llval = alloc_ty(bcx, var_ty, bcx.ident(ident));
2073     bcx = populate(bcx, var_ty, llval);
2074     let llmap = match binding_mode {
2075         BindLocal => bcx.fcx.lllocals,
2076         BindArgument => bcx.fcx.llargs
2077     };
2078     llmap.insert(p_id, llval);
2079     add_clean(bcx, llval, var_ty);
2080     return bcx;
2081 }
2082
2083 fn bind_irrefutable_pat(bcx: @mut Block,
2084                         pat: @ast::Pat,
2085                         val: ValueRef,
2086                         binding_mode: IrrefutablePatternBindingMode)
2087                         -> @mut Block {
2088     /*!
2089      * A simple version of the pattern matching code that only handles
2090      * irrefutable patterns. This is used in let/argument patterns,
2091      * not in match statements. Unifying this code with the code above
2092      * sounds nice, but in practice it produces very inefficient code,
2093      * since the match code is so much more general. In most cases,
2094      * LLVM is able to optimize the code, but it causes longer compile
2095      * times and makes the generated code nigh impossible to read.
2096      *
2097      * # Arguments
2098      * - bcx: starting basic block context
2099      * - pat: the irrefutable pattern being matched.
2100      * - val: a pointer to the value being matched. If pat matches a value
2101      *   of type T, then this is a T*. If the value is moved from `pat`,
2102      *   then `*pat` will be zeroed; otherwise, it's existing cleanup
2103      *   applies.
2104      * - binding_mode: is this for an argument or a local variable?
2105      */
2106
2107     debug2!("bind_irrefutable_pat(bcx={}, pat={}, binding_mode={:?})",
2108            bcx.to_str(),
2109            pat.repr(bcx.tcx()),
2110            binding_mode);
2111
2112     if bcx.sess().asm_comments() {
2113         add_comment(bcx, format!("bind_irrefutable_pat(pat={})",
2114                               pat.repr(bcx.tcx())));
2115     }
2116
2117     let _indenter = indenter();
2118
2119     let _icx = push_ctxt("alt::bind_irrefutable_pat");
2120     let mut bcx = bcx;
2121     let tcx = bcx.tcx();
2122     let ccx = bcx.ccx();
2123     match pat.node {
2124         ast::PatIdent(pat_binding_mode, ref path, inner) => {
2125             if pat_is_binding(tcx.def_map, pat) {
2126                 // Allocate the stack slot where the value of this
2127                 // binding will live and place it into the appropriate
2128                 // map.
2129                 bcx = mk_binding_alloca(
2130                     bcx, pat.id, path, binding_mode,
2131                     |bcx, variable_ty, llvariable_val| {
2132                         match pat_binding_mode {
2133                             ast::BindInfer => {
2134                                 // By value binding: move the value that `val`
2135                                 // points at into the binding's stack slot.
2136                                 let datum = Datum {val: val,
2137                                                    ty: variable_ty,
2138                                                    mode: ByRef(ZeroMem)};
2139                                 datum.store_to(bcx, INIT, llvariable_val)
2140                             }
2141
2142                             ast::BindByRef(_) => {
2143                                 // By ref binding: the value of the variable
2144                                 // is the pointer `val` itself.
2145                                 Store(bcx, val, llvariable_val);
2146                                 bcx
2147                             }
2148                         }
2149                     });
2150             }
2151
2152             for &inner_pat in inner.iter() {
2153                 bcx = bind_irrefutable_pat(bcx, inner_pat, val, binding_mode);
2154             }
2155         }
2156         ast::PatEnum(_, ref sub_pats) => {
2157             match bcx.tcx().def_map.find(&pat.id) {
2158                 Some(&ast::DefVariant(enum_id, var_id, _)) => {
2159                     let repr = adt::represent_node(bcx, pat.id);
2160                     let vinfo = ty::enum_variant_with_id(ccx.tcx,
2161                                                          enum_id,
2162                                                          var_id);
2163                     let args = extract_variant_args(bcx,
2164                                                     repr,
2165                                                     vinfo.disr_val,
2166                                                     val);
2167                     for sub_pat in sub_pats.iter() {
2168                         for (i, argval) in args.vals.iter().enumerate() {
2169                             bcx = bind_irrefutable_pat(bcx, sub_pat[i],
2170                                                        *argval, binding_mode);
2171                         }
2172                     }
2173                 }
2174                 Some(&ast::DefFn(*)) |
2175                 Some(&ast::DefStruct(*)) => {
2176                     match *sub_pats {
2177                         None => {
2178                             // This is a unit-like struct. Nothing to do here.
2179                         }
2180                         Some(ref elems) => {
2181                             // This is the tuple struct case.
2182                             let repr = adt::represent_node(bcx, pat.id);
2183                             for (i, elem) in elems.iter().enumerate() {
2184                                 let fldptr = adt::trans_field_ptr(bcx, repr,
2185                                                                   val, 0, i);
2186                                 bcx = bind_irrefutable_pat(bcx, *elem,
2187                                                            fldptr, binding_mode);
2188                             }
2189                         }
2190                     }
2191                 }
2192                 Some(&ast::DefStatic(_, false)) => {
2193                 }
2194                 _ => {
2195                     // Nothing to do here.
2196                 }
2197             }
2198         }
2199         ast::PatStruct(_, ref fields, _) => {
2200             let tcx = bcx.tcx();
2201             let pat_ty = node_id_type(bcx, pat.id);
2202             let pat_repr = adt::represent_type(bcx.ccx(), pat_ty);
2203             do expr::with_field_tys(tcx, pat_ty, None) |discr, field_tys| {
2204                 for f in fields.iter() {
2205                     let ix = ty::field_idx_strict(tcx, f.ident.name, field_tys);
2206                     let fldptr = adt::trans_field_ptr(bcx, pat_repr, val,
2207                                                       discr, ix);
2208                     bcx = bind_irrefutable_pat(bcx, f.pat, fldptr, binding_mode);
2209                 }
2210             }
2211         }
2212         ast::PatTup(ref elems) => {
2213             let repr = adt::represent_node(bcx, pat.id);
2214             for (i, elem) in elems.iter().enumerate() {
2215                 let fldptr = adt::trans_field_ptr(bcx, repr, val, 0, i);
2216                 bcx = bind_irrefutable_pat(bcx, *elem, fldptr, binding_mode);
2217             }
2218         }
2219         ast::PatBox(inner) | ast::PatUniq(inner) => {
2220             let pat_ty = node_id_type(bcx, pat.id);
2221             let llbox = Load(bcx, val);
2222             let unboxed = match ty::get(pat_ty).sty {
2223                 ty::ty_uniq(*) if !ty::type_contents(bcx.tcx(), pat_ty).contains_managed() => llbox,
2224                     _ => GEPi(bcx, llbox, [0u, abi::box_field_body])
2225             };
2226             bcx = bind_irrefutable_pat(bcx, inner, unboxed, binding_mode);
2227         }
2228         ast::PatRegion(inner) => {
2229             let loaded_val = Load(bcx, val);
2230             bcx = bind_irrefutable_pat(bcx, inner, loaded_val, binding_mode);
2231         }
2232         ast::PatVec(*) => {
2233             bcx.tcx().sess.span_bug(
2234                 pat.span,
2235                 format!("vector patterns are never irrefutable!"));
2236         }
2237         ast::PatWild | ast::PatLit(_) | ast::PatRange(_, _) => ()
2238     }
2239     return bcx;
2240 }
2241
2242 fn simple_identifier<'a>(pat: &'a ast::Pat) -> Option<&'a ast::Path> {
2243     match pat.node {
2244         ast::PatIdent(ast::BindInfer, ref path, None) => {
2245             Some(path)
2246         }
2247         _ => {
2248             None
2249         }
2250     }
2251 }
2252