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