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