]> git.ipfire.org Git - thirdparty/gcc.git/blob - gcc/d/dmd/dcast.c
Merge dmd upstream 6243fa6d2
[thirdparty/gcc.git] / gcc / d / dmd / dcast.c
1
2 /* Compiler implementation of the D programming language
3 * Copyright (C) 1999-2018 by The D Language Foundation, All Rights Reserved
4 * written by Walter Bright
5 * http://www.digitalmars.com
6 * Distributed under the Boost Software License, Version 1.0.
7 * http://www.boost.org/LICENSE_1_0.txt
8 * https://github.com/D-Programming-Language/dmd/blob/master/src/cast.c
9 */
10
11 #include "root/dsystem.h" // mem{set|cpy}()
12 #include "root/rmem.h"
13
14 #include "mars.h"
15 #include "expression.h"
16 #include "mtype.h"
17 #include "utf.h"
18 #include "declaration.h"
19 #include "aggregate.h"
20 #include "template.h"
21 #include "scope.h"
22 #include "id.h"
23 #include "init.h"
24 #include "tokens.h"
25
26 FuncDeclaration *isFuncAddress(Expression *e, bool *hasOverloads = NULL);
27 bool isCommutative(TOK op);
28 MOD MODmerge(MOD mod1, MOD mod2);
29 Expression *semantic(Expression *e, Scope *sc);
30
31 /* ==================== implicitCast ====================== */
32
33 /**************************************
34 * Do an implicit cast.
35 * Issue error if it can't be done.
36 */
37
38
39 Expression *implicitCastTo(Expression *e, Scope *sc, Type *t)
40 {
41 class ImplicitCastTo : public Visitor
42 {
43 public:
44 Type *t;
45 Scope *sc;
46 Expression *result;
47
48 ImplicitCastTo(Scope *sc, Type *t)
49 : t(t), sc(sc)
50 {
51 result = NULL;
52 }
53
54 void visit(Expression *e)
55 {
56 //printf("Expression::implicitCastTo(%s of type %s) => %s\n", e->toChars(), e->type->toChars(), t->toChars());
57
58 MATCH match = e->implicitConvTo(t);
59 if (match)
60 {
61 if (match == MATCHconst &&
62 (e->type->constConv(t) ||
63 (!e->isLvalue() && e->type->equivalent(t))))
64 {
65 /* Do not emit CastExp for const conversions and
66 * unique conversions on rvalue.
67 */
68 result = e->copy();
69 result->type = t;
70 return;
71 }
72 result = e->castTo(sc, t);
73 return;
74 }
75
76 result = e->optimize(WANTvalue);
77 if (result != e)
78 {
79 result->accept(this);
80 return;
81 }
82
83 if (t->ty != Terror && e->type->ty != Terror)
84 {
85 if (!t->deco)
86 {
87 e->error("forward reference to type %s", t->toChars());
88 }
89 else
90 {
91 //printf("type %p ty %d deco %p\n", type, type->ty, type->deco);
92 //type = type->semantic(loc, sc);
93 //printf("type %s t %s\n", type->deco, t->deco);
94 e->error("cannot implicitly convert expression (%s) of type %s to %s",
95 e->toChars(), e->type->toChars(), t->toChars());
96 }
97 }
98 result = new ErrorExp();
99 }
100
101 void visit(StringExp *e)
102 {
103 //printf("StringExp::implicitCastTo(%s of type %s) => %s\n", e->toChars(), e->type->toChars(), t->toChars());
104 visit((Expression *)e);
105 if (result->op == TOKstring)
106 {
107 // Retain polysemous nature if it started out that way
108 ((StringExp *)result)->committed = e->committed;
109 }
110 }
111
112 void visit(ErrorExp *e)
113 {
114 result = e;
115 }
116
117 void visit(FuncExp *e)
118 {
119 //printf("FuncExp::implicitCastTo type = %p %s, t = %s\n", e->type, e->type ? e->type->toChars() : NULL, t->toChars());
120 FuncExp *fe;
121 if (e->matchType(t, sc, &fe) > MATCHnomatch)
122 {
123 result = fe;
124 return;
125 }
126 visit((Expression *)e);
127 }
128
129 void visit(ArrayLiteralExp *e)
130 {
131 visit((Expression *)e);
132
133 Type *tb = result->type->toBasetype();
134 if (tb->ty == Tarray)
135 semanticTypeInfo(sc, ((TypeDArray *)tb)->next);
136 }
137
138 void visit(SliceExp *e)
139 {
140 visit((Expression *)e);
141 if (result->op != TOKslice)
142 return;
143
144 e = (SliceExp *)result;
145 if (e->e1->op == TOKarrayliteral)
146 {
147 ArrayLiteralExp *ale = (ArrayLiteralExp *)e->e1;
148 Type *tb = t->toBasetype();
149 Type *tx;
150 if (tb->ty == Tsarray)
151 tx = tb->nextOf()->sarrayOf(ale->elements ? ale->elements->dim : 0);
152 else
153 tx = tb->nextOf()->arrayOf();
154 e->e1 = ale->implicitCastTo(sc, tx);
155 }
156 }
157 };
158
159 ImplicitCastTo v(sc, t);
160 e->accept(&v);
161 return v.result;
162 }
163
164 /*******************************************
165 * Return MATCH level of implicitly converting e to type t.
166 * Don't do the actual cast; don't change e.
167 */
168
169 MATCH implicitConvTo(Expression *e, Type *t)
170 {
171 class ImplicitConvTo : public Visitor
172 {
173 public:
174 Type *t;
175 MATCH result;
176
177 ImplicitConvTo(Type *t)
178 : t(t)
179 {
180 result = MATCHnomatch;
181 }
182
183 void visit(Expression *e)
184 {
185 //static int nest; if (++nest == 10) halt();
186 if (t == Type::terror)
187 return;
188 if (!e->type)
189 {
190 e->error("%s is not an expression", e->toChars());
191 e->type = Type::terror;
192 }
193 Expression *ex = e->optimize(WANTvalue);
194 if (ex->type->equals(t))
195 {
196 result = MATCHexact;
197 return;
198 }
199 if (ex != e)
200 {
201 //printf("\toptimized to %s of type %s\n", e->toChars(), e->type->toChars());
202 result = ex->implicitConvTo(t);
203 return;
204 }
205 MATCH match = e->type->implicitConvTo(t);
206 if (match != MATCHnomatch)
207 {
208 result = match;
209 return;
210 }
211
212 /* See if we can do integral narrowing conversions
213 */
214 if (e->type->isintegral() && t->isintegral() &&
215 e->type->isTypeBasic() && t->isTypeBasic())
216 {
217 IntRange src = getIntRange(e);
218 IntRange target = IntRange::fromType(t);
219 if (target.contains(src))
220 {
221 result = MATCHconvert;
222 return;
223 }
224 }
225 }
226
227 /******
228 * Given expression e of type t, see if we can implicitly convert e
229 * to type tprime, where tprime is type t with mod bits added.
230 * Returns:
231 * match level
232 */
233 static MATCH implicitMod(Expression *e, Type *t, MOD mod)
234 {
235 Type *tprime;
236 if (t->ty == Tpointer)
237 tprime = t->nextOf()->castMod(mod)->pointerTo();
238 else if (t->ty == Tarray)
239 tprime = t->nextOf()->castMod(mod)->arrayOf();
240 else if (t->ty == Tsarray)
241 tprime = t->nextOf()->castMod(mod)->sarrayOf(t->size() / t->nextOf()->size());
242 else
243 tprime = t->castMod(mod);
244
245 return e->implicitConvTo(tprime);
246 }
247
248 static MATCH implicitConvToAddMin(BinExp *e, Type *t)
249 {
250 /* Is this (ptr +- offset)? If so, then ask ptr
251 * if the conversion can be done.
252 * This is to support doing things like implicitly converting a mutable unique
253 * pointer to an immutable pointer.
254 */
255
256 Type *typeb = e->type->toBasetype();
257 Type *tb = t->toBasetype();
258 if (typeb->ty != Tpointer || tb->ty != Tpointer)
259 return MATCHnomatch;
260
261 Type *t1b = e->e1->type->toBasetype();
262 Type *t2b = e->e2->type->toBasetype();
263 if (t1b->ty == Tpointer && t2b->isintegral() &&
264 t1b->equivalent(tb))
265 {
266 // ptr + offset
267 // ptr - offset
268 MATCH m = e->e1->implicitConvTo(t);
269 return (m > MATCHconst) ? MATCHconst : m;
270 }
271 if (t2b->ty == Tpointer && t1b->isintegral() &&
272 t2b->equivalent(tb))
273 {
274 // offset + ptr
275 MATCH m = e->e2->implicitConvTo(t);
276 return (m > MATCHconst) ? MATCHconst : m;
277 }
278
279 return MATCHnomatch;
280 }
281
282 void visit(AddExp *e)
283 {
284 visit((Expression *)e);
285 if (result == MATCHnomatch)
286 result = implicitConvToAddMin(e, t);
287 }
288
289 void visit(MinExp *e)
290 {
291 visit((Expression *)e);
292 if (result == MATCHnomatch)
293 result = implicitConvToAddMin(e, t);
294 }
295
296 void visit(IntegerExp *e)
297 {
298 MATCH m = e->type->implicitConvTo(t);
299 if (m >= MATCHconst)
300 {
301 result = m;
302 return;
303 }
304
305 TY ty = e->type->toBasetype()->ty;
306 TY toty = t->toBasetype()->ty;
307 TY oldty = ty;
308
309 if (m == MATCHnomatch && t->ty == Tenum)
310 return;
311
312 if (t->ty == Tvector)
313 {
314 TypeVector *tv = (TypeVector *)t;
315 TypeBasic *tb = tv->elementType();
316 if (tb->ty == Tvoid)
317 return;
318 toty = tb->ty;
319 }
320
321 switch (ty)
322 {
323 case Tbool:
324 case Tint8:
325 case Tchar:
326 case Tuns8:
327 case Tint16:
328 case Tuns16:
329 case Twchar:
330 ty = Tint32;
331 break;
332
333 case Tdchar:
334 ty = Tuns32;
335 break;
336
337 default:
338 break;
339 }
340
341 // Only allow conversion if no change in value
342 dinteger_t value = e->toInteger();
343 switch (toty)
344 {
345 case Tbool:
346 if ((value & 1) != value)
347 return;
348 break;
349
350 case Tint8:
351 if (ty == Tuns64 && value & ~0x7FUL)
352 return;
353 else if ((signed char)value != (sinteger_t)value)
354 return;
355 break;
356
357 case Tchar:
358 if ((oldty == Twchar || oldty == Tdchar) && value > 0x7F)
359 return;
360 /* fall through */
361 case Tuns8:
362 //printf("value = %llu %llu\n", (dinteger_t)(unsigned char)value, value);
363 if ((unsigned char)value != value)
364 return;
365 break;
366
367 case Tint16:
368 if (ty == Tuns64 && value & ~0x7FFFUL)
369 return;
370 else if ((short)value != (sinteger_t)value)
371 return;
372 break;
373
374 case Twchar:
375 if (oldty == Tdchar && value > 0xD7FF && value < 0xE000)
376 return;
377 /* fall through */
378 case Tuns16:
379 if ((unsigned short)value != value)
380 return;
381 break;
382
383 case Tint32:
384 if (ty == Tuns32)
385 {
386 }
387 else if (ty == Tuns64 && value & ~0x7FFFFFFFUL)
388 return;
389 else if ((int)value != (sinteger_t)value)
390 return;
391 break;
392
393 case Tuns32:
394 if (ty == Tint32)
395 {
396 }
397 else if ((unsigned)value != value)
398 return;
399 break;
400
401 case Tdchar:
402 if (value > 0x10FFFFUL)
403 return;
404 break;
405
406 case Tfloat32:
407 {
408 volatile float f;
409 if (e->type->isunsigned())
410 {
411 f = (float)value;
412 if (f != value)
413 return;
414 }
415 else
416 {
417 f = (float)(sinteger_t)value;
418 if (f != (sinteger_t)value)
419 return;
420 }
421 break;
422 }
423
424 case Tfloat64:
425 {
426 volatile double f;
427 if (e->type->isunsigned())
428 {
429 f = (double)value;
430 if (f != value)
431 return;
432 }
433 else
434 {
435 f = (double)(sinteger_t)value;
436 if (f != (sinteger_t)value)
437 return;
438 }
439 break;
440 }
441
442 case Tfloat80:
443 {
444 volatile_longdouble f;
445 if (e->type->isunsigned())
446 {
447 f = ldouble(value);
448 if ((dinteger_t)f != value) // isn't this a noop, because the compiler prefers ld
449 return;
450 }
451 else
452 {
453 f = ldouble((sinteger_t)value);
454 if ((sinteger_t)f != (sinteger_t)value)
455 return;
456 }
457 break;
458 }
459
460 case Tpointer:
461 //printf("type = %s\n", type->toBasetype()->toChars());
462 //printf("t = %s\n", t->toBasetype()->toChars());
463 if (ty == Tpointer &&
464 e->type->toBasetype()->nextOf()->ty == t->toBasetype()->nextOf()->ty)
465 {
466 /* Allow things like:
467 * const char* P = cast(char *)3;
468 * char* q = P;
469 */
470 break;
471 }
472 /* fall through */
473
474 default:
475 visit((Expression *)e);
476 return;
477 }
478
479 //printf("MATCHconvert\n");
480 result = MATCHconvert;
481 }
482
483 void visit(ErrorExp *)
484 {
485 // no match
486 }
487
488 void visit(NullExp *e)
489 {
490 if (e->type->equals(t))
491 {
492 result = MATCHexact;
493 return;
494 }
495
496 /* Allow implicit conversions from immutable to mutable|const,
497 * and mutable to immutable. It works because, after all, a null
498 * doesn't actually point to anything.
499 */
500 if (t->equivalent(e->type))
501 {
502 result = MATCHconst;
503 return;
504 }
505
506 visit((Expression *)e);
507 }
508
509 void visit(StructLiteralExp *e)
510 {
511 visit((Expression *)e);
512 if (result != MATCHnomatch)
513 return;
514 if (e->type->ty == t->ty && e->type->ty == Tstruct &&
515 ((TypeStruct *)e->type)->sym == ((TypeStruct *)t)->sym)
516 {
517 result = MATCHconst;
518 for (size_t i = 0; i < e->elements->dim; i++)
519 {
520 Expression *el = (*e->elements)[i];
521 if (!el)
522 continue;
523 Type *te = el->type;
524 te = e->sd->fields[i]->type->addMod(t->mod);
525 MATCH m2 = el->implicitConvTo(te);
526 //printf("\t%s => %s, match = %d\n", el->toChars(), te->toChars(), m2);
527 if (m2 < result)
528 result = m2;
529 }
530 }
531 }
532
533 void visit(StringExp *e)
534 {
535 if (!e->committed && t->ty == Tpointer && t->nextOf()->ty == Tvoid)
536 return;
537
538 if (e->type->ty == Tsarray || e->type->ty == Tarray || e->type->ty == Tpointer)
539 {
540 TY tyn = e->type->nextOf()->ty;
541 if (tyn == Tchar || tyn == Twchar || tyn == Tdchar)
542 {
543 switch (t->ty)
544 {
545 case Tsarray:
546 if (e->type->ty == Tsarray)
547 {
548 TY tynto = t->nextOf()->ty;
549 if (tynto == tyn)
550 {
551 if (((TypeSArray *)e->type)->dim->toInteger() ==
552 ((TypeSArray *)t)->dim->toInteger())
553 {
554 result = MATCHexact;
555 }
556 return;
557 }
558 if (tynto == Tchar || tynto == Twchar || tynto == Tdchar)
559 {
560 if (e->committed && tynto != tyn)
561 return;
562 size_t fromlen = e->numberOfCodeUnits(tynto);
563 size_t tolen = (size_t)((TypeSArray *)t)->dim->toInteger();
564 if (tolen < fromlen)
565 return;
566 if (tolen != fromlen)
567 {
568 // implicit length extending
569 result = MATCHconvert;
570 return;
571 }
572 }
573 if (!e->committed && (tynto == Tchar || tynto == Twchar || tynto == Tdchar))
574 {
575 result = MATCHexact;
576 return;
577 }
578 }
579 else if (e->type->ty == Tarray)
580 {
581 TY tynto = t->nextOf()->ty;
582 if (tynto == Tchar || tynto == Twchar || tynto == Tdchar)
583 {
584 if (e->committed && tynto != tyn)
585 return;
586 size_t fromlen = e->numberOfCodeUnits(tynto);
587 size_t tolen = (size_t)((TypeSArray *)t)->dim->toInteger();
588 if (tolen < fromlen)
589 return;
590 if (tolen != fromlen)
591 {
592 // implicit length extending
593 result = MATCHconvert;
594 return;
595 }
596 }
597 if (tynto == tyn)
598 {
599 result = MATCHexact;
600 return;
601 }
602 if (!e->committed && (tynto == Tchar || tynto == Twchar || tynto == Tdchar))
603 {
604 result = MATCHexact;
605 return;
606 }
607 }
608 /* fall through */
609 case Tarray:
610 case Tpointer:
611 Type *tn = t->nextOf();
612 MATCH m = MATCHexact;
613 if (e->type->nextOf()->mod != tn->mod)
614 {
615 if (!tn->isConst())
616 return;
617 m = MATCHconst;
618 }
619 if (!e->committed)
620 {
621 switch (tn->ty)
622 {
623 case Tchar:
624 if (e->postfix == 'w' || e->postfix == 'd')
625 m = MATCHconvert;
626 result = m;
627 return;
628 case Twchar:
629 if (e->postfix != 'w')
630 m = MATCHconvert;
631 result = m;
632 return;
633 case Tdchar:
634 if (e->postfix != 'd')
635 m = MATCHconvert;
636 result = m;
637 return;
638 }
639 }
640 break;
641 }
642 }
643 }
644
645 visit((Expression *)e);
646 }
647
648 void visit(ArrayLiteralExp *e)
649 {
650 Type *typeb = e->type->toBasetype();
651 Type *tb = t->toBasetype();
652 if ((tb->ty == Tarray || tb->ty == Tsarray) &&
653 (typeb->ty == Tarray || typeb->ty == Tsarray))
654 {
655 result = MATCHexact;
656 Type *typen = typeb->nextOf()->toBasetype();
657
658 if (tb->ty == Tsarray)
659 {
660 TypeSArray *tsa = (TypeSArray *)tb;
661 if (e->elements->dim != tsa->dim->toInteger())
662 result = MATCHnomatch;
663 }
664
665 Type *telement = tb->nextOf();
666 if (!e->elements->dim)
667 {
668 if (typen->ty != Tvoid)
669 result = typen->implicitConvTo(telement);
670 }
671 else
672 {
673 if (e->basis)
674 {
675 MATCH m = e->basis->implicitConvTo(telement);
676 if (m < result)
677 result = m;
678 }
679 for (size_t i = 0; i < e->elements->dim; i++)
680 {
681 Expression *el = (*e->elements)[i];
682 if (result == MATCHnomatch)
683 break;
684 if (!el)
685 continue;
686 MATCH m = el->implicitConvTo(telement);
687 if (m < result)
688 result = m; // remember worst match
689 }
690 }
691
692 if (!result)
693 result = e->type->implicitConvTo(t);
694
695 return;
696 }
697 else if (tb->ty == Tvector &&
698 (typeb->ty == Tarray || typeb->ty == Tsarray))
699 {
700 result = MATCHexact;
701 // Convert array literal to vector type
702 TypeVector *tv = (TypeVector *)tb;
703 TypeSArray *tbase = (TypeSArray *)tv->basetype;
704 assert(tbase->ty == Tsarray);
705 const size_t edim = e->elements->dim;
706 const size_t tbasedim = tbase->dim->toInteger();
707 if (edim > tbasedim)
708 {
709 result = MATCHnomatch;
710 return;
711 }
712
713 Type *telement = tv->elementType();
714 if (edim < tbasedim)
715 {
716 Expression *el = typeb->nextOf()->defaultInitLiteral(e->loc);
717 MATCH m = el->implicitConvTo(telement);
718 if (m < result)
719 result = m; // remember worst match
720 }
721 for (size_t i = 0; i < edim; i++)
722 {
723 Expression *el = (*e->elements)[i];
724 MATCH m = el->implicitConvTo(telement);
725 if (m < result)
726 result = m; // remember worst match
727 if (result == MATCHnomatch)
728 break; // no need to check for worse
729 }
730 return;
731 }
732
733 visit((Expression *)e);
734 }
735
736 void visit(AssocArrayLiteralExp *e)
737 {
738 Type *typeb = e->type->toBasetype();
739 Type *tb = t->toBasetype();
740 if (tb->ty == Taarray && typeb->ty == Taarray)
741 {
742 result = MATCHexact;
743 for (size_t i = 0; i < e->keys->dim; i++)
744 {
745 Expression *el = (*e->keys)[i];
746 MATCH m = el->implicitConvTo(((TypeAArray *)tb)->index);
747 if (m < result)
748 result = m; // remember worst match
749 if (result == MATCHnomatch)
750 break; // no need to check for worse
751 el = (*e->values)[i];
752 m = el->implicitConvTo(tb->nextOf());
753 if (m < result)
754 result = m; // remember worst match
755 if (result == MATCHnomatch)
756 break; // no need to check for worse
757 }
758 return;
759 }
760 else
761 visit((Expression *)e);
762 }
763
764 void visit(CallExp *e)
765 {
766 visit((Expression *)e);
767 if (result != MATCHnomatch)
768 return;
769
770 /* Allow the result of strongly pure functions to
771 * convert to immutable
772 */
773 if (e->f && e->f->isolateReturn())
774 {
775 result = e->type->immutableOf()->implicitConvTo(t);
776 if (result > MATCHconst) // Match level is MATCHconst at best.
777 result = MATCHconst;
778 return;
779 }
780
781 /* Conversion is 'const' conversion if:
782 * 1. function is pure (weakly pure is ok)
783 * 2. implicit conversion only fails because of mod bits
784 * 3. each function parameter can be implicitly converted to the mod bits
785 */
786 Type *tx = e->f ? e->f->type : e->e1->type;
787 tx = tx->toBasetype();
788 if (tx->ty != Tfunction)
789 return;
790 TypeFunction *tf = (TypeFunction *)tx;
791
792 if (tf->purity == PUREimpure)
793 return;
794 if (e->f && e->f->isNested())
795 return;
796
797 /* See if fail only because of mod bits.
798 *
799 * Bugzilla 14155: All pure functions can access global immutable data.
800 * So the returned pointer may refer an immutable global data,
801 * and then the returned pointer that points non-mutable object
802 * cannot be unique pointer.
803 *
804 * Example:
805 * immutable g;
806 * static this() { g = 1; }
807 * const(int*) foo() pure { return &g; }
808 * void test() {
809 * immutable(int*) ip = foo(); // OK
810 * int* mp = foo(); // should be disallowed
811 * }
812 */
813 if (e->type->immutableOf()->implicitConvTo(t) < MATCHconst &&
814 e->type->addMod(MODshared)->implicitConvTo(t) < MATCHconst &&
815 e->type->implicitConvTo(t->addMod(MODshared)) < MATCHconst)
816 {
817 return;
818 }
819 // Allow a conversion to immutable type, or
820 // conversions of mutable types between thread-local and shared.
821
822 /* Get mod bits of what we're converting to
823 */
824 Type *tb = t->toBasetype();
825 MOD mod = tb->mod;
826 if (tf->isref)
827 ;
828 else
829 {
830 Type *ti = getIndirection(t);
831 if (ti)
832 mod = ti->mod;
833 }
834 if (mod & MODwild)
835 return; // not sure what to do with this
836
837 /* Apply mod bits to each function parameter,
838 * and see if we can convert the function argument to the modded type
839 */
840
841 size_t nparams = Parameter::dim(tf->parameters);
842 size_t j = (tf->linkage == LINKd && tf->varargs == 1); // if TypeInfoArray was prepended
843 if (e->e1->op == TOKdotvar)
844 {
845 /* Treat 'this' as just another function argument
846 */
847 DotVarExp *dve = (DotVarExp *)e->e1;
848 Type *targ = dve->e1->type;
849 if (targ->constConv(targ->castMod(mod)) == MATCHnomatch)
850 return;
851 }
852 for (size_t i = j; i < e->arguments->dim; ++i)
853 {
854 Expression *earg = (*e->arguments)[i];
855 Type *targ = earg->type->toBasetype();
856 if (i - j < nparams)
857 {
858 Parameter *fparam = Parameter::getNth(tf->parameters, i - j);
859 if (fparam->storageClass & STClazy)
860 return; // not sure what to do with this
861 Type *tparam = fparam->type;
862 if (!tparam)
863 continue;
864 if (fparam->storageClass & (STCout | STCref))
865 {
866 if (targ->constConv(tparam->castMod(mod)) == MATCHnomatch)
867 return;
868 continue;
869 }
870 }
871
872 if (implicitMod(earg, targ, mod) == MATCHnomatch)
873 return;
874 }
875
876 /* Success
877 */
878 result = MATCHconst;
879 }
880
881 void visit(AddrExp *e)
882 {
883 result = e->type->implicitConvTo(t);
884 //printf("\tresult = %d\n", result);
885
886 if (result != MATCHnomatch)
887 return;
888
889 // Look for pointers to functions where the functions are overloaded.
890
891 t = t->toBasetype();
892
893 if (e->e1->op == TOKoverloadset &&
894 (t->ty == Tpointer || t->ty == Tdelegate) && t->nextOf()->ty == Tfunction)
895 {
896 OverExp *eo = (OverExp *)e->e1;
897 FuncDeclaration *f = NULL;
898 for (size_t i = 0; i < eo->vars->a.dim; i++)
899 {
900 Dsymbol *s = eo->vars->a[i];
901 FuncDeclaration *f2 = s->isFuncDeclaration();
902 assert(f2);
903 if (f2->overloadExactMatch(t->nextOf()))
904 {
905 if (f)
906 {
907 /* Error if match in more than one overload set,
908 * even if one is a 'better' match than the other.
909 */
910 ScopeDsymbol::multiplyDefined(e->loc, f, f2);
911 }
912 else
913 f = f2;
914 result = MATCHexact;
915 }
916 }
917 }
918
919 if (e->type->ty == Tpointer && e->type->nextOf()->ty == Tfunction &&
920 t->ty == Tpointer && t->nextOf()->ty == Tfunction &&
921 e->e1->op == TOKvar)
922 {
923 /* I don't think this can ever happen -
924 * it should have been
925 * converted to a SymOffExp.
926 */
927 assert(0);
928 }
929
930 //printf("\tresult = %d\n", result);
931 }
932
933 void visit(SymOffExp *e)
934 {
935 result = e->type->implicitConvTo(t);
936 //printf("\tresult = %d\n", result);
937 if (result != MATCHnomatch)
938 return;
939
940 // Look for pointers to functions where the functions are overloaded.
941 t = t->toBasetype();
942 if (e->type->ty == Tpointer && e->type->nextOf()->ty == Tfunction &&
943 (t->ty == Tpointer || t->ty == Tdelegate) && t->nextOf()->ty == Tfunction)
944 {
945 if (FuncDeclaration *f = e->var->isFuncDeclaration())
946 {
947 f = f->overloadExactMatch(t->nextOf());
948 if (f)
949 {
950 if ((t->ty == Tdelegate && (f->needThis() || f->isNested())) ||
951 (t->ty == Tpointer && !(f->needThis() || f->isNested())))
952 {
953 result = MATCHexact;
954 }
955 }
956 }
957 }
958 //printf("\tresult = %d\n", result);
959 }
960
961 void visit(DelegateExp *e)
962 {
963 result = e->type->implicitConvTo(t);
964 if (result != MATCHnomatch)
965 return;
966
967 // Look for pointers to functions where the functions are overloaded.
968 t = t->toBasetype();
969 if (e->type->ty == Tdelegate &&
970 t->ty == Tdelegate)
971 {
972 if (e->func && e->func->overloadExactMatch(t->nextOf()))
973 result = MATCHexact;
974 }
975 }
976
977 void visit(FuncExp *e)
978 {
979 //printf("FuncExp::implicitConvTo type = %p %s, t = %s\n", e->type, e->type ? e->type->toChars() : NULL, t->toChars());
980 MATCH m = e->matchType(t, NULL, NULL, 1);
981 if (m > MATCHnomatch)
982 {
983 result = m;
984 return;
985 }
986 visit((Expression *)e);
987 }
988
989 void visit(OrExp *e)
990 {
991 visit((Expression *)e);
992 if (result != MATCHnomatch)
993 return;
994
995 MATCH m1 = e->e1->implicitConvTo(t);
996 MATCH m2 = e->e2->implicitConvTo(t);
997
998 // Pick the worst match
999 result = (m1 < m2) ? m1 : m2;
1000 }
1001
1002 void visit(XorExp *e)
1003 {
1004 visit((Expression *)e);
1005 if (result != MATCHnomatch)
1006 return;
1007
1008 MATCH m1 = e->e1->implicitConvTo(t);
1009 MATCH m2 = e->e2->implicitConvTo(t);
1010
1011 // Pick the worst match
1012 result = (m1 < m2) ? m1 : m2;
1013 }
1014
1015 void visit(CondExp *e)
1016 {
1017 MATCH m1 = e->e1->implicitConvTo(t);
1018 MATCH m2 = e->e2->implicitConvTo(t);
1019 //printf("CondExp: m1 %d m2 %d\n", m1, m2);
1020
1021 // Pick the worst match
1022 result = (m1 < m2) ? m1 : m2;
1023 }
1024
1025 void visit(CommaExp *e)
1026 {
1027 e->e2->accept(this);
1028 }
1029
1030 void visit(CastExp *e)
1031 {
1032 result = e->type->implicitConvTo(t);
1033 if (result != MATCHnomatch)
1034 return;
1035
1036 if (t->isintegral() &&
1037 e->e1->type->isintegral() &&
1038 e->e1->implicitConvTo(t) != MATCHnomatch)
1039 result = MATCHconvert;
1040 else
1041 visit((Expression *)e);
1042 }
1043
1044 void visit(NewExp *e)
1045 {
1046 visit((Expression *)e);
1047 if (result != MATCHnomatch)
1048 return;
1049
1050 /* Calling new() is like calling a pure function. We can implicitly convert the
1051 * return from new() to t using the same algorithm as in CallExp, with the function
1052 * 'arguments' being:
1053 * thisexp
1054 * newargs
1055 * arguments
1056 * .init
1057 * 'member' and 'allocator' need to be pure.
1058 */
1059
1060 /* See if fail only because of mod bits
1061 */
1062 if (e->type->immutableOf()->implicitConvTo(t->immutableOf()) == MATCHnomatch)
1063 return;
1064
1065 /* Get mod bits of what we're converting to
1066 */
1067 Type *tb = t->toBasetype();
1068 MOD mod = tb->mod;
1069 if (Type *ti = getIndirection(t))
1070 mod = ti->mod;
1071 if (mod & MODwild)
1072 return; // not sure what to do with this
1073
1074 /* Apply mod bits to each argument,
1075 * and see if we can convert the argument to the modded type
1076 */
1077
1078 if (e->thisexp)
1079 {
1080 /* Treat 'this' as just another function argument
1081 */
1082 Type *targ = e->thisexp->type;
1083 if (targ->constConv(targ->castMod(mod)) == MATCHnomatch)
1084 return;
1085 }
1086
1087 /* Check call to 'allocator', then 'member'
1088 */
1089 FuncDeclaration *fd = e->allocator;
1090 for (int count = 0; count < 2; ++count, (fd = e->member))
1091 {
1092 if (!fd)
1093 continue;
1094 if (fd->errors || fd->type->ty != Tfunction)
1095 return; // error
1096 TypeFunction *tf = (TypeFunction *)fd->type;
1097 if (tf->purity == PUREimpure)
1098 return; // impure
1099
1100 if (fd == e->member)
1101 {
1102 if (e->type->immutableOf()->implicitConvTo(t) < MATCHconst &&
1103 e->type->addMod(MODshared)->implicitConvTo(t) < MATCHconst &&
1104 e->type->implicitConvTo(t->addMod(MODshared)) < MATCHconst)
1105 {
1106 return;
1107 }
1108 // Allow a conversion to immutable type, or
1109 // conversions of mutable types between thread-local and shared.
1110 }
1111
1112 Expressions *args = (fd == e->allocator) ? e->newargs : e->arguments;
1113
1114 size_t nparams = Parameter::dim(tf->parameters);
1115 size_t j = (tf->linkage == LINKd && tf->varargs == 1); // if TypeInfoArray was prepended
1116 for (size_t i = j; i < e->arguments->dim; ++i)
1117 {
1118 Expression *earg = (*args)[i];
1119 Type *targ = earg->type->toBasetype();
1120 if (i - j < nparams)
1121 {
1122 Parameter *fparam = Parameter::getNth(tf->parameters, i - j);
1123 if (fparam->storageClass & STClazy)
1124 return; // not sure what to do with this
1125 Type *tparam = fparam->type;
1126 if (!tparam)
1127 continue;
1128 if (fparam->storageClass & (STCout | STCref))
1129 {
1130 if (targ->constConv(tparam->castMod(mod)) == MATCHnomatch)
1131 return;
1132 continue;
1133 }
1134 }
1135
1136 if (implicitMod(earg, targ, mod) == MATCHnomatch)
1137 return;
1138 }
1139 }
1140
1141 /* If no 'member', then construction is by simple assignment,
1142 * and just straight check 'arguments'
1143 */
1144 if (!e->member && e->arguments)
1145 {
1146 for (size_t i = 0; i < e->arguments->dim; ++i)
1147 {
1148 Expression *earg = (*e->arguments)[i];
1149 if (!earg) // Bugzilla 14853: if it's on overlapped field
1150 continue;
1151 Type *targ = earg->type->toBasetype();
1152 if (implicitMod(earg, targ, mod) == MATCHnomatch)
1153 return;
1154 }
1155 }
1156
1157 /* Consider the .init expression as an argument
1158 */
1159 Type *ntb = e->newtype->toBasetype();
1160 if (ntb->ty == Tarray)
1161 ntb = ntb->nextOf()->toBasetype();
1162 if (ntb->ty == Tstruct)
1163 {
1164 // Don't allow nested structs - uplevel reference may not be convertible
1165 StructDeclaration *sd = ((TypeStruct *)ntb)->sym;
1166 sd->size(e->loc); // resolve any forward references
1167 if (sd->isNested())
1168 return;
1169 }
1170 if (ntb->isZeroInit(e->loc))
1171 {
1172 /* Zeros are implicitly convertible, except for special cases.
1173 */
1174 if (ntb->ty == Tclass)
1175 {
1176 /* With new() must look at the class instance initializer.
1177 */
1178 ClassDeclaration *cd = ((TypeClass *)ntb)->sym;
1179
1180 cd->size(e->loc); // resolve any forward references
1181
1182 if (cd->isNested())
1183 return; // uplevel reference may not be convertible
1184
1185 assert(!cd->isInterfaceDeclaration());
1186
1187 struct ClassCheck
1188 {
1189 static bool convertible(Loc loc, ClassDeclaration *cd, MOD mod)
1190 {
1191 for (size_t i = 0; i < cd->fields.dim; i++)
1192 {
1193 VarDeclaration *v = cd->fields[i];
1194 Initializer *init = v->_init;
1195 if (init)
1196 {
1197 if (init->isVoidInitializer())
1198 ;
1199 else if (ExpInitializer *ei = init->isExpInitializer())
1200 {
1201 Type *tb = v->type->toBasetype();
1202 if (implicitMod(ei->exp, tb, mod) == MATCHnomatch)
1203 return false;
1204 }
1205 else
1206 {
1207 /* Enhancement: handle StructInitializer and ArrayInitializer
1208 */
1209 return false;
1210 }
1211 }
1212 else if (!v->type->isZeroInit(loc))
1213 return false;
1214 }
1215 return cd->baseClass ? convertible(loc, cd->baseClass, mod) : true;
1216 }
1217 };
1218
1219 if (!ClassCheck::convertible(e->loc, cd, mod))
1220 return;
1221 }
1222 }
1223 else
1224 {
1225 Expression *earg = e->newtype->defaultInitLiteral(e->loc);
1226 Type *targ = e->newtype->toBasetype();
1227
1228 if (implicitMod(earg, targ, mod) == MATCHnomatch)
1229 return;
1230 }
1231
1232 /* Success
1233 */
1234 result = MATCHconst;
1235 }
1236
1237 void visit(SliceExp *e)
1238 {
1239 //printf("SliceExp::implicitConvTo e = %s, type = %s\n", e->toChars(), e->type->toChars());
1240 visit((Expression *)e);
1241 if (result != MATCHnomatch)
1242 return;
1243
1244 Type *tb = t->toBasetype();
1245 Type *typeb = e->type->toBasetype();
1246 if (tb->ty == Tsarray && typeb->ty == Tarray)
1247 {
1248 typeb = toStaticArrayType(e);
1249 if (typeb)
1250 result = typeb->implicitConvTo(t);
1251 return;
1252 }
1253
1254 /* If the only reason it won't convert is because of the mod bits,
1255 * then test for conversion by seeing if e1 can be converted with those
1256 * same mod bits.
1257 */
1258 Type *t1b = e->e1->type->toBasetype();
1259 if (tb->ty == Tarray && typeb->equivalent(tb))
1260 {
1261 Type *tbn = tb->nextOf();
1262 Type *tx = NULL;
1263
1264 /* If e->e1 is dynamic array or pointer, the uniqueness of e->e1
1265 * is equivalent with the uniqueness of the referred data. And in here
1266 * we can have arbitrary typed reference for that.
1267 */
1268 if (t1b->ty == Tarray)
1269 tx = tbn->arrayOf();
1270 if (t1b->ty == Tpointer)
1271 tx = tbn->pointerTo();
1272
1273 /* If e->e1 is static array, at least it should be an rvalue.
1274 * If not, e->e1 is a reference, and its uniqueness does not link
1275 * to the uniqueness of the referred data.
1276 */
1277 if (t1b->ty == Tsarray && !e->e1->isLvalue())
1278 tx = tbn->sarrayOf(t1b->size() / tbn->size());
1279
1280 if (tx)
1281 {
1282 result = e->e1->implicitConvTo(tx);
1283 if (result > MATCHconst) // Match level is MATCHconst at best.
1284 result = MATCHconst;
1285 }
1286 }
1287
1288 // Enhancement 10724
1289 if (tb->ty == Tpointer && e->e1->op == TOKstring)
1290 e->e1->accept(this);
1291 }
1292 };
1293
1294 ImplicitConvTo v(t);
1295 e->accept(&v);
1296 return v.result;
1297 }
1298
1299 Type *toStaticArrayType(SliceExp *e)
1300 {
1301 if (e->lwr && e->upr)
1302 {
1303 // For the following code to work, e should be optimized beforehand.
1304 // (eg. $ in lwr and upr should be already resolved, if possible)
1305 Expression *lwr = e->lwr->optimize(WANTvalue);
1306 Expression *upr = e->upr->optimize(WANTvalue);
1307 if (lwr->isConst() && upr->isConst())
1308 {
1309 size_t len = (size_t)(upr->toUInteger() - lwr->toUInteger());
1310 return e->type->toBasetype()->nextOf()->sarrayOf(len);
1311 }
1312 }
1313 else
1314 {
1315 Type *t1b = e->e1->type->toBasetype();
1316 if (t1b->ty == Tsarray)
1317 return t1b;
1318 }
1319 return NULL;
1320 }
1321
1322 /* ==================== castTo ====================== */
1323
1324 /**************************************
1325 * Do an explicit cast.
1326 * Assume that the 'this' expression does not have any indirections.
1327 */
1328
1329 Expression *castTo(Expression *e, Scope *sc, Type *t)
1330 {
1331 class CastTo : public Visitor
1332 {
1333 public:
1334 Type *t;
1335 Scope *sc;
1336 Expression *result;
1337
1338 CastTo(Scope *sc, Type *t)
1339 : t(t), sc(sc)
1340 {
1341 result = NULL;
1342 }
1343
1344 void visit(Expression *e)
1345 {
1346 //printf("Expression::castTo(this=%s, t=%s)\n", e->toChars(), t->toChars());
1347 if (e->type->equals(t))
1348 {
1349 result = e;
1350 return;
1351 }
1352 if (e->op == TOKvar)
1353 {
1354 VarDeclaration *v = ((VarExp *)e)->var->isVarDeclaration();
1355 if (v && v->storage_class & STCmanifest)
1356 {
1357 result = e->ctfeInterpret();
1358 result = result->castTo(sc, t);
1359 return;
1360 }
1361 }
1362
1363 Type *tob = t->toBasetype();
1364 Type *t1b = e->type->toBasetype();
1365 if (tob->equals(t1b))
1366 {
1367 result = e->copy(); // because of COW for assignment to e->type
1368 result->type = t;
1369 return;
1370 }
1371
1372 /* Make semantic error against invalid cast between concrete types.
1373 * Assume that 'e' is never be any placeholder expressions.
1374 * The result of these checks should be consistent with CastExp::toElem().
1375 */
1376
1377 // Fat Value types
1378 const bool tob_isFV = (tob->ty == Tstruct || tob->ty == Tsarray || tob->ty == Tvector);
1379 const bool t1b_isFV = (t1b->ty == Tstruct || t1b->ty == Tsarray || t1b->ty == Tvector);
1380
1381 // Fat Reference types
1382 const bool tob_isFR = (tob->ty == Tarray || tob->ty == Tdelegate);
1383 const bool t1b_isFR = (t1b->ty == Tarray || t1b->ty == Tdelegate);
1384
1385 // Reference types
1386 const bool tob_isR = (tob_isFR || tob->ty == Tpointer || tob->ty == Taarray || tob->ty == Tclass);
1387 const bool t1b_isR = (t1b_isFR || t1b->ty == Tpointer || t1b->ty == Taarray || t1b->ty == Tclass);
1388
1389 // Arithmetic types (== valueable basic types)
1390 const bool tob_isA = ((tob->isintegral() || tob->isfloating()) && tob->ty != Tvector);
1391 const bool t1b_isA = ((t1b->isintegral() || t1b->isfloating()) && t1b->ty != Tvector);
1392
1393 if (AggregateDeclaration *t1ad = isAggregate(t1b))
1394 {
1395 AggregateDeclaration *toad = isAggregate(tob);
1396 if (t1ad != toad && t1ad->aliasthis)
1397 {
1398 if (t1b->ty == Tclass && tob->ty == Tclass)
1399 {
1400 ClassDeclaration *t1cd = t1b->isClassHandle();
1401 ClassDeclaration *tocd = tob->isClassHandle();
1402 int offset;
1403 if (tocd->isBaseOf(t1cd, &offset))
1404 goto Lok;
1405 }
1406
1407 /* Forward the cast to our alias this member, rewrite to:
1408 * cast(to)e1.aliasthis
1409 */
1410 result = resolveAliasThis(sc, e);
1411 result = result->castTo(sc, t);
1412 return;
1413 }
1414 }
1415 else if (tob->ty == Tvector && t1b->ty != Tvector)
1416 {
1417 //printf("test1 e = %s, e->type = %s, tob = %s\n", e->toChars(), e->type->toChars(), tob->toChars());
1418 TypeVector *tv = (TypeVector *)tob;
1419 result = new CastExp(e->loc, e, tv->elementType());
1420 result = new VectorExp(e->loc, result, tob);
1421 result = ::semantic(result, sc);
1422 return;
1423 }
1424 else if (tob->ty != Tvector && t1b->ty == Tvector)
1425 {
1426 // T[n] <-- __vector(U[m])
1427 if (tob->ty == Tsarray)
1428 {
1429 if (t1b->size(e->loc) == tob->size(e->loc))
1430 goto Lok;
1431 }
1432 goto Lfail;
1433 }
1434 else if (t1b->implicitConvTo(tob) == MATCHconst && t->equals(e->type->constOf()))
1435 {
1436 result = e->copy();
1437 result->type = t;
1438 return;
1439 }
1440
1441 // arithmetic values vs. other arithmetic values
1442 // arithmetic values vs. T*
1443 if ((tob_isA && (t1b_isA || t1b->ty == Tpointer)) ||
1444 (t1b_isA && (tob_isA || tob->ty == Tpointer)))
1445 {
1446 goto Lok;
1447 }
1448
1449 // arithmetic values vs. references or fat values
1450 if ((tob_isA && (t1b_isR || t1b_isFV)) ||
1451 (t1b_isA && (tob_isR || tob_isFV)))
1452 {
1453 goto Lfail;
1454 }
1455
1456 // Bugzlla 3133: A cast between fat values is possible only when the sizes match.
1457 if (tob_isFV && t1b_isFV)
1458 {
1459 if (t1b->size(e->loc) == tob->size(e->loc))
1460 goto Lok;
1461 e->error("cannot cast expression %s of type %s to %s because of different sizes",
1462 e->toChars(), e->type->toChars(), t->toChars());
1463 result = new ErrorExp();
1464 return;
1465 }
1466
1467 // Fat values vs. null or references
1468 if ((tob_isFV && (t1b->ty == Tnull || t1b_isR)) ||
1469 (t1b_isFV && (tob->ty == Tnull || tob_isR)))
1470 {
1471 if (tob->ty == Tpointer && t1b->ty == Tsarray)
1472 {
1473 // T[n] sa;
1474 // cast(U*)sa; // ==> cast(U*)sa.ptr;
1475 result = new AddrExp(e->loc, e, t);
1476 return;
1477 }
1478 if (tob->ty == Tarray && t1b->ty == Tsarray)
1479 {
1480 // T[n] sa;
1481 // cast(U[])sa; // ==> cast(U[])sa[];
1482 d_uns64 fsize = t1b->nextOf()->size();
1483 d_uns64 tsize = tob->nextOf()->size();
1484 if ((((TypeSArray *)t1b)->dim->toInteger() * fsize) % tsize != 0)
1485 {
1486 // copied from sarray_toDarray() in e2ir.c
1487 e->error("cannot cast expression %s of type %s to %s since sizes don't line up",
1488 e->toChars(), e->type->toChars(), t->toChars());
1489 result = new ErrorExp();
1490 return;
1491 }
1492 goto Lok;
1493 }
1494 goto Lfail;
1495 }
1496
1497 /* For references, any reinterpret casts are allowed to same 'ty' type.
1498 * T* to U*
1499 * R1 function(P1) to R2 function(P2)
1500 * R1 delegate(P1) to R2 delegate(P2)
1501 * T[] to U[]
1502 * V1[K1] to V2[K2]
1503 * class/interface A to B (will be a dynamic cast if possible)
1504 */
1505 if (tob->ty == t1b->ty && tob_isR && t1b_isR)
1506 goto Lok;
1507
1508 // typeof(null) <-- non-null references or values
1509 if (tob->ty == Tnull && t1b->ty != Tnull)
1510 goto Lfail; // Bugzilla 14629
1511 // typeof(null) --> non-null references or arithmetic values
1512 if (t1b->ty == Tnull && tob->ty != Tnull)
1513 goto Lok;
1514
1515 // Check size mismatch of references.
1516 // Tarray and Tdelegate are (void*).sizeof*2, but others have (void*).sizeof.
1517 if ((tob_isFR && t1b_isR) || (t1b_isFR && tob_isR))
1518 {
1519 if (tob->ty == Tpointer && t1b->ty == Tarray)
1520 {
1521 // T[] da;
1522 // cast(U*)da; // ==> cast(U*)da.ptr;
1523 goto Lok;
1524 }
1525 if (tob->ty == Tpointer && t1b->ty == Tdelegate)
1526 {
1527 // void delegate() dg;
1528 // cast(U*)dg; // ==> cast(U*)dg.ptr;
1529 // Note that it happens even when U is a Tfunction!
1530 e->deprecation("casting from %s to %s is deprecated", e->type->toChars(), t->toChars());
1531 goto Lok;
1532 }
1533 goto Lfail;
1534 }
1535
1536 if (t1b->ty == Tvoid && tob->ty != Tvoid)
1537 {
1538 Lfail:
1539 e->error("cannot cast expression %s of type %s to %s",
1540 e->toChars(), e->type->toChars(), t->toChars());
1541 result = new ErrorExp();
1542 return;
1543 }
1544
1545 Lok:
1546 result = new CastExp(e->loc, e, t);
1547 result->type = t; // Don't call semantic()
1548 //printf("Returning: %s\n", result->toChars());
1549 }
1550
1551 void visit(ErrorExp *e)
1552 {
1553 result = e;
1554 }
1555
1556 void visit(RealExp *e)
1557 {
1558 if (!e->type->equals(t))
1559 {
1560 if ((e->type->isreal() && t->isreal()) ||
1561 (e->type->isimaginary() && t->isimaginary())
1562 )
1563 {
1564 result = e->copy();
1565 result->type = t;
1566 }
1567 else
1568 visit((Expression *)e);
1569 return;
1570 }
1571 result = e;
1572 }
1573
1574 void visit(ComplexExp *e)
1575 {
1576 if (!e->type->equals(t))
1577 {
1578 if (e->type->iscomplex() && t->iscomplex())
1579 {
1580 result = e->copy();
1581 result->type = t;
1582 }
1583 else
1584 visit((Expression *)e);
1585 return;
1586 }
1587 result = e;
1588 }
1589
1590 void visit(NullExp *e)
1591 {
1592 //printf("NullExp::castTo(t = %s) %s\n", t->toChars(), toChars());
1593 visit((Expression *)e);
1594 if (result->op == TOKnull)
1595 {
1596 NullExp *ex = (NullExp *)result;
1597 ex->committed = 1;
1598 return;
1599 }
1600 }
1601
1602 void visit(StructLiteralExp *e)
1603 {
1604 visit((Expression *)e);
1605 if (result->op == TOKstructliteral)
1606 ((StructLiteralExp *)result)->stype = t; // commit type
1607 }
1608
1609 void visit(StringExp *e)
1610 {
1611 /* This follows copy-on-write; any changes to 'this'
1612 * will result in a copy.
1613 * The this->string member is considered immutable.
1614 */
1615 int copied = 0;
1616
1617 //printf("StringExp::castTo(t = %s), '%s' committed = %d\n", t->toChars(), e->toChars(), e->committed);
1618
1619 if (!e->committed && t->ty == Tpointer && t->nextOf()->ty == Tvoid)
1620 {
1621 e->error("cannot convert string literal to void*");
1622 result = new ErrorExp();
1623 return;
1624 }
1625
1626 StringExp *se = e;
1627 if (!e->committed)
1628 {
1629 se = (StringExp *)e->copy();
1630 se->committed = 1;
1631 copied = 1;
1632 }
1633
1634 if (e->type->equals(t))
1635 {
1636 result = se;
1637 return;
1638 }
1639
1640 Type *tb = t->toBasetype();
1641 //printf("\ttype = %s\n", e->type->toChars());
1642 if (tb->ty == Tdelegate && e->type->toBasetype()->ty != Tdelegate)
1643 {
1644 visit((Expression *)e);
1645 return;
1646 }
1647
1648 Type *typeb = e->type->toBasetype();
1649 if (typeb->equals(tb))
1650 {
1651 if (!copied)
1652 {
1653 se = (StringExp *)e->copy();
1654 copied = 1;
1655 }
1656 se->type = t;
1657 result = se;
1658 return;
1659 }
1660
1661 /* Handle reinterpret casts:
1662 * cast(wchar[3])"abcd"c --> [\u6261, \u6463, \u0000]
1663 * cast(wchar[2])"abcd"c --> [\u6261, \u6463]
1664 * cast(wchar[1])"abcd"c --> [\u6261]
1665 */
1666 if (e->committed && tb->ty == Tsarray && typeb->ty == Tarray)
1667 {
1668 se = (StringExp *)e->copy();
1669 d_uns64 szx = tb->nextOf()->size();
1670 assert(szx <= 255);
1671 se->sz = (unsigned char)szx;
1672 se->len = (size_t)((TypeSArray *)tb)->dim->toInteger();
1673 se->committed = 1;
1674 se->type = t;
1675
1676 /* Assure space for terminating 0
1677 */
1678 if ((se->len + 1) * se->sz > (e->len + 1) * e->sz)
1679 {
1680 void *s = (void *)mem.xmalloc((se->len + 1) * se->sz);
1681 memcpy(s, se->string, se->len * se->sz);
1682 memset((char *)s + se->len * se->sz, 0, se->sz);
1683 se->string = s;
1684 }
1685 result = se;
1686 return;
1687 }
1688
1689 if (tb->ty != Tsarray && tb->ty != Tarray && tb->ty != Tpointer)
1690 {
1691 if (!copied)
1692 {
1693 se = (StringExp *)e->copy();
1694 copied = 1;
1695 }
1696 goto Lcast;
1697 }
1698 if (typeb->ty != Tsarray && typeb->ty != Tarray && typeb->ty != Tpointer)
1699 {
1700 if (!copied)
1701 {
1702 se = (StringExp *)e->copy();
1703 copied = 1;
1704 }
1705 goto Lcast;
1706 }
1707
1708 if (typeb->nextOf()->size() == tb->nextOf()->size())
1709 {
1710 if (!copied)
1711 {
1712 se = (StringExp *)e->copy();
1713 copied = 1;
1714 }
1715 if (tb->ty == Tsarray)
1716 goto L2; // handle possible change in static array dimension
1717 se->type = t;
1718 result = se;
1719 return;
1720 }
1721
1722 if (e->committed)
1723 goto Lcast;
1724
1725 #define X(tf,tt) ((int)(tf) * 256 + (int)(tt))
1726 {
1727 OutBuffer buffer;
1728 size_t newlen = 0;
1729 int tfty = typeb->nextOf()->toBasetype()->ty;
1730 int ttty = tb->nextOf()->toBasetype()->ty;
1731 switch (X(tfty, ttty))
1732 {
1733 case X(Tchar, Tchar):
1734 case X(Twchar,Twchar):
1735 case X(Tdchar,Tdchar):
1736 break;
1737
1738 case X(Tchar, Twchar):
1739 for (size_t u = 0; u < e->len;)
1740 {
1741 unsigned c;
1742 const char *p = utf_decodeChar((utf8_t *)se->string, e->len, &u, &c);
1743 if (p)
1744 e->error("%s", p);
1745 else
1746 buffer.writeUTF16(c);
1747 }
1748 newlen = buffer.offset / 2;
1749 buffer.writeUTF16(0);
1750 goto L1;
1751
1752 case X(Tchar, Tdchar):
1753 for (size_t u = 0; u < e->len;)
1754 {
1755 unsigned c;
1756 const char *p = utf_decodeChar((utf8_t *)se->string, e->len, &u, &c);
1757 if (p)
1758 e->error("%s", p);
1759 buffer.write4(c);
1760 newlen++;
1761 }
1762 buffer.write4(0);
1763 goto L1;
1764
1765 case X(Twchar,Tchar):
1766 for (size_t u = 0; u < e->len;)
1767 {
1768 unsigned c;
1769 const char *p = utf_decodeWchar((unsigned short *)se->string, e->len, &u, &c);
1770 if (p)
1771 e->error("%s", p);
1772 else
1773 buffer.writeUTF8(c);
1774 }
1775 newlen = buffer.offset;
1776 buffer.writeUTF8(0);
1777 goto L1;
1778
1779 case X(Twchar,Tdchar):
1780 for (size_t u = 0; u < e->len;)
1781 {
1782 unsigned c;
1783 const char *p = utf_decodeWchar((unsigned short *)se->string, e->len, &u, &c);
1784 if (p)
1785 e->error("%s", p);
1786 buffer.write4(c);
1787 newlen++;
1788 }
1789 buffer.write4(0);
1790 goto L1;
1791
1792 case X(Tdchar,Tchar):
1793 for (size_t u = 0; u < e->len; u++)
1794 {
1795 unsigned c = ((unsigned *)se->string)[u];
1796 if (!utf_isValidDchar(c))
1797 e->error("invalid UCS-32 char \\U%08x", c);
1798 else
1799 buffer.writeUTF8(c);
1800 newlen++;
1801 }
1802 newlen = buffer.offset;
1803 buffer.writeUTF8(0);
1804 goto L1;
1805
1806 case X(Tdchar,Twchar):
1807 for (size_t u = 0; u < e->len; u++)
1808 {
1809 unsigned c = ((unsigned *)se->string)[u];
1810 if (!utf_isValidDchar(c))
1811 e->error("invalid UCS-32 char \\U%08x", c);
1812 else
1813 buffer.writeUTF16(c);
1814 newlen++;
1815 }
1816 newlen = buffer.offset / 2;
1817 buffer.writeUTF16(0);
1818 goto L1;
1819
1820 L1:
1821 if (!copied)
1822 {
1823 se = (StringExp *)e->copy();
1824 copied = 1;
1825 }
1826 se->string = buffer.extractData();
1827 se->len = newlen;
1828
1829 {
1830 d_uns64 szx = tb->nextOf()->size();
1831 assert(szx <= 255);
1832 se->sz = (unsigned char)szx;
1833 }
1834 break;
1835
1836 default:
1837 assert(typeb->nextOf()->size() != tb->nextOf()->size());
1838 goto Lcast;
1839 }
1840 }
1841 #undef X
1842 L2:
1843 assert(copied);
1844
1845 // See if need to truncate or extend the literal
1846 if (tb->ty == Tsarray)
1847 {
1848 size_t dim2 = (size_t)((TypeSArray *)tb)->dim->toInteger();
1849
1850 //printf("dim from = %d, to = %d\n", (int)se->len, (int)dim2);
1851
1852 // Changing dimensions
1853 if (dim2 != se->len)
1854 {
1855 // Copy when changing the string literal
1856 size_t newsz = se->sz;
1857 size_t d = (dim2 < se->len) ? dim2 : se->len;
1858 void *s = (void *)mem.xmalloc((dim2 + 1) * newsz);
1859 memcpy(s, se->string, d * newsz);
1860 // Extend with 0, add terminating 0
1861 memset((char *)s + d * newsz, 0, (dim2 + 1 - d) * newsz);
1862 se->string = s;
1863 se->len = dim2;
1864 }
1865 }
1866 se->type = t;
1867 result = se;
1868 return;
1869
1870 Lcast:
1871 result = new CastExp(e->loc, se, t);
1872 result->type = t; // so semantic() won't be run on e
1873 }
1874
1875 void visit(AddrExp *e)
1876 {
1877 Type *tb;
1878
1879 result = e;
1880
1881 tb = t->toBasetype();
1882 e->type = e->type->toBasetype();
1883 if (!tb->equals(e->type))
1884 {
1885 // Look for pointers to functions where the functions are overloaded.
1886
1887 if (e->e1->op == TOKoverloadset &&
1888 (t->ty == Tpointer || t->ty == Tdelegate) && t->nextOf()->ty == Tfunction)
1889 {
1890 OverExp *eo = (OverExp *)e->e1;
1891 FuncDeclaration *f = NULL;
1892 for (size_t i = 0; i < eo->vars->a.dim; i++)
1893 {
1894 Dsymbol *s = eo->vars->a[i];
1895 FuncDeclaration *f2 = s->isFuncDeclaration();
1896 assert(f2);
1897 if (f2->overloadExactMatch(t->nextOf()))
1898 {
1899 if (f)
1900 {
1901 /* Error if match in more than one overload set,
1902 * even if one is a 'better' match than the other.
1903 */
1904 ScopeDsymbol::multiplyDefined(e->loc, f, f2);
1905 }
1906 else
1907 f = f2;
1908 }
1909 }
1910 if (f)
1911 {
1912 f->tookAddressOf++;
1913 SymOffExp *se = new SymOffExp(e->loc, f, 0, false);
1914 ::semantic(se, sc);
1915 // Let SymOffExp::castTo() do the heavy lifting
1916 visit(se);
1917 return;
1918 }
1919 }
1920
1921 if (e->type->ty == Tpointer && e->type->nextOf()->ty == Tfunction &&
1922 tb->ty == Tpointer && tb->nextOf()->ty == Tfunction &&
1923 e->e1->op == TOKvar)
1924 {
1925 VarExp *ve = (VarExp *)e->e1;
1926 FuncDeclaration *f = ve->var->isFuncDeclaration();
1927 if (f)
1928 {
1929 assert(f->isImportedSymbol());
1930 f = f->overloadExactMatch(tb->nextOf());
1931 if (f)
1932 {
1933 result = new VarExp(e->loc, f, false);
1934 result->type = f->type;
1935 result = new AddrExp(e->loc, result, t);
1936 return;
1937 }
1938 }
1939 }
1940
1941 if (FuncDeclaration *f = isFuncAddress(e))
1942 {
1943 if (f->checkForwardRef(e->loc))
1944 {
1945 result = new ErrorExp();
1946 return;
1947 }
1948 }
1949
1950 visit((Expression *)e);
1951 }
1952 result->type = t;
1953 }
1954
1955 void visit(TupleExp *e)
1956 {
1957 if (e->type->equals(t))
1958 {
1959 result = e;
1960 return;
1961 }
1962
1963 TupleExp *te = (TupleExp *)e->copy();
1964 te->e0 = e->e0 ? e->e0->copy() : NULL;
1965 te->exps = (Expressions *)e->exps->copy();
1966 for (size_t i = 0; i < te->exps->dim; i++)
1967 {
1968 Expression *ex = (*te->exps)[i];
1969 ex = ex->castTo(sc, t);
1970 (*te->exps)[i] = ex;
1971 }
1972 result = te;
1973
1974 /* Questionable behavior: In here, result->type is not set to t.
1975 * Therefoe:
1976 * TypeTuple!(int, int) values;
1977 * auto values2 = cast(long)values;
1978 * // typeof(values2) == TypeTuple!(int, int) !!
1979 *
1980 * Only when the casted tuple is immediately expanded, it would work.
1981 * auto arr = [cast(long)values];
1982 * // typeof(arr) == long[]
1983 */
1984 }
1985
1986 void visit(ArrayLiteralExp *e)
1987 {
1988 if (e->type == t)
1989 {
1990 result = e;
1991 return;
1992 }
1993 ArrayLiteralExp *ae = e;
1994 Type *typeb = e->type->toBasetype();
1995 Type *tb = t->toBasetype();
1996 if ((tb->ty == Tarray || tb->ty == Tsarray) &&
1997 (typeb->ty == Tarray || typeb->ty == Tsarray))
1998 {
1999 if (tb->nextOf()->toBasetype()->ty == Tvoid && typeb->nextOf()->toBasetype()->ty != Tvoid)
2000 {
2001 // Don't do anything to cast non-void[] to void[]
2002 }
2003 else if (typeb->ty == Tsarray && typeb->nextOf()->toBasetype()->ty == Tvoid)
2004 {
2005 // Don't do anything for casting void[n] to others
2006 }
2007 else
2008 {
2009 if (tb->ty == Tsarray)
2010 {
2011 TypeSArray *tsa = (TypeSArray *)tb;
2012 if (e->elements->dim != tsa->dim->toInteger())
2013 goto L1;
2014 }
2015
2016 ae = (ArrayLiteralExp *)e->copy();
2017 if (e->basis)
2018 ae->basis = e->basis->castTo(sc, tb->nextOf());
2019 ae->elements = e->elements->copy();
2020 for (size_t i = 0; i < e->elements->dim; i++)
2021 {
2022 Expression *ex = (*e->elements)[i];
2023 if (!ex)
2024 continue;
2025 ex = ex->castTo(sc, tb->nextOf());
2026 (*ae->elements)[i] = ex;
2027 }
2028 ae->type = t;
2029 result = ae;
2030 return;
2031 }
2032 }
2033 else if (tb->ty == Tpointer && typeb->ty == Tsarray)
2034 {
2035 Type *tp = typeb->nextOf()->pointerTo();
2036 if (!tp->equals(ae->type))
2037 {
2038 ae = (ArrayLiteralExp *)e->copy();
2039 ae->type = tp;
2040 }
2041 }
2042 else if (tb->ty == Tvector &&
2043 (typeb->ty == Tarray || typeb->ty == Tsarray))
2044 {
2045 // Convert array literal to vector type
2046 TypeVector *tv = (TypeVector *)tb;
2047 TypeSArray *tbase = (TypeSArray *)tv->basetype;
2048 assert(tbase->ty == Tsarray);
2049 const size_t edim = e->elements->dim;
2050 const size_t tbasedim = tbase->dim->toInteger();
2051 if (edim > tbasedim)
2052 goto L1;
2053
2054 ae = (ArrayLiteralExp *)e->copy();
2055 ae->type = tbase; // Bugzilla 12642
2056 ae->elements = e->elements->copy();
2057 Type *telement = tv->elementType();
2058 for (size_t i = 0; i < edim; i++)
2059 {
2060 Expression *ex = (*e->elements)[i];
2061 ex = ex->castTo(sc, telement);
2062 (*ae->elements)[i] = ex;
2063 }
2064 // Fill in the rest with the default initializer
2065 ae->elements->setDim(tbasedim);
2066 for (size_t i = edim; i < tbasedim; i++)
2067 {
2068 Expression *ex = typeb->nextOf()->defaultInitLiteral(e->loc);
2069 ex = ex->castTo(sc, telement);
2070 (*ae->elements)[i] = ex;
2071 }
2072 Expression *ev = new VectorExp(e->loc, ae, tb);
2073 ev = ::semantic(ev, sc);
2074 result = ev;
2075 return;
2076 }
2077 L1:
2078 visit((Expression *)ae);
2079 }
2080
2081 void visit(AssocArrayLiteralExp *e)
2082 {
2083 if (e->type == t)
2084 {
2085 result = e;
2086 return;
2087 }
2088 Type *typeb = e->type->toBasetype();
2089 Type *tb = t->toBasetype();
2090 if (tb->ty == Taarray && typeb->ty == Taarray &&
2091 tb->nextOf()->toBasetype()->ty != Tvoid)
2092 {
2093 AssocArrayLiteralExp *ae = (AssocArrayLiteralExp *)e->copy();
2094 ae->keys = e->keys->copy();
2095 ae->values = e->values->copy();
2096 assert(e->keys->dim == e->values->dim);
2097 for (size_t i = 0; i < e->keys->dim; i++)
2098 {
2099 Expression *ex = (*e->values)[i];
2100 ex = ex->castTo(sc, tb->nextOf());
2101 (*ae->values)[i] = ex;
2102
2103 ex = (*e->keys)[i];
2104 ex = ex->castTo(sc, ((TypeAArray *)tb)->index);
2105 (*ae->keys)[i] = ex;
2106 }
2107 ae->type = t;
2108 result = ae;
2109 return;
2110 }
2111 visit((Expression *)e);
2112 }
2113
2114 void visit(SymOffExp *e)
2115 {
2116 if (e->type == t && !e->hasOverloads)
2117 {
2118 result = e;
2119 return;
2120 }
2121 Type *tb = t->toBasetype();
2122 Type *typeb = e->type->toBasetype();
2123
2124 if (tb->equals(typeb))
2125 {
2126 result = e->copy();
2127 result->type = t;
2128 ((SymOffExp *)result)->hasOverloads = false;
2129 return;
2130 }
2131
2132 // Look for pointers to functions where the functions are overloaded.
2133 if (e->hasOverloads &&
2134 typeb->ty == Tpointer && typeb->nextOf()->ty == Tfunction &&
2135 (tb->ty == Tpointer || tb->ty == Tdelegate) && tb->nextOf()->ty == Tfunction)
2136 {
2137 FuncDeclaration *f = e->var->isFuncDeclaration();
2138 f = f ? f->overloadExactMatch(tb->nextOf()) : NULL;
2139 if (f)
2140 {
2141 if (tb->ty == Tdelegate)
2142 {
2143 if (f->needThis() && hasThis(sc))
2144 {
2145 result = new DelegateExp(e->loc, new ThisExp(e->loc), f, false);
2146 result = ::semantic(result, sc);
2147 }
2148 else if (f->isNested())
2149 {
2150 result = new DelegateExp(e->loc, new IntegerExp(0), f, false);
2151 result = ::semantic(result, sc);
2152 }
2153 else if (f->needThis())
2154 {
2155 e->error("no 'this' to create delegate for %s", f->toChars());
2156 result = new ErrorExp();
2157 return;
2158 }
2159 else
2160 {
2161 e->error("cannot cast from function pointer to delegate");
2162 result = new ErrorExp();
2163 return;
2164 }
2165 }
2166 else
2167 {
2168 result = new SymOffExp(e->loc, f, 0, false);
2169 result->type = t;
2170 }
2171 f->tookAddressOf++;
2172 return;
2173 }
2174 }
2175
2176 if (FuncDeclaration *f = isFuncAddress(e))
2177 {
2178 if (f->checkForwardRef(e->loc))
2179 {
2180 result = new ErrorExp();
2181 return;
2182 }
2183 }
2184
2185 visit((Expression *)e);
2186 }
2187
2188 void visit(DelegateExp *e)
2189 {
2190 static const char msg[] = "cannot form delegate due to covariant return type";
2191
2192 Type *tb = t->toBasetype();
2193 Type *typeb = e->type->toBasetype();
2194 if (!tb->equals(typeb) || e->hasOverloads)
2195 {
2196 // Look for delegates to functions where the functions are overloaded.
2197 if (typeb->ty == Tdelegate &&
2198 tb->ty == Tdelegate)
2199 {
2200 if (e->func)
2201 {
2202 FuncDeclaration *f = e->func->overloadExactMatch(tb->nextOf());
2203 if (f)
2204 {
2205 int offset;
2206 if (f->tintro && f->tintro->nextOf()->isBaseOf(f->type->nextOf(), &offset) && offset)
2207 e->error("%s", msg);
2208 if (f != e->func) // if address not already marked as taken
2209 f->tookAddressOf++;
2210 result = new DelegateExp(e->loc, e->e1, f, false);
2211 result->type = t;
2212 return;
2213 }
2214 if (e->func->tintro)
2215 e->error("%s", msg);
2216 }
2217 }
2218
2219 if (FuncDeclaration *f = isFuncAddress(e))
2220 {
2221 if (f->checkForwardRef(e->loc))
2222 {
2223 result = new ErrorExp();
2224 return;
2225 }
2226 }
2227
2228 visit((Expression *)e);
2229 }
2230 else
2231 {
2232 int offset;
2233 e->func->tookAddressOf++;
2234 if (e->func->tintro && e->func->tintro->nextOf()->isBaseOf(e->func->type->nextOf(), &offset) && offset)
2235 e->error("%s", msg);
2236 result = e->copy();
2237 result->type = t;
2238 }
2239 }
2240
2241 void visit(FuncExp *e)
2242 {
2243 //printf("FuncExp::castTo type = %s, t = %s\n", e->type->toChars(), t->toChars());
2244 FuncExp *fe;
2245 if (e->matchType(t, sc, &fe, 1) > MATCHnomatch)
2246 {
2247 result = fe;
2248 return;
2249 }
2250 visit((Expression *)e);
2251 }
2252
2253 void visit(CondExp *e)
2254 {
2255 if (!e->type->equals(t))
2256 {
2257 result = new CondExp(e->loc, e->econd, e->e1->castTo(sc, t), e->e2->castTo(sc, t));
2258 result->type = t;
2259 return;
2260 }
2261 result = e;
2262 }
2263
2264 void visit(CommaExp *e)
2265 {
2266 Expression *e2c = e->e2->castTo(sc, t);
2267
2268 if (e2c != e->e2)
2269 {
2270 result = new CommaExp(e->loc, e->e1, e2c);
2271 result->type = e2c->type;
2272 }
2273 else
2274 {
2275 result = e;
2276 result->type = e->e2->type;
2277 }
2278 }
2279
2280 void visit(SliceExp *e)
2281 {
2282 //printf("SliceExp::castTo e = %s, type = %s, t = %s\n", e->toChars(), e->type->toChars(), t->toChars());
2283 Type *typeb = e->type->toBasetype();
2284 Type *tb = t->toBasetype();
2285 if (e->type->equals(t) || typeb->ty != Tarray ||
2286 (tb->ty != Tarray && tb->ty != Tsarray))
2287 {
2288 visit((Expression *)e);
2289 return;
2290 }
2291
2292 if (tb->ty == Tarray)
2293 {
2294 if (typeb->nextOf()->equivalent(tb->nextOf()))
2295 {
2296 // T[] to const(T)[]
2297 result = e->copy();
2298 result->type = t;
2299 }
2300 else
2301 {
2302 visit((Expression *)e);
2303 }
2304 return;
2305 }
2306
2307 // Handle the cast from Tarray to Tsarray with CT-known slicing
2308
2309 TypeSArray *tsa = (TypeSArray *)toStaticArrayType(e);
2310 if (tsa && tsa->size(e->loc) == tb->size(e->loc))
2311 {
2312 /* Match if the sarray sizes are equal:
2313 * T[a .. b] to const(T)[b-a]
2314 * T[a .. b] to U[dim] if (T.sizeof*(b-a) == U.sizeof*dim)
2315 *
2316 * If a SliceExp has Tsarray, it will become lvalue.
2317 * That's handled in SliceExp::isLvalue and toLvalue
2318 */
2319 result = e->copy();
2320 result->type = t;
2321 return;
2322 }
2323 if (tsa && tsa->dim->equals(((TypeSArray *)tb)->dim))
2324 {
2325 /* Match if the dimensions are equal
2326 * with the implicit conversion of e->e1:
2327 * cast(float[2]) [2.0, 1.0, 0.0][0..2];
2328 */
2329 Type *t1b = e->e1->type->toBasetype();
2330 if (t1b->ty == Tsarray)
2331 t1b = tb->nextOf()->sarrayOf(((TypeSArray *)t1b)->dim->toInteger());
2332 else if (t1b->ty == Tarray)
2333 t1b = tb->nextOf()->arrayOf();
2334 else if (t1b->ty == Tpointer)
2335 t1b = tb->nextOf()->pointerTo();
2336 else
2337 assert(0);
2338 if (e->e1->implicitConvTo(t1b) > MATCHnomatch)
2339 {
2340 Expression *e1x = e->e1->implicitCastTo(sc, t1b);
2341 assert(e1x->op != TOKerror);
2342 e = (SliceExp *)e->copy();
2343 e->e1 = e1x;
2344 e->type = t;
2345 result = e;
2346 return;
2347 }
2348 }
2349 e->error("cannot cast expression %s of type %s to %s",
2350 e->toChars(), tsa ? tsa->toChars() : e->type->toChars(),
2351 t->toChars());
2352 result = new ErrorExp();
2353 }
2354 };
2355
2356 CastTo v(sc, t);
2357 e->accept(&v);
2358 return v.result;
2359 }
2360
2361 /* ==================== inferType ====================== */
2362
2363 /****************************************
2364 * Set type inference target
2365 * t Target type
2366 * flag 1: don't put an error when inference fails
2367 */
2368
2369 Expression *inferType(Expression *e, Type *t, int flag)
2370 {
2371 class InferType : public Visitor
2372 {
2373 public:
2374 Type *t;
2375 int flag;
2376 Expression *result;
2377
2378 InferType(Type *t, int flag)
2379 : t(t), flag(flag)
2380 {
2381 result = NULL;
2382 }
2383
2384
2385 void visit(Expression *e)
2386 {
2387 result = e;
2388 }
2389
2390 void visit(ArrayLiteralExp *ale)
2391 {
2392 Type *tb = t->toBasetype();
2393 if (tb->ty == Tarray || tb->ty == Tsarray)
2394 {
2395 Type *tn = tb->nextOf();
2396 if (ale->basis)
2397 ale->basis = inferType(ale->basis, tn, flag);
2398 for (size_t i = 0; i < ale->elements->dim; i++)
2399 {
2400 Expression *e = (*ale->elements)[i];
2401 if (e)
2402 {
2403 e = inferType(e, tn, flag);
2404 (*ale->elements)[i] = e;
2405 }
2406 }
2407 }
2408 result = ale;
2409 }
2410
2411 void visit(AssocArrayLiteralExp *aale)
2412 {
2413 Type *tb = t->toBasetype();
2414 if (tb->ty == Taarray)
2415 {
2416 TypeAArray *taa = (TypeAArray *)tb;
2417 Type *ti = taa->index;
2418 Type *tv = taa->nextOf();
2419 for (size_t i = 0; i < aale->keys->dim; i++)
2420 {
2421 Expression *e = (*aale->keys)[i];
2422 if (e)
2423 {
2424 e = inferType(e, ti, flag);
2425 (*aale->keys)[i] = e;
2426 }
2427 }
2428 for (size_t i = 0; i < aale->values->dim; i++)
2429 {
2430 Expression *e = (*aale->values)[i];
2431 if (e)
2432 {
2433 e = inferType(e, tv, flag);
2434 (*aale->values)[i] = e;
2435 }
2436 }
2437 }
2438 result = aale;
2439 }
2440
2441 void visit(FuncExp *fe)
2442 {
2443 //printf("FuncExp::inferType('%s'), to=%s\n", fe->type ? fe->type->toChars() : "null", t->toChars());
2444 if (t->ty == Tdelegate ||
2445 (t->ty == Tpointer && t->nextOf()->ty == Tfunction))
2446 {
2447 fe->fd->treq = t;
2448 }
2449 result = fe;
2450 }
2451
2452 void visit(CondExp *ce)
2453 {
2454 Type *tb = t->toBasetype();
2455 ce->e1 = inferType(ce->e1, tb, flag);
2456 ce->e2 = inferType(ce->e2, tb, flag);
2457 result = ce;
2458 }
2459 };
2460
2461 if (!t)
2462 return e;
2463
2464 InferType v(t, flag);
2465 e->accept(&v);
2466 return v.result;
2467 }
2468
2469 /* ==================== ====================== */
2470
2471 /****************************************
2472 * Scale addition/subtraction to/from pointer.
2473 */
2474
2475 Expression *scaleFactor(BinExp *be, Scope *sc)
2476 {
2477 Type *t1b = be->e1->type->toBasetype();
2478 Type *t2b = be->e2->type->toBasetype();
2479 Expression *eoff;
2480
2481 if (t1b->ty == Tpointer && t2b->isintegral())
2482 {
2483 // Need to adjust operator by the stride
2484 // Replace (ptr + int) with (ptr + (int * stride))
2485 Type *t = Type::tptrdiff_t;
2486
2487 d_uns64 stride = t1b->nextOf()->size(be->loc);
2488 if (!t->equals(t2b))
2489 be->e2 = be->e2->castTo(sc, t);
2490 eoff = be->e2;
2491 be->e2 = new MulExp(be->loc, be->e2, new IntegerExp(Loc(), stride, t));
2492 be->e2->type = t;
2493 be->type = be->e1->type;
2494 }
2495 else if (t2b->ty == Tpointer && t1b->isintegral())
2496 {
2497 // Need to adjust operator by the stride
2498 // Replace (int + ptr) with (ptr + (int * stride))
2499 Type *t = Type::tptrdiff_t;
2500 Expression *e;
2501
2502 d_uns64 stride = t2b->nextOf()->size(be->loc);
2503 if (!t->equals(t1b))
2504 e = be->e1->castTo(sc, t);
2505 else
2506 e = be->e1;
2507 eoff = e;
2508 e = new MulExp(be->loc, e, new IntegerExp(Loc(), stride, t));
2509 e->type = t;
2510 be->type = be->e2->type;
2511 be->e1 = be->e2;
2512 be->e2 = e;
2513 }
2514 else
2515 assert(0);
2516
2517 if (sc->func && !sc->intypeof)
2518 {
2519 eoff = eoff->optimize(WANTvalue);
2520 if (eoff->op == TOKint64 && eoff->toInteger() == 0)
2521 ;
2522 else if (sc->func->setUnsafe())
2523 {
2524 be->error("pointer arithmetic not allowed in @safe functions");
2525 return new ErrorExp();
2526 }
2527 }
2528
2529 return be;
2530 }
2531
2532 /**************************************
2533 * Return true if e is an empty array literal with dimensionality
2534 * equal to or less than type of other array.
2535 * [], [[]], [[[]]], etc.
2536 * I.e., make sure that [1,2] is compatible with [],
2537 * [[1,2]] is compatible with [[]], etc.
2538 */
2539 bool isVoidArrayLiteral(Expression *e, Type *other)
2540 {
2541 while (e->op == TOKarrayliteral && e->type->ty == Tarray
2542 && (((ArrayLiteralExp *)e)->elements->dim == 1))
2543 {
2544 ArrayLiteralExp *ale = (ArrayLiteralExp *)e;
2545 e = ale->getElement(0);
2546 if (other->ty == Tsarray || other->ty == Tarray)
2547 other = other->nextOf();
2548 else
2549 return false;
2550 }
2551 if (other->ty != Tsarray && other->ty != Tarray)
2552 return false;
2553 Type *t = e->type;
2554 return (e->op == TOKarrayliteral && t->ty == Tarray &&
2555 t->nextOf()->ty == Tvoid &&
2556 ((ArrayLiteralExp *)e)->elements->dim == 0);
2557 }
2558
2559 // used by deduceType()
2560 Type *rawTypeMerge(Type *t1, Type *t2)
2561 {
2562 if (t1->equals(t2))
2563 return t1;
2564 if (t1->equivalent(t2))
2565 return t1->castMod(MODmerge(t1->mod, t2->mod));
2566
2567 Type *t1b = t1->toBasetype();
2568 Type *t2b = t2->toBasetype();
2569 if (t1b->equals(t2b))
2570 return t1b;
2571 if (t1b->equivalent(t2b))
2572 return t1b->castMod(MODmerge(t1b->mod, t2b->mod));
2573
2574 TY ty = (TY)impcnvResult[t1b->ty][t2b->ty];
2575 if (ty != Terror)
2576 return Type::basic[ty];
2577
2578 return NULL;
2579 }
2580
2581 /**************************************
2582 * Combine types.
2583 * Output:
2584 * *pt merged type, if *pt is not NULL
2585 * *pe1 rewritten e1
2586 * *pe2 rewritten e2
2587 * Returns:
2588 * true success
2589 * false failed
2590 */
2591
2592 bool typeMerge(Scope *sc, TOK op, Type **pt, Expression **pe1, Expression **pe2)
2593 {
2594 //printf("typeMerge() %s op %s\n", (*pe1)->toChars(), (*pe2)->toChars());
2595
2596 MATCH m;
2597 Expression *e1 = *pe1;
2598 Expression *e2 = *pe2;
2599 Type *t1b = e1->type->toBasetype();
2600 Type *t2b = e2->type->toBasetype();
2601
2602 if (op != TOKquestion ||
2603 (t1b->ty != t2b->ty && (t1b->isTypeBasic() && t2b->isTypeBasic())))
2604 {
2605 e1 = integralPromotions(e1, sc);
2606 e2 = integralPromotions(e2, sc);
2607 }
2608
2609 Type *t1 = e1->type;
2610 Type *t2 = e2->type;
2611 assert(t1);
2612 Type *t = t1;
2613
2614 /* The start type of alias this type recursion.
2615 * In following case, we should save A, and stop recursion
2616 * if it appears again.
2617 * X -> Y -> [A] -> B -> A -> B -> ...
2618 */
2619 Type *att1 = NULL;
2620 Type *att2 = NULL;
2621
2622 //if (t1) printf("\tt1 = %s\n", t1->toChars());
2623 //if (t2) printf("\tt2 = %s\n", t2->toChars());
2624 assert(t2);
2625
2626 if (t1->mod != t2->mod &&
2627 t1->ty == Tenum && t2->ty == Tenum &&
2628 ((TypeEnum *)t1)->sym == ((TypeEnum *)t2)->sym)
2629 {
2630 unsigned char mod = MODmerge(t1->mod, t2->mod);
2631 t1 = t1->castMod(mod);
2632 t2 = t2->castMod(mod);
2633 }
2634
2635 Lagain:
2636 t1b = t1->toBasetype();
2637 t2b = t2->toBasetype();
2638
2639 TY ty = (TY)impcnvResult[t1b->ty][t2b->ty];
2640 if (ty != Terror)
2641 {
2642 TY ty1 = (TY)impcnvType1[t1b->ty][t2b->ty];
2643 TY ty2 = (TY)impcnvType2[t1b->ty][t2b->ty];
2644
2645 if (t1b->ty == ty1) // if no promotions
2646 {
2647 if (t1->equals(t2))
2648 {
2649 t = t1;
2650 goto Lret;
2651 }
2652
2653 if (t1b->equals(t2b))
2654 {
2655 t = t1b;
2656 goto Lret;
2657 }
2658 }
2659
2660 t = Type::basic[ty];
2661
2662 t1 = Type::basic[ty1];
2663 t2 = Type::basic[ty2];
2664 e1 = e1->castTo(sc, t1);
2665 e2 = e2->castTo(sc, t2);
2666 //printf("after typeCombine():\n");
2667 //print();
2668 //printf("ty = %d, ty1 = %d, ty2 = %d\n", ty, ty1, ty2);
2669 goto Lret;
2670 }
2671
2672 t1 = t1b;
2673 t2 = t2b;
2674
2675 if (t1->ty == Ttuple || t2->ty == Ttuple)
2676 goto Lincompatible;
2677
2678 if (t1->equals(t2))
2679 {
2680 // merging can not result in new enum type
2681 if (t->ty == Tenum)
2682 t = t1b;
2683 }
2684 else if ((t1->ty == Tpointer && t2->ty == Tpointer) ||
2685 (t1->ty == Tdelegate && t2->ty == Tdelegate))
2686 {
2687 // Bring pointers to compatible type
2688 Type *t1n = t1->nextOf();
2689 Type *t2n = t2->nextOf();
2690
2691 if (t1n->equals(t2n))
2692 ;
2693 else if (t1n->ty == Tvoid) // pointers to void are always compatible
2694 t = t2;
2695 else if (t2n->ty == Tvoid)
2696 ;
2697 else if (t1->implicitConvTo(t2))
2698 {
2699 goto Lt2;
2700 }
2701 else if (t2->implicitConvTo(t1))
2702 {
2703 goto Lt1;
2704 }
2705 else if (t1n->ty == Tfunction && t2n->ty == Tfunction)
2706 {
2707 TypeFunction *tf1 = (TypeFunction *)t1n;
2708 TypeFunction *tf2 = (TypeFunction *)t2n;
2709 tf1->purityLevel();
2710 tf2->purityLevel();
2711
2712 TypeFunction *d = (TypeFunction *)tf1->syntaxCopy();
2713
2714 if (tf1->purity != tf2->purity)
2715 d->purity = PUREimpure;
2716 assert(d->purity != PUREfwdref);
2717
2718 d->isnothrow = (tf1->isnothrow && tf2->isnothrow);
2719 d->isnogc = (tf1->isnogc && tf2->isnogc);
2720
2721 if (tf1->trust == tf2->trust)
2722 d->trust = tf1->trust;
2723 else if (tf1->trust <= TRUSTsystem || tf2->trust <= TRUSTsystem)
2724 d->trust = TRUSTsystem;
2725 else
2726 d->trust = TRUSTtrusted;
2727
2728 Type *tx = NULL;
2729 if (t1->ty == Tdelegate)
2730 {
2731 tx = new TypeDelegate(d);
2732 }
2733 else
2734 tx = d->pointerTo();
2735
2736 tx = tx->semantic(e1->loc, sc);
2737
2738 if (t1->implicitConvTo(tx) && t2->implicitConvTo(tx))
2739 {
2740 t = tx;
2741 e1 = e1->castTo(sc, t);
2742 e2 = e2->castTo(sc, t);
2743 goto Lret;
2744 }
2745 goto Lincompatible;
2746 }
2747 else if (t1n->mod != t2n->mod)
2748 {
2749 if (!t1n->isImmutable() && !t2n->isImmutable() && t1n->isShared() != t2n->isShared())
2750 goto Lincompatible;
2751 unsigned char mod = MODmerge(t1n->mod, t2n->mod);
2752 t1 = t1n->castMod(mod)->pointerTo();
2753 t2 = t2n->castMod(mod)->pointerTo();
2754 t = t1;
2755 goto Lagain;
2756 }
2757 else if (t1n->ty == Tclass && t2n->ty == Tclass)
2758 {
2759 ClassDeclaration *cd1 = t1n->isClassHandle();
2760 ClassDeclaration *cd2 = t2n->isClassHandle();
2761 int offset;
2762
2763 if (cd1->isBaseOf(cd2, &offset))
2764 {
2765 if (offset)
2766 e2 = e2->castTo(sc, t);
2767 }
2768 else if (cd2->isBaseOf(cd1, &offset))
2769 {
2770 t = t2;
2771 if (offset)
2772 e1 = e1->castTo(sc, t);
2773 }
2774 else
2775 goto Lincompatible;
2776 }
2777 else
2778 {
2779 t1 = t1n->constOf()->pointerTo();
2780 t2 = t2n->constOf()->pointerTo();
2781 if (t1->implicitConvTo(t2))
2782 {
2783 goto Lt2;
2784 }
2785 else if (t2->implicitConvTo(t1))
2786 {
2787 goto Lt1;
2788 }
2789 goto Lincompatible;
2790 }
2791 }
2792 else if ((t1->ty == Tsarray || t1->ty == Tarray) &&
2793 ((e2->op == TOKnull && t2->ty == Tpointer && t2->nextOf()->ty == Tvoid) ||
2794 (e2->op == TOKarrayliteral && t2->ty == Tsarray && t2->nextOf()->ty == Tvoid && ((TypeSArray *)t2)->dim->toInteger() == 0) ||
2795 (isVoidArrayLiteral(e2, t1)))
2796 )
2797 {
2798 /* (T[n] op void*) => T[]
2799 * (T[] op void*) => T[]
2800 * (T[n] op void[0]) => T[]
2801 * (T[] op void[0]) => T[]
2802 * (T[n] op void[]) => T[]
2803 * (T[] op void[]) => T[]
2804 */
2805 goto Lx1;
2806 }
2807 else if ((t2->ty == Tsarray || t2->ty == Tarray) &&
2808 ((e1->op == TOKnull && t1->ty == Tpointer && t1->nextOf()->ty == Tvoid) ||
2809 (e1->op == TOKarrayliteral && t1->ty == Tsarray && t1->nextOf()->ty == Tvoid && ((TypeSArray *)t1)->dim->toInteger() == 0) ||
2810 (isVoidArrayLiteral(e1, t2)))
2811 )
2812 {
2813 /* (void* op T[n]) => T[]
2814 * (void* op T[]) => T[]
2815 * (void[0] op T[n]) => T[]
2816 * (void[0] op T[]) => T[]
2817 * (void[] op T[n]) => T[]
2818 * (void[] op T[]) => T[]
2819 */
2820 goto Lx2;
2821 }
2822 else if ((t1->ty == Tsarray || t1->ty == Tarray) &&
2823 (m = t1->implicitConvTo(t2)) != MATCHnomatch)
2824 {
2825 // Bugzilla 7285: Tsarray op [x, y, ...] should to be Tsarray
2826 // Bugzilla 14737: Tsarray ~ [x, y, ...] should to be Tarray
2827 if (t1->ty == Tsarray && e2->op == TOKarrayliteral && op != TOKcat)
2828 goto Lt1;
2829 if (m == MATCHconst &&
2830 (op == TOKaddass || op == TOKminass || op == TOKmulass ||
2831 op == TOKdivass || op == TOKmodass || op == TOKpowass ||
2832 op == TOKandass || op == TOKorass || op == TOKxorass)
2833 )
2834 {
2835 // Don't make the lvalue const
2836 t = t2;
2837 goto Lret;
2838 }
2839 goto Lt2;
2840 }
2841 else if ((t2->ty == Tsarray || t2->ty == Tarray) && t2->implicitConvTo(t1))
2842 {
2843 // Bugzilla 7285 & 14737
2844 if (t2->ty == Tsarray && e1->op == TOKarrayliteral && op != TOKcat)
2845 goto Lt2;
2846 goto Lt1;
2847 }
2848 else if ((t1->ty == Tsarray || t1->ty == Tarray || t1->ty == Tpointer) &&
2849 (t2->ty == Tsarray || t2->ty == Tarray || t2->ty == Tpointer) &&
2850 t1->nextOf()->mod != t2->nextOf()->mod
2851 )
2852 {
2853 /* If one is mutable and the other invariant, then retry
2854 * with both of them as const
2855 */
2856 Type *t1n = t1->nextOf();
2857 Type *t2n = t2->nextOf();
2858 unsigned char mod;
2859 if (e1->op == TOKnull && e2->op != TOKnull)
2860 mod = t2n->mod;
2861 else if (e1->op != TOKnull && e2->op == TOKnull)
2862 mod = t1n->mod;
2863 else if (!t1n->isImmutable() && !t2n->isImmutable() && t1n->isShared() != t2n->isShared())
2864 goto Lincompatible;
2865 else
2866 mod = MODmerge(t1n->mod, t2n->mod);
2867
2868 if (t1->ty == Tpointer)
2869 t1 = t1n->castMod(mod)->pointerTo();
2870 else
2871 t1 = t1n->castMod(mod)->arrayOf();
2872
2873 if (t2->ty == Tpointer)
2874 t2 = t2n->castMod(mod)->pointerTo();
2875 else
2876 t2 = t2n->castMod(mod)->arrayOf();
2877 t = t1;
2878 goto Lagain;
2879 }
2880 else if (t1->ty == Tclass && t2->ty == Tclass)
2881 {
2882 if (t1->mod != t2->mod)
2883 {
2884 unsigned char mod;
2885 if (e1->op == TOKnull && e2->op != TOKnull)
2886 mod = t2->mod;
2887 else if (e1->op != TOKnull && e2->op == TOKnull)
2888 mod = t1->mod;
2889 else if (!t1->isImmutable() && !t2->isImmutable() && t1->isShared() != t2->isShared())
2890 goto Lincompatible;
2891 else
2892 mod = MODmerge(t1->mod, t2->mod);
2893 t1 = t1->castMod(mod);
2894 t2 = t2->castMod(mod);
2895 t = t1;
2896 goto Lagain;
2897 }
2898 goto Lcc;
2899 }
2900 else if (t1->ty == Tclass || t2->ty == Tclass)
2901 {
2902 Lcc:
2903 while (1)
2904 {
2905 MATCH i1 = e2->implicitConvTo(t1);
2906 MATCH i2 = e1->implicitConvTo(t2);
2907
2908 if (i1 && i2)
2909 {
2910 // We have the case of class vs. void*, so pick class
2911 if (t1->ty == Tpointer)
2912 i1 = MATCHnomatch;
2913 else if (t2->ty == Tpointer)
2914 i2 = MATCHnomatch;
2915 }
2916
2917 if (i2)
2918 {
2919 e2 = e2->castTo(sc, t2);
2920 goto Lt2;
2921 }
2922 else if (i1)
2923 {
2924 e1 = e1->castTo(sc, t1);
2925 goto Lt1;
2926 }
2927 else if (t1->ty == Tclass && t2->ty == Tclass)
2928 {
2929 TypeClass *tc1 = (TypeClass *)t1;
2930 TypeClass *tc2 = (TypeClass *)t2;
2931
2932 /* Pick 'tightest' type
2933 */
2934 ClassDeclaration *cd1 = tc1->sym->baseClass;
2935 ClassDeclaration *cd2 = tc2->sym->baseClass;
2936
2937 if (cd1 && cd2)
2938 {
2939 t1 = cd1->type->castMod(t1->mod);
2940 t2 = cd2->type->castMod(t2->mod);
2941 }
2942 else if (cd1)
2943 t1 = cd1->type;
2944 else if (cd2)
2945 t2 = cd2->type;
2946 else
2947 goto Lincompatible;
2948 }
2949 else if (t1->ty == Tstruct && ((TypeStruct *)t1)->sym->aliasthis)
2950 {
2951 if (att1 && e1->type == att1)
2952 goto Lincompatible;
2953 if (!att1 && e1->type->checkAliasThisRec())
2954 att1 = e1->type;
2955 //printf("att tmerge(c || c) e1 = %s\n", e1->type->toChars());
2956 e1 = resolveAliasThis(sc, e1);
2957 t1 = e1->type;
2958 continue;
2959 }
2960 else if (t2->ty == Tstruct && ((TypeStruct *)t2)->sym->aliasthis)
2961 {
2962 if (att2 && e2->type == att2)
2963 goto Lincompatible;
2964 if (!att2 && e2->type->checkAliasThisRec())
2965 att2 = e2->type;
2966 //printf("att tmerge(c || c) e2 = %s\n", e2->type->toChars());
2967 e2 = resolveAliasThis(sc, e2);
2968 t2 = e2->type;
2969 continue;
2970 }
2971 else
2972 goto Lincompatible;
2973 }
2974 }
2975 else if (t1->ty == Tstruct && t2->ty == Tstruct)
2976 {
2977 if (t1->mod != t2->mod)
2978 {
2979 if (!t1->isImmutable() && !t2->isImmutable() && t1->isShared() != t2->isShared())
2980 goto Lincompatible;
2981 unsigned char mod = MODmerge(t1->mod, t2->mod);
2982 t1 = t1->castMod(mod);
2983 t2 = t2->castMod(mod);
2984 t = t1;
2985 goto Lagain;
2986 }
2987
2988 TypeStruct *ts1 = (TypeStruct *)t1;
2989 TypeStruct *ts2 = (TypeStruct *)t2;
2990 if (ts1->sym != ts2->sym)
2991 {
2992 if (!ts1->sym->aliasthis && !ts2->sym->aliasthis)
2993 goto Lincompatible;
2994
2995 MATCH i1 = MATCHnomatch;
2996 MATCH i2 = MATCHnomatch;
2997
2998 Expression *e1b = NULL;
2999 Expression *e2b = NULL;
3000 if (ts2->sym->aliasthis)
3001 {
3002 if (att2 && e2->type == att2)
3003 goto Lincompatible;
3004 if (!att2 && e2->type->checkAliasThisRec())
3005 att2 = e2->type;
3006 //printf("att tmerge(s && s) e2 = %s\n", e2->type->toChars());
3007 e2b = resolveAliasThis(sc, e2);
3008 i1 = e2b->implicitConvTo(t1);
3009 }
3010 if (ts1->sym->aliasthis)
3011 {
3012 if (att1 && e1->type == att1)
3013 goto Lincompatible;
3014 if (!att1 && e1->type->checkAliasThisRec())
3015 att1 = e1->type;
3016 //printf("att tmerge(s && s) e1 = %s\n", e1->type->toChars());
3017 e1b = resolveAliasThis(sc, e1);
3018 i2 = e1b->implicitConvTo(t2);
3019 }
3020 if (i1 && i2)
3021 goto Lincompatible;
3022
3023 if (i1)
3024 goto Lt1;
3025 else if (i2)
3026 goto Lt2;
3027
3028 if (e1b)
3029 {
3030 e1 = e1b;
3031 t1 = e1b->type->toBasetype();
3032 }
3033 if (e2b)
3034 {
3035 e2 = e2b;
3036 t2 = e2b->type->toBasetype();
3037 }
3038 t = t1;
3039 goto Lagain;
3040 }
3041 }
3042 else if (t1->ty == Tstruct || t2->ty == Tstruct)
3043 {
3044 if (t1->ty == Tstruct && ((TypeStruct *)t1)->sym->aliasthis)
3045 {
3046 if (att1 && e1->type == att1)
3047 goto Lincompatible;
3048 if (!att1 && e1->type->checkAliasThisRec())
3049 att1 = e1->type;
3050 //printf("att tmerge(s || s) e1 = %s\n", e1->type->toChars());
3051 e1 = resolveAliasThis(sc, e1);
3052 t1 = e1->type;
3053 t = t1;
3054 goto Lagain;
3055 }
3056 if (t2->ty == Tstruct && ((TypeStruct *)t2)->sym->aliasthis)
3057 {
3058 if (att2 && e2->type == att2)
3059 goto Lincompatible;
3060 if (!att2 && e2->type->checkAliasThisRec())
3061 att2 = e2->type;
3062 //printf("att tmerge(s || s) e2 = %s\n", e2->type->toChars());
3063 e2 = resolveAliasThis(sc, e2);
3064 t2 = e2->type;
3065 t = t2;
3066 goto Lagain;
3067 }
3068 goto Lincompatible;
3069 }
3070 else if ((e1->op == TOKstring || e1->op == TOKnull) && e1->implicitConvTo(t2))
3071 {
3072 goto Lt2;
3073 }
3074 else if ((e2->op == TOKstring || e2->op == TOKnull) && e2->implicitConvTo(t1))
3075 {
3076 goto Lt1;
3077 }
3078 else if (t1->ty == Tsarray && t2->ty == Tsarray &&
3079 e2->implicitConvTo(t1->nextOf()->arrayOf()))
3080 {
3081 Lx1:
3082 t = t1->nextOf()->arrayOf(); // T[]
3083 e1 = e1->castTo(sc, t);
3084 e2 = e2->castTo(sc, t);
3085 }
3086 else if (t1->ty == Tsarray && t2->ty == Tsarray &&
3087 e1->implicitConvTo(t2->nextOf()->arrayOf()))
3088 {
3089 Lx2:
3090 t = t2->nextOf()->arrayOf();
3091 e1 = e1->castTo(sc, t);
3092 e2 = e2->castTo(sc, t);
3093 }
3094 else if (t1->ty == Tvector && t2->ty == Tvector)
3095 {
3096 // Bugzilla 13841, all vector types should have no common types between
3097 // different vectors, even though their sizes are same.
3098 TypeVector *tv1 = (TypeVector *)t1;
3099 TypeVector *tv2 = (TypeVector *)t2;
3100 if (!tv1->basetype->equals(tv2->basetype))
3101 goto Lincompatible;
3102
3103 goto LmodCompare;
3104 }
3105 else if (t1->ty == Tvector && t2->ty != Tvector &&
3106 e2->implicitConvTo(t1))
3107 {
3108 e2 = e2->castTo(sc, t1);
3109 t2 = t1;
3110 t = t1;
3111 goto Lagain;
3112 }
3113 else if (t2->ty == Tvector && t1->ty != Tvector &&
3114 e1->implicitConvTo(t2))
3115 {
3116 e1 = e1->castTo(sc, t2);
3117 t1 = t2;
3118 t = t1;
3119 goto Lagain;
3120 }
3121 else if (t1->isintegral() && t2->isintegral())
3122 {
3123 if (t1->ty != t2->ty)
3124 {
3125 if (t1->ty == Tvector || t2->ty == Tvector)
3126 goto Lincompatible;
3127 e1 = integralPromotions(e1, sc);
3128 e2 = integralPromotions(e2, sc);
3129 t1 = e1->type;
3130 t2 = e2->type;
3131 goto Lagain;
3132 }
3133 assert(t1->ty == t2->ty);
3134 LmodCompare:
3135 if (!t1->isImmutable() && !t2->isImmutable() && t1->isShared() != t2->isShared())
3136 goto Lincompatible;
3137 unsigned char mod = MODmerge(t1->mod, t2->mod);
3138
3139 t1 = t1->castMod(mod);
3140 t2 = t2->castMod(mod);
3141 t = t1;
3142 e1 = e1->castTo(sc, t);
3143 e2 = e2->castTo(sc, t);
3144 goto Lagain;
3145 }
3146 else if (t1->ty == Tnull && t2->ty == Tnull)
3147 {
3148 unsigned char mod = MODmerge(t1->mod, t2->mod);
3149
3150 t = t1->castMod(mod);
3151 e1 = e1->castTo(sc, t);
3152 e2 = e2->castTo(sc, t);
3153 goto Lret;
3154 }
3155 else if (t2->ty == Tnull &&
3156 (t1->ty == Tpointer || t1->ty == Taarray || t1->ty == Tarray))
3157 {
3158 goto Lt1;
3159 }
3160 else if (t1->ty == Tnull &&
3161 (t2->ty == Tpointer || t2->ty == Taarray || t2->ty == Tarray))
3162 {
3163 goto Lt2;
3164 }
3165 else if (t1->ty == Tarray && isBinArrayOp(op) && isArrayOpOperand(e1))
3166 {
3167 if (e2->implicitConvTo(t1->nextOf()))
3168 {
3169 // T[] op T
3170 // T[] op cast(T)U
3171 e2 = e2->castTo(sc, t1->nextOf());
3172 t = t1->nextOf()->arrayOf();
3173 }
3174 else if (t1->nextOf()->implicitConvTo(e2->type))
3175 {
3176 // (cast(T)U)[] op T (Bugzilla 12780)
3177 // e1 is left as U[], it will be handled in arrayOp() later.
3178 t = e2->type->arrayOf();
3179 }
3180 else if (t2->ty == Tarray && isArrayOpOperand(e2))
3181 {
3182 if (t1->nextOf()->implicitConvTo(t2->nextOf()))
3183 {
3184 // (cast(T)U)[] op T[] (Bugzilla 12780)
3185 // e1 is left as U[], it will be handled in arrayOp() later.
3186 t = t2->nextOf()->arrayOf();
3187 }
3188 else if (t2->nextOf()->implicitConvTo(t1->nextOf()))
3189 {
3190 // T[] op (cast(T)U)[] (Bugzilla 12780)
3191 // e2 is left as U[], it will be handled in arrayOp() later.
3192 t = t1->nextOf()->arrayOf();
3193 }
3194 else
3195 goto Lincompatible;
3196 }
3197 else
3198 goto Lincompatible;
3199 }
3200 else if (t2->ty == Tarray && isBinArrayOp(op) && isArrayOpOperand(e2))
3201 {
3202 if (e1->implicitConvTo(t2->nextOf()))
3203 {
3204 // T op T[]
3205 // cast(T)U op T[]
3206 e1 = e1->castTo(sc, t2->nextOf());
3207 t = t2->nextOf()->arrayOf();
3208 }
3209 else if (t2->nextOf()->implicitConvTo(e1->type))
3210 {
3211 // T op (cast(T)U)[] (Bugzilla 12780)
3212 // e2 is left as U[], it will be handled in arrayOp() later.
3213 t = e1->type->arrayOf();
3214 }
3215 else
3216 goto Lincompatible;
3217
3218 //printf("test %s\n", Token::toChars(op));
3219 e1 = e1->optimize(WANTvalue);
3220 if (isCommutative(op) && e1->isConst())
3221 {
3222 /* Swap operands to minimize number of functions generated
3223 */
3224 //printf("swap %s\n", Token::toChars(op));
3225 Expression *tmp = e1;
3226 e1 = e2;
3227 e2 = tmp;
3228 }
3229 }
3230 else
3231 {
3232 Lincompatible:
3233 return false;
3234 }
3235 Lret:
3236 if (!*pt)
3237 *pt = t;
3238 *pe1 = e1;
3239 *pe2 = e2;
3240 //print();
3241 return true;
3242
3243
3244 Lt1:
3245 e2 = e2->castTo(sc, t1);
3246 t = t1;
3247 goto Lret;
3248
3249 Lt2:
3250 e1 = e1->castTo(sc, t2);
3251 t = t2;
3252 goto Lret;
3253 }
3254
3255 /************************************
3256 * Bring leaves to common type.
3257 * Returns ErrorExp if error occurs. otherwise returns NULL.
3258 */
3259
3260 Expression *typeCombine(BinExp *be, Scope *sc)
3261 {
3262 Type *t1 = be->e1->type->toBasetype();
3263 Type *t2 = be->e2->type->toBasetype();
3264
3265 if (be->op == TOKmin || be->op == TOKadd)
3266 {
3267 // struct+struct, and class+class are errors
3268 if (t1->ty == Tstruct && t2->ty == Tstruct)
3269 goto Lerror;
3270 else if (t1->ty == Tclass && t2->ty == Tclass)
3271 goto Lerror;
3272 else if (t1->ty == Taarray && t2->ty == Taarray)
3273 goto Lerror;
3274 }
3275
3276 if (!typeMerge(sc, be->op, &be->type, &be->e1, &be->e2))
3277 goto Lerror;
3278 // If the types have no value, return an error
3279 if (be->e1->op == TOKerror)
3280 return be->e1;
3281 if (be->e2->op == TOKerror)
3282 return be->e2;
3283 return NULL;
3284
3285 Lerror:
3286 Expression *ex = be->incompatibleTypes();
3287 if (ex->op == TOKerror)
3288 return ex;
3289 return new ErrorExp();
3290 }
3291
3292 /***********************************
3293 * Do integral promotions (convertchk).
3294 * Don't convert <array of> to <pointer to>
3295 */
3296
3297 Expression *integralPromotions(Expression *e, Scope *sc)
3298 {
3299 //printf("integralPromotions %s %s\n", e->toChars(), e->type->toChars());
3300 switch (e->type->toBasetype()->ty)
3301 {
3302 case Tvoid:
3303 e->error("void has no value");
3304 return new ErrorExp();
3305
3306 case Tint8:
3307 case Tuns8:
3308 case Tint16:
3309 case Tuns16:
3310 case Tbool:
3311 case Tchar:
3312 case Twchar:
3313 e = e->castTo(sc, Type::tint32);
3314 break;
3315
3316 case Tdchar:
3317 e = e->castTo(sc, Type::tuns32);
3318 break;
3319 default:
3320 break;
3321 }
3322 return e;
3323 }
3324
3325 /***********************************
3326 * See if both types are arrays that can be compared
3327 * for equality. Return true if so.
3328 * If they are arrays, but incompatible, issue error.
3329 * This is to enable comparing things like an immutable
3330 * array with a mutable one.
3331 */
3332
3333 bool arrayTypeCompatible(Loc loc, Type *t1, Type *t2)
3334 {
3335 t1 = t1->toBasetype()->merge2();
3336 t2 = t2->toBasetype()->merge2();
3337
3338 if ((t1->ty == Tarray || t1->ty == Tsarray || t1->ty == Tpointer) &&
3339 (t2->ty == Tarray || t2->ty == Tsarray || t2->ty == Tpointer))
3340 {
3341 if (t1->nextOf()->implicitConvTo(t2->nextOf()) < MATCHconst &&
3342 t2->nextOf()->implicitConvTo(t1->nextOf()) < MATCHconst &&
3343 (t1->nextOf()->ty != Tvoid && t2->nextOf()->ty != Tvoid))
3344 {
3345 error(loc, "array equality comparison type mismatch, %s vs %s", t1->toChars(), t2->toChars());
3346 }
3347 return true;
3348 }
3349 return false;
3350 }
3351
3352 /***********************************
3353 * See if both types are arrays that can be compared
3354 * for equality without any casting. Return true if so.
3355 * This is to enable comparing things like an immutable
3356 * array with a mutable one.
3357 */
3358 bool arrayTypeCompatibleWithoutCasting(Type *t1, Type *t2)
3359 {
3360 t1 = t1->toBasetype();
3361 t2 = t2->toBasetype();
3362
3363 if ((t1->ty == Tarray || t1->ty == Tsarray || t1->ty == Tpointer) &&
3364 t2->ty == t1->ty)
3365 {
3366 if (t1->nextOf()->implicitConvTo(t2->nextOf()) >= MATCHconst ||
3367 t2->nextOf()->implicitConvTo(t1->nextOf()) >= MATCHconst)
3368 return true;
3369 }
3370 return false;
3371 }
3372
3373 /******************************************************************/
3374
3375 /* Determine the integral ranges of an expression.
3376 * This is used to determine if implicit narrowing conversions will
3377 * be allowed.
3378 */
3379
3380 IntRange getIntRange(Expression *e)
3381 {
3382 class IntRangeVisitor : public Visitor
3383 {
3384 private:
3385 static uinteger_t getMask(uinteger_t v)
3386 {
3387 // Ref: http://graphics.stanford.edu/~seander/bithacks.html#RoundUpPowerOf2
3388 v |= v >> 1;
3389 v |= v >> 2;
3390 v |= v >> 4;
3391 v |= v >> 8;
3392 v |= v >> 16;
3393 v |= v >> 32;
3394 return v;
3395 }
3396
3397 // The algorithms for &, |, ^ are not yet the best! Sometimes they will produce
3398 // not the tightest bound. See
3399 // https://github.com/D-Programming-Language/dmd/pull/116
3400 // for detail.
3401 static IntRange unsignedBitwiseAnd(const IntRange& a, const IntRange& b)
3402 {
3403 // the DiffMasks stores the mask of bits which are variable in the range.
3404 uinteger_t aDiffMask = getMask(a.imin.value ^ a.imax.value);
3405 uinteger_t bDiffMask = getMask(b.imin.value ^ b.imax.value);
3406 // Since '&' computes the digitwise-minimum, the we could set all varying
3407 // digits to 0 to get a lower bound, and set all varying digits to 1 to get
3408 // an upper bound.
3409 IntRange result;
3410 result.imin.value = (a.imin.value & ~aDiffMask) & (b.imin.value & ~bDiffMask);
3411 result.imax.value = (a.imax.value | aDiffMask) & (b.imax.value | bDiffMask);
3412 // Sometimes the upper bound is overestimated. The upper bound will never
3413 // exceed the input.
3414 if (result.imax.value > a.imax.value)
3415 result.imax.value = a.imax.value;
3416 if (result.imax.value > b.imax.value)
3417 result.imax.value = b.imax.value;
3418 result.imin.negative = result.imax.negative = a.imin.negative && b.imin.negative;
3419 return result;
3420 }
3421 static IntRange unsignedBitwiseOr(const IntRange& a, const IntRange& b)
3422 {
3423 // the DiffMasks stores the mask of bits which are variable in the range.
3424 uinteger_t aDiffMask = getMask(a.imin.value ^ a.imax.value);
3425 uinteger_t bDiffMask = getMask(b.imin.value ^ b.imax.value);
3426 // The imax algorithm by Adam D. Ruppe.
3427 // http://www.digitalmars.com/pnews/read.php?server=news.digitalmars.com&group=digitalmars.D&artnum=108796
3428 IntRange result;
3429 result.imin.value = (a.imin.value & ~aDiffMask) | (b.imin.value & ~bDiffMask);
3430 result.imax.value = a.imax.value | b.imax.value | getMask(a.imax.value & b.imax.value);
3431 // Sometimes the lower bound is underestimated. The lower bound will never
3432 // less than the input.
3433 if (result.imin.value < a.imin.value)
3434 result.imin.value = a.imin.value;
3435 if (result.imin.value < b.imin.value)
3436 result.imin.value = b.imin.value;
3437 result.imin.negative = result.imax.negative = a.imin.negative || b.imin.negative;
3438 return result;
3439 }
3440 static IntRange unsignedBitwiseXor(const IntRange& a, const IntRange& b)
3441 {
3442 // the DiffMasks stores the mask of bits which are variable in the range.
3443 uinteger_t aDiffMask = getMask(a.imin.value ^ a.imax.value);
3444 uinteger_t bDiffMask = getMask(b.imin.value ^ b.imax.value);
3445 IntRange result;
3446 result.imin.value = (a.imin.value ^ b.imin.value) & ~(aDiffMask | bDiffMask);
3447 result.imax.value = (a.imax.value ^ b.imax.value) | (aDiffMask | bDiffMask);
3448 result.imin.negative = result.imax.negative = a.imin.negative != b.imin.negative;
3449 return result;
3450 }
3451
3452 public:
3453 IntRange range;
3454
3455 void visit(Expression *e)
3456 {
3457 range = IntRange::fromType(e->type);
3458 }
3459
3460 void visit(IntegerExp *e)
3461 {
3462 range = IntRange(SignExtendedNumber(e->getInteger())).cast(e->type);
3463 }
3464
3465 void visit(CastExp *e)
3466 {
3467 range = getIntRange(e->e1).cast(e->type);
3468 }
3469
3470 void visit(AddExp *e)
3471 {
3472 IntRange ir1 = getIntRange(e->e1);
3473 IntRange ir2 = getIntRange(e->e2);
3474 range = IntRange(ir1.imin + ir2.imin, ir1.imax + ir2.imax).cast(e->type);
3475 }
3476
3477 void visit(MinExp *e)
3478 {
3479 IntRange ir1 = getIntRange(e->e1);
3480 IntRange ir2 = getIntRange(e->e2);
3481 range = IntRange(ir1.imin - ir2.imax, ir1.imax - ir2.imin).cast(e->type);
3482 }
3483
3484 void visit(DivExp *e)
3485 {
3486 IntRange ir1 = getIntRange(e->e1);
3487 IntRange ir2 = getIntRange(e->e2);
3488
3489 // Should we ignore the possibility of div-by-0???
3490 if (ir2.containsZero())
3491 {
3492 visit((Expression *)e);
3493 return;
3494 }
3495
3496 // [a,b] / [c,d] = [min (a/c, a/d, b/c, b/d), max (a/c, a/d, b/c, b/d)]
3497 SignExtendedNumber bdy[4];
3498 bdy[0] = ir1.imin / ir2.imin;
3499 bdy[1] = ir1.imin / ir2.imax;
3500 bdy[2] = ir1.imax / ir2.imin;
3501 bdy[3] = ir1.imax / ir2.imax;
3502 range = IntRange::fromNumbers4(bdy).cast(e->type);
3503 }
3504
3505 void visit(MulExp *e)
3506 {
3507 IntRange ir1 = getIntRange(e->e1);
3508 IntRange ir2 = getIntRange(e->e2);
3509
3510 // [a,b] * [c,d] = [min (ac, ad, bc, bd), max (ac, ad, bc, bd)]
3511 SignExtendedNumber bdy[4];
3512 bdy[0] = ir1.imin * ir2.imin;
3513 bdy[1] = ir1.imin * ir2.imax;
3514 bdy[2] = ir1.imax * ir2.imin;
3515 bdy[3] = ir1.imax * ir2.imax;
3516 range = IntRange::fromNumbers4(bdy).cast(e->type);
3517 }
3518
3519 void visit(ModExp *e)
3520 {
3521 IntRange irNum = getIntRange(e->e1);
3522 IntRange irDen = getIntRange(e->e2).absNeg();
3523
3524 /*
3525 due to the rules of D (C)'s % operator, we need to consider the cases
3526 separately in different range of signs.
3527
3528 case 1. [500, 1700] % [7, 23] (numerator is always positive)
3529 = [0, 22]
3530 case 2. [-500, 1700] % [7, 23] (numerator can be negative)
3531 = [-22, 22]
3532 case 3. [-1700, -500] % [7, 23] (numerator is always negative)
3533 = [-22, 0]
3534
3535 the number 22 is the maximum absolute value in the denomator's range. We
3536 don't care about divide by zero.
3537 */
3538
3539 // Modding on 0 is invalid anyway.
3540 if (!irDen.imin.negative)
3541 {
3542 visit((Expression *)e);
3543 return;
3544 }
3545
3546 ++ irDen.imin;
3547 irDen.imax = -irDen.imin;
3548
3549 if (!irNum.imin.negative)
3550 irNum.imin.value = 0;
3551 else if (irNum.imin < irDen.imin)
3552 irNum.imin = irDen.imin;
3553
3554 if (irNum.imax.negative)
3555 {
3556 irNum.imax.negative = false;
3557 irNum.imax.value = 0;
3558 }
3559 else if (irNum.imax > irDen.imax)
3560 irNum.imax = irDen.imax;
3561
3562 range = irNum.cast(e->type);
3563 }
3564
3565 void visit(AndExp *e)
3566 {
3567 IntRange ir1 = getIntRange(e->e1);
3568 IntRange ir2 = getIntRange(e->e2);
3569
3570 IntRange ir1neg, ir1pos, ir2neg, ir2pos;
3571 bool has1neg, has1pos, has2neg, has2pos;
3572
3573 ir1.splitBySign(ir1neg, has1neg, ir1pos, has1pos);
3574 ir2.splitBySign(ir2neg, has2neg, ir2pos, has2pos);
3575
3576 IntRange result;
3577 bool hasResult = false;
3578 if (has1pos && has2pos)
3579 result.unionOrAssign(unsignedBitwiseAnd(ir1pos, ir2pos), hasResult);
3580 if (has1pos && has2neg)
3581 result.unionOrAssign(unsignedBitwiseAnd(ir1pos, ir2neg), hasResult);
3582 if (has1neg && has2pos)
3583 result.unionOrAssign(unsignedBitwiseAnd(ir1neg, ir2pos), hasResult);
3584 if (has1neg && has2neg)
3585 result.unionOrAssign(unsignedBitwiseAnd(ir1neg, ir2neg), hasResult);
3586 assert(hasResult);
3587 range = result.cast(e->type);
3588 }
3589
3590 void visit(OrExp *e)
3591 {
3592 IntRange ir1 = getIntRange(e->e1);
3593 IntRange ir2 = getIntRange(e->e2);
3594
3595 IntRange ir1neg, ir1pos, ir2neg, ir2pos;
3596 bool has1neg, has1pos, has2neg, has2pos;
3597
3598 ir1.splitBySign(ir1neg, has1neg, ir1pos, has1pos);
3599 ir2.splitBySign(ir2neg, has2neg, ir2pos, has2pos);
3600
3601 IntRange result;
3602 bool hasResult = false;
3603 if (has1pos && has2pos)
3604 result.unionOrAssign(unsignedBitwiseOr(ir1pos, ir2pos), hasResult);
3605 if (has1pos && has2neg)
3606 result.unionOrAssign(unsignedBitwiseOr(ir1pos, ir2neg), hasResult);
3607 if (has1neg && has2pos)
3608 result.unionOrAssign(unsignedBitwiseOr(ir1neg, ir2pos), hasResult);
3609 if (has1neg && has2neg)
3610 result.unionOrAssign(unsignedBitwiseOr(ir1neg, ir2neg), hasResult);
3611
3612 assert(hasResult);
3613 range = result.cast(e->type);
3614 }
3615
3616 void visit(XorExp *e)
3617 {
3618 IntRange ir1 = getIntRange(e->e1);
3619 IntRange ir2 = getIntRange(e->e2);
3620
3621 IntRange ir1neg, ir1pos, ir2neg, ir2pos;
3622 bool has1neg, has1pos, has2neg, has2pos;
3623
3624 ir1.splitBySign(ir1neg, has1neg, ir1pos, has1pos);
3625 ir2.splitBySign(ir2neg, has2neg, ir2pos, has2pos);
3626
3627 IntRange result;
3628 bool hasResult = false;
3629 if (has1pos && has2pos)
3630 result.unionOrAssign(unsignedBitwiseXor(ir1pos, ir2pos), hasResult);
3631 if (has1pos && has2neg)
3632 result.unionOrAssign(unsignedBitwiseXor(ir1pos, ir2neg), hasResult);
3633 if (has1neg && has2pos)
3634 result.unionOrAssign(unsignedBitwiseXor(ir1neg, ir2pos), hasResult);
3635 if (has1neg && has2neg)
3636 result.unionOrAssign(unsignedBitwiseXor(ir1neg, ir2neg), hasResult);
3637
3638 assert(hasResult);
3639 range = result.cast(e->type);
3640 }
3641
3642 void visit(ShlExp *e)
3643 {
3644 IntRange ir1 = getIntRange(e->e1);
3645 IntRange ir2 = getIntRange(e->e2);
3646
3647 if (ir2.imin.negative)
3648 ir2 = IntRange(SignExtendedNumber(0), SignExtendedNumber(64));
3649
3650 SignExtendedNumber lower = ir1.imin << (ir1.imin.negative ? ir2.imax : ir2.imin);
3651 SignExtendedNumber upper = ir1.imax << (ir1.imax.negative ? ir2.imin : ir2.imax);
3652
3653 range = IntRange(lower, upper).cast(e->type);
3654 }
3655
3656 void visit(ShrExp *e)
3657 {
3658 IntRange ir1 = getIntRange(e->e1);
3659 IntRange ir2 = getIntRange(e->e2);
3660
3661 if (ir2.imin.negative)
3662 ir2 = IntRange(SignExtendedNumber(0), SignExtendedNumber(64));
3663
3664 SignExtendedNumber lower = ir1.imin >> (ir1.imin.negative ? ir2.imin : ir2.imax);
3665 SignExtendedNumber upper = ir1.imax >> (ir1.imax.negative ? ir2.imax : ir2.imin);
3666
3667 range = IntRange(lower, upper).cast(e->type);
3668 }
3669
3670 void visit(UshrExp *e)
3671 {
3672 IntRange ir1 = getIntRange(e->e1).castUnsigned(e->e1->type);
3673 IntRange ir2 = getIntRange(e->e2);
3674
3675 if (ir2.imin.negative)
3676 ir2 = IntRange(SignExtendedNumber(0), SignExtendedNumber(64));
3677
3678 range = IntRange(ir1.imin >> ir2.imax, ir1.imax >> ir2.imin).cast(e->type);
3679 }
3680
3681 void visit(AssignExp *e)
3682 {
3683 range = getIntRange(e->e2).cast(e->type);
3684 }
3685
3686 void visit(CondExp *e)
3687 {
3688 // No need to check e->econd; assume caller has called optimize()
3689 IntRange ir1 = getIntRange(e->e1);
3690 IntRange ir2 = getIntRange(e->e2);
3691 range = ir1.unionWith(ir2).cast(e->type);
3692 }
3693
3694 void visit(VarExp *e)
3695 {
3696 Expression *ie;
3697 VarDeclaration* vd = e->var->isVarDeclaration();
3698 if (vd && vd->range)
3699 range = vd->range->cast(e->type);
3700 else if (vd && vd->_init && !vd->type->isMutable() &&
3701 (ie = vd->getConstInitializer()) != NULL)
3702 ie->accept(this);
3703 else
3704 visit((Expression *)e);
3705 }
3706
3707 void visit(CommaExp *e)
3708 {
3709 e->e2->accept(this);
3710 }
3711
3712 void visit(ComExp *e)
3713 {
3714 IntRange ir = getIntRange(e->e1);
3715 range = IntRange(SignExtendedNumber(~ir.imax.value, !ir.imax.negative),
3716 SignExtendedNumber(~ir.imin.value, !ir.imin.negative)).cast(e->type);
3717 }
3718
3719 void visit(NegExp *e)
3720 {
3721 IntRange ir = getIntRange(e->e1);
3722 range = IntRange(-ir.imax, -ir.imin).cast(e->type);
3723 }
3724 };
3725
3726 IntRangeVisitor v;
3727 e->accept(&v);
3728 return v.range;
3729 }