forked from llvm/llvm-project
-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathCompiler.cpp
6640 lines (5648 loc) · 196 KB
/
Compiler.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
//===--- Compiler.cpp - Code generator for expressions ---*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
#include "Compiler.h"
#include "ByteCodeEmitter.h"
#include "Context.h"
#include "FixedPoint.h"
#include "Floating.h"
#include "Function.h"
#include "InterpShared.h"
#include "PrimType.h"
#include "Program.h"
#include "clang/AST/Attr.h"
using namespace clang;
using namespace clang::interp;
using APSInt = llvm::APSInt;
namespace clang {
namespace interp {
/// Scope used to handle temporaries in toplevel variable declarations.
template <class Emitter> class DeclScope final : public LocalScope<Emitter> {
public:
DeclScope(Compiler<Emitter> *Ctx, const ValueDecl *VD)
: LocalScope<Emitter>(Ctx, VD), Scope(Ctx->P, VD),
OldInitializingDecl(Ctx->InitializingDecl) {
Ctx->InitializingDecl = VD;
Ctx->InitStack.push_back(InitLink::Decl(VD));
}
void addExtended(const Scope::Local &Local) override {
return this->addLocal(Local);
}
~DeclScope() {
this->Ctx->InitializingDecl = OldInitializingDecl;
this->Ctx->InitStack.pop_back();
}
private:
Program::DeclScope Scope;
const ValueDecl *OldInitializingDecl;
};
/// Scope used to handle initialization methods.
template <class Emitter> class OptionScope final {
public:
/// Root constructor, compiling or discarding primitives.
OptionScope(Compiler<Emitter> *Ctx, bool NewDiscardResult,
bool NewInitializing)
: Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult),
OldInitializing(Ctx->Initializing) {
Ctx->DiscardResult = NewDiscardResult;
Ctx->Initializing = NewInitializing;
}
~OptionScope() {
Ctx->DiscardResult = OldDiscardResult;
Ctx->Initializing = OldInitializing;
}
private:
/// Parent context.
Compiler<Emitter> *Ctx;
/// Old discard flag to restore.
bool OldDiscardResult;
bool OldInitializing;
};
template <class Emitter>
bool InitLink::emit(Compiler<Emitter> *Ctx, const Expr *E) const {
switch (Kind) {
case K_This:
return Ctx->emitThis(E);
case K_Field:
// We're assuming there's a base pointer on the stack already.
return Ctx->emitGetPtrFieldPop(Offset, E);
case K_Temp:
return Ctx->emitGetPtrLocal(Offset, E);
case K_Decl:
return Ctx->visitDeclRef(D, E);
case K_Elem:
if (!Ctx->emitConstUint32(Offset, E))
return false;
return Ctx->emitArrayElemPtrPopUint32(E);
case K_RVO:
return Ctx->emitRVOPtr(E);
case K_InitList:
return true;
default:
llvm_unreachable("Unhandled InitLink kind");
}
return true;
}
/// Scope managing label targets.
template <class Emitter> class LabelScope {
public:
virtual ~LabelScope() {}
protected:
LabelScope(Compiler<Emitter> *Ctx) : Ctx(Ctx) {}
/// Compiler instance.
Compiler<Emitter> *Ctx;
};
/// Sets the context for break/continue statements.
template <class Emitter> class LoopScope final : public LabelScope<Emitter> {
public:
using LabelTy = typename Compiler<Emitter>::LabelTy;
using OptLabelTy = typename Compiler<Emitter>::OptLabelTy;
LoopScope(Compiler<Emitter> *Ctx, LabelTy BreakLabel, LabelTy ContinueLabel)
: LabelScope<Emitter>(Ctx), OldBreakLabel(Ctx->BreakLabel),
OldContinueLabel(Ctx->ContinueLabel),
OldBreakVarScope(Ctx->BreakVarScope),
OldContinueVarScope(Ctx->ContinueVarScope) {
this->Ctx->BreakLabel = BreakLabel;
this->Ctx->ContinueLabel = ContinueLabel;
this->Ctx->BreakVarScope = this->Ctx->VarScope;
this->Ctx->ContinueVarScope = this->Ctx->VarScope;
}
~LoopScope() {
this->Ctx->BreakLabel = OldBreakLabel;
this->Ctx->ContinueLabel = OldContinueLabel;
this->Ctx->ContinueVarScope = OldContinueVarScope;
this->Ctx->BreakVarScope = OldBreakVarScope;
}
private:
OptLabelTy OldBreakLabel;
OptLabelTy OldContinueLabel;
VariableScope<Emitter> *OldBreakVarScope;
VariableScope<Emitter> *OldContinueVarScope;
};
// Sets the context for a switch scope, mapping labels.
template <class Emitter> class SwitchScope final : public LabelScope<Emitter> {
public:
using LabelTy = typename Compiler<Emitter>::LabelTy;
using OptLabelTy = typename Compiler<Emitter>::OptLabelTy;
using CaseMap = typename Compiler<Emitter>::CaseMap;
SwitchScope(Compiler<Emitter> *Ctx, CaseMap &&CaseLabels, LabelTy BreakLabel,
OptLabelTy DefaultLabel)
: LabelScope<Emitter>(Ctx), OldBreakLabel(Ctx->BreakLabel),
OldDefaultLabel(this->Ctx->DefaultLabel),
OldCaseLabels(std::move(this->Ctx->CaseLabels)),
OldLabelVarScope(Ctx->BreakVarScope) {
this->Ctx->BreakLabel = BreakLabel;
this->Ctx->DefaultLabel = DefaultLabel;
this->Ctx->CaseLabels = std::move(CaseLabels);
this->Ctx->BreakVarScope = this->Ctx->VarScope;
}
~SwitchScope() {
this->Ctx->BreakLabel = OldBreakLabel;
this->Ctx->DefaultLabel = OldDefaultLabel;
this->Ctx->CaseLabels = std::move(OldCaseLabels);
this->Ctx->BreakVarScope = OldLabelVarScope;
}
private:
OptLabelTy OldBreakLabel;
OptLabelTy OldDefaultLabel;
CaseMap OldCaseLabels;
VariableScope<Emitter> *OldLabelVarScope;
};
template <class Emitter> class StmtExprScope final {
public:
StmtExprScope(Compiler<Emitter> *Ctx) : Ctx(Ctx), OldFlag(Ctx->InStmtExpr) {
Ctx->InStmtExpr = true;
}
~StmtExprScope() { Ctx->InStmtExpr = OldFlag; }
private:
Compiler<Emitter> *Ctx;
bool OldFlag;
};
} // namespace interp
} // namespace clang
template <class Emitter>
bool Compiler<Emitter>::VisitCastExpr(const CastExpr *CE) {
const Expr *SubExpr = CE->getSubExpr();
switch (CE->getCastKind()) {
case CK_LValueToRValue: {
if (DiscardResult)
return this->discard(SubExpr);
std::optional<PrimType> SubExprT = classify(SubExpr->getType());
// Prepare storage for the result.
if (!Initializing && !SubExprT) {
std::optional<unsigned> LocalIndex = allocateLocal(SubExpr);
if (!LocalIndex)
return false;
if (!this->emitGetPtrLocal(*LocalIndex, CE))
return false;
}
if (!this->visit(SubExpr))
return false;
if (SubExprT)
return this->emitLoadPop(*SubExprT, CE);
// If the subexpr type is not primitive, we need to perform a copy here.
// This happens for example in C when dereferencing a pointer of struct
// type.
return this->emitMemcpy(CE);
}
case CK_DerivedToBaseMemberPointer: {
assert(classifyPrim(CE->getType()) == PT_MemberPtr);
assert(classifyPrim(SubExpr->getType()) == PT_MemberPtr);
const auto *FromMP = SubExpr->getType()->getAs<MemberPointerType>();
const auto *ToMP = CE->getType()->getAs<MemberPointerType>();
unsigned DerivedOffset = collectBaseOffset(QualType(ToMP->getClass(), 0),
QualType(FromMP->getClass(), 0));
if (!this->delegate(SubExpr))
return false;
return this->emitGetMemberPtrBasePop(DerivedOffset, CE);
}
case CK_BaseToDerivedMemberPointer: {
assert(classifyPrim(CE) == PT_MemberPtr);
assert(classifyPrim(SubExpr) == PT_MemberPtr);
const auto *FromMP = SubExpr->getType()->getAs<MemberPointerType>();
const auto *ToMP = CE->getType()->getAs<MemberPointerType>();
unsigned DerivedOffset = collectBaseOffset(QualType(FromMP->getClass(), 0),
QualType(ToMP->getClass(), 0));
if (!this->delegate(SubExpr))
return false;
return this->emitGetMemberPtrBasePop(-DerivedOffset, CE);
}
case CK_UncheckedDerivedToBase:
case CK_DerivedToBase: {
if (!this->delegate(SubExpr))
return false;
const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
if (const auto *PT = dyn_cast<PointerType>(Ty))
return PT->getPointeeType()->getAsCXXRecordDecl();
return Ty->getAsCXXRecordDecl();
};
// FIXME: We can express a series of non-virtual casts as a single
// GetPtrBasePop op.
QualType CurType = SubExpr->getType();
for (const CXXBaseSpecifier *B : CE->path()) {
if (B->isVirtual()) {
if (!this->emitGetPtrVirtBasePop(extractRecordDecl(B->getType()), CE))
return false;
CurType = B->getType();
} else {
unsigned DerivedOffset = collectBaseOffset(B->getType(), CurType);
if (!this->emitGetPtrBasePop(DerivedOffset, CE))
return false;
CurType = B->getType();
}
}
return true;
}
case CK_BaseToDerived: {
if (!this->delegate(SubExpr))
return false;
unsigned DerivedOffset =
collectBaseOffset(SubExpr->getType(), CE->getType());
return this->emitGetPtrDerivedPop(DerivedOffset, CE);
}
case CK_FloatingCast: {
// HLSL uses CK_FloatingCast to cast between vectors.
if (!SubExpr->getType()->isFloatingType() ||
!CE->getType()->isFloatingType())
return false;
if (DiscardResult)
return this->discard(SubExpr);
if (!this->visit(SubExpr))
return false;
const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
return this->emitCastFP(TargetSemantics, getRoundingMode(CE), CE);
}
case CK_IntegralToFloating: {
if (DiscardResult)
return this->discard(SubExpr);
std::optional<PrimType> FromT = classify(SubExpr->getType());
if (!FromT)
return false;
if (!this->visit(SubExpr))
return false;
const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
return this->emitCastIntegralFloating(*FromT, TargetSemantics,
getFPOptions(CE), CE);
}
case CK_FloatingToBoolean:
case CK_FloatingToIntegral: {
if (DiscardResult)
return this->discard(SubExpr);
std::optional<PrimType> ToT = classify(CE->getType());
if (!ToT)
return false;
if (!this->visit(SubExpr))
return false;
if (ToT == PT_IntAP)
return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(CE->getType()),
getFPOptions(CE), CE);
if (ToT == PT_IntAPS)
return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(CE->getType()),
getFPOptions(CE), CE);
return this->emitCastFloatingIntegral(*ToT, getFPOptions(CE), CE);
}
case CK_NullToPointer:
case CK_NullToMemberPointer: {
if (!this->discard(SubExpr))
return false;
if (DiscardResult)
return true;
const Descriptor *Desc = nullptr;
const QualType PointeeType = CE->getType()->getPointeeType();
if (!PointeeType.isNull()) {
if (std::optional<PrimType> T = classify(PointeeType))
Desc = P.createDescriptor(SubExpr, *T);
else
Desc = P.createDescriptor(SubExpr, PointeeType.getTypePtr(),
std::nullopt, true, false,
/*IsMutable=*/false, nullptr);
}
uint64_t Val = Ctx.getASTContext().getTargetNullPointerValue(CE->getType());
return this->emitNull(classifyPrim(CE->getType()), Val, Desc, CE);
}
case CK_PointerToIntegral: {
if (DiscardResult)
return this->discard(SubExpr);
if (!this->visit(SubExpr))
return false;
// If SubExpr doesn't result in a pointer, make it one.
if (PrimType FromT = classifyPrim(SubExpr->getType()); FromT != PT_Ptr) {
assert(isPtrType(FromT));
if (!this->emitDecayPtr(FromT, PT_Ptr, CE))
return false;
}
PrimType T = classifyPrim(CE->getType());
if (T == PT_IntAP)
return this->emitCastPointerIntegralAP(Ctx.getBitWidth(CE->getType()),
CE);
if (T == PT_IntAPS)
return this->emitCastPointerIntegralAPS(Ctx.getBitWidth(CE->getType()),
CE);
return this->emitCastPointerIntegral(T, CE);
}
case CK_ArrayToPointerDecay: {
if (!this->visit(SubExpr))
return false;
if (!this->emitArrayDecay(CE))
return false;
if (DiscardResult)
return this->emitPopPtr(CE);
return true;
}
case CK_IntegralToPointer: {
QualType IntType = SubExpr->getType();
assert(IntType->isIntegralOrEnumerationType());
if (!this->visit(SubExpr))
return false;
// FIXME: I think the discard is wrong since the int->ptr cast might cause a
// diagnostic.
PrimType T = classifyPrim(IntType);
if (DiscardResult)
return this->emitPop(T, CE);
QualType PtrType = CE->getType();
const Descriptor *Desc;
if (std::optional<PrimType> T = classify(PtrType->getPointeeType()))
Desc = P.createDescriptor(SubExpr, *T);
else if (PtrType->getPointeeType()->isVoidType())
Desc = nullptr;
else
Desc = P.createDescriptor(CE, PtrType->getPointeeType().getTypePtr(),
Descriptor::InlineDescMD, true, false,
/*IsMutable=*/false, nullptr);
if (!this->emitGetIntPtr(T, Desc, CE))
return false;
PrimType DestPtrT = classifyPrim(PtrType);
if (DestPtrT == PT_Ptr)
return true;
// In case we're converting the integer to a non-Pointer.
return this->emitDecayPtr(PT_Ptr, DestPtrT, CE);
}
case CK_AtomicToNonAtomic:
case CK_ConstructorConversion:
case CK_FunctionToPointerDecay:
case CK_NonAtomicToAtomic:
case CK_NoOp:
case CK_UserDefinedConversion:
case CK_AddressSpaceConversion:
case CK_CPointerToObjCPointerCast:
return this->delegate(SubExpr);
case CK_BitCast: {
// Reject bitcasts to atomic types.
if (CE->getType()->isAtomicType()) {
if (!this->discard(SubExpr))
return false;
return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, CE);
}
if (DiscardResult)
return this->discard(SubExpr);
QualType SubExprTy = SubExpr->getType();
std::optional<PrimType> FromT = classify(SubExprTy);
// Casts from integer/vector to vector.
if (CE->getType()->isVectorType())
return this->emitBuiltinBitCast(CE);
std::optional<PrimType> ToT = classify(CE->getType());
if (!FromT || !ToT)
return false;
assert(isPtrType(*FromT));
assert(isPtrType(*ToT));
if (FromT == ToT) {
if (CE->getType()->isVoidPointerType())
return this->delegate(SubExpr);
if (!this->visit(SubExpr))
return false;
if (FromT == PT_Ptr)
return this->emitPtrPtrCast(SubExprTy->isVoidPointerType(), CE);
return true;
}
if (!this->visit(SubExpr))
return false;
return this->emitDecayPtr(*FromT, *ToT, CE);
}
case CK_LValueToRValueBitCast:
return this->emitBuiltinBitCast(CE);
case CK_IntegralToBoolean:
case CK_FixedPointToBoolean:
case CK_BooleanToSignedIntegral:
case CK_IntegralCast: {
if (DiscardResult)
return this->discard(SubExpr);
std::optional<PrimType> FromT = classify(SubExpr->getType());
std::optional<PrimType> ToT = classify(CE->getType());
if (!FromT || !ToT)
return false;
if (!this->visit(SubExpr))
return false;
// Possibly diagnose casts to enum types if the target type does not
// have a fixed size.
if (Ctx.getLangOpts().CPlusPlus && CE->getType()->isEnumeralType()) {
if (const auto *ET = CE->getType().getCanonicalType()->getAs<EnumType>();
ET && !ET->getDecl()->isFixed()) {
if (!this->emitCheckEnumValue(*FromT, ET->getDecl(), CE))
return false;
}
}
auto maybeNegate = [&]() -> bool {
if (CE->getCastKind() == CK_BooleanToSignedIntegral)
return this->emitNeg(*ToT, CE);
return true;
};
if (ToT == PT_IntAP)
return this->emitCastAP(*FromT, Ctx.getBitWidth(CE->getType()), CE) &&
maybeNegate();
if (ToT == PT_IntAPS)
return this->emitCastAPS(*FromT, Ctx.getBitWidth(CE->getType()), CE) &&
maybeNegate();
if (FromT == ToT)
return true;
if (!this->emitCast(*FromT, *ToT, CE))
return false;
return maybeNegate();
}
case CK_PointerToBoolean:
case CK_MemberPointerToBoolean: {
PrimType PtrT = classifyPrim(SubExpr->getType());
if (!this->visit(SubExpr))
return false;
return this->emitIsNonNull(PtrT, CE);
}
case CK_IntegralComplexToBoolean:
case CK_FloatingComplexToBoolean: {
if (DiscardResult)
return this->discard(SubExpr);
if (!this->visit(SubExpr))
return false;
return this->emitComplexBoolCast(SubExpr);
}
case CK_IntegralComplexToReal:
case CK_FloatingComplexToReal:
return this->emitComplexReal(SubExpr);
case CK_IntegralRealToComplex:
case CK_FloatingRealToComplex: {
// We're creating a complex value here, so we need to
// allocate storage for it.
if (!Initializing) {
unsigned LocalIndex = allocateTemporary(CE);
if (!this->emitGetPtrLocal(LocalIndex, CE))
return false;
}
// Init the complex value to {SubExpr, 0}.
if (!this->visitArrayElemInit(0, SubExpr))
return false;
// Zero-init the second element.
PrimType T = classifyPrim(SubExpr->getType());
if (!this->visitZeroInitializer(T, SubExpr->getType(), SubExpr))
return false;
return this->emitInitElem(T, 1, SubExpr);
}
case CK_IntegralComplexCast:
case CK_FloatingComplexCast:
case CK_IntegralComplexToFloatingComplex:
case CK_FloatingComplexToIntegralComplex: {
assert(CE->getType()->isAnyComplexType());
assert(SubExpr->getType()->isAnyComplexType());
if (DiscardResult)
return this->discard(SubExpr);
if (!Initializing) {
std::optional<unsigned> LocalIndex = allocateLocal(CE);
if (!LocalIndex)
return false;
if (!this->emitGetPtrLocal(*LocalIndex, CE))
return false;
}
// Location for the SubExpr.
// Since SubExpr is of complex type, visiting it results in a pointer
// anyway, so we just create a temporary pointer variable.
unsigned SubExprOffset = allocateLocalPrimitive(
SubExpr, PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false);
if (!this->visit(SubExpr))
return false;
if (!this->emitSetLocal(PT_Ptr, SubExprOffset, CE))
return false;
PrimType SourceElemT = classifyComplexElementType(SubExpr->getType());
QualType DestElemType =
CE->getType()->getAs<ComplexType>()->getElementType();
PrimType DestElemT = classifyPrim(DestElemType);
// Cast both elements individually.
for (unsigned I = 0; I != 2; ++I) {
if (!this->emitGetLocal(PT_Ptr, SubExprOffset, CE))
return false;
if (!this->emitArrayElemPop(SourceElemT, I, CE))
return false;
// Do the cast.
if (!this->emitPrimCast(SourceElemT, DestElemT, DestElemType, CE))
return false;
// Save the value.
if (!this->emitInitElem(DestElemT, I, CE))
return false;
}
return true;
}
case CK_VectorSplat: {
assert(!classify(CE->getType()));
assert(classify(SubExpr->getType()));
assert(CE->getType()->isVectorType());
if (DiscardResult)
return this->discard(SubExpr);
if (!Initializing) {
std::optional<unsigned> LocalIndex = allocateLocal(CE);
if (!LocalIndex)
return false;
if (!this->emitGetPtrLocal(*LocalIndex, CE))
return false;
}
const auto *VT = CE->getType()->getAs<VectorType>();
PrimType ElemT = classifyPrim(SubExpr->getType());
unsigned ElemOffset = allocateLocalPrimitive(
SubExpr, ElemT, /*IsConst=*/true, /*IsExtended=*/false);
// Prepare a local variable for the scalar value.
if (!this->visit(SubExpr))
return false;
if (classifyPrim(SubExpr) == PT_Ptr && !this->emitLoadPop(ElemT, CE))
return false;
if (!this->emitSetLocal(ElemT, ElemOffset, CE))
return false;
for (unsigned I = 0; I != VT->getNumElements(); ++I) {
if (!this->emitGetLocal(ElemT, ElemOffset, CE))
return false;
if (!this->emitInitElem(ElemT, I, CE))
return false;
}
return true;
}
case CK_HLSLVectorTruncation: {
assert(SubExpr->getType()->isVectorType());
if (std::optional<PrimType> ResultT = classify(CE)) {
assert(!DiscardResult);
// Result must be either a float or integer. Take the first element.
if (!this->visit(SubExpr))
return false;
return this->emitArrayElemPop(*ResultT, 0, CE);
}
// Otherwise, this truncates from one vector type to another.
assert(CE->getType()->isVectorType());
if (!Initializing) {
unsigned LocalIndex = allocateTemporary(CE);
if (!this->emitGetPtrLocal(LocalIndex, CE))
return false;
}
unsigned ToSize = CE->getType()->getAs<VectorType>()->getNumElements();
assert(SubExpr->getType()->getAs<VectorType>()->getNumElements() > ToSize);
if (!this->visit(SubExpr))
return false;
return this->emitCopyArray(classifyVectorElementType(CE->getType()), 0, 0,
ToSize, CE);
};
case CK_IntegralToFixedPoint: {
if (!this->visit(SubExpr))
return false;
auto Sem = Ctx.getASTContext().getFixedPointSemantics(CE->getType());
uint32_t I;
std::memcpy(&I, &Sem, sizeof(Sem));
return this->emitCastIntegralFixedPoint(classifyPrim(SubExpr->getType()), I,
CE);
}
case CK_FloatingToFixedPoint: {
if (!this->visit(SubExpr))
return false;
auto Sem = Ctx.getASTContext().getFixedPointSemantics(CE->getType());
uint32_t I;
std::memcpy(&I, &Sem, sizeof(Sem));
return this->emitCastFloatingFixedPoint(I, CE);
}
case CK_FixedPointToFloating: {
if (!this->visit(SubExpr))
return false;
const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
return this->emitCastFixedPointFloating(TargetSemantics, CE);
}
case CK_FixedPointToIntegral: {
if (!this->visit(SubExpr))
return false;
return this->emitCastFixedPointIntegral(classifyPrim(CE->getType()), CE);
}
case CK_FixedPointCast: {
if (!this->visit(SubExpr))
return false;
auto Sem = Ctx.getASTContext().getFixedPointSemantics(CE->getType());
uint32_t I;
std::memcpy(&I, &Sem, sizeof(Sem));
return this->emitCastFixedPoint(I, CE);
}
case CK_ToVoid:
return discard(SubExpr);
default:
return this->emitInvalid(CE);
}
llvm_unreachable("Unhandled clang::CastKind enum");
}
template <class Emitter>
bool Compiler<Emitter>::VisitIntegerLiteral(const IntegerLiteral *LE) {
if (DiscardResult)
return true;
return this->emitConst(LE->getValue(), LE);
}
template <class Emitter>
bool Compiler<Emitter>::VisitFloatingLiteral(const FloatingLiteral *E) {
if (DiscardResult)
return true;
return this->emitConstFloat(E->getValue(), E);
}
template <class Emitter>
bool Compiler<Emitter>::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
assert(E->getType()->isAnyComplexType());
if (DiscardResult)
return true;
if (!Initializing) {
unsigned LocalIndex = allocateTemporary(E);
if (!this->emitGetPtrLocal(LocalIndex, E))
return false;
}
const Expr *SubExpr = E->getSubExpr();
PrimType SubExprT = classifyPrim(SubExpr->getType());
if (!this->visitZeroInitializer(SubExprT, SubExpr->getType(), SubExpr))
return false;
if (!this->emitInitElem(SubExprT, 0, SubExpr))
return false;
return this->visitArrayElemInit(1, SubExpr);
}
template <class Emitter>
bool Compiler<Emitter>::VisitFixedPointLiteral(const FixedPointLiteral *E) {
assert(E->getType()->isFixedPointType());
assert(classifyPrim(E) == PT_FixedPoint);
if (DiscardResult)
return true;
auto Sem = Ctx.getASTContext().getFixedPointSemantics(E->getType());
APInt Value = E->getValue();
return this->emitConstFixedPoint(FixedPoint(Value, Sem), E);
}
template <class Emitter>
bool Compiler<Emitter>::VisitParenExpr(const ParenExpr *E) {
return this->delegate(E->getSubExpr());
}
template <class Emitter>
bool Compiler<Emitter>::VisitBinaryOperator(const BinaryOperator *BO) {
// Need short-circuiting for these.
if (BO->isLogicalOp() && !BO->getType()->isVectorType())
return this->VisitLogicalBinOp(BO);
const Expr *LHS = BO->getLHS();
const Expr *RHS = BO->getRHS();
// Handle comma operators. Just discard the LHS
// and delegate to RHS.
if (BO->isCommaOp()) {
if (!this->discard(LHS))
return false;
if (RHS->getType()->isVoidType())
return this->discard(RHS);
return this->delegate(RHS);
}
if (BO->getType()->isAnyComplexType())
return this->VisitComplexBinOp(BO);
if (BO->getType()->isVectorType())
return this->VisitVectorBinOp(BO);
if ((LHS->getType()->isAnyComplexType() ||
RHS->getType()->isAnyComplexType()) &&
BO->isComparisonOp())
return this->emitComplexComparison(LHS, RHS, BO);
if (LHS->getType()->isFixedPointType() || RHS->getType()->isFixedPointType())
return this->VisitFixedPointBinOp(BO);
if (BO->isPtrMemOp()) {
if (!this->visit(LHS))
return false;
if (!this->visit(RHS))
return false;
if (!this->emitToMemberPtr(BO))
return false;
if (classifyPrim(BO) == PT_MemberPtr)
return true;
if (!this->emitCastMemberPtrPtr(BO))
return false;
return DiscardResult ? this->emitPopPtr(BO) : true;
}
// Typecheck the args.
std::optional<PrimType> LT = classify(LHS);
std::optional<PrimType> RT = classify(RHS);
std::optional<PrimType> T = classify(BO->getType());
// Special case for C++'s three-way/spaceship operator <=>, which
// returns a std::{strong,weak,partial}_ordering (which is a class, so doesn't
// have a PrimType).
if (!T && BO->getOpcode() == BO_Cmp) {
if (DiscardResult)
return true;
const ComparisonCategoryInfo *CmpInfo =
Ctx.getASTContext().CompCategories.lookupInfoForType(BO->getType());
assert(CmpInfo);
// We need a temporary variable holding our return value.
if (!Initializing) {
std::optional<unsigned> ResultIndex = this->allocateLocal(BO);
if (!this->emitGetPtrLocal(*ResultIndex, BO))
return false;
}
if (!visit(LHS) || !visit(RHS))
return false;
return this->emitCMP3(*LT, CmpInfo, BO);
}
if (!LT || !RT || !T)
return false;
// Pointer arithmetic special case.
if (BO->getOpcode() == BO_Add || BO->getOpcode() == BO_Sub) {
if (isPtrType(*T) || (isPtrType(*LT) && isPtrType(*RT)))
return this->VisitPointerArithBinOp(BO);
}
// Assignmentes require us to evalute the RHS first.
if (BO->getOpcode() == BO_Assign) {
if (!visit(RHS) || !visit(LHS))
return false;
if (!this->emitFlip(*LT, *RT, BO))
return false;
} else {
if (!visit(LHS) || !visit(RHS))
return false;
}
// For languages such as C, cast the result of one
// of our comparision opcodes to T (which is usually int).
auto MaybeCastToBool = [this, T, BO](bool Result) {
if (!Result)
return false;
if (DiscardResult)
return this->emitPop(*T, BO);
if (T != PT_Bool)
return this->emitCast(PT_Bool, *T, BO);
return true;
};
auto Discard = [this, T, BO](bool Result) {
if (!Result)
return false;
return DiscardResult ? this->emitPop(*T, BO) : true;
};
switch (BO->getOpcode()) {
case BO_EQ:
return MaybeCastToBool(this->emitEQ(*LT, BO));
case BO_NE:
return MaybeCastToBool(this->emitNE(*LT, BO));
case BO_LT:
return MaybeCastToBool(this->emitLT(*LT, BO));
case BO_LE:
return MaybeCastToBool(this->emitLE(*LT, BO));
case BO_GT:
return MaybeCastToBool(this->emitGT(*LT, BO));
case BO_GE:
return MaybeCastToBool(this->emitGE(*LT, BO));
case BO_Sub:
if (BO->getType()->isFloatingType())
return Discard(this->emitSubf(getFPOptions(BO), BO));
return Discard(this->emitSub(*T, BO));
case BO_Add:
if (BO->getType()->isFloatingType())
return Discard(this->emitAddf(getFPOptions(BO), BO));
return Discard(this->emitAdd(*T, BO));
case BO_Mul:
if (BO->getType()->isFloatingType())
return Discard(this->emitMulf(getFPOptions(BO), BO));
return Discard(this->emitMul(*T, BO));
case BO_Rem:
return Discard(this->emitRem(*T, BO));
case BO_Div:
if (BO->getType()->isFloatingType())
return Discard(this->emitDivf(getFPOptions(BO), BO));
return Discard(this->emitDiv(*T, BO));
case BO_Assign:
if (DiscardResult)
return LHS->refersToBitField() ? this->emitStoreBitFieldPop(*T, BO)
: this->emitStorePop(*T, BO);
if (LHS->refersToBitField()) {
if (!this->emitStoreBitField(*T, BO))
return false;
} else {
if (!this->emitStore(*T, BO))
return false;
}
// Assignments aren't necessarily lvalues in C.
// Load from them in that case.
if (!BO->isLValue())
return this->emitLoadPop(*T, BO);
return true;
case BO_And:
return Discard(this->emitBitAnd(*T, BO));
case BO_Or:
return Discard(this->emitBitOr(*T, BO));
case BO_Shl:
return Discard(this->emitShl(*LT, *RT, BO));
case BO_Shr:
return Discard(this->emitShr(*LT, *RT, BO));
case BO_Xor:
return Discard(this->emitBitXor(*T, BO));
case BO_LOr:
case BO_LAnd:
llvm_unreachable("Already handled earlier");
default:
return false;
}
llvm_unreachable("Unhandled binary op");
}
/// Perform addition/subtraction of a pointer and an integer or
/// subtraction of two pointers.
template <class Emitter>
bool Compiler<Emitter>::VisitPointerArithBinOp(const BinaryOperator *E) {
BinaryOperatorKind Op = E->getOpcode();
const Expr *LHS = E->getLHS();
const Expr *RHS = E->getRHS();
if ((Op != BO_Add && Op != BO_Sub) ||
(!LHS->getType()->isPointerType() && !RHS->getType()->isPointerType()))
return false;
std::optional<PrimType> LT = classify(LHS);
std::optional<PrimType> RT = classify(RHS);
if (!LT || !RT)
return false;
// Visit the given pointer expression and optionally convert to a PT_Ptr.
auto visitAsPointer = [&](const Expr *E, PrimType T) -> bool {
if (!this->visit(E))
return false;
if (T != PT_Ptr)
return this->emitDecayPtr(T, PT_Ptr, E);
return true;
};