forked from ldc-developers/ldc
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathctfeexpr.d
2045 lines (1924 loc) · 65.8 KB
/
ctfeexpr.d
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
/**
* CTFE for expressions involving pointers, slices, array concatenation etc.
*
* Copyright: Copyright (C) 1999-2024 by The D Language Foundation, All Rights Reserved
* Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
* License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
* Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/ctfeexpr.d, _ctfeexpr.d)
* Documentation: https://dlang.org/phobos/dmd_ctfeexpr.html
* Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/ctfeexpr.d
*/
module dmd.ctfeexpr;
import core.stdc.stdio;
import core.stdc.string;
import dmd.arraytypes;
import dmd.astenums;
import dmd.constfold;
import dmd.compiler;
import dmd.dcast : implicitConvTo;
import dmd.dclass;
import dmd.declaration;
import dmd.dinterpret;
import dmd.dstruct;
import dmd.dtemplate;
import dmd.errors;
import dmd.expression;
import dmd.func;
import dmd.globals;
import dmd.location;
import dmd.mtype;
import dmd.root.bitarray;
import dmd.root.complex;
import dmd.root.ctfloat;
import dmd.root.port;
import dmd.root.rmem;
import dmd.tokens;
import dmd.typesem;
import dmd.visitor;
/****************************************************************/
/* A type meant as a union of all the Expression types,
* to serve essentially as a Variant that will sit on the stack
* during CTFE to reduce memory consumption.
*/
extern (D) struct UnionExp
{
// yes, default constructor does nothing
extern (D) this(Expression e) nothrow
{
memcpy(&this, cast(void*)e, e.size);
}
/* Extract pointer to Expression
*/
extern (D) Expression exp() return nothrow
{
return cast(Expression)&u;
}
/* Convert to an allocated Expression
*/
extern (D) Expression copy()
{
Expression e = exp();
//if (e.size > sizeof(u)) printf("%s\n", EXPtoString(e.op).ptr);
assert(e.size <= u.sizeof);
switch (e.op)
{
case EXP.cantExpression: return CTFEExp.cantexp;
case EXP.voidExpression: return CTFEExp.voidexp;
case EXP.break_: return CTFEExp.breakexp;
case EXP.continue_: return CTFEExp.continueexp;
case EXP.goto_: return CTFEExp.gotoexp;
default: return e.copy();
}
}
private:
// Ensure that the union is suitably aligned.
align(8) union _AnonStruct_u
{
char[__traits(classInstanceSize, Expression)] exp;
char[__traits(classInstanceSize, IntegerExp)] integerexp;
char[__traits(classInstanceSize, ErrorExp)] errorexp;
char[__traits(classInstanceSize, RealExp)] realexp;
char[__traits(classInstanceSize, ComplexExp)] complexexp;
char[__traits(classInstanceSize, SymOffExp)] symoffexp;
char[__traits(classInstanceSize, StringExp)] stringexp;
char[__traits(classInstanceSize, ArrayLiteralExp)] arrayliteralexp;
char[__traits(classInstanceSize, AssocArrayLiteralExp)] assocarrayliteralexp;
char[__traits(classInstanceSize, StructLiteralExp)] structliteralexp;
char[__traits(classInstanceSize, CompoundLiteralExp)] compoundliteralexp;
char[__traits(classInstanceSize, NullExp)] nullexp;
char[__traits(classInstanceSize, DotVarExp)] dotvarexp;
char[__traits(classInstanceSize, AddrExp)] addrexp;
char[__traits(classInstanceSize, IndexExp)] indexexp;
char[__traits(classInstanceSize, SliceExp)] sliceexp;
char[__traits(classInstanceSize, VectorExp)] vectorexp;
}
_AnonStruct_u u;
}
void emplaceExp(T : Expression, Args...)(void* p, Args args)
{
static if (__VERSION__ < 2099)
const init = typeid(T).initializer;
else
const init = __traits(initSymbol, T);
p[0 .. __traits(classInstanceSize, T)] = init[];
(cast(T)p).__ctor(args);
}
void emplaceExp(T : UnionExp)(T* p, Expression e) nothrow
{
memcpy(p, cast(void*)e, e.size);
}
// Generate an error message when this exception is not caught
void generateUncaughtError(ThrownExceptionExp tee)
{
UnionExp ue = void;
Expression e = resolveSlice((*tee.thrown.value.elements)[0], &ue);
StringExp se = e.toStringExp();
error(tee.thrown.loc, "uncaught CTFE exception `%s(%s)`", tee.thrown.type.toChars(), se ? se.toChars() : e.toChars());
/* Also give the line where the throw statement was. We won't have it
* in the case where the ThrowStatement is generated internally
* (eg, in ScopeStatement)
*/
if (tee.loc.isValid() && !tee.loc.equals(tee.thrown.loc))
.errorSupplemental(tee.loc, "thrown from here");
}
/*************************
* Same as getFieldIndex, but checks for a direct match with the VarDeclaration
* Returns:
* index of the field, or -1 if not found
*/
int findFieldIndexByName(const StructDeclaration sd, const VarDeclaration v) pure @safe nothrow
{
foreach (i, field; sd.fields)
{
if (field == v)
return cast(int)i;
}
return -1;
}
// True if 'e' is CTFEExp::cantexp, or an exception
bool exceptionOrCantInterpret(const Expression e) @safe nothrow
{
return e && (e.op == EXP.cantExpression || e.op == EXP.thrownException || e.op == EXP.showCtfeContext);
}
/************** Aggregate literals (AA/string/array/struct) ******************/
// Given expr, which evaluates to an array/AA/string literal,
// return true if it needs to be copied
bool needToCopyLiteral(const Expression expr) nothrow
{
Expression e = cast()expr;
for (;;)
{
switch (e.op)
{
case EXP.arrayLiteral:
return e.isArrayLiteralExp().ownedByCtfe == OwnedBy.code;
case EXP.assocArrayLiteral:
return e.isAssocArrayLiteralExp().ownedByCtfe == OwnedBy.code;
case EXP.structLiteral:
return e.isStructLiteralExp().ownedByCtfe == OwnedBy.code;
case EXP.string_:
case EXP.this_:
case EXP.variable:
return false;
case EXP.assign:
return false;
case EXP.index:
case EXP.dotVariable:
case EXP.slice:
case EXP.cast_:
e = e.isUnaExp().e1;
continue;
case EXP.concatenate:
return needToCopyLiteral(e.isBinExp().e1) || needToCopyLiteral(e.isBinExp().e2);
case EXP.concatenateAssign:
case EXP.concatenateElemAssign:
case EXP.concatenateDcharAssign:
e = e.isBinExp().e2;
continue;
default:
return false;
}
}
}
private Expressions* copyLiteralArray(Expressions* oldelems, Expression basis = null)
{
if (!oldelems)
return oldelems;
incArrayAllocs();
auto newelems = new Expressions(oldelems.length);
foreach (i, el; *oldelems)
{
(*newelems)[i] = copyLiteral(el ? el : basis).copy();
}
return newelems;
}
// Make a copy of the ArrayLiteral, AALiteral, String, or StructLiteral.
// This value will be used for in-place modification.
UnionExp copyLiteral(Expression e)
{
UnionExp ue = void;
if (auto se = e.isStringExp()) // syntaxCopy doesn't make a copy for StringExp!
{
char* s = cast(char*)mem.xcalloc(se.len + 1, se.sz);
const slice = se.peekData();
memcpy(s, slice.ptr, slice.length);
emplaceExp!(StringExp)(&ue, se.loc, s[0 .. se.len * se.sz], se.len, se.sz);
StringExp se2 = ue.exp().isStringExp();
se2.committed = se.committed;
se2.postfix = se.postfix;
se2.type = se.type;
se2.ownedByCtfe = OwnedBy.ctfe;
return ue;
}
if (auto ale = e.isArrayLiteralExp())
{
auto elements = copyLiteralArray(ale.elements, ale.basis);
emplaceExp!(ArrayLiteralExp)(&ue, e.loc, e.type, elements);
ArrayLiteralExp r = ue.exp().isArrayLiteralExp();
r.ownedByCtfe = OwnedBy.ctfe;
return ue;
}
if (auto aae = e.isAssocArrayLiteralExp())
{
emplaceExp!(AssocArrayLiteralExp)(&ue, aae.loc, copyLiteralArray(aae.keys), copyLiteralArray(aae.values));
AssocArrayLiteralExp r = ue.exp().isAssocArrayLiteralExp();
r.type = aae.type;
r.lowering = aae.lowering;
r.ownedByCtfe = OwnedBy.ctfe;
return ue;
}
if (auto sle = e.isStructLiteralExp())
{
/* syntaxCopy doesn't work for struct literals, because of a nasty special
* case: block assignment is permitted inside struct literals, eg,
* an int[4] array can be initialized with a single int.
*/
auto oldelems = sle.elements;
auto newelems = new Expressions(oldelems.length);
foreach (i, ref el; *newelems)
{
// We need the struct definition to detect block assignment
auto v = sle.sd.fields[i];
auto m = (*oldelems)[i];
// If it is a void assignment, use the default initializer
if (!m)
m = voidInitLiteral(v.type, v).copy();
if (v.type.ty == Tarray || v.type.ty == Taarray)
{
// Don't have to copy array references
}
else
{
// Buzilla 15681: Copy the source element always.
m = copyLiteral(m).copy();
// Block assignment from inside struct literals
if (v.type.ty != m.type.ty && v.type.ty == Tsarray)
{
auto tsa = v.type.isTypeSArray();
auto len = cast(size_t)tsa.dim.toInteger();
m = createBlockDuplicatedArrayLiteral(&ue, e.loc, v.type, m, len);
if (m == ue.exp())
m = ue.copy();
}
}
el = m;
}
emplaceExp!(StructLiteralExp)(&ue, e.loc, sle.sd, newelems, sle.stype);
auto r = ue.exp().isStructLiteralExp();
r.type = e.type;
r.ownedByCtfe = OwnedBy.ctfe;
r.origin = sle.origin;
return ue;
}
switch(e.op)
{
case EXP.function_:
case EXP.delegate_:
case EXP.symbolOffset:
case EXP.null_:
case EXP.variable:
case EXP.dotVariable:
case EXP.int64:
case EXP.float64:
case EXP.complex80:
case EXP.void_:
case EXP.vector:
case EXP.typeid_:
// Simple value types
// Keep e1 for DelegateExp and DotVarExp
emplaceExp!(UnionExp)(&ue, e);
Expression r = ue.exp();
r.type = e.type;
return ue;
default: break;
}
if (auto se = e.isSliceExp())
{
if (se.type.toBasetype().ty == Tsarray)
{
// same with resolveSlice()
if (se.e1.op == EXP.null_)
{
emplaceExp!(NullExp)(&ue, se.loc, se.type);
return ue;
}
ue = Slice(se.type, se.e1, se.lwr, se.upr);
auto r = ue.exp().isArrayLiteralExp();
r.elements = copyLiteralArray(r.elements);
r.ownedByCtfe = OwnedBy.ctfe;
return ue;
}
else
{
// Array slices only do a shallow copy
emplaceExp!(SliceExp)(&ue, e.loc, se.e1, se.lwr, se.upr);
Expression r = ue.exp();
r.type = e.type;
return ue;
}
}
if (isPointer(e.type))
{
// For pointers, we only do a shallow copy.
if (auto ae = e.isAddrExp())
emplaceExp!(AddrExp)(&ue, e.loc, ae.e1);
else if (auto ie = e.isIndexExp())
emplaceExp!(IndexExp)(&ue, e.loc, ie.e1, ie.e2);
else if (auto dve = e.isDotVarExp())
{
emplaceExp!(DotVarExp)(&ue, e.loc, dve.e1, dve.var, dve.hasOverloads);
}
else
assert(0);
Expression r = ue.exp();
r.type = e.type;
return ue;
}
if (auto cre = e.isClassReferenceExp())
{
emplaceExp!(ClassReferenceExp)(&ue, e.loc, cre.value, e.type);
return ue;
}
if (e.op == EXP.error)
{
emplaceExp!(UnionExp)(&ue, e);
return ue;
}
error(e.loc, "CTFE internal error: literal `%s`", e.toChars());
assert(0);
}
/* Deal with type painting.
* Type painting is a major nuisance: we can't just set
* e.type = type, because that would change the original literal.
* But, we can't simply copy the literal either, because that would change
* the values of any pointers.
*/
Expression paintTypeOntoLiteral(Type type, Expression lit)
{
if (lit.type.equals(type))
return lit;
return paintTypeOntoLiteralCopy(type, lit).copy();
}
Expression paintTypeOntoLiteral(UnionExp* pue, Type type, Expression lit)
{
if (lit.type.equals(type))
return lit;
*pue = paintTypeOntoLiteralCopy(type, lit);
return pue.exp();
}
private UnionExp paintTypeOntoLiteralCopy(Type type, Expression lit)
{
UnionExp ue;
if (lit.type.equals(type))
{
emplaceExp!(UnionExp)(&ue, lit);
return ue;
}
// If it is a cast to inout, retain the original type of the referenced part.
if (type.hasWild())
{
emplaceExp!(UnionExp)(&ue, lit);
ue.exp().type = type;
return ue;
}
if (auto se = lit.isSliceExp())
{
emplaceExp!(SliceExp)(&ue, lit.loc, se.e1, se.lwr, se.upr);
}
else if (auto ie = lit.isIndexExp())
{
emplaceExp!(IndexExp)(&ue, lit.loc, ie.e1, ie.e2);
}
else if (lit.op == EXP.arrayLiteral)
{
emplaceExp!(SliceExp)(&ue, lit.loc, lit, ctfeEmplaceExp!IntegerExp(Loc.initial, 0, Type.tsize_t), ArrayLength(Type.tsize_t, lit).copy());
}
else if (lit.op == EXP.string_)
{
// For strings, we need to introduce another level of indirection
emplaceExp!(SliceExp)(&ue, lit.loc, lit, ctfeEmplaceExp!IntegerExp(Loc.initial, 0, Type.tsize_t), ArrayLength(Type.tsize_t, lit).copy());
}
else if (auto aae = lit.isAssocArrayLiteralExp())
{
// TODO: we should be creating a reference to this AAExp, not
// just a ref to the keys and values.
OwnedBy wasOwned = aae.ownedByCtfe;
emplaceExp!(AssocArrayLiteralExp)(&ue, lit.loc, aae.keys, aae.values);
aae = ue.exp().isAssocArrayLiteralExp();
aae.ownedByCtfe = wasOwned;
}
else
{
// Can't type paint from struct to struct*; this needs another
// level of indirection
if (lit.op == EXP.structLiteral && isPointer(type))
error(lit.loc, "CTFE internal error: painting `%s`", type.toChars());
ue = copyLiteral(lit);
}
ue.exp().type = type;
return ue;
}
/*************************************
* If e is a SliceExp, constant fold it.
* Params:
* e = expression to resolve
* pue = if not null, store resulting expression here
* Returns:
* resulting expression
*/
Expression resolveSlice(Expression e, UnionExp* pue = null)
{
SliceExp se = e.isSliceExp();
if (!se)
return e;
if (se.e1.op == EXP.null_)
return se.e1;
if (pue)
{
*pue = Slice(e.type, se.e1, se.lwr, se.upr);
return pue.exp();
}
else
return Slice(e.type, se.e1, se.lwr, se.upr).copy();
}
/* Determine the array length, without interpreting it.
* e must be an array literal, or a slice
* It's very wasteful to resolve the slice when we only
* need the length.
*/
uinteger_t resolveArrayLength(Expression e)
{
switch (e.op)
{
case EXP.vector:
return e.isVectorExp().dim;
case EXP.null_:
return 0;
case EXP.slice:
{
auto se = e.isSliceExp();
const ilo = se.lwr.toInteger();
const iup = se.upr.toInteger();
return iup - ilo;
}
case EXP.string_:
return e.isStringExp().len;
case EXP.arrayLiteral:
{
const ale = e.isArrayLiteralExp();
return ale.elements ? ale.elements.length : 0;
}
case EXP.assocArrayLiteral:
{
return e.isAssocArrayLiteralExp().keys.length;
}
default:
assert(0);
}
}
/******************************
* Helper for NewExp
* Create an array literal consisting of 'elem' duplicated 'dim' times.
* Params:
* pue = where to store result
* loc = source location where the interpretation occurs
* type = target type of the result
* elem = the source of array element, it will be owned by the result
* dim = element number of the result
* Returns:
* Constructed ArrayLiteralExp
*/
ArrayLiteralExp createBlockDuplicatedArrayLiteral(UnionExp* pue, const ref Loc loc, Type type, Expression elem, size_t dim)
{
if (type.ty == Tsarray && type.nextOf().ty == Tsarray && elem.type.ty != Tsarray)
{
// If it is a multidimensional array literal, do it recursively
auto tsa = type.nextOf().isTypeSArray();
const len = cast(size_t)tsa.dim.toInteger();
elem = createBlockDuplicatedArrayLiteral(pue, loc, type.nextOf(), elem, len);
if (elem == pue.exp())
elem = pue.copy();
}
// Buzilla 15681
const tb = elem.type.toBasetype();
const mustCopy = tb.ty == Tstruct || tb.ty == Tsarray;
auto elements = new Expressions(dim);
foreach (i, ref el; *elements)
{
el = mustCopy && i ? copyLiteral(elem).copy() : elem;
}
emplaceExp!(ArrayLiteralExp)(pue, loc, type, elements);
auto ale = pue.exp().isArrayLiteralExp();
ale.ownedByCtfe = OwnedBy.ctfe;
return ale;
}
/******************************
* Helper for NewExp
* Create a string literal consisting of 'value' duplicated 'dim' times.
*/
StringExp createBlockDuplicatedStringLiteral(UnionExp* pue, const ref Loc loc, Type type, dchar value, size_t dim, ubyte sz)
{
auto s = cast(char*)mem.xcalloc(dim, sz);
foreach (elemi; 0 .. dim)
{
switch (sz)
{
case 1:
s[elemi] = cast(char)value;
break;
case 2:
(cast(wchar*)s)[elemi] = cast(wchar)value;
break;
case 4:
(cast(dchar*)s)[elemi] = value;
break;
case 8:
(cast(ulong*)s)[elemi] = value;
break;
default:
assert(0);
}
}
emplaceExp!(StringExp)(pue, loc, s[0 .. dim * sz], dim, sz);
auto se = pue.exp().isStringExp();
se.type = type;
se.committed = true;
se.ownedByCtfe = OwnedBy.ctfe;
return se;
}
// Return true if t is an AA
bool isAssocArray(Type t)
{
return t.toBasetype().isTypeAArray() !is null;
}
// Given a template AA type, extract the corresponding built-in AA type
TypeAArray toBuiltinAAType(Type t)
{
return t.toBasetype().isTypeAArray();
}
/************** TypeInfo operations ************************************/
// Return true if type is TypeInfo_Class
bool isTypeInfo_Class(const Type type) nothrow
{
auto tc = cast()type.isTypeClass();
return tc && (Type.dtypeinfo == tc.sym || Type.dtypeinfo.isBaseOf(tc.sym, null));
}
/************** Pointer operations ************************************/
// Return true if t is a pointer (not a function pointer)
bool isPointer(Type t)
{
Type tb = t.toBasetype();
return tb.ty == Tpointer && tb.nextOf().ty != Tfunction;
}
// For CTFE only. Returns true if 'e' is true or a non-null pointer.
bool isTrueBool(Expression e)
{
return e.toBool().hasValue(true) || ((e.type.ty == Tpointer || e.type.ty == Tclass) && e.op != EXP.null_);
}
/* Is it safe to convert from srcPointee* to destPointee* ?
* srcPointee is the genuine type (never void).
* destPointee may be void.
*/
bool isSafePointerCast(Type srcPointee, Type destPointee)
{
// It's safe to cast S** to D** if it's OK to cast S* to D*
while (srcPointee.ty == Tpointer && destPointee.ty == Tpointer)
{
srcPointee = srcPointee.nextOf();
destPointee = destPointee.nextOf();
}
// It's OK if both are the same (modulo const)
if (srcPointee.constConv(destPointee))
return true;
// It's ok to cast from/to shared because CTFE is single threaded anyways
if (srcPointee.unSharedOf() == destPointee.unSharedOf())
return true;
// It's OK if function pointers differ only in safe/pure/nothrow
if (srcPointee.ty == Tfunction && destPointee.ty == Tfunction)
{
return srcPointee.covariant(destPointee) == Covariant.yes ||
destPointee.covariant(srcPointee) == Covariant.yes;
}
// it's OK to cast to void*
if (destPointee.ty == Tvoid)
return true;
// It's OK to cast from V[K] to void*
if (srcPointee.ty == Taarray && destPointee == Type.tvoidptr)
return true;
// It's OK if they are the same size (static array of) integers, eg:
// int* --> uint*
// int[5][] --> uint[5][]
if (srcPointee.ty == Tsarray && destPointee.ty == Tsarray)
{
if (srcPointee.size() != destPointee.size())
return false;
srcPointee = srcPointee.baseElemOf();
destPointee = destPointee.baseElemOf();
}
return srcPointee.isintegral() && destPointee.isintegral() && srcPointee.size() == destPointee.size();
}
Expression getAggregateFromPointer(Expression e, dinteger_t* ofs)
{
*ofs = 0;
if (auto ae = e.isAddrExp())
e = ae.e1;
if (auto soe = e.isSymOffExp())
*ofs = soe.offset;
if (auto dve = e.isDotVarExp())
{
auto ex = dve.e1;
const v = dve.var.isVarDeclaration();
assert(v);
StructLiteralExp se = (ex.op == EXP.classReference)
? ex.isClassReferenceExp().value
: ex.isStructLiteralExp();
// We can't use getField, because it makes a copy
const i = (ex.op == EXP.classReference)
? ex.isClassReferenceExp().getFieldIndex(e.type, v.offset)
: se.getFieldIndex(e.type, v.offset);
e = (*se.elements)[i];
}
if (auto ie = e.isIndexExp())
{
// Note that each AA element is part of its own memory block
if ((ie.e1.type.ty == Tarray || ie.e1.type.ty == Tsarray || ie.e1.op == EXP.string_ || ie.e1.op == EXP.arrayLiteral) && ie.e2.op == EXP.int64)
{
*ofs = ie.e2.toInteger();
return ie.e1;
}
}
if (auto se = e.isSliceExp())
{
if (se && e.type.toBasetype().ty == Tsarray &&
(se.e1.type.ty == Tarray || se.e1.type.ty == Tsarray || se.e1.op == EXP.string_ || se.e1.op == EXP.arrayLiteral) && se.lwr.op == EXP.int64)
{
*ofs = se.lwr.toInteger();
return se.e1;
}
}
// It can be a `null` disguised as a cast, e.g. `cast(void*)0`.
if (auto ie = e.isIntegerExp())
if (ie.type.ty == Tpointer && ie.getInteger() == 0)
return new NullExp(ie.loc, e.type.nextOf());
// Those casts are invalid, but let the rest of the code handle it,
// as it could be something like `x !is null`, which doesn't need
// to dereference the pointer, even if the pointer is `cast(void*)420`.
return e;
}
/** Return true if agg1 and agg2 are pointers to the same memory block
*/
bool pointToSameMemoryBlock(Expression agg1, Expression agg2)
{
if (agg1 == agg2)
return true;
// For integers cast to pointers, we regard them as non-comparable
// unless they are identical. (This may be overly strict).
if (agg1.op == EXP.int64 && agg2.op == EXP.int64 && agg1.toInteger() == agg2.toInteger())
{
return true;
}
// Note that type painting can occur with VarExp, so we
// must compare the variables being pointed to.
if (agg1.op == EXP.variable && agg2.op == EXP.variable && agg1.isVarExp().var == agg2.isVarExp().var)
{
return true;
}
if (agg1.op == EXP.symbolOffset && agg2.op == EXP.symbolOffset && agg1.isSymOffExp().var == agg2.isSymOffExp().var)
{
return true;
}
return false;
}
// return e1 - e2 as an integer, or error if not possible
Expression pointerDifference(UnionExp* pue, const ref Loc loc, Type type, Expression e1, Expression e2)
{
dinteger_t ofs1, ofs2;
Expression agg1 = getAggregateFromPointer(e1, &ofs1);
Expression agg2 = getAggregateFromPointer(e2, &ofs2);
if (agg1 == agg2)
{
Type pointee = agg1.type.nextOf();
const sz = pointee.size();
emplaceExp!(IntegerExp)(pue, loc, (ofs1 - ofs2) * sz, type);
}
else if (agg1.op == EXP.string_ && agg2.op == EXP.string_ &&
agg1.isStringExp().peekString().ptr == agg2.isStringExp().peekString().ptr)
{
Type pointee = agg1.type.nextOf();
const sz = pointee.size();
emplaceExp!(IntegerExp)(pue, loc, (ofs1 - ofs2) * sz, type);
}
else if (agg1.op == EXP.symbolOffset && agg2.op == EXP.symbolOffset &&
agg1.isSymOffExp().var == agg2.isSymOffExp().var)
{
emplaceExp!(IntegerExp)(pue, loc, ofs1 - ofs2, type);
}
else
{
error(loc, "`%s - %s` cannot be interpreted at compile time: cannot subtract pointers to two different memory blocks", e1.toChars(), e2.toChars());
emplaceExp!(CTFEExp)(pue, EXP.cantExpression);
}
return pue.exp();
}
// Return eptr op e2, where eptr is a pointer, e2 is an integer,
// and op is EXP.add or EXP.min
Expression pointerArithmetic(UnionExp* pue, const ref Loc loc, EXP op, Type type, Expression eptr, Expression e2)
{
if (eptr.type.nextOf().ty == Tvoid)
{
error(loc, "cannot perform arithmetic on `void*` pointers at compile time");
Lcant:
emplaceExp!(CTFEExp)(pue, EXP.cantExpression);
return pue.exp();
}
if (eptr.op == EXP.address)
eptr = eptr.isAddrExp().e1;
dinteger_t ofs1;
Expression agg1 = getAggregateFromPointer(eptr, &ofs1);
if (agg1.op == EXP.symbolOffset)
{
if (agg1.isSymOffExp().var.type.ty != Tsarray)
{
error(loc, "cannot perform pointer arithmetic on arrays of unknown length at compile time");
goto Lcant;
}
}
else if (agg1.op != EXP.string_ && agg1.op != EXP.arrayLiteral)
{
error(loc, "cannot perform pointer arithmetic on non-arrays at compile time");
goto Lcant;
}
dinteger_t ofs2 = e2.toInteger();
Type pointee = agg1.type.toBasetype().nextOf();
dinteger_t sz = pointee.size();
sinteger_t indx;
dinteger_t len;
if (auto soe = agg1.isSymOffExp())
{
indx = ofs1 / sz;
len = soe.var.type.isTypeSArray().dim.toInteger();
}
else
{
Expression dollar = ArrayLength(Type.tsize_t, agg1).copy();
assert(!CTFEExp.isCantExp(dollar));
indx = ofs1;
len = dollar.toInteger();
}
if (op == EXP.add || op == EXP.addAssign || op == EXP.plusPlus)
indx += ofs2 / sz;
else if (op == EXP.min || op == EXP.minAssign || op == EXP.minusMinus)
indx -= ofs2 / sz;
else
{
error(loc, "CTFE internal error: bad pointer operation");
goto Lcant;
}
if (indx < 0 || len < indx)
{
error(loc, "cannot assign pointer to index %lld inside memory block `[0..%lld]`", indx, len);
goto Lcant;
}
if (agg1.op == EXP.symbolOffset)
{
emplaceExp!(SymOffExp)(pue, loc, agg1.isSymOffExp().var, indx * sz);
SymOffExp se = pue.exp().isSymOffExp();
se.type = type;
return pue.exp();
}
if (agg1.op != EXP.arrayLiteral && agg1.op != EXP.string_)
{
error(loc, "CTFE internal error: pointer arithmetic `%s`", agg1.toChars());
goto Lcant;
}
if (auto tsa = eptr.type.toBasetype().isTypeSArray())
{
dinteger_t dim = tsa.dim.toInteger();
// Create a CTFE pointer &agg1[indx .. indx+dim]
auto se = ctfeEmplaceExp!SliceExp(loc, agg1,
ctfeEmplaceExp!IntegerExp(loc, indx, Type.tsize_t),
ctfeEmplaceExp!IntegerExp(loc, indx + dim, Type.tsize_t));
se.type = type.toBasetype().nextOf();
emplaceExp!(AddrExp)(pue, loc, se);
pue.exp().type = type;
return pue.exp();
}
// Create a CTFE pointer &agg1[indx]
auto ofs = ctfeEmplaceExp!IntegerExp(loc, indx, Type.tsize_t);
Expression ie = ctfeEmplaceExp!IndexExp(loc, agg1, ofs);
ie.type = type.toBasetype().nextOf(); // https://issues.dlang.org/show_bug.cgi?id=13992
emplaceExp!(AddrExp)(pue, loc, ie);
pue.exp().type = type;
return pue.exp();
}
// Return 1 if true, 0 if false
// -1 if comparison is illegal because they point to non-comparable memory blocks
int comparePointers(EXP op, Expression agg1, dinteger_t ofs1, Expression agg2, dinteger_t ofs2)
{
if (pointToSameMemoryBlock(agg1, agg2))
{
int n;
switch (op)
{
case EXP.lessThan:
n = (ofs1 < ofs2);
break;
case EXP.lessOrEqual:
n = (ofs1 <= ofs2);
break;
case EXP.greaterThan:
n = (ofs1 > ofs2);
break;
case EXP.greaterOrEqual:
n = (ofs1 >= ofs2);
break;
case EXP.identity:
case EXP.equal:
n = (ofs1 == ofs2);
break;
case EXP.notIdentity:
case EXP.notEqual:
n = (ofs1 != ofs2);
break;
default:
assert(0);
}
return n;
}
const null1 = (agg1.op == EXP.null_);
const null2 = (agg2.op == EXP.null_);
int cmp;
if (null1 || null2)
{
switch (op)
{
case EXP.lessThan:
cmp = null1 && !null2;
break;
case EXP.greaterThan:
cmp = !null1 && null2;
break;
case EXP.lessOrEqual:
cmp = null1;
break;
case EXP.greaterOrEqual:
cmp = null2;
break;
case EXP.identity:
case EXP.equal:
case EXP.notIdentity: // 'cmp' gets inverted below
case EXP.notEqual:
cmp = (null1 == null2);
break;
default:
assert(0);
}
}
else
{
switch (op)
{
case EXP.identity:
case EXP.equal:
case EXP.notIdentity: // 'cmp' gets inverted below
case EXP.notEqual:
cmp = 0;
break;
default:
return -1; // memory blocks are different
}
}
if (op == EXP.notIdentity || op == EXP.notEqual)
cmp ^= 1;
return cmp;
}
// True if conversion from type 'from' to 'to' involves a reinterpret_cast
// floating point -> integer or integer -> floating point
bool isFloatIntPaint(Type to, Type from)
{
return from.size() == to.size() && (from.isintegral() && to.isfloating() || from.isfloating() && to.isintegral());
}
// Reinterpret float/int value 'fromVal' as a float/integer of type 'to'.
Expression paintFloatInt(UnionExp* pue, Expression fromVal, Type to)
{
if (exceptionOrCantInterpret(fromVal))
return fromVal;
assert(to.size() == 4 || to.size() == 8);
return Compiler.paintAsType(pue, fromVal, to);
}
/******** Constant folding, with support for CTFE ***************************/
/// Return true if non-pointer expression e can be compared
/// with >,is, ==, etc, using ctfeCmp, ctfeEqual, ctfeIdentity
bool isCtfeComparable(Expression e)
{
if (e.op == EXP.slice)
e = e.isSliceExp().e1;
if (e.isConst() != 1)
{
if (e.op == EXP.null_ || e.op == EXP.string_ || e.op == EXP.function_ || e.op == EXP.delegate_ || e.op == EXP.arrayLiteral || e.op == EXP.structLiteral || e.op == EXP.assocArrayLiteral || e.op == EXP.classReference)
{
return true;
}
// https://issues.dlang.org/show_bug.cgi?id=14123
// TypeInfo object is comparable in CTFE
if (e.op == EXP.typeid_)
return true;
return false;
}
return true;
}
/// Map EXP comparison ops
private bool numCmp(N)(EXP op, N n1, N n2) nothrow
{
switch (op)
{
case EXP.lessThan:
return n1 < n2;
case EXP.lessOrEqual:
return n1 <= n2;
case EXP.greaterThan:
return n1 > n2;
case EXP.greaterOrEqual:
return n1 >= n2;