-
Notifications
You must be signed in to change notification settings - Fork 24
/
expr.go
1489 lines (1386 loc) · 40.5 KB
/
expr.go
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 (c) 2024 The GoPlus Authors (goplus.org). All rights reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package ssa
import (
"bytes"
"fmt"
"go/constant"
"go/token"
"go/types"
"log"
"github.com/goplus/llgo/internal/abi"
"github.com/goplus/llvm"
)
// -----------------------------------------------------------------------------
type Expr struct {
impl llvm.Value
Type
}
var Nil Expr // Zero value is a nil Expr
// IsNil checks if the expression is nil or not.
func (v Expr) IsNil() bool {
return v.Type == nil
}
// Do evaluates the delay expression and returns the result.
func (v Expr) Do(b Builder) Expr {
switch vt := v.Type; vt.kind {
case vkPhisExpr:
e := vt.raw.Type.(*phisExprTy)
return b.aggregateValue(e.Type, e.phis...)
}
return v
}
// -----------------------------------------------------------------------------
type pyVarTy struct {
mod Expr
name string
}
func (p pyVarTy) Underlying() types.Type {
panic("don't call")
}
func (p pyVarTy) String() string {
return "pyVar"
}
func pyVarExpr(mod Expr, name string) Expr {
tvar := &aType{raw: rawType{&pyVarTy{mod, name}}, kind: vkPyVarRef}
return Expr{Type: tvar}
}
// -----------------------------------------------------------------------------
type phisExprTy struct {
phis []llvm.Value
Type
}
func (p phisExprTy) Underlying() types.Type {
panic("don't call")
}
func (p phisExprTy) String() string {
return "phisExpr"
}
func phisExpr(t Type, phis []llvm.Value) Expr {
tphi := &aType{raw: rawType{&phisExprTy{phis, t}}, kind: vkPhisExpr}
return Expr{Type: tphi}
}
// -----------------------------------------------------------------------------
// Null returns a null constant expression.
func (p Program) Null(t Type) Expr {
return Expr{llvm.ConstNull(t.ll), t}
}
// PyNull returns a null *PyObject constant expression.
func (p Program) PyNull() Expr {
return p.Null(p.PyObjectPtr())
}
// BoolVal returns a boolean constant expression.
func (p Program) BoolVal(v bool) Expr {
t := p.Bool()
var bv uint64
if v {
bv = 1
}
ret := llvm.ConstInt(t.ll, bv, v)
return Expr{ret, t}
}
// IntVal returns an integer constant expression.
func (p Program) IntVal(v uint64, t Type) Expr {
ret := llvm.ConstInt(t.ll, v, false)
return Expr{ret, t}
}
func (p Program) FloatVal(v float64, t Type) Expr {
ret := llvm.ConstFloat(t.ll, v)
return Expr{ret, t}
}
// Val returns a constant expression.
func (p Program) Val(v interface{}) Expr {
switch v := v.(type) {
case int:
return p.IntVal(uint64(v), p.Int())
case uintptr:
return p.IntVal(uint64(v), p.Uintptr())
case bool:
return p.BoolVal(v)
case float64:
t := p.Float64()
ret := llvm.ConstFloat(t.ll, v)
return Expr{ret, t}
}
panic("todo")
}
// Const returns a constant expression.
func (b Builder) Const(v constant.Value, typ Type) Expr {
prog := b.Prog
if v == nil {
return prog.Null(typ)
}
raw := typ.raw.Type
switch t := raw.(type) {
case *types.Basic:
kind := t.Kind()
switch {
case kind == types.Bool:
return prog.BoolVal(constant.BoolVal(v))
case kind >= types.Int && kind <= types.Int64:
if v, exact := constant.Int64Val(v); exact {
return prog.IntVal(uint64(v), typ)
}
case kind >= types.Uint && kind <= types.Uintptr:
if v, exact := constant.Uint64Val(v); exact {
return prog.IntVal(v, typ)
}
case kind == types.Float32 || kind == types.Float64:
if v, exact := constant.Float64Val(v); exact {
return prog.FloatVal(v, typ)
}
case kind == types.String:
return b.Str(constant.StringVal(v))
}
}
panic(fmt.Sprintf("unsupported Const: %v, %v", v, raw))
}
// SizeOf returns the size of a type.
func (b Builder) SizeOf(t Type, n ...int64) Expr {
prog := b.Prog
size := prog.SizeOf(t, n...)
return prog.IntVal(size, prog.Uintptr())
}
// CStr returns a c-style string constant expression.
func (b Builder) CStr(v string) Expr {
return Expr{llvm.CreateGlobalStringPtr(b.impl, v), b.Prog.CStr()}
}
// Str returns a Go string constant expression.
func (b Builder) Str(v string) (ret Expr) {
prog := b.Prog
cstr := b.CStr(v)
ret = b.InlineCall(b.Func.Pkg.rtFunc("NewString"), cstr, prog.Val(len(v)))
ret.Type = prog.String()
return
}
// -----------------------------------------------------------------------------
const (
mathOpBase = token.ADD
mathOpLast = token.REM
)
var mathOpToLLVM = []llvm.Opcode{
int(token.ADD-mathOpBase)<<2 | vkSigned: llvm.Add,
int(token.ADD-mathOpBase)<<2 | vkUnsigned: llvm.Add,
int(token.ADD-mathOpBase)<<2 | vkFloat: llvm.FAdd,
int(token.SUB-mathOpBase)<<2 | vkSigned: llvm.Sub,
int(token.SUB-mathOpBase)<<2 | vkUnsigned: llvm.Sub,
int(token.SUB-mathOpBase)<<2 | vkFloat: llvm.FSub,
int(token.MUL-mathOpBase)<<2 | vkSigned: llvm.Mul,
int(token.MUL-mathOpBase)<<2 | vkUnsigned: llvm.Mul,
int(token.MUL-mathOpBase)<<2 | vkFloat: llvm.FMul,
int(token.QUO-mathOpBase)<<2 | vkSigned: llvm.SDiv,
int(token.QUO-mathOpBase)<<2 | vkUnsigned: llvm.UDiv,
int(token.QUO-mathOpBase)<<2 | vkFloat: llvm.FDiv,
int(token.REM-mathOpBase)<<2 | vkSigned: llvm.SRem,
int(token.REM-mathOpBase)<<2 | vkUnsigned: llvm.URem,
int(token.REM-mathOpBase)<<2 | vkFloat: llvm.FRem,
}
func mathOpIdx(op token.Token, x valueKind) int {
return int(op-mathOpBase)<<2 | x
}
// ADD SUB MUL QUO REM + - * / %
func isMathOp(op token.Token) bool {
return op >= mathOpBase && op <= mathOpLast
}
const (
logicOpBase = token.AND
logicOpLast = token.AND_NOT
)
var logicOpToLLVM = []llvm.Opcode{
token.AND - logicOpBase: llvm.And,
token.OR - logicOpBase: llvm.Or,
token.XOR - logicOpBase: llvm.Xor,
token.SHL - logicOpBase: llvm.Shl,
token.SHR - logicOpBase: llvm.AShr, // Arithmetic Shift Right
}
// AND OR XOR SHL SHR AND_NOT & | ^ << >> &^
func isLogicOp(op token.Token) bool {
return op >= logicOpBase && op <= logicOpLast
}
const (
predOpBase = token.EQL
predOpLast = token.GEQ
)
var intPredOpToLLVM = []llvm.IntPredicate{
token.EQL - predOpBase: llvm.IntEQ,
token.NEQ - predOpBase: llvm.IntNE,
token.LSS - predOpBase: llvm.IntSLT,
token.LEQ - predOpBase: llvm.IntSLE,
token.GTR - predOpBase: llvm.IntSGT,
token.GEQ - predOpBase: llvm.IntSGE,
}
var uintPredOpToLLVM = []llvm.IntPredicate{
token.EQL - predOpBase: llvm.IntEQ,
token.NEQ - predOpBase: llvm.IntNE,
token.LSS - predOpBase: llvm.IntULT,
token.LEQ - predOpBase: llvm.IntULE,
token.GTR - predOpBase: llvm.IntUGT,
token.GEQ - predOpBase: llvm.IntUGE,
}
var floatPredOpToLLVM = []llvm.FloatPredicate{
token.EQL - predOpBase: llvm.FloatOEQ,
token.NEQ - predOpBase: llvm.FloatONE,
token.LSS - predOpBase: llvm.FloatOLT,
token.LEQ - predOpBase: llvm.FloatOLE,
token.GTR - predOpBase: llvm.FloatOGT,
token.GEQ - predOpBase: llvm.FloatOGE,
}
var boolPredOpToLLVM = []llvm.IntPredicate{
token.EQL - predOpBase: llvm.IntEQ,
token.NEQ - predOpBase: llvm.IntNE,
}
// EQL NEQ LSS LEQ GTR GEQ == != < <= < >=
func isPredOp(op token.Token) bool {
return op >= predOpBase && op <= predOpLast
}
// The BinOp instruction yields the result of binary operation (x op y).
// op can be:
// ADD SUB MUL QUO REM + - * / %
// AND OR XOR SHL SHR AND_NOT & | ^ << >> &^
// EQL NEQ LSS LEQ GTR GEQ == != < <= < >=
func (b Builder) BinOp(op token.Token, x, y Expr) Expr {
if debugInstr {
log.Printf("BinOp %d, %v, %v\n", op, x.impl, y.impl)
}
switch {
case isMathOp(op): // op: + - * / %
kind := x.kind
switch kind {
case vkString:
if op == token.ADD {
pkg := b.Func.Pkg
return Expr{b.InlineCall(pkg.rtFunc("StringCat"), x, y).impl, x.Type}
}
case vkComplex:
default:
idx := mathOpIdx(op, kind)
if llop := mathOpToLLVM[idx]; llop != 0 {
return Expr{llvm.CreateBinOp(b.impl, llop, x.impl, y.impl), x.Type}
}
}
case isLogicOp(op): // op: & | ^ << >> &^
switch op {
case token.AND_NOT:
return Expr{b.impl.CreateAnd(x.impl, b.impl.CreateNot(y.impl, ""), ""), x.Type}
case token.SHL, token.SHR:
if needsNegativeCheck(y) {
check := Expr{b.impl.CreateICmp(llvm.IntSLT, y.impl, llvm.ConstInt(y.ll, 0, false), ""), b.Prog.Bool()}
b.InlineCall(b.Func.Pkg.rtFunc("AssertNegativeShift"), check)
}
xsize, ysize := b.Prog.SizeOf(x.Type), b.Prog.SizeOf(y.Type)
if xsize != ysize {
y = b.Convert(x.Type, y)
}
overflows := b.impl.CreateICmp(llvm.IntUGE, y.impl, llvm.ConstInt(y.ll, xsize*8, false), "")
xzero := llvm.ConstInt(x.ll, 0, false)
if op == token.SHL {
rhs := b.impl.CreateShl(x.impl, y.impl, "")
return Expr{b.impl.CreateSelect(overflows, xzero, rhs, ""), x.Type}
} else {
if x.kind == vkSigned {
rhs := b.impl.CreateSelect(overflows, llvm.ConstInt(y.ll, 8*xsize-1, false), y.impl, "")
return Expr{b.impl.CreateAShr(x.impl, rhs, ""), x.Type}
} else {
rsh := b.impl.CreateLShr(x.impl, y.impl, "")
return Expr{b.impl.CreateSelect(overflows, xzero, rsh, ""), x.Type}
}
}
default:
llop := logicOpToLLVM[op-logicOpBase]
return Expr{llvm.CreateBinOp(b.impl, llop, x.impl, y.impl), x.Type}
}
case isPredOp(op): // op: == != < <= < >=
tret := b.Prog.Bool()
kind := x.kind
switch kind {
case vkSigned:
pred := intPredOpToLLVM[op-predOpBase]
return Expr{llvm.CreateICmp(b.impl, pred, x.impl, y.impl), tret}
case vkUnsigned, vkPtr:
pred := uintPredOpToLLVM[op-predOpBase]
return Expr{llvm.CreateICmp(b.impl, pred, x.impl, y.impl), tret}
case vkFloat:
pred := floatPredOpToLLVM[op-predOpBase]
return Expr{llvm.CreateFCmp(b.impl, pred, x.impl, y.impl), tret}
case vkBool:
pred := boolPredOpToLLVM[op-predOpBase]
return Expr{llvm.CreateICmp(b.impl, pred, x.impl, y.impl), tret}
case vkString, vkComplex:
panic("todo")
}
}
panic("todo")
}
// The UnOp instruction yields the result of (op x).
// ARROW is channel receive.
// MUL is pointer indirection (load).
// XOR is bitwise complement.
// SUB is negation.
// NOT is logical negation.
func (b Builder) UnOp(op token.Token, x Expr) (ret Expr) {
if debugInstr {
log.Printf("UnOp %v, %v\n", op, x.impl)
}
switch op {
case token.MUL:
return b.Load(x)
case token.SUB:
switch t := x.Type.raw.Underlying().(type) {
case *types.Basic:
ret.Type = x.Type
if t.Info()&types.IsInteger != 0 {
ret.impl = b.impl.CreateNeg(x.impl, "")
} else if t.Info()&types.IsFloat != 0 {
ret.impl = b.impl.CreateFNeg(x.impl, "")
} else {
panic("todo")
}
default:
panic("unreachable")
}
case token.NOT:
ret.Type = x.Type
ret.impl = b.impl.CreateNot(x.impl, "")
case token.XOR:
ret.Type = x.Type
ret.impl = b.impl.CreateXor(x.impl, llvm.ConstInt(x.Type.ll, ^uint64(0), false), "")
case token.ARROW:
panic("todo")
}
return
}
// -----------------------------------------------------------------------------
func checkExpr(v Expr, t types.Type, b Builder) Expr {
if t, ok := t.(*types.Struct); ok && isClosure(t) {
if v.kind != vkClosure {
return b.Func.Pkg.closureStub(b, t, v)
}
}
return v
}
func llvmParamsEx(data Expr, vals []Expr, params *types.Tuple, b Builder) (ret []llvm.Value) {
if data.IsNil() {
return llvmParams(0, vals, params, b)
}
ret = llvmParams(1, vals, params, b)
ret[0] = data.impl
return
}
func llvmParams(base int, vals []Expr, params *types.Tuple, b Builder) (ret []llvm.Value) {
n := params.Len()
if n > 0 {
ret = make([]llvm.Value, len(vals)+base)
for idx, v := range vals {
i := base + idx
if i < n {
v = checkExpr(v, params.At(i).Type(), b)
}
ret[i] = v.impl
}
}
return
}
func llvmFields(vals []Expr, t *types.Struct, b Builder) (ret []llvm.Value) {
n := t.NumFields()
if n > 0 {
ret = make([]llvm.Value, len(vals))
for i, v := range vals {
if i < n {
v = checkExpr(v, t.Field(i).Type(), b)
}
ret[i] = v.impl
}
}
return
}
func llvmDelayValues(f func(i int) Expr, n int) []llvm.Value {
ret := make([]llvm.Value, n)
for i := 0; i < n; i++ {
ret[i] = f(i).impl
}
return ret
}
func llvmBlocks(bblks []BasicBlock) []llvm.BasicBlock {
ret := make([]llvm.BasicBlock, len(bblks))
for i, v := range bblks {
ret[i] = v.impl
}
return ret
}
// Phi represents a phi node.
type Phi struct {
Expr
}
// AddIncoming adds incoming values to a phi node.
func (p Phi) AddIncoming(b Builder, bblks []BasicBlock, f func(i int) Expr) {
bs := llvmBlocks(bblks)
if p.kind != vkPhisExpr { // normal phi node
vs := llvmDelayValues(f, len(bblks))
p.impl.AddIncoming(vs, bs)
return
}
e := p.raw.Type.(*phisExprTy)
phis := e.phis
vals := make([][]llvm.Value, len(phis))
for iblk, blk := range bblks {
last := blk.impl.LastInstruction()
b.impl.SetInsertPointBefore(last)
impl := b.impl
val := f(iblk).impl
for i := range phis {
if iblk == 0 {
vals[i] = make([]llvm.Value, len(bblks))
}
vals[i][iblk] = llvm.CreateExtractValue(impl, val, i)
}
}
for i, phi := range phis {
phi.AddIncoming(vals[i], bs)
}
}
// Phi returns a phi node.
func (b Builder) Phi(t Type) Phi {
impl := b.impl
switch tund := t.raw.Type.Underlying().(type) {
case *types.Basic:
kind := tund.Kind()
switch kind {
case types.String:
prog := b.Prog
phis := make([]llvm.Value, 2)
phis[0] = llvm.CreatePHI(impl, prog.tyVoidPtr())
phis[1] = llvm.CreatePHI(impl, prog.tyInt())
return Phi{phisExpr(t, phis)}
}
case *types.Struct:
panic("todo")
}
phi := llvm.CreatePHI(impl, t.ll)
return Phi{Expr{phi, t}}
}
// -----------------------------------------------------------------------------
// Advance returns the pointer ptr advanced by offset.
func (b Builder) Advance(ptr Expr, offset Expr) Expr {
if debugInstr {
log.Printf("Advance %v, %v\n", ptr.impl, offset.impl)
}
var elem llvm.Type
var prog = b.Prog
switch t := ptr.raw.Type.(type) {
case *types.Basic: // void
elem = prog.tyInt8()
default:
elem = prog.rawType(t.(*types.Pointer).Elem()).ll
}
ret := llvm.CreateGEP(b.impl, elem, ptr.impl, []llvm.Value{offset.impl})
return Expr{ret, ptr.Type}
}
// Load returns the value at the pointer ptr.
func (b Builder) Load(ptr Expr) Expr {
if debugInstr {
log.Printf("Load %v\n", ptr.impl)
}
if ptr.kind == vkPyVarRef {
return b.pyLoad(ptr)
}
telem := b.Prog.Elem(ptr.Type)
return Expr{llvm.CreateLoad(b.impl, telem.ll, ptr.impl), telem}
}
// Store stores val at the pointer ptr.
func (b Builder) Store(ptr, val Expr) Builder {
raw := ptr.raw.Type
if debugInstr {
log.Printf("Store %v, %v, %v\n", raw, ptr.impl, val.impl)
}
val = checkExpr(val, raw.(*types.Pointer).Elem(), b)
b.impl.CreateStore(val.impl, ptr.impl)
return b
}
func (b Builder) aggregateAlloc(t Type, flds ...llvm.Value) llvm.Value {
prog := b.Prog
pkg := b.Func.Pkg
size := prog.SizeOf(t)
ptr := b.InlineCall(pkg.rtFunc("AllocU"), prog.IntVal(size, prog.Uintptr())).impl
tll := t.ll
impl := b.impl
for i, fld := range flds {
impl.CreateStore(fld, llvm.CreateStructGEP(impl, tll, ptr, i))
}
return ptr
}
// aggregateValue yields the value of the aggregate X with the fields
func (b Builder) aggregateValue(t Type, flds ...llvm.Value) Expr {
tll := t.ll
impl := b.impl
ptr := llvm.CreateAlloca(impl, tll)
for i, fld := range flds {
impl.CreateStore(fld, llvm.CreateStructGEP(impl, tll, ptr, i))
}
return Expr{llvm.CreateLoad(b.impl, tll, ptr), t}
}
// The MakeClosure instruction yields a closure value whose code is
// Fn and whose free variables' values are supplied by Bindings.
//
// Type() returns a (possibly named) *types.Signature.
//
// Example printed form:
//
// t0 = make closure anon@1.2 [x y z]
// t1 = make closure bound$(main.I).add [i]
func (b Builder) MakeClosure(fn Expr, bindings []Expr) Expr {
if debugInstr {
log.Printf("MakeClosure %v, %v\n", fn, bindings)
}
prog := b.Prog
tfn := fn.Type
sig := tfn.raw.Type.(*types.Signature)
tctx := sig.Params().At(0).Type().Underlying().(*types.Pointer).Elem().(*types.Struct)
flds := llvmFields(bindings, tctx, b)
data := b.aggregateAlloc(prog.rawType(tctx), flds...)
return b.aggregateValue(prog.Closure(tfn), fn.impl, data)
}
// The FieldAddr instruction yields the address of Field of *struct X.
//
// The field is identified by its index within the field list of the
// struct type of X.
//
// Dynamically, this instruction panics if X evaluates to a nil
// pointer.
//
// Type() returns a (possibly named) *types.Pointer.
//
// Example printed form:
//
// t1 = &t0.name [#1]
func (b Builder) FieldAddr(x Expr, idx int) Expr {
if debugInstr {
log.Printf("FieldAddr %v, %d\n", x.impl, idx)
}
prog := b.Prog
tstruc := prog.Elem(x.Type)
telem := prog.Field(tstruc, idx)
pt := prog.Pointer(telem)
return Expr{llvm.CreateStructGEP(b.impl, tstruc.ll, x.impl, idx), pt}
}
// The Field instruction yields the value of Field of struct X.
func (b Builder) Field(x Expr, idx int) Expr {
if debugInstr {
log.Printf("Field %v, %d\n", x.impl, idx)
}
return b.getField(x, idx)
}
func (b Builder) getField(x Expr, idx int) Expr {
tfld := b.Prog.Field(x.Type, idx)
fld := llvm.CreateExtractValue(b.impl, x.impl, idx)
return Expr{fld, tfld}
}
// StringData returns the data pointer of a string.
func (b Builder) StringData(x Expr) Expr {
if debugInstr {
log.Printf("StringData %v\n", x.impl)
}
prog := b.Prog
ptr := llvm.CreateExtractValue(b.impl, x.impl, 0)
return Expr{ptr, prog.CStr()}
}
// StringLen returns the length of a string.
func (b Builder) StringLen(x Expr) Expr {
if debugInstr {
log.Printf("StringLen %v\n", x.impl)
}
prog := b.Prog
ptr := llvm.CreateExtractValue(b.impl, x.impl, 1)
return Expr{ptr, prog.Int()}
}
// SliceData returns the data pointer of a slice.
func (b Builder) SliceData(x Expr) Expr {
if debugInstr {
log.Printf("SliceData %v\n", x.impl)
}
prog := b.Prog
ptr := llvm.CreateExtractValue(b.impl, x.impl, 0)
return Expr{ptr, prog.CStr()}
}
// SliceLen returns the length of a slice.
func (b Builder) SliceLen(x Expr) Expr {
if debugInstr {
log.Printf("SliceLen %v\n", x.impl)
}
prog := b.Prog
ptr := llvm.CreateExtractValue(b.impl, x.impl, 1)
return Expr{ptr, prog.Int()}
}
// SliceCap returns the length of a slice cap.
func (b Builder) SliceCap(x Expr) Expr {
if debugInstr {
log.Printf("SliceCap %v\n", x.impl)
}
prog := b.Prog
ptr := llvm.CreateExtractValue(b.impl, x.impl, 2)
return Expr{ptr, prog.Int()}
}
// The IndexAddr instruction yields the address of the element at
// index `idx` of collection `x`. `idx` is an integer expression.
//
// The elements of maps and strings are not addressable; use Lookup (map),
// Index (string), or MapUpdate instead.
//
// Dynamically, this instruction panics if `x` evaluates to a nil *array
// pointer.
//
// Example printed form:
//
// t2 = &t0[t1]
func (b Builder) IndexAddr(x, idx Expr) Expr {
if debugInstr {
log.Printf("IndexAddr %v, %v\n", x.impl, idx.impl)
}
idx = b.checkIndex(idx)
prog := b.Prog
telem := prog.Index(x.Type)
pt := prog.Pointer(telem)
switch x.raw.Type.Underlying().(type) {
case *types.Slice:
ptr := b.SliceData(x)
indices := []llvm.Value{idx.impl}
return Expr{llvm.CreateInBoundsGEP(b.impl, telem.ll, ptr.impl, indices), pt}
}
// case *types.Pointer:
indices := []llvm.Value{idx.impl}
return Expr{llvm.CreateInBoundsGEP(b.impl, telem.ll, x.impl, indices), pt}
}
func needsNegativeCheck(x Expr) bool {
if x.kind == vkSigned {
if rv := x.impl.IsAConstantInt(); !rv.IsNil() && rv.SExtValue() >= 0 {
return false
}
return true
}
return false
}
// check index >= 0 and size to uint
func (b Builder) checkIndex(idx Expr) Expr {
if needsNegativeCheck(idx) {
check := Expr{b.impl.CreateICmp(llvm.IntSLT, idx.impl, llvm.ConstInt(idx.ll, 0, false), ""), b.Prog.Bool()}
b.InlineCall(b.Func.Pkg.rtFunc("AssertIndexRange"), check)
}
typ := b.Prog.Uint()
if b.Prog.SizeOf(idx.Type) < b.Prog.SizeOf(typ) {
idx.Type = typ
idx.impl = castUintptr(b, idx.impl, typ)
}
return idx
}
// The Index instruction yields element Index of collection X, an array,
// string or type parameter containing an array, a string, a pointer to an,
// array or a slice.
//
// Example printed form:
//
// t2 = t0[t1]
func (b Builder) Index(x, idx Expr, addr func(Expr) Expr) Expr {
if debugInstr {
log.Printf("Index %v, %v\n", x.impl, idx.impl)
}
prog := b.Prog
var telem Type
var ptr Expr
switch t := x.raw.Type.Underlying().(type) {
case *types.Basic:
if t.Kind() != types.String {
panic(fmt.Errorf("invalid operation: cannot index %v", t))
}
telem = prog.rawType(types.Typ[types.Byte])
ptr = b.StringData(x)
case *types.Array:
telem = prog.Index(x.Type)
if addr != nil {
ptr = addr(x)
} else {
size := b.SizeOf(telem, t.Len())
ptr = b.Alloca(size)
b.Store(ptr, x)
}
}
idx = b.checkIndex(idx)
pt := prog.Pointer(telem)
indices := []llvm.Value{idx.impl}
buf := Expr{llvm.CreateInBoundsGEP(b.impl, telem.ll, ptr.impl, indices), pt}
return b.Load(buf)
}
// The Lookup instruction yields element Index of collection map X.
// Index is the appropriate key type.
//
// If CommaOk, the result is a 2-tuple of the value above and a
// boolean indicating the result of a map membership test for the key.
// The components of the tuple are accessed using Extract.
//
// Example printed form:
//
// t2 = t0[t1]
// t5 = t3[t4],ok
func (b Builder) Lookup(x, key Expr, commaOk bool) (ret Expr) {
if debugInstr {
log.Printf("Lookup %v, %v, %v\n", x.impl, key.impl, commaOk)
}
// TODO(xsw)
// panic("todo")
return
}
// The Slice instruction yields a slice of an existing string, slice
// or *array X between optional integer bounds Low and High.
//
// Dynamically, this instruction panics if X evaluates to a nil *array
// pointer.
//
// Type() returns string if the type of X was string, otherwise a
// *types.Slice with the same element type as X.
//
// Example printed form:
//
// t1 = slice t0[1:]
func (b Builder) Slice(x, low, high, max Expr) (ret Expr) {
if debugInstr {
log.Printf("Slice %v, %v, %v\n", x.impl, low.impl, high.impl)
}
prog := b.Prog
pkg := b.Func.Pkg
var nCap Expr
var nEltSize Expr
var base Expr
if low.IsNil() {
low = prog.IntVal(0, prog.Int())
}
switch t := x.raw.Type.Underlying().(type) {
case *types.Basic:
if t.Kind() != types.String {
panic(fmt.Errorf("invalid operation: cannot slice %v", t))
}
if high.IsNil() {
high = b.StringLen(x)
}
ret.Type = x.Type
ret.impl = b.InlineCall(pkg.rtFunc("NewStringSlice"), x, low, high).impl
return
case *types.Slice:
nEltSize = b.SizeOf(prog.Index(x.Type))
nCap = b.SliceCap(x)
if high.IsNil() {
high = b.SliceCap(x)
}
ret.Type = x.Type
base = b.SliceData(x)
case *types.Pointer:
telem := t.Elem()
switch te := telem.Underlying().(type) {
case *types.Array:
elem := prog.rawType(te.Elem())
ret.Type = prog.Slice(elem)
nEltSize = b.SizeOf(elem)
nCap = prog.IntVal(uint64(te.Len()), prog.Int())
if high.IsNil() {
high = nCap
}
base = x
}
}
if max.IsNil() {
max = nCap
}
ret.impl = b.InlineCall(pkg.rtFunc("NewSlice3"), base, nEltSize, nCap, low, high, max).impl
return
}
// -----------------------------------------------------------------------------
// The MakeMap instruction creates a new hash-table-based map object
// and yields a value of kind map.
//
// t is a (possibly named) *types.Map.
//
// Example printed form:
//
// t1 = make map[string]int t0
// t1 = make StringIntMap t0
func (b Builder) MakeMap(t Type, nReserve Expr) (ret Expr) {
if debugInstr {
log.Printf("MakeMap %v, %v\n", t.RawType(), nReserve.impl)
}
pkg := b.Func.Pkg
ret.Type = t
ret.impl = b.InlineCall(pkg.rtFunc("MakeSmallMap")).impl
// TODO(xsw): nReserve
return
}
// The MakeSlice instruction yields a slice of length Len backed by a
// newly allocated array of length Cap.
//
// Both Len and Cap must be non-nil Values of integer type.
//
// (Alloc(types.Array) followed by Slice will not suffice because
// Alloc can only create arrays of constant length.)
//
// Type() returns a (possibly named) *types.Slice.
//
// Example printed form:
//
// t1 = make []string 1:int t0
// t1 = make StringSlice 1:int t0
func (b Builder) MakeSlice(t Type, len, cap Expr) (ret Expr) {
if debugInstr {
log.Printf("MakeSlice %v, %v, %v\n", t.RawType(), len.impl, cap.impl)
}
pkg := b.Func.Pkg
if cap.IsNil() {
cap = len
}
elemSize := b.SizeOf(b.Prog.Index(t))
size := b.BinOp(token.MUL, cap, elemSize)
ptr := b.InlineCall(pkg.rtFunc("AllocZ"), size)
ret.impl = b.InlineCall(pkg.rtFunc("NewSlice"), ptr, len, cap).impl
ret.Type = t
return
}
// -----------------------------------------------------------------------------
// The Alloc instruction reserves space for a variable of the given type,
// zero-initializes it, and yields its address.
//
// If heap is false, Alloc zero-initializes the same local variable in
// the call frame and returns its address; in this case the Alloc must
// be present in Function.Locals. We call this a "local" alloc.
//
// If heap is true, Alloc allocates a new zero-initialized variable
// each time the instruction is executed. We call this a "new" alloc.
//
// When Alloc is applied to a channel, map or slice type, it returns
// the address of an uninitialized (nil) reference of that kind; store
// the result of MakeSlice, MakeMap or MakeChan in that location to
// instantiate these types.
//
// Example printed form:
//
// t0 = local int
// t1 = new int
func (b Builder) Alloc(elem Type, heap bool) (ret Expr) {
if debugInstr {
log.Printf("Alloc %v, %v\n", elem.RawType(), heap)
}
prog := b.Prog
pkg := b.Func.Pkg
size := b.SizeOf(elem)
if heap {
ret = b.InlineCall(pkg.rtFunc("AllocZ"), size)
} else {
ret = Expr{llvm.CreateAlloca(b.impl, elem.ll), prog.VoidPtr()}
ret.impl = b.InlineCall(pkg.rtFunc("Zeroinit"), ret, size).impl
}
ret.Type = prog.Pointer(elem)
return
}
// Alloca allocates space for n bytes.
func (b Builder) Alloca(n Expr) (ret Expr) {
if debugInstr {
log.Printf("Alloca %v\n", n.impl)
}
prog := b.Prog
telem := prog.tyInt8()
ret.impl = llvm.CreateArrayAlloca(b.impl, telem, n.impl)
ret.Type = prog.VoidPtr()
return
}
/*
// ArrayAlloca reserves space for an array of n elements of type telem.
func (b Builder) ArrayAlloca(telem Type, n Expr) (ret Expr) {
if debugInstr {
log.Printf("ArrayAlloca %v, %v\n", telem.t, n.impl)
}
ret.impl = llvm.CreateArrayAlloca(b.impl, telem.ll, n.impl)
ret.Type = b.Prog.Pointer(telem)
return
}
*/