/
expr.rs
1842 lines (1658 loc) · 66.7 KB
/
expr.rs
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2012 The Rust Project Developers. See the COPYRIGHT
// file at the top-level directory of this distribution and at
// http://rust-lang.org/COPYRIGHT.
//
// Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
// http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
// <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
// option. This file may not be copied, modified, or distributed
// except according to those terms.
/*!
# Translation of expressions.
## Recommended entry point
If you wish to translate an expression, the preferred way to do
so is to use:
expr::trans_into(block, expr, Dest) -> block
This will generate code that evaluates `expr`, storing the result into
`Dest`, which must either be the special flag ignore (throw the result
away) or be a pointer to memory of the same type/size as the
expression. It returns the resulting basic block. This form will
handle all automatic adjustments for you. The value will be moved if
its type is linear and copied otherwise.
## Translation to a datum
In some cases, `trans_into()` is too narrow of an interface.
Generally this occurs either when you know that the result value is
going to be a scalar, or when you need to evaluate the expression into
some memory location so you can go and inspect it (e.g., assignments,
`match` expressions, the `&` operator).
In such cases, you want the following function:
trans_to_datum(block, expr) -> DatumBlock
This function generates code to evaluate the expression and return a
`Datum` describing where the result is to be found. This function
tries to return its result in the most efficient way possible, without
introducing extra copies or sacrificing information. Therefore, for
lvalue expressions, you always get a by-ref `Datum` in return that
points at the memory for this lvalue. For rvalue expressions, we will
return a by-value `Datum` whenever possible, but it is often necessary
to allocate a stack slot, store the result of the rvalue in there, and
then return a pointer to the slot (see the discussion later on about
the different kinds of rvalues).
NB: The `trans_to_datum()` function does perform adjustments, but
since it returns a pointer to the value "in place" it does not handle
moves. If you wish to copy/move the value returned into a new
location, you should use the Datum method `store_to()` (move or copy
depending on type). You can also use `move_to()` (force move) or
`copy_to()` (force copy) for special situations.
## Translating local variables
`trans_local_var()` can be used to trans a ref to a local variable
that is not an expression. This is needed for captures.
## Ownership and cleanups
The current system for cleanups associates required cleanups with
block contexts. Block contexts are structured into a tree that
resembles the code itself. Not every block context has cleanups
associated with it, only those blocks that have a kind of
`block_scope`. See `common::block_kind` for more details.
If you invoke `trans_into()`, no cleanup is scheduled for you. The
value is written into the given destination and is assumed to be owned
by that destination.
When you invoke `trans_to_datum()` on an rvalue, the resulting
datum/value will have an appropriate cleanup scheduled for the
innermost cleanup scope. If you later use `move_to()` or
`drop_val()`, this cleanup will be canceled.
During the evaluation of an expression, temporary cleanups are created
and later canceled. These represent intermediate or partial results
which must be cleaned up in the event of task failure.
## Implementation details
We divide expressions into three categories, based on how they are most
naturally implemented:
1. Lvalues
2. Datum rvalues
3. DPS rvalues
4. Statement rvalues
Lvalues always refer to user-assignable memory locations.
Translating those always results in a by-ref datum; this introduces
no inefficiencies into the generated code, because all lvalues are
naturally addressable.
Datum rvalues are rvalues that always generate datums as a result.
These are generally scalar results, such as `a+b` where `a` and `b`
are integers.
DPS rvalues are rvalues that, when translated, must be given a
memory location to write into (or the Ignore flag). These are
generally expressions that produce structural results that are
larger than one word (e.g., a struct literal), but also expressions
(like `if`) that involve control flow (otherwise we'd have to
generate phi nodes).
Finally, statement rvalues are rvalues that always produce a nil
return type, such as `while` loops or assignments (`a = b`).
*/
use back::abi;
use back::link;
use lib::llvm::{ValueRef, llvm, SetLinkage, False};
use lib;
use metadata::csearch;
use metadata::cstore;
use middle::trans::_match;
use middle::trans::adt;
use middle::trans::asm;
use middle::trans::base::*;
use middle::trans::base;
use middle::trans::build::*;
use middle::trans::callee::DoAutorefArg;
use middle::trans::callee;
use middle::trans::closure;
use middle::trans::common::*;
use middle::trans::consts;
use middle::trans::controlflow;
use middle::trans::datum::*;
use middle::trans::debuginfo;
use middle::trans::machine;
use middle::trans::meth;
use middle::trans::inline;
use middle::trans::tvec;
use middle::trans::type_of;
use middle::ty::struct_fields;
use middle::ty::{AutoBorrowObj, AutoDerefRef, AutoAddEnv, AutoUnsafe};
use middle::ty::{AutoPtr, AutoBorrowVec, AutoBorrowVecRef, AutoBorrowFn};
use middle::ty;
use util::common::indenter;
use util::ppaux::Repr;
use middle::trans::machine::llsize_of;
use middle::trans::type_::Type;
use std::hashmap::HashMap;
use std::vec;
use syntax::print::pprust::{expr_to_str};
use syntax::ast;
use syntax::ast_map::path_mod;
use syntax::codemap;
// Destinations
// These are passed around by the code generating functions to track the
// destination of a computation's value.
#[deriving(Eq)]
pub enum Dest {
SaveIn(ValueRef),
Ignore,
}
impl Dest {
pub fn to_str(&self, ccx: &CrateContext) -> ~str {
match *self {
SaveIn(v) => format!("SaveIn({})", ccx.tn.val_to_str(v)),
Ignore => ~"Ignore"
}
}
}
fn drop_and_cancel_clean(bcx: @mut Block, dat: Datum) -> @mut Block {
let bcx = dat.drop_val(bcx);
dat.cancel_clean(bcx);
return bcx;
}
pub fn trans_to_datum(bcx: @mut Block, expr: &ast::Expr) -> DatumBlock {
debug!("trans_to_datum(expr={})", bcx.expr_to_str(expr));
let mut bcx = bcx;
let mut datum = unpack_datum!(bcx, trans_to_datum_unadjusted(bcx, expr));
let adjustment = match bcx.tcx().adjustments.find_copy(&expr.id) {
None => { return DatumBlock {bcx: bcx, datum: datum}; }
Some(adj) => { adj }
};
debug!("unadjusted datum: {}", datum.to_str(bcx.ccx()));
match *adjustment {
AutoAddEnv(*) => {
datum = unpack_datum!(bcx, add_env(bcx, expr, datum));
}
AutoDerefRef(ref adj) => {
if adj.autoderefs > 0 {
datum =
unpack_datum!(
bcx,
datum.autoderef(bcx, expr.span,
expr.id, adj.autoderefs));
}
datum = match adj.autoref {
None => {
datum
}
Some(AutoUnsafe(*)) | // region + unsafe ptrs have same repr
Some(AutoPtr(*)) => {
unpack_datum!(bcx, auto_ref(bcx, datum))
}
Some(AutoBorrowVec(*)) => {
unpack_datum!(bcx, auto_slice(bcx, adj.autoderefs,
expr, datum))
}
Some(AutoBorrowVecRef(*)) => {
unpack_datum!(bcx, auto_slice_and_ref(bcx, adj.autoderefs,
expr, datum))
}
Some(AutoBorrowFn(*)) => {
let adjusted_ty = ty::adjust_ty(bcx.tcx(), expr.span,
datum.ty, Some(adjustment));
unpack_datum!(bcx, auto_borrow_fn(bcx, adjusted_ty, datum))
}
Some(AutoBorrowObj(*)) => {
unpack_datum!(bcx, auto_borrow_obj(
bcx, adj.autoderefs, expr, datum))
}
};
}
}
debug!("after adjustments, datum={}", datum.to_str(bcx.ccx()));
return DatumBlock {bcx: bcx, datum: datum};
fn auto_ref(bcx: @mut Block, datum: Datum) -> DatumBlock {
DatumBlock {bcx: bcx, datum: datum.to_rptr(bcx)}
}
fn auto_borrow_fn(bcx: @mut Block,
adjusted_ty: ty::t,
datum: Datum) -> DatumBlock {
// Currently, all closure types are represented precisely the
// same, so no runtime adjustment is required, but we still
// must patchup the type.
DatumBlock {bcx: bcx,
datum: Datum {val: datum.val, ty: adjusted_ty,
mode: datum.mode}}
}
fn auto_slice(bcx: @mut Block,
autoderefs: uint,
expr: &ast::Expr,
datum: Datum) -> DatumBlock {
// This is not the most efficient thing possible; since slices
// are two words it'd be better if this were compiled in
// 'dest' mode, but I can't find a nice way to structure the
// code and keep it DRY that accommodates that use case at the
// moment.
let tcx = bcx.tcx();
let unit_ty = ty::sequence_element_type(tcx, datum.ty);
let (bcx, base, len) =
datum.get_vec_base_and_len(bcx, expr.span, expr.id, autoderefs+1);
// this type may have a different region/mutability than the
// real one, but it will have the same runtime representation
let slice_ty = ty::mk_evec(tcx,
ty::mt { ty: unit_ty, mutbl: ast::MutImmutable },
ty::vstore_slice(ty::re_static));
let scratch = scratch_datum(bcx, slice_ty, "__adjust", false);
Store(bcx, base, GEPi(bcx, scratch.val, [0u, abi::slice_elt_base]));
Store(bcx, len, GEPi(bcx, scratch.val, [0u, abi::slice_elt_len]));
DatumBlock {bcx: bcx, datum: scratch}
}
fn add_env(bcx: @mut Block, expr: &ast::Expr, datum: Datum) -> DatumBlock {
// This is not the most efficient thing possible; since closures
// are two words it'd be better if this were compiled in
// 'dest' mode, but I can't find a nice way to structure the
// code and keep it DRY that accommodates that use case at the
// moment.
let tcx = bcx.tcx();
let closure_ty = expr_ty_adjusted(bcx, expr);
debug!("add_env(closure_ty={})", closure_ty.repr(tcx));
let scratch = scratch_datum(bcx, closure_ty, "__adjust", false);
let llfn = GEPi(bcx, scratch.val, [0u, abi::fn_field_code]);
assert_eq!(datum.appropriate_mode(bcx.ccx()), ByValue);
Store(bcx, datum.to_appropriate_llval(bcx), llfn);
let llenv = GEPi(bcx, scratch.val, [0u, abi::fn_field_box]);
Store(bcx, base::null_env_ptr(bcx.ccx()), llenv);
DatumBlock {bcx: bcx, datum: scratch}
}
fn auto_slice_and_ref(bcx: @mut Block,
autoderefs: uint,
expr: &ast::Expr,
datum: Datum) -> DatumBlock {
let DatumBlock { bcx, datum } = auto_slice(bcx, autoderefs, expr, datum);
auto_ref(bcx, datum)
}
fn auto_borrow_obj(mut bcx: @mut Block,
autoderefs: uint,
expr: &ast::Expr,
source_datum: Datum) -> DatumBlock {
let tcx = bcx.tcx();
let target_obj_ty = expr_ty_adjusted(bcx, expr);
debug!("auto_borrow_obj(target={})",
target_obj_ty.repr(tcx));
// Extract source store information
let (source_store, source_mutbl) = match ty::get(source_datum.ty).sty {
ty::ty_trait(_, _, s, m, _) => (s, m),
_ => {
bcx.sess().span_bug(
expr.span,
format!("auto_borrow_trait_obj expected a trait, found {}",
source_datum.ty.repr(bcx.tcx())));
}
};
// check if any borrowing is really needed or we could reuse the source_datum instead
match ty::get(target_obj_ty).sty {
ty::ty_trait(_, _, ty::RegionTraitStore(target_scope), target_mutbl, _) => {
if target_mutbl == ast::MutImmutable && target_mutbl == source_mutbl {
match source_store {
ty::RegionTraitStore(source_scope) => {
if tcx.region_maps.is_subregion_of(target_scope, source_scope) {
return DatumBlock { bcx: bcx, datum: source_datum };
}
},
_ => {}
};
}
},
_ => {}
}
let scratch = scratch_datum(bcx, target_obj_ty,
"__auto_borrow_obj", false);
// Convert a @Object, ~Object, or &Object pair into an &Object pair.
// Get a pointer to the source object, which is represented as
// a (vtable, data) pair.
let source_llval = source_datum.to_ref_llval(bcx);
// Set the vtable field of the new pair
let vtable_ptr = GEPi(bcx, source_llval, [0u, abi::trt_field_vtable]);
let vtable = Load(bcx, vtable_ptr);
Store(bcx, vtable, GEPi(bcx, scratch.val, [0u, abi::trt_field_vtable]));
// Load the data for the source, which is either an @T,
// ~T, or &T, depending on source_obj_ty.
let source_data_ptr = GEPi(bcx, source_llval, [0u, abi::trt_field_box]);
let source_data = Load(bcx, source_data_ptr); // always a ptr
let target_data = match source_store {
ty::BoxTraitStore(*) => {
// For deref of @T or @mut T, create a dummy datum and
// use the datum's deref method. This is more work
// than just calling GEPi ourselves, but it ensures
// that any write guards will be appropriate
// processed. Note that we don't know the type T, so
// just substitute `i8`-- it doesn't really matter for
// our purposes right now.
let source_ty =
ty::mk_box(tcx,
ty::mt {
ty: ty::mk_i8(),
mutbl: source_mutbl});
let source_datum =
Datum {val: source_data,
ty: source_ty,
mode: ByValue};
let derefd_datum =
unpack_datum!(bcx,
source_datum.deref(bcx,
expr,
autoderefs));
derefd_datum.to_rptr(bcx).to_value_llval(bcx)
}
ty::UniqTraitStore(*) => {
// For a ~T box, there may or may not be a header,
// depending on whether the type T references managed
// boxes. However, since we do not *know* the type T
// for objects, this presents a hurdle. Our solution is
// to load the "borrow offset" from the type descriptor;
// this value will either be 0 or sizeof(BoxHeader), depending
// on the type T.
let llopaque =
PointerCast(bcx, source_data, Type::opaque().ptr_to());
let lltydesc_ptr_ptr =
PointerCast(bcx, vtable,
bcx.ccx().tydesc_type.ptr_to().ptr_to());
let lltydesc_ptr =
Load(bcx, lltydesc_ptr_ptr);
let borrow_offset_ptr =
GEPi(bcx, lltydesc_ptr,
[0, abi::tydesc_field_borrow_offset]);
let borrow_offset =
Load(bcx, borrow_offset_ptr);
InBoundsGEP(bcx, llopaque, [borrow_offset])
}
ty::RegionTraitStore(*) => {
source_data
}
};
Store(bcx, target_data,
GEPi(bcx, scratch.val, [0u, abi::trt_field_box]));
DatumBlock { bcx: bcx, datum: scratch }
}
}
pub fn trans_into(bcx: @mut Block, expr: &ast::Expr, dest: Dest) -> @mut Block {
if bcx.tcx().adjustments.contains_key(&expr.id) {
// use trans_to_datum, which is mildly less efficient but
// which will perform the adjustments:
let datumblock = trans_to_datum(bcx, expr);
return match dest {
Ignore => datumblock.bcx,
SaveIn(lldest) => datumblock.store_to(INIT, lldest)
};
}
let ty = expr_ty(bcx, expr);
debug!("trans_into_unadjusted(expr={}, dest={})",
bcx.expr_to_str(expr),
dest.to_str(bcx.ccx()));
let _indenter = indenter();
debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
let dest = {
if ty::type_is_voidish(bcx.tcx(), ty) {
Ignore
} else {
dest
}
};
let kind = bcx.expr_kind(expr);
debug!("expr kind = {:?}", kind);
return match kind {
ty::LvalueExpr => {
let datumblock = trans_lvalue_unadjusted(bcx, expr);
match dest {
Ignore => datumblock.bcx,
SaveIn(lldest) => datumblock.store_to(INIT, lldest)
}
}
ty::RvalueDatumExpr => {
let datumblock = trans_rvalue_datum_unadjusted(bcx, expr);
match dest {
Ignore => datumblock.drop_val(),
// When processing an rvalue, the value will be newly
// allocated, so we always `move_to` so as not to
// unnecessarily inc ref counts and so forth:
SaveIn(lldest) => datumblock.move_to(INIT, lldest)
}
}
ty::RvalueDpsExpr => {
trans_rvalue_dps_unadjusted(bcx, expr, dest)
}
ty::RvalueStmtExpr => {
trans_rvalue_stmt_unadjusted(bcx, expr)
}
};
}
fn trans_lvalue(bcx: @mut Block, expr: &ast::Expr) -> DatumBlock {
/*!
*
* Translates an lvalue expression, always yielding a by-ref
* datum. Generally speaking you should call trans_to_datum()
* instead, but sometimes we call trans_lvalue() directly as a
* means of asserting that a particular expression is an lvalue. */
return match bcx.tcx().adjustments.find(&expr.id) {
None => trans_lvalue_unadjusted(bcx, expr),
Some(_) => {
bcx.sess().span_bug(
expr.span,
format!("trans_lvalue() called on an expression \
with adjustments"));
}
};
}
fn trans_to_datum_unadjusted(bcx: @mut Block, expr: &ast::Expr) -> DatumBlock {
/*!
* Translates an expression into a datum. If this expression
* is an rvalue, this will result in a temporary value being
* created. If you plan to store the value somewhere else,
* you should prefer `trans_into()` instead.
*/
let mut bcx = bcx;
debug!("trans_to_datum_unadjusted(expr={})", bcx.expr_to_str(expr));
let _indenter = indenter();
debuginfo::set_source_location(bcx.fcx, expr.id, expr.span);
match ty::expr_kind(bcx.tcx(), bcx.ccx().maps.method_map, expr) {
ty::LvalueExpr => {
return trans_lvalue_unadjusted(bcx, expr);
}
ty::RvalueDatumExpr => {
let datum = unpack_datum!(bcx, {
trans_rvalue_datum_unadjusted(bcx, expr)
});
datum.add_clean(bcx);
return DatumBlock {bcx: bcx, datum: datum};
}
ty::RvalueStmtExpr => {
bcx = trans_rvalue_stmt_unadjusted(bcx, expr);
return nil(bcx, expr_ty(bcx, expr));
}
ty::RvalueDpsExpr => {
let ty = expr_ty(bcx, expr);
if ty::type_is_voidish(bcx.tcx(), ty) {
bcx = trans_rvalue_dps_unadjusted(bcx, expr, Ignore);
return nil(bcx, ty);
} else {
let scratch = scratch_datum(bcx, ty, "", false);
bcx = trans_rvalue_dps_unadjusted(
bcx, expr, SaveIn(scratch.val));
// Note: this is not obviously a good idea. It causes
// immediate values to be loaded immediately after a
// return from a call or other similar expression,
// which in turn leads to alloca's having shorter
// lifetimes and hence larger stack frames. However,
// in turn it can lead to more register pressure.
// Still, in practice it seems to increase
// performance, since we have fewer problems with
// morestack churn.
let scratch = scratch.to_appropriate_datum(bcx);
scratch.add_clean(bcx);
return DatumBlock {bcx: bcx, datum: scratch};
}
}
}
fn nil(bcx: @mut Block, ty: ty::t) -> DatumBlock {
let datum = immediate_rvalue(C_nil(), ty);
DatumBlock {bcx: bcx, datum: datum}
}
}
fn trans_rvalue_datum_unadjusted(bcx: @mut Block, expr: &ast::Expr) -> DatumBlock {
let _icx = push_ctxt("trans_rvalue_datum_unadjusted");
trace_span!(bcx, expr.span, shorten(bcx.expr_to_str(expr)));
match expr.node {
ast::ExprPath(_) | ast::ExprSelf => {
return trans_def_datum_unadjusted(bcx, expr, bcx.def(expr.id));
}
ast::ExprVstore(contents, ast::ExprVstoreBox) |
ast::ExprVstore(contents, ast::ExprVstoreMutBox) => {
return tvec::trans_uniq_or_managed_vstore(bcx, heap_managed,
expr, contents);
}
ast::ExprVstore(contents, ast::ExprVstoreUniq) => {
let heap = heap_for_unique(bcx, expr_ty(bcx, contents));
return tvec::trans_uniq_or_managed_vstore(bcx, heap,
expr, contents);
}
ast::ExprLit(lit) => {
return trans_immediate_lit(bcx, expr, *lit);
}
ast::ExprBinary(_, op, lhs, rhs) => {
// if overloaded, would be RvalueDpsExpr
assert!(!bcx.ccx().maps.method_map.contains_key(&expr.id));
return trans_binary(bcx, expr, op, lhs, rhs);
}
ast::ExprUnary(_, op, x) => {
return trans_unary_datum(bcx, expr, op, x);
}
ast::ExprAddrOf(_, x) => {
return trans_addr_of(bcx, expr, x);
}
ast::ExprCast(val, _) => {
return trans_imm_cast(bcx, val, expr.id);
}
ast::ExprParen(e) => {
return trans_rvalue_datum_unadjusted(bcx, e);
}
ast::ExprLogLevel => {
return trans_log_level(bcx);
}
_ => {
bcx.tcx().sess.span_bug(
expr.span,
format!("trans_rvalue_datum_unadjusted reached \
fall-through case: {:?}",
expr.node));
}
}
}
fn trans_rvalue_stmt_unadjusted(bcx: @mut Block, expr: &ast::Expr) -> @mut Block {
let mut bcx = bcx;
let _icx = push_ctxt("trans_rvalue_stmt");
if bcx.unreachable {
return bcx;
}
trace_span!(bcx, expr.span, shorten(bcx.expr_to_str(expr)));
match expr.node {
ast::ExprBreak(label_opt) => {
return controlflow::trans_break(bcx, label_opt);
}
ast::ExprAgain(label_opt) => {
return controlflow::trans_cont(bcx, label_opt);
}
ast::ExprRet(ex) => {
return controlflow::trans_ret(bcx, ex);
}
ast::ExprWhile(cond, ref body) => {
return controlflow::trans_while(bcx, cond, body);
}
ast::ExprLoop(ref body, opt_label) => {
// FIXME #6993: map can go away when ast.rs is changed
return controlflow::trans_loop(bcx, body, opt_label.map(|x| x.name));
}
ast::ExprAssign(dst, src) => {
let src_datum = unpack_datum!(
bcx, trans_to_datum(bcx, src));
let dst_datum = unpack_datum!(
bcx, trans_lvalue(bcx, dst));
return src_datum.store_to_datum(
bcx, DROP_EXISTING, dst_datum);
}
ast::ExprAssignOp(callee_id, op, dst, src) => {
return trans_assign_op(bcx, expr, callee_id, op, dst, src);
}
ast::ExprParen(a) => {
return trans_rvalue_stmt_unadjusted(bcx, a);
}
ast::ExprInlineAsm(ref a) => {
return asm::trans_inline_asm(bcx, a);
}
_ => {
bcx.tcx().sess.span_bug(
expr.span,
format!("trans_rvalue_stmt_unadjusted reached \
fall-through case: {:?}",
expr.node));
}
};
}
fn trans_rvalue_dps_unadjusted(bcx: @mut Block, expr: &ast::Expr,
dest: Dest) -> @mut Block {
let _icx = push_ctxt("trans_rvalue_dps_unadjusted");
let tcx = bcx.tcx();
trace_span!(bcx, expr.span, shorten(bcx.expr_to_str(expr)));
match expr.node {
ast::ExprParen(e) => {
return trans_rvalue_dps_unadjusted(bcx, e, dest);
}
ast::ExprPath(_) | ast::ExprSelf => {
return trans_def_dps_unadjusted(bcx, expr,
bcx.def(expr.id), dest);
}
ast::ExprIf(cond, ref thn, els) => {
return controlflow::trans_if(bcx, cond, thn, els, dest);
}
ast::ExprMatch(discr, ref arms) => {
return _match::trans_match(bcx, expr, discr, *arms, dest);
}
ast::ExprBlock(ref blk) => {
return do base::with_scope(bcx, blk.info(),
"block-expr body") |bcx| {
controlflow::trans_block(bcx, blk, dest)
};
}
ast::ExprStruct(_, ref fields, base) => {
return trans_rec_or_struct(bcx, (*fields), base, expr.span, expr.id, dest);
}
ast::ExprTup(ref args) => {
let repr = adt::represent_type(bcx.ccx(), expr_ty(bcx, expr));
let numbered_fields: ~[(uint, @ast::Expr)] =
args.iter().enumerate().map(|(i, arg)| (i, *arg)).collect();
return trans_adt(bcx, repr, 0, numbered_fields, None, dest);
}
ast::ExprLit(@codemap::Spanned {node: ast::lit_str(s, _), _}) => {
return tvec::trans_lit_str(bcx, expr, s, dest);
}
ast::ExprVstore(contents, ast::ExprVstoreSlice) |
ast::ExprVstore(contents, ast::ExprVstoreMutSlice) => {
return tvec::trans_slice_vstore(bcx, expr, contents, dest);
}
ast::ExprVec(*) | ast::ExprRepeat(*) => {
return tvec::trans_fixed_vstore(bcx, expr, expr, dest);
}
ast::ExprFnBlock(ref decl, ref body) => {
let expr_ty = expr_ty(bcx, expr);
let sigil = ty::ty_closure_sigil(expr_ty);
debug!("translating fn_block {} with type {}",
expr_to_str(expr, tcx.sess.intr()),
expr_ty.repr(tcx));
return closure::trans_expr_fn(bcx, sigil, decl, body,
expr.id, expr.id, dest);
}
ast::ExprDoBody(blk) => {
return trans_into(bcx, blk, dest);
}
ast::ExprCall(f, ref args, _) => {
return callee::trans_call(
bcx, expr, f, callee::ArgExprs(*args), expr.id, dest);
}
ast::ExprMethodCall(callee_id, rcvr, _, _, ref args, _) => {
return callee::trans_method_call(bcx,
expr,
callee_id,
rcvr,
callee::ArgExprs(*args),
dest);
}
ast::ExprBinary(callee_id, _, lhs, rhs) => {
// if not overloaded, would be RvalueDatumExpr
return trans_overloaded_op(bcx,
expr,
callee_id,
lhs,
~[rhs],
expr_ty(bcx, expr),
dest);
}
ast::ExprUnary(callee_id, _, subexpr) => {
// if not overloaded, would be RvalueDatumExpr
return trans_overloaded_op(bcx,
expr,
callee_id,
subexpr,
~[],
expr_ty(bcx, expr),
dest);
}
ast::ExprIndex(callee_id, base, idx) => {
// if not overloaded, would be RvalueDatumExpr
return trans_overloaded_op(bcx,
expr,
callee_id,
base,
~[idx],
expr_ty(bcx, expr),
dest);
}
ast::ExprCast(val, _) => {
match ty::get(node_id_type(bcx, expr.id)).sty {
ty::ty_trait(_, _, store, _, _) => {
return meth::trans_trait_cast(bcx, val, expr.id, dest,
store);
}
_ => {
bcx.tcx().sess.span_bug(expr.span,
"expr_cast of non-trait");
}
}
}
ast::ExprAssignOp(callee_id, op, dst, src) => {
return trans_assign_op(bcx, expr, callee_id, op, dst, src);
}
_ => {
bcx.tcx().sess.span_bug(
expr.span,
format!("trans_rvalue_dps_unadjusted reached fall-through case: {:?}",
expr.node));
}
}
}
fn trans_def_dps_unadjusted(bcx: @mut Block, ref_expr: &ast::Expr,
def: ast::Def, dest: Dest) -> @mut Block {
let _icx = push_ctxt("trans_def_dps_unadjusted");
let ccx = bcx.ccx();
let lldest = match dest {
SaveIn(lldest) => lldest,
Ignore => { return bcx; }
};
match def {
ast::DefVariant(tid, vid, _) => {
let variant_info = ty::enum_variant_with_id(ccx.tcx, tid, vid);
if variant_info.args.len() > 0u {
// N-ary variant.
let fn_data = callee::trans_fn_ref(bcx, vid, ref_expr.id);
Store(bcx, fn_data.llfn, lldest);
return bcx;
} else {
// Nullary variant.
let ty = expr_ty(bcx, ref_expr);
let repr = adt::represent_type(ccx, ty);
adt::trans_start_init(bcx, repr, lldest,
variant_info.disr_val);
return bcx;
}
}
ast::DefStruct(def_id) => {
let ty = expr_ty(bcx, ref_expr);
match ty::get(ty).sty {
ty::ty_struct(did, _) if ty::has_dtor(ccx.tcx, did) => {
let repr = adt::represent_type(ccx, ty);
adt::trans_start_init(bcx, repr, lldest, 0);
}
ty::ty_bare_fn(*) => {
let fn_data = callee::trans_fn_ref(bcx, def_id, ref_expr.id);
Store(bcx, fn_data.llfn, lldest);
}
_ => ()
}
return bcx;
}
_ => {
bcx.tcx().sess.span_bug(ref_expr.span, format!(
"Non-DPS def {:?} referened by {}",
def, bcx.node_id_to_str(ref_expr.id)));
}
}
}
fn trans_def_datum_unadjusted(bcx: @mut Block,
ref_expr: &ast::Expr,
def: ast::Def) -> DatumBlock
{
let _icx = push_ctxt("trans_def_datum_unadjusted");
let fn_data = match def {
ast::DefFn(did, _) |
ast::DefStaticMethod(did, ast::FromImpl(_), _) => {
callee::trans_fn_ref(bcx, did, ref_expr.id)
}
ast::DefStaticMethod(impl_did, ast::FromTrait(trait_did), _) => {
meth::trans_static_method_callee(bcx,
impl_did,
trait_did,
ref_expr.id)
}
_ => {
bcx.tcx().sess.span_bug(ref_expr.span, format!(
"Non-DPS def {:?} referened by {}",
def, bcx.node_id_to_str(ref_expr.id)));
}
};
let fn_ty = expr_ty(bcx, ref_expr);
DatumBlock {
bcx: bcx,
datum: Datum {
val: fn_data.llfn,
ty: fn_ty,
mode: ByValue
}
}
}
fn trans_lvalue_unadjusted(bcx: @mut Block, expr: &ast::Expr) -> DatumBlock {
/*!
*
* Translates an lvalue expression, always yielding a by-ref
* datum. Does not apply any adjustments. */
let _icx = push_ctxt("trans_lval");
let mut bcx = bcx;
debug!("trans_lvalue(expr={})", bcx.expr_to_str(expr));
let _indenter = indenter();
trace_span!(bcx, expr.span, shorten(bcx.expr_to_str(expr)));
return match expr.node {
ast::ExprParen(e) => {
trans_lvalue_unadjusted(bcx, e)
}
ast::ExprPath(_) | ast::ExprSelf => {
trans_def_lvalue(bcx, expr, bcx.def(expr.id))
}
ast::ExprField(base, ident, _) => {
trans_rec_field(bcx, base, ident)
}
ast::ExprIndex(_, base, idx) => {
trans_index(bcx, expr, base, idx)
}
ast::ExprUnary(_, ast::UnDeref, base) => {
let basedatum = unpack_datum!(bcx, trans_to_datum(bcx, base));
basedatum.deref(bcx, expr, 0)
}
_ => {
bcx.tcx().sess.span_bug(
expr.span,
format!("trans_lvalue reached fall-through case: {:?}",
expr.node));
}
};
fn trans_rec_field(bcx: @mut Block,
base: &ast::Expr,
field: ast::Ident) -> DatumBlock {
//! Translates `base.field`.
let mut bcx = bcx;
let _icx = push_ctxt("trans_rec_field");
let base_datum = unpack_datum!(bcx, trans_to_datum(bcx, base));
let repr = adt::represent_type(bcx.ccx(), base_datum.ty);
do with_field_tys(bcx.tcx(), base_datum.ty, None) |discr, field_tys| {
let ix = ty::field_idx_strict(bcx.tcx(), field.name, field_tys);
DatumBlock {
datum: do base_datum.get_element(bcx,
field_tys[ix].mt.ty,
ZeroMem) |srcval| {
adt::trans_field_ptr(bcx, repr, srcval, discr, ix)
},
bcx: bcx
}
}
}
fn trans_index(bcx: @mut Block,
index_expr: &ast::Expr,
base: &ast::Expr,
idx: &ast::Expr) -> DatumBlock {
//! Translates `base[idx]`.
let _icx = push_ctxt("trans_index");
let ccx = bcx.ccx();
let mut bcx = bcx;
let base_datum = unpack_datum!(bcx, trans_to_datum(bcx, base));
// Translate index expression and cast to a suitable LLVM integer.
// Rust is less strict than LLVM in this regard.
let Result {bcx, val: ix_val} = trans_to_datum(bcx, idx).to_result();
let ix_size = machine::llbitsize_of_real(bcx.ccx(), val_ty(ix_val));
let int_size = machine::llbitsize_of_real(bcx.ccx(), ccx.int_type);
let ix_val = {
if ix_size < int_size {
if ty::type_is_signed(expr_ty(bcx, idx)) {
SExt(bcx, ix_val, ccx.int_type)
} else { ZExt(bcx, ix_val, ccx.int_type) }
} else if ix_size > int_size {
Trunc(bcx, ix_val, ccx.int_type)
} else {
ix_val
}
};
let vt = tvec::vec_types(bcx, base_datum.ty);
base::maybe_name_value(bcx.ccx(), vt.llunit_size, "unit_sz");
let (bcx, base, len) =
base_datum.get_vec_base_and_len(bcx, index_expr.span, index_expr.id, 0);
debug!("trans_index: base {}", bcx.val_to_str(base));
debug!("trans_index: len {}", bcx.val_to_str(len));
let bounds_check = ICmp(bcx, lib::llvm::IntUGE, ix_val, len);
let expect = ccx.intrinsics.get_copy(&("llvm.expect.i1"));
let expected = Call(bcx, expect, [bounds_check, C_i1(false)], []);
let bcx = do with_cond(bcx, expected) |bcx| {
controlflow::trans_fail_bounds_check(bcx, index_expr.span, ix_val, len)
};
let elt = InBoundsGEP(bcx, base, [ix_val]);
let elt = PointerCast(bcx, elt, vt.llunit_ty.ptr_to());
return DatumBlock {
bcx: bcx,
datum: Datum {val: elt,
ty: vt.unit_ty,
mode: ByRef(ZeroMem)}
};
}
fn trans_def_lvalue(bcx: @mut Block,
ref_expr: &ast::Expr,