forked from rust-lang/rust
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase.rs
2867 lines (2606 loc) · 102 KB
/
base.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.
// trans.rs: Translate the completed AST to the LLVM IR.
//
// Some functions here, such as trans_block and trans_expr, return a value --
// the result of the translation to LLVM -- while others, such as trans_fn,
// trans_impl, and trans_item, are called only for the side effect of adding a
// particular definition to the LLVM IR output we're producing.
//
// Hopefully useful general knowledge about trans:
//
// * There's no way to find out the ty::t type of a ValueRef. Doing so
// would be "trying to get the eggs out of an omelette" (credit:
// pcwalton). You can, instead, find out its TypeRef by calling val_ty,
// but many TypeRefs correspond to one ty::t; for instance, tup(int, int,
// int) and rec(x=int, y=int, z=int) will have the same TypeRef.
use back::link::{mangle_exported_name};
use back::link::{mangle_internal_name_by_path_and_seq};
use back::link::{mangle_internal_name_by_path};
use back::link::{mangle_internal_name_by_seq};
use back::link::{mangle_internal_name_by_type_only};
use back::{link, abi, upcall};
use driver::session;
use driver::session::Session;
use lib::llvm::{ModuleRef, ValueRef, TypeRef, BasicBlockRef};
use lib::llvm::{True, False};
use lib::llvm::{llvm, mk_target_data, mk_type_names};
use metadata::common::link_meta;
use metadata::{csearch, cstore, decoder, encoder};
use middle::pat_util::*;
use middle::trans::build::*;
use middle::trans::common::*;
use middle::trans::shape::*;
use middle::trans::type_of::*;
use util::common::indenter;
use util::common::is_main_name;
use util::ppaux::{ty_to_str, ty_to_short_str};
use util::ppaux;
use core::libc::{c_uint, c_ulonglong};
use core::option::{is_none, is_some};
use std::map::HashMap;
use std::smallintmap;
use std::{map, time, list};
use syntax::ast_map::{path, path_mod, path_name};
use syntax::ast_util::{def_id_of_def, local_def, path_to_ident};
use syntax::attr;
use syntax::codemap::span;
use syntax::diagnostic::expect;
use syntax::parse::token::special_idents;
use syntax::print::pprust::{expr_to_str, stmt_to_str, path_to_str};
use syntax::visit;
use syntax::visit::vt;
use syntax::{ast, ast_util, codemap, ast_map};
struct icx_popper {
ccx: @crate_ctxt,
drop {
if self.ccx.sess.count_llvm_insns() {
self.ccx.stats.llvm_insn_ctxt.pop();
}
}
}
fn icx_popper(ccx: @crate_ctxt) -> icx_popper {
icx_popper {
ccx: ccx
}
}
trait get_insn_ctxt {
fn insn_ctxt(s: &str) -> icx_popper;
}
impl @crate_ctxt: get_insn_ctxt {
fn insn_ctxt(s: &str) -> icx_popper {
debug!("new insn_ctxt: %s", s);
if self.sess.count_llvm_insns() {
self.stats.llvm_insn_ctxt.push(str::from_slice(s));
}
icx_popper(self)
}
}
impl block: get_insn_ctxt {
fn insn_ctxt(s: &str) -> icx_popper {
self.ccx().insn_ctxt(s)
}
}
impl fn_ctxt: get_insn_ctxt {
fn insn_ctxt(s: &str) -> icx_popper {
self.ccx.insn_ctxt(s)
}
}
fn log_fn_time(ccx: @crate_ctxt, name: ~str, start: time::Timespec,
end: time::Timespec) {
let elapsed = 1000 * ((end.sec - start.sec) as int) +
((end.nsec as int) - (start.nsec as int)) / 1000000;
ccx.stats.fn_times.push({ident: name, time: elapsed});
}
fn decl_fn(llmod: ModuleRef, name: ~str, cc: lib::llvm::CallConv,
llty: TypeRef) -> ValueRef {
let llfn: ValueRef = str::as_c_str(name, |buf| {
llvm::LLVMGetOrInsertFunction(llmod, buf, llty)
});
lib::llvm::SetFunctionCallConv(llfn, cc);
return llfn;
}
fn decl_cdecl_fn(llmod: ModuleRef, name: ~str, llty: TypeRef) -> ValueRef {
return decl_fn(llmod, name, lib::llvm::CCallConv, llty);
}
// Only use this if you are going to actually define the function. It's
// not valid to simply declare a function as internal.
fn decl_internal_cdecl_fn(llmod: ModuleRef, name: ~str, llty: TypeRef) ->
ValueRef {
let llfn = decl_cdecl_fn(llmod, name, llty);
lib::llvm::SetLinkage(llfn, lib::llvm::InternalLinkage);
return llfn;
}
fn get_extern_fn(externs: HashMap<~str, ValueRef>,
llmod: ModuleRef, name: ~str,
cc: lib::llvm::CallConv, ty: TypeRef) -> ValueRef {
if externs.contains_key(name) { return externs.get(name); }
let f = decl_fn(llmod, name, cc, ty);
externs.insert(name, f);
return f;
}
fn get_extern_const(externs: HashMap<~str, ValueRef>, llmod: ModuleRef,
name: ~str, ty: TypeRef) -> ValueRef {
if externs.contains_key(name) { return externs.get(name); }
let c = str::as_c_str(name, |buf| llvm::LLVMAddGlobal(llmod, ty, buf));
externs.insert(name, c);
return c;
}
fn get_simple_extern_fn(cx: block,
externs: HashMap<~str, ValueRef>,
llmod: ModuleRef,
name: ~str, n_args: int) -> ValueRef {
let _icx = cx.insn_ctxt("get_simple_extern_fn");
let ccx = cx.fcx.ccx;
let inputs = vec::from_elem(n_args as uint, ccx.int_type);
let output = ccx.int_type;
let t = T_fn(inputs, output);
return get_extern_fn(externs, llmod, name, lib::llvm::CCallConv, t);
}
fn trans_foreign_call(cx: block, externs: HashMap<~str, ValueRef>,
llmod: ModuleRef, name: ~str, args: ~[ValueRef]) ->
ValueRef {
let _icx = cx.insn_ctxt("trans_foreign_call");
let n = args.len() as int;
let llforeign: ValueRef =
get_simple_extern_fn(cx, externs, llmod, name, n);
return Call(cx, llforeign, args);
}
fn umax(cx: block, a: ValueRef, b: ValueRef) -> ValueRef {
let _icx = cx.insn_ctxt("umax");
let cond = ICmp(cx, lib::llvm::IntULT, a, b);
return Select(cx, cond, b, a);
}
fn umin(cx: block, a: ValueRef, b: ValueRef) -> ValueRef {
let _icx = cx.insn_ctxt("umin");
let cond = ICmp(cx, lib::llvm::IntULT, a, b);
return Select(cx, cond, a, b);
}
// Given a pointer p, returns a pointer sz(p) (i.e., inc'd by sz bytes).
// The type of the returned pointer is always i8*. If you care about the
// return type, use bump_ptr().
fn ptr_offs(bcx: block, base: ValueRef, sz: ValueRef) -> ValueRef {
let _icx = bcx.insn_ctxt("ptr_offs");
let raw = PointerCast(bcx, base, T_ptr(T_i8()));
InBoundsGEP(bcx, raw, ~[sz])
}
// Increment a pointer by a given amount and then cast it to be a pointer
// to a given type.
fn bump_ptr(bcx: block, t: ty::t, base: ValueRef, sz: ValueRef) ->
ValueRef {
let _icx = bcx.insn_ctxt("bump_ptr");
let ccx = bcx.ccx();
let bumped = ptr_offs(bcx, base, sz);
let typ = T_ptr(type_of(ccx, t));
PointerCast(bcx, bumped, typ)
}
// Replacement for the LLVM 'GEP' instruction when field indexing into a enum.
// @llblobptr is the data part of a enum value; its actual type
// is meaningless, as it will be cast away.
fn GEP_enum(bcx: block, llblobptr: ValueRef, enum_id: ast::def_id,
variant_id: ast::def_id, ty_substs: ~[ty::t],
ix: uint) -> ValueRef {
let _icx = bcx.insn_ctxt("GEP_enum");
let ccx = bcx.ccx();
let variant = ty::enum_variant_with_id(ccx.tcx, enum_id, variant_id);
assert ix < variant.args.len();
let arg_lltys = vec::map(variant.args, |aty| {
type_of(ccx, ty::subst_tps(ccx.tcx, ty_substs, None, *aty))
});
let typed_blobptr = PointerCast(bcx, llblobptr,
T_ptr(T_struct(arg_lltys)));
GEPi(bcx, typed_blobptr, [0u, ix])
}
// Returns a pointer to the body for the box. The box may be an opaque
// box. The result will be casted to the type of body_t, if it is statically
// known.
//
// The runtime equivalent is box_body() in "rust_internal.h".
fn opaque_box_body(bcx: block,
body_t: ty::t,
boxptr: ValueRef) -> ValueRef {
let _icx = bcx.insn_ctxt("opaque_box_body");
let ccx = bcx.ccx();
let boxptr = PointerCast(bcx, boxptr, T_ptr(T_box_header(ccx)));
let bodyptr = GEPi(bcx, boxptr, [1u]);
PointerCast(bcx, bodyptr, T_ptr(type_of(ccx, body_t)))
}
// malloc_raw_dyn: allocates a box to contain a given type, but with a
// potentially dynamic size.
fn malloc_raw_dyn(bcx: block, t: ty::t, heap: heap,
size: ValueRef) -> Result {
let _icx = bcx.insn_ctxt("malloc_raw");
let ccx = bcx.ccx();
let (mk_fn, rtcall) = match heap {
heap_shared => (ty::mk_imm_box, ~"malloc"),
heap_exchange => (ty::mk_imm_uniq, ~"exchange_malloc")
};
// Grab the TypeRef type of box_ptr_ty.
let box_ptr_ty = mk_fn(bcx.tcx(), t);
let llty = type_of(ccx, box_ptr_ty);
// Get the tydesc for the body:
let static_ti = get_tydesc(ccx, t);
glue::lazily_emit_all_tydesc_glue(ccx, static_ti);
// Allocate space:
let tydesc = PointerCast(bcx, static_ti.tydesc, T_ptr(T_i8()));
let rval = alloca_zeroed(bcx, T_ptr(T_i8()));
let bcx = callee::trans_rtcall(bcx, rtcall, ~[tydesc, size],
expr::SaveIn(rval));
return rslt(bcx, PointerCast(bcx, Load(bcx, rval), llty));
}
/**
* Get the type of a box in the default address space.
*
* Shared box pointers live in address space 1 so the GC strategy can find
* them. Before taking a pointer to the inside of a box it should be cast into
* address space 0. Otherwise the resulting (non-box) pointer will be in the
* wrong address space and thus be the wrong type.
*/
fn non_gc_box_cast(bcx: block, val: ValueRef) -> ValueRef {
debug!("non_gc_box_cast");
add_comment(bcx, ~"non_gc_box_cast");
assert(llvm::LLVMGetPointerAddressSpace(val_ty(val)) == gc_box_addrspace
|| bcx.unreachable);
let non_gc_t = T_ptr(llvm::LLVMGetElementType(val_ty(val)));
PointerCast(bcx, val, non_gc_t)
}
// malloc_raw: expects an unboxed type and returns a pointer to
// enough space for a box of that type. This includes a rust_opaque_box
// header.
fn malloc_raw(bcx: block, t: ty::t, heap: heap) -> Result {
malloc_raw_dyn(bcx, t, heap, llsize_of(bcx.ccx(), type_of(bcx.ccx(), t)))
}
// malloc_general_dyn: usefully wraps malloc_raw_dyn; allocates a box,
// and pulls out the body
fn malloc_general_dyn(bcx: block, t: ty::t, heap: heap, size: ValueRef)
-> {bcx: block, box: ValueRef, body: ValueRef} {
let _icx = bcx.insn_ctxt("malloc_general");
let Result {bcx: bcx, val: llbox} = malloc_raw_dyn(bcx, t, heap, size);
let non_gc_box = non_gc_box_cast(bcx, llbox);
let body = GEPi(bcx, non_gc_box, [0u, abi::box_field_body]);
return {bcx: bcx, box: llbox, body: body};
}
fn malloc_general(bcx: block, t: ty::t, heap: heap)
-> {bcx: block, box: ValueRef, body: ValueRef} {
malloc_general_dyn(bcx, t, heap,
llsize_of(bcx.ccx(), type_of(bcx.ccx(), t)))
}
fn malloc_boxed(bcx: block, t: ty::t)
-> {bcx: block, box: ValueRef, body: ValueRef} {
malloc_general(bcx, t, heap_shared)
}
fn malloc_unique(bcx: block, t: ty::t)
-> {bcx: block, box: ValueRef, body: ValueRef} {
malloc_general(bcx, t, heap_exchange)
}
// Type descriptor and type glue stuff
fn get_tydesc_simple(ccx: @crate_ctxt, t: ty::t) -> ValueRef {
get_tydesc(ccx, t).tydesc
}
fn get_tydesc(ccx: @crate_ctxt, t: ty::t) -> @tydesc_info {
match ccx.tydescs.find(t) {
Some(inf) => inf,
_ => {
ccx.stats.n_static_tydescs += 1u;
let inf = glue::declare_tydesc(ccx, t);
ccx.tydescs.insert(t, inf);
inf
}
}
}
fn set_no_inline(f: ValueRef) {
llvm::LLVMAddFunctionAttr(f, lib::llvm::NoInlineAttribute as c_ulonglong,
0u as c_ulonglong);
}
fn set_no_unwind(f: ValueRef) {
llvm::LLVMAddFunctionAttr(f, lib::llvm::NoUnwindAttribute as c_ulonglong,
0u as c_ulonglong);
}
// Tell LLVM to emit the information necessary to unwind the stack for the
// function f.
fn set_uwtable(f: ValueRef) {
llvm::LLVMAddFunctionAttr(f, lib::llvm::UWTableAttribute as c_ulonglong,
0u as c_ulonglong);
}
fn set_inline_hint(f: ValueRef) {
llvm::LLVMAddFunctionAttr(f, lib::llvm::InlineHintAttribute
as c_ulonglong, 0u as c_ulonglong);
}
fn set_inline_hint_if_appr(attrs: ~[ast::attribute],
llfn: ValueRef) {
match attr::find_inline_attr(attrs) {
attr::ia_hint => set_inline_hint(llfn),
attr::ia_always => set_always_inline(llfn),
attr::ia_never => set_no_inline(llfn),
attr::ia_none => { /* fallthrough */ }
}
}
fn set_always_inline(f: ValueRef) {
llvm::LLVMAddFunctionAttr(f, lib::llvm::AlwaysInlineAttribute
as c_ulonglong, 0u as c_ulonglong);
}
fn set_custom_stack_growth_fn(f: ValueRef) {
llvm::LLVMAddFunctionAttr(f, 0u as c_ulonglong, 1u as c_ulonglong);
}
fn set_glue_inlining(f: ValueRef, t: ty::t) {
if ty::type_is_structural(t) {
set_no_inline(f);
} else { set_always_inline(f); }
}
// Double-check that we never ask LLVM to declare the same symbol twice. It
// silently mangles such symbols, breaking our linkage model.
fn note_unique_llvm_symbol(ccx: @crate_ctxt, sym: ~str) {
if ccx.all_llvm_symbols.contains_key(sym) {
ccx.sess.bug(~"duplicate LLVM symbol: " + sym);
}
ccx.all_llvm_symbols.insert(sym, ());
}
fn get_res_dtor(ccx: @crate_ctxt, did: ast::def_id,
parent_id: ast::def_id, substs: ~[ty::t])
-> ValueRef {
let _icx = ccx.insn_ctxt("trans_res_dtor");
if (substs.is_not_empty()) {
let did = if did.crate != ast::local_crate {
inline::maybe_instantiate_inline(ccx, did, true)
} else { did };
assert did.crate == ast::local_crate;
monomorphize::monomorphic_fn(ccx, did, substs, None, None, None).val
} else if did.crate == ast::local_crate {
get_item_val(ccx, did.node)
} else {
let tcx = ccx.tcx;
let name = csearch::get_symbol(ccx.sess.cstore, did);
let class_ty = ty::subst_tps(tcx, substs, None,
ty::lookup_item_type(tcx, parent_id).ty);
let llty = type_of_dtor(ccx, class_ty);
get_extern_fn(ccx.externs, ccx.llmod, name, lib::llvm::CCallConv,
llty)
}
}
// Structural comparison: a rather involved form of glue.
fn maybe_name_value(cx: @crate_ctxt, v: ValueRef, s: ~str) {
if cx.sess.opts.save_temps {
let _: () = str::as_c_str(s, |buf| llvm::LLVMSetValueName(v, buf));
}
}
// Used only for creating scalar comparison glue.
enum scalar_type { nil_type, signed_int, unsigned_int, floating_point, }
fn compare_scalar_types(cx: block, lhs: ValueRef, rhs: ValueRef,
t: ty::t, op: ast::binop) -> Result {
let f = |a| compare_scalar_values(cx, lhs, rhs, a, op);
match ty::get(t).sty {
ty::ty_nil => rslt(cx, f(nil_type)),
ty::ty_bool | ty::ty_ptr(_) => rslt(cx, f(unsigned_int)),
ty::ty_int(_) => rslt(cx, f(signed_int)),
ty::ty_uint(_) => rslt(cx, f(unsigned_int)),
ty::ty_float(_) => rslt(cx, f(floating_point)),
ty::ty_type => {
rslt(
controlflow::trans_fail(
cx, None,
~"attempt to compare values of type type"),
C_nil())
}
_ => {
// Should never get here, because t is scalar.
cx.sess().bug(~"non-scalar type passed to \
compare_scalar_types")
}
}
}
// A helper function to do the actual comparison of scalar values.
fn compare_scalar_values(cx: block, lhs: ValueRef, rhs: ValueRef,
nt: scalar_type, op: ast::binop) -> ValueRef {
let _icx = cx.insn_ctxt("compare_scalar_values");
fn die_(cx: block) -> ! {
cx.tcx().sess.bug(~"compare_scalar_values: must be a\
comparison operator");
}
let die = fn@() -> ! { die_(cx) };
match nt {
nil_type => {
// We don't need to do actual comparisons for nil.
// () == () holds but () < () does not.
match op {
ast::eq | ast::le | ast::ge => return C_bool(true),
ast::ne | ast::lt | ast::gt => return C_bool(false),
// refinements would be nice
_ => die()
}
}
floating_point => {
let cmp = match op {
ast::eq => lib::llvm::RealOEQ,
ast::ne => lib::llvm::RealUNE,
ast::lt => lib::llvm::RealOLT,
ast::le => lib::llvm::RealOLE,
ast::gt => lib::llvm::RealOGT,
ast::ge => lib::llvm::RealOGE,
_ => die()
};
return FCmp(cx, cmp, lhs, rhs);
}
signed_int => {
let cmp = match op {
ast::eq => lib::llvm::IntEQ,
ast::ne => lib::llvm::IntNE,
ast::lt => lib::llvm::IntSLT,
ast::le => lib::llvm::IntSLE,
ast::gt => lib::llvm::IntSGT,
ast::ge => lib::llvm::IntSGE,
_ => die()
};
return ICmp(cx, cmp, lhs, rhs);
}
unsigned_int => {
let cmp = match op {
ast::eq => lib::llvm::IntEQ,
ast::ne => lib::llvm::IntNE,
ast::lt => lib::llvm::IntULT,
ast::le => lib::llvm::IntULE,
ast::gt => lib::llvm::IntUGT,
ast::ge => lib::llvm::IntUGE,
_ => die()
};
return ICmp(cx, cmp, lhs, rhs);
}
}
}
type val_pair_fn = fn@(block, ValueRef, ValueRef) -> block;
type val_and_ty_fn = fn@(block, ValueRef, ty::t) -> block;
fn load_inbounds(cx: block, p: ValueRef, idxs: &[uint]) -> ValueRef {
return Load(cx, GEPi(cx, p, idxs));
}
fn store_inbounds(cx: block, v: ValueRef, p: ValueRef, idxs: &[uint]) {
Store(cx, v, GEPi(cx, p, idxs));
}
// Iterates through the elements of a structural type.
fn iter_structural_ty(cx: block, av: ValueRef, t: ty::t,
f: val_and_ty_fn) -> block {
let _icx = cx.insn_ctxt("iter_structural_ty");
fn iter_variant(cx: block, a_tup: ValueRef,
variant: ty::VariantInfo,
tps: ~[ty::t], tid: ast::def_id,
f: val_and_ty_fn) -> block {
let _icx = cx.insn_ctxt("iter_variant");
if variant.args.len() == 0u { return cx; }
let fn_ty = variant.ctor_ty;
let ccx = cx.ccx();
let mut cx = cx;
match ty::get(fn_ty).sty {
ty::ty_fn(ref fn_ty) => {
let mut j = 0u;
let v_id = variant.id;
for vec::each(fn_ty.sig.inputs) |a| {
let llfldp_a = GEP_enum(cx, a_tup, tid, v_id, tps, j);
// XXX: Is "None" right here?
let ty_subst = ty::subst_tps(ccx.tcx, tps, None, a.ty);
cx = f(cx, llfldp_a, ty_subst);
j += 1u;
}
}
_ => cx.tcx().sess.bug(~"iter_variant: not a function type")
}
return cx;
}
/*
Typestate constraint that shows the unimpl case doesn't happen?
*/
let mut cx = cx;
match ty::get(t).sty {
ty::ty_rec(*) | ty::ty_struct(*) => {
do expr::with_field_tys(cx.tcx(), t, None) |_has_dtor, field_tys| {
for vec::eachi(field_tys) |i, field_ty| {
let llfld_a = GEPi(cx, av, struct_field(i));
cx = f(cx, llfld_a, field_ty.mt.ty);
}
}
}
ty::ty_estr(ty::vstore_fixed(_)) |
ty::ty_evec(_, ty::vstore_fixed(_)) => {
let (base, len) = tvec::get_base_and_len(cx, av, t);
cx = tvec::iter_vec_raw(cx, base, t, len, f);
}
ty::ty_tup(args) => {
for vec::eachi(args) |i, arg| {
let llfld_a = GEPi(cx, av, [0u, i]);
cx = f(cx, llfld_a, *arg);
}
}
ty::ty_enum(tid, ref substs) => {
let variants = ty::enum_variants(cx.tcx(), tid);
let n_variants = (*variants).len();
// Cast the enums to types we can GEP into.
if n_variants == 1u {
return iter_variant(cx, av, variants[0],
(*substs).tps, tid, f);
}
let ccx = cx.ccx();
let llenumty = T_opaque_enum_ptr(ccx);
let av_enum = PointerCast(cx, av, llenumty);
let lldiscrim_a_ptr = GEPi(cx, av_enum, [0u, 0u]);
let llunion_a_ptr = GEPi(cx, av_enum, [0u, 1u]);
let lldiscrim_a = Load(cx, lldiscrim_a_ptr);
// NB: we must hit the discriminant first so that structural
// comparison know not to proceed when the discriminants differ.
cx = f(cx, lldiscrim_a_ptr, ty::mk_int(cx.tcx()));
let unr_cx = sub_block(cx, ~"enum-iter-unr");
Unreachable(unr_cx);
let llswitch = Switch(cx, lldiscrim_a, unr_cx.llbb, n_variants);
let next_cx = sub_block(cx, ~"enum-iter-next");
for vec::each(*variants) |variant| {
let variant_cx =
sub_block(cx,
~"enum-iter-variant-" +
int::to_str(variant.disr_val, 10u));
AddCase(llswitch, C_int(ccx, variant.disr_val), variant_cx.llbb);
let variant_cx =
iter_variant(variant_cx, llunion_a_ptr, *variant,
(*substs).tps, tid, f);
Br(variant_cx, next_cx.llbb);
}
return next_cx;
}
_ => cx.sess().unimpl(~"type in iter_structural_ty")
}
return cx;
}
fn cast_shift_expr_rhs(cx: block, op: ast::binop,
lhs: ValueRef, rhs: ValueRef) -> ValueRef {
cast_shift_rhs(op, lhs, rhs,
|a,b| Trunc(cx, a, b),
|a,b| ZExt(cx, a, b))
}
fn cast_shift_const_rhs(op: ast::binop,
lhs: ValueRef, rhs: ValueRef) -> ValueRef {
cast_shift_rhs(op, lhs, rhs,
llvm::LLVMConstTrunc, llvm::LLVMConstZExt)
}
fn cast_shift_rhs(op: ast::binop,
lhs: ValueRef, rhs: ValueRef,
trunc: fn(ValueRef, TypeRef) -> ValueRef,
zext: fn(ValueRef, TypeRef) -> ValueRef
) -> ValueRef {
// Shifts may have any size int on the rhs
if ast_util::is_shift_binop(op) {
let rhs_llty = val_ty(rhs);
let lhs_llty = val_ty(lhs);
let rhs_sz = llvm::LLVMGetIntTypeWidth(rhs_llty);
let lhs_sz = llvm::LLVMGetIntTypeWidth(lhs_llty);
if lhs_sz < rhs_sz {
trunc(rhs, lhs_llty)
} else if lhs_sz > rhs_sz {
// FIXME (#1877: If shifting by negative
// values becomes not undefined then this is wrong.
zext(rhs, lhs_llty)
} else {
rhs
}
} else {
rhs
}
}
fn fail_if_zero(cx: block, span: span, divmod: ast::binop,
rhs: ValueRef, rhs_t: ty::t) -> block {
let text = if divmod == ast::div {
~"divide by zero"
} else {
~"modulo zero"
};
let is_zero = match ty::get(rhs_t).sty {
ty::ty_int(t) => {
let zero = C_integral(T_int_ty(cx.ccx(), t), 0u64, False);
ICmp(cx, lib::llvm::IntEQ, rhs, zero)
}
ty::ty_uint(t) => {
let zero = C_integral(T_uint_ty(cx.ccx(), t), 0u64, False);
ICmp(cx, lib::llvm::IntEQ, rhs, zero)
}
_ => {
cx.tcx().sess.bug(~"fail-if-zero on unexpected type: " +
ty_to_str(cx.ccx().tcx, rhs_t));
}
};
do with_cond(cx, is_zero) |bcx| {
controlflow::trans_fail(bcx, Some(span), text)
}
}
fn null_env_ptr(bcx: block) -> ValueRef {
C_null(T_opaque_box_ptr(bcx.ccx()))
}
fn trans_external_path(ccx: @crate_ctxt, did: ast::def_id, t: ty::t)
-> ValueRef {
let name = csearch::get_symbol(ccx.sess.cstore, did);
match ty::get(t).sty {
ty::ty_fn(_) => {
let llty = type_of_fn_from_ty(ccx, t);
return get_extern_fn(ccx.externs, ccx.llmod, name,
lib::llvm::CCallConv, llty);
}
_ => {
let llty = type_of(ccx, t);
return get_extern_const(ccx.externs, ccx.llmod, name, llty);
}
};
}
fn lookup_discriminant(ccx: @crate_ctxt, vid: ast::def_id) -> ValueRef {
let _icx = ccx.insn_ctxt("lookup_discriminant");
match ccx.discrims.find(vid) {
None => {
// It's an external discriminant that we haven't seen yet.
assert (vid.crate != ast::local_crate);
let sym = csearch::get_symbol(ccx.sess.cstore, vid);
let gvar = str::as_c_str(sym, |buf| {
llvm::LLVMAddGlobal(ccx.llmod, ccx.int_type, buf)
});
lib::llvm::SetLinkage(gvar, lib::llvm::ExternalLinkage);
llvm::LLVMSetGlobalConstant(gvar, True);
ccx.discrims.insert(vid, gvar);
return gvar;
}
Some(llval) => return llval,
}
}
fn invoke(bcx: block, llfn: ValueRef, llargs: ~[ValueRef]) -> block {
let _icx = bcx.insn_ctxt("invoke_");
if bcx.unreachable { return bcx; }
if need_invoke(bcx) {
log(debug, ~"invoking");
let normal_bcx = sub_block(bcx, ~"normal return");
Invoke(bcx, llfn, llargs, normal_bcx.llbb, get_landing_pad(bcx));
return normal_bcx;
} else {
log(debug, ~"calling");
Call(bcx, llfn, llargs);
return bcx;
}
}
fn need_invoke(bcx: block) -> bool {
if (bcx.ccx().sess.opts.debugging_opts & session::no_landing_pads != 0) {
return false;
}
// Avoid using invoke if we are already inside a landing pad.
if bcx.is_lpad {
return false;
}
if have_cached_lpad(bcx) {
return true;
}
// Walk the scopes to look for cleanups
let mut cur = bcx;
loop {
match cur.kind {
block_scope(ref inf) => {
for vec::each((*inf).cleanups) |cleanup| {
match *cleanup {
clean(_, cleanup_type) | clean_temp(_, _, cleanup_type) => {
if cleanup_type == normal_exit_and_unwind {
return true;
}
}
}
}
}
_ => ()
}
cur = match cur.parent {
Some(next) => next,
None => return false
}
}
}
fn have_cached_lpad(bcx: block) -> bool {
let mut res = false;
do in_lpad_scope_cx(bcx) |inf| {
match inf.landing_pad {
Some(_) => res = true,
None => res = false
}
}
return res;
}
fn in_lpad_scope_cx(bcx: block, f: fn(scope_info)) {
let mut bcx = bcx;
loop {
match bcx.kind {
block_scope(ref inf) => {
if (*inf).cleanups.len() > 0u || bcx.parent.is_none() {
f((*inf)); return;
}
}
_ => ()
}
bcx = block_parent(bcx);
}
}
fn get_landing_pad(bcx: block) -> BasicBlockRef {
let _icx = bcx.insn_ctxt("get_landing_pad");
let mut cached = None, pad_bcx = bcx; // Guaranteed to be set below
do in_lpad_scope_cx(bcx) |inf| {
// If there is a valid landing pad still around, use it
match copy inf.landing_pad {
Some(target) => cached = Some(target),
None => {
pad_bcx = lpad_block(bcx, ~"unwind");
inf.landing_pad = Some(pad_bcx.llbb);
}
}
}
// Can't return from block above
match cached { Some(b) => return b, None => () }
// The landing pad return type (the type being propagated). Not sure what
// this represents but it's determined by the personality function and
// this is what the EH proposal example uses.
let llretty = T_struct(~[T_ptr(T_i8()), T_i32()]);
// The exception handling personality function. This is the C++
// personality function __gxx_personality_v0, wrapped in our naming
// convention.
let personality = bcx.ccx().upcalls.rust_personality;
// The only landing pad clause will be 'cleanup'
let llretval = LandingPad(pad_bcx, llretty, personality, 1u);
// The landing pad block is a cleanup
SetCleanup(pad_bcx, llretval);
// Because we may have unwound across a stack boundary, we must call into
// the runtime to figure out which stack segment we are on and place the
// stack limit back into the TLS.
Call(pad_bcx, bcx.ccx().upcalls.reset_stack_limit, ~[]);
// We store the retval in a function-central alloca, so that calls to
// Resume can find it.
match copy bcx.fcx.personality {
Some(addr) => Store(pad_bcx, llretval, addr),
None => {
let addr = alloca(pad_bcx, val_ty(llretval));
bcx.fcx.personality = Some(addr);
Store(pad_bcx, llretval, addr);
}
}
// Unwind all parent scopes, and finish with a Resume instr
cleanup_and_leave(pad_bcx, None, None);
return pad_bcx.llbb;
}
// Arranges for the value found in `*root_loc` to be dropped once the scope
// associated with `scope_id` exits. This is used to keep boxes live when
// there are extant region pointers pointing at the interior.
//
// Note that `root_loc` is not the value itself but rather a pointer to the
// value. Generally it in alloca'd value. The reason for this is that the
// value is initialized in an inner block but may be freed in some outer
// block, so an SSA value that is valid in the inner block may not be valid in
// the outer block. In fact, the inner block may not even execute. Rather
// than generate the full SSA form, we just use an alloca'd value.
fn add_root_cleanup(bcx: block, scope_id: ast::node_id,
root_loc: ValueRef, ty: ty::t) {
debug!("add_root_cleanup(bcx=%s, scope_id=%d, root_loc=%s, ty=%s)",
bcx.to_str(), scope_id, val_str(bcx.ccx().tn, root_loc),
ppaux::ty_to_str(bcx.ccx().tcx, ty));
let bcx_scope = find_bcx_for_scope(bcx, scope_id);
add_clean_temp_mem(bcx_scope, root_loc, ty);
fn find_bcx_for_scope(bcx: block, scope_id: ast::node_id) -> block {
let mut bcx_sid = bcx;
loop {
bcx_sid = match bcx_sid.node_info {
Some({id, _}) if id == scope_id => {
return bcx_sid
}
_ => {
match bcx_sid.parent {
None => bcx.tcx().sess.bug(
fmt!("no enclosing scope with id %d", scope_id)),
Some(bcx_par) => bcx_par
}
}
}
}
}
}
fn do_spill(bcx: block, v: ValueRef, t: ty::t) -> ValueRef {
if ty::type_is_bot(t) {
return C_null(T_ptr(T_i8()));
}
let llptr = alloc_ty(bcx, t);
Store(bcx, v, llptr);
return llptr;
}
// Since this function does *not* root, it is the caller's responsibility to
// ensure that the referent is pointed to by a root.
// [Note-arg-mode]
// ++ mode is temporary, due to how borrowck treats enums. With hope,
// will go away anyway when we get rid of modes.
fn do_spill_noroot(++cx: block, v: ValueRef) -> ValueRef {
let llptr = alloca(cx, val_ty(v));
Store(cx, v, llptr);
return llptr;
}
fn spill_if_immediate(cx: block, v: ValueRef, t: ty::t) -> ValueRef {
let _icx = cx.insn_ctxt("spill_if_immediate");
if ty::type_is_immediate(t) { return do_spill(cx, v, t); }
return v;
}
fn load_if_immediate(cx: block, v: ValueRef, t: ty::t) -> ValueRef {
let _icx = cx.insn_ctxt("load_if_immediate");
if ty::type_is_immediate(t) { return Load(cx, v); }
return v;
}
fn trans_trace(bcx: block, sp_opt: Option<span>, trace_str: ~str) {
if !bcx.sess().trace() { return; }
let _icx = bcx.insn_ctxt("trans_trace");
add_comment(bcx, trace_str);
let V_trace_str = C_cstr(bcx.ccx(), trace_str);
let {V_filename, V_line} = match sp_opt {
Some(sp) => {
let sess = bcx.sess();
let loc = sess.parse_sess.cm.lookup_char_pos(sp.lo);
{V_filename: C_cstr(bcx.ccx(), loc.file.name),
V_line: loc.line as int}
}
None => {
{V_filename: C_cstr(bcx.ccx(), ~"<runtime>"),
V_line: 0}
}
};
let ccx = bcx.ccx();
let V_trace_str = PointerCast(bcx, V_trace_str, T_ptr(T_i8()));
let V_filename = PointerCast(bcx, V_filename, T_ptr(T_i8()));
let args = ~[V_trace_str, V_filename, C_int(ccx, V_line)];
Call(bcx, ccx.upcalls.trace, args);
}
fn build_return(bcx: block) {
let _icx = bcx.insn_ctxt("build_return");
Br(bcx, bcx.fcx.llreturn);
}
fn ignore_lhs(_bcx: block, local: @ast::local) -> bool {
match local.node.pat.node {
ast::pat_wild => true, _ => false
}
}
fn init_local(bcx: block, local: @ast::local) -> block {
debug!("init_local(bcx=%s, local.id=%?)",
bcx.to_str(), local.node.id);
let _indenter = indenter();
let _icx = bcx.insn_ctxt("init_local");
let ty = node_id_type(bcx, local.node.id);
debug!("ty=%s", bcx.ty_to_str(ty));
if ignore_lhs(bcx, local) {
// Handle let _ = e; just like e;
match local.node.init {
Some(init) => {
return expr::trans_into(bcx, init, expr::Ignore);
}
None => { return bcx; }
}
}
let llptr = match bcx.fcx.lllocals.find(local.node.id) {
Some(local_mem(v)) => v,
_ => { bcx.tcx().sess.span_bug(local.span,
~"init_local: Someone forgot to document why it's\
safe to assume local.node.init must be local_mem!");
}
};
let mut bcx = bcx;
match local.node.init {
Some(init) => {
bcx = expr::trans_into(bcx, init, expr::SaveIn(llptr));
}
_ => {
zero_mem(bcx, llptr, ty);
}
}
// Make a note to drop this slot on the way out.
debug!("adding clean for %?/%s to bcx=%s",
local.node.id, bcx.ty_to_str(ty),
bcx.to_str());
add_clean(bcx, llptr, ty);