1 //===--- ByteCodeExprGen.cpp - Code generator for expressions ---*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "ByteCodeExprGen.h"
10 #include "ByteCodeEmitter.h"
11 #include "ByteCodeGenError.h"
12 #include "ByteCodeStmtGen.h"
19 using namespace clang
;
20 using namespace clang::interp
;
22 using APSInt
= llvm::APSInt
;
27 /// Scope used to handle temporaries in toplevel variable declarations.
28 template <class Emitter
> class DeclScope final
: public VariableScope
<Emitter
> {
30 DeclScope(ByteCodeExprGen
<Emitter
> *Ctx
, const ValueDecl
*VD
)
31 : VariableScope
<Emitter
>(Ctx
), Scope(Ctx
->P
, VD
),
32 OldGlobalDecl(Ctx
->GlobalDecl
) {
33 Ctx
->GlobalDecl
= Context::shouldBeGloballyIndexed(VD
);
36 void addExtended(const Scope::Local
&Local
) override
{
37 return this->addLocal(Local
);
40 ~DeclScope() { this->Ctx
->GlobalDecl
= OldGlobalDecl
; }
43 Program::DeclScope Scope
;
47 /// Scope used to handle initialization methods.
48 template <class Emitter
> class OptionScope final
{
50 /// Root constructor, compiling or discarding primitives.
51 OptionScope(ByteCodeExprGen
<Emitter
> *Ctx
, bool NewDiscardResult
,
53 : Ctx(Ctx
), OldDiscardResult(Ctx
->DiscardResult
),
54 OldInitializing(Ctx
->Initializing
) {
55 Ctx
->DiscardResult
= NewDiscardResult
;
56 Ctx
->Initializing
= NewInitializing
;
60 Ctx
->DiscardResult
= OldDiscardResult
;
61 Ctx
->Initializing
= OldInitializing
;
66 ByteCodeExprGen
<Emitter
> *Ctx
;
67 /// Old discard flag to restore.
68 bool OldDiscardResult
;
75 template <class Emitter
>
76 bool ByteCodeExprGen
<Emitter
>::VisitCastExpr(const CastExpr
*CE
) {
77 const Expr
*SubExpr
= CE
->getSubExpr();
78 switch (CE
->getCastKind()) {
80 case CK_LValueToRValue
: {
82 SubExpr
, DerefKind::Read
,
84 // Value loaded - nothing to do here.
87 [this, CE
](PrimType T
) {
88 // Pointer on stack - dereference it.
89 if (!this->emitLoadPop(T
, CE
))
91 return DiscardResult
? this->emitPop(T
, CE
) : true;
95 case CK_UncheckedDerivedToBase
:
96 case CK_DerivedToBase
: {
97 if (!this->visit(SubExpr
))
100 unsigned DerivedOffset
= collectBaseOffset(getRecordTy(CE
->getType()),
101 getRecordTy(SubExpr
->getType()));
103 return this->emitGetPtrBasePop(DerivedOffset
, CE
);
106 case CK_BaseToDerived
: {
107 if (!this->visit(SubExpr
))
110 unsigned DerivedOffset
= collectBaseOffset(getRecordTy(SubExpr
->getType()),
111 getRecordTy(CE
->getType()));
113 return this->emitGetPtrDerivedPop(DerivedOffset
, CE
);
116 case CK_FloatingCast
: {
118 return this->discard(SubExpr
);
119 if (!this->visit(SubExpr
))
121 const auto *TargetSemantics
= &Ctx
.getFloatSemantics(CE
->getType());
122 return this->emitCastFP(TargetSemantics
, getRoundingMode(CE
), CE
);
125 case CK_IntegralToFloating
: {
127 return this->discard(SubExpr
);
128 std::optional
<PrimType
> FromT
= classify(SubExpr
->getType());
132 if (!this->visit(SubExpr
))
135 const auto *TargetSemantics
= &Ctx
.getFloatSemantics(CE
->getType());
136 llvm::RoundingMode RM
= getRoundingMode(CE
);
137 return this->emitCastIntegralFloating(*FromT
, TargetSemantics
, RM
, CE
);
140 case CK_FloatingToBoolean
:
141 case CK_FloatingToIntegral
: {
143 return this->discard(SubExpr
);
145 std::optional
<PrimType
> ToT
= classify(CE
->getType());
150 if (!this->visit(SubExpr
))
154 return this->emitCastFloatingIntegralAP(Ctx
.getBitWidth(CE
->getType()),
156 if (ToT
== PT_IntAPS
)
157 return this->emitCastFloatingIntegralAPS(Ctx
.getBitWidth(CE
->getType()),
160 return this->emitCastFloatingIntegral(*ToT
, CE
);
163 case CK_NullToPointer
:
166 return this->emitNull(classifyPrim(CE
->getType()), CE
);
168 case CK_PointerToIntegral
: {
169 // TODO: Discard handling.
170 if (!this->visit(SubExpr
))
173 PrimType T
= classifyPrim(CE
->getType());
174 return this->emitCastPointerIntegral(T
, CE
);
177 case CK_ArrayToPointerDecay
: {
178 if (!this->visit(SubExpr
))
180 if (!this->emitArrayDecay(CE
))
183 return this->emitPopPtr(CE
);
187 case CK_AtomicToNonAtomic
:
188 case CK_ConstructorConversion
:
189 case CK_FunctionToPointerDecay
:
190 case CK_NonAtomicToAtomic
:
192 case CK_UserDefinedConversion
:
194 return this->delegate(SubExpr
);
196 case CK_IntegralToBoolean
:
197 case CK_IntegralCast
: {
199 return this->discard(SubExpr
);
200 std::optional
<PrimType
> FromT
= classify(SubExpr
->getType());
201 std::optional
<PrimType
> ToT
= classify(CE
->getType());
206 if (!this->visit(SubExpr
))
210 return this->emitCastAP(*FromT
, Ctx
.getBitWidth(CE
->getType()), CE
);
211 if (ToT
== PT_IntAPS
)
212 return this->emitCastAPS(*FromT
, Ctx
.getBitWidth(CE
->getType()), CE
);
216 return this->emitCast(*FromT
, *ToT
, CE
);
219 case CK_PointerToBoolean
: {
220 PrimType PtrT
= classifyPrim(SubExpr
->getType());
222 // Just emit p != nullptr for this.
223 if (!this->visit(SubExpr
))
226 if (!this->emitNull(PtrT
, CE
))
229 return this->emitNE(PtrT
, CE
);
232 case CK_IntegralComplexToBoolean
:
233 case CK_FloatingComplexToBoolean
: {
234 std::optional
<PrimType
> ElemT
=
235 classifyComplexElementType(SubExpr
->getType());
238 // We emit the expression (__real(E) != 0 || __imag(E) != 0)
239 // for us, that means (bool)E[0] || (bool)E[1]
240 if (!this->visit(SubExpr
))
242 if (!this->emitConstUint8(0, CE
))
244 if (!this->emitArrayElemPtrUint8(CE
))
246 if (!this->emitLoadPop(*ElemT
, CE
))
248 if (*ElemT
== PT_Float
) {
249 if (!this->emitCastFloatingIntegral(PT_Bool
, CE
))
252 if (!this->emitCast(*ElemT
, PT_Bool
, CE
))
256 // We now have the bool value of E[0] on the stack.
257 LabelTy LabelTrue
= this->getLabel();
258 if (!this->jumpTrue(LabelTrue
))
261 if (!this->emitConstUint8(1, CE
))
263 if (!this->emitArrayElemPtrPopUint8(CE
))
265 if (!this->emitLoadPop(*ElemT
, CE
))
267 if (*ElemT
== PT_Float
) {
268 if (!this->emitCastFloatingIntegral(PT_Bool
, CE
))
271 if (!this->emitCast(*ElemT
, PT_Bool
, CE
))
274 // Leave the boolean value of E[1] on the stack.
275 LabelTy EndLabel
= this->getLabel();
276 this->jump(EndLabel
);
278 this->emitLabel(LabelTrue
);
279 if (!this->emitPopPtr(CE
))
281 if (!this->emitConstBool(true, CE
))
284 this->fallthrough(EndLabel
);
285 this->emitLabel(EndLabel
);
290 case CK_IntegralComplexToReal
:
291 case CK_FloatingComplexToReal
:
292 return this->emitComplexReal(SubExpr
);
295 return discard(SubExpr
);
298 assert(false && "Cast not implemented");
300 llvm_unreachable("Unhandled clang::CastKind enum");
303 template <class Emitter
>
304 bool ByteCodeExprGen
<Emitter
>::VisitIntegerLiteral(const IntegerLiteral
*LE
) {
308 return this->emitConst(LE
->getValue(), LE
);
311 template <class Emitter
>
312 bool ByteCodeExprGen
<Emitter
>::VisitFloatingLiteral(const FloatingLiteral
*E
) {
316 return this->emitConstFloat(E
->getValue(), E
);
319 template <class Emitter
>
320 bool ByteCodeExprGen
<Emitter
>::VisitParenExpr(const ParenExpr
*E
) {
321 return this->delegate(E
->getSubExpr());
324 template <class Emitter
>
325 bool ByteCodeExprGen
<Emitter
>::VisitBinaryOperator(const BinaryOperator
*BO
) {
326 // Need short-circuiting for these.
327 if (BO
->isLogicalOp())
328 return this->VisitLogicalBinOp(BO
);
330 if (BO
->getType()->isAnyComplexType())
331 return this->VisitComplexBinOp(BO
);
333 const Expr
*LHS
= BO
->getLHS();
334 const Expr
*RHS
= BO
->getRHS();
336 if (BO
->isPtrMemOp())
337 return this->visit(RHS
);
339 // Typecheck the args.
340 std::optional
<PrimType
> LT
= classify(LHS
->getType());
341 std::optional
<PrimType
> RT
= classify(RHS
->getType());
342 std::optional
<PrimType
> T
= classify(BO
->getType());
344 // Deal with operations which have composite or void types.
345 if (BO
->isCommaOp()) {
346 if (!this->discard(LHS
))
348 if (RHS
->getType()->isVoidType())
349 return this->discard(RHS
);
351 return this->delegate(RHS
);
354 // Special case for C++'s three-way/spaceship operator <=>, which
355 // returns a std::{strong,weak,partial}_ordering (which is a class, so doesn't
360 const ComparisonCategoryInfo
*CmpInfo
=
361 Ctx
.getASTContext().CompCategories
.lookupInfoForType(BO
->getType());
364 // We need a temporary variable holding our return value.
366 std::optional
<unsigned> ResultIndex
= this->allocateLocal(BO
, false);
367 if (!this->emitGetPtrLocal(*ResultIndex
, BO
))
371 if (!visit(LHS
) || !visit(RHS
))
374 return this->emitCMP3(*LT
, CmpInfo
, BO
);
377 if (!LT
|| !RT
|| !T
)
378 return this->bail(BO
);
380 // Pointer arithmetic special case.
381 if (BO
->getOpcode() == BO_Add
|| BO
->getOpcode() == BO_Sub
) {
382 if (T
== PT_Ptr
|| (LT
== PT_Ptr
&& RT
== PT_Ptr
))
383 return this->VisitPointerArithBinOp(BO
);
386 if (!visit(LHS
) || !visit(RHS
))
389 // For languages such as C, cast the result of one
390 // of our comparision opcodes to T (which is usually int).
391 auto MaybeCastToBool
= [this, T
, BO
](bool Result
) {
395 return this->emitPop(*T
, BO
);
397 return this->emitCast(PT_Bool
, *T
, BO
);
401 auto Discard
= [this, T
, BO
](bool Result
) {
404 return DiscardResult
? this->emitPop(*T
, BO
) : true;
407 switch (BO
->getOpcode()) {
409 return MaybeCastToBool(this->emitEQ(*LT
, BO
));
411 return MaybeCastToBool(this->emitNE(*LT
, BO
));
413 return MaybeCastToBool(this->emitLT(*LT
, BO
));
415 return MaybeCastToBool(this->emitLE(*LT
, BO
));
417 return MaybeCastToBool(this->emitGT(*LT
, BO
));
419 return MaybeCastToBool(this->emitGE(*LT
, BO
));
421 if (BO
->getType()->isFloatingType())
422 return Discard(this->emitSubf(getRoundingMode(BO
), BO
));
423 return Discard(this->emitSub(*T
, BO
));
425 if (BO
->getType()->isFloatingType())
426 return Discard(this->emitAddf(getRoundingMode(BO
), BO
));
427 return Discard(this->emitAdd(*T
, BO
));
429 if (BO
->getType()->isFloatingType())
430 return Discard(this->emitMulf(getRoundingMode(BO
), BO
));
431 return Discard(this->emitMul(*T
, BO
));
433 return Discard(this->emitRem(*T
, BO
));
435 if (BO
->getType()->isFloatingType())
436 return Discard(this->emitDivf(getRoundingMode(BO
), BO
));
437 return Discard(this->emitDiv(*T
, BO
));
440 return LHS
->refersToBitField() ? this->emitStoreBitFieldPop(*T
, BO
)
441 : this->emitStorePop(*T
, BO
);
442 return LHS
->refersToBitField() ? this->emitStoreBitField(*T
, BO
)
443 : this->emitStore(*T
, BO
);
445 return Discard(this->emitBitAnd(*T
, BO
));
447 return Discard(this->emitBitOr(*T
, BO
));
449 return Discard(this->emitShl(*LT
, *RT
, BO
));
451 return Discard(this->emitShr(*LT
, *RT
, BO
));
453 return Discard(this->emitBitXor(*T
, BO
));
456 llvm_unreachable("Already handled earlier");
458 return this->bail(BO
);
461 llvm_unreachable("Unhandled binary op");
464 /// Perform addition/subtraction of a pointer and an integer or
465 /// subtraction of two pointers.
466 template <class Emitter
>
467 bool ByteCodeExprGen
<Emitter
>::VisitPointerArithBinOp(const BinaryOperator
*E
) {
468 BinaryOperatorKind Op
= E
->getOpcode();
469 const Expr
*LHS
= E
->getLHS();
470 const Expr
*RHS
= E
->getRHS();
472 if ((Op
!= BO_Add
&& Op
!= BO_Sub
) ||
473 (!LHS
->getType()->isPointerType() && !RHS
->getType()->isPointerType()))
476 std::optional
<PrimType
> LT
= classify(LHS
);
477 std::optional
<PrimType
> RT
= classify(RHS
);
482 if (LHS
->getType()->isPointerType() && RHS
->getType()->isPointerType()) {
486 assert(E
->getType()->isIntegerType());
487 if (!visit(RHS
) || !visit(LHS
))
490 return this->emitSubPtr(classifyPrim(E
->getType()), E
);
494 if (LHS
->getType()->isIntegerType()) {
495 if (!visit(RHS
) || !visit(LHS
))
498 } else if (RHS
->getType()->isIntegerType()) {
499 if (!visit(LHS
) || !visit(RHS
))
507 return this->emitAddOffset(OffsetType
, E
);
508 else if (Op
== BO_Sub
)
509 return this->emitSubOffset(OffsetType
, E
);
511 return this->bail(E
);
514 template <class Emitter
>
515 bool ByteCodeExprGen
<Emitter
>::VisitLogicalBinOp(const BinaryOperator
*E
) {
516 assert(E
->isLogicalOp());
517 BinaryOperatorKind Op
= E
->getOpcode();
518 const Expr
*LHS
= E
->getLHS();
519 const Expr
*RHS
= E
->getRHS();
520 std::optional
<PrimType
> T
= classify(E
->getType());
523 // Logical OR. Visit LHS and only evaluate RHS if LHS was FALSE.
524 LabelTy LabelTrue
= this->getLabel();
525 LabelTy LabelEnd
= this->getLabel();
527 if (!this->visitBool(LHS
))
529 if (!this->jumpTrue(LabelTrue
))
532 if (!this->visitBool(RHS
))
534 if (!this->jump(LabelEnd
))
537 this->emitLabel(LabelTrue
);
538 this->emitConstBool(true, E
);
539 this->fallthrough(LabelEnd
);
540 this->emitLabel(LabelEnd
);
543 assert(Op
== BO_LAnd
);
545 // Visit LHS. Only visit RHS if LHS was TRUE.
546 LabelTy LabelFalse
= this->getLabel();
547 LabelTy LabelEnd
= this->getLabel();
549 if (!this->visitBool(LHS
))
551 if (!this->jumpFalse(LabelFalse
))
554 if (!this->visitBool(RHS
))
556 if (!this->jump(LabelEnd
))
559 this->emitLabel(LabelFalse
);
560 this->emitConstBool(false, E
);
561 this->fallthrough(LabelEnd
);
562 this->emitLabel(LabelEnd
);
566 return this->emitPopBool(E
);
568 // For C, cast back to integer type.
571 return this->emitCast(PT_Bool
, *T
, E
);
575 template <class Emitter
>
576 bool ByteCodeExprGen
<Emitter
>::VisitComplexBinOp(const BinaryOperator
*E
) {
577 assert(Initializing
);
579 const Expr
*LHS
= E
->getLHS();
580 const Expr
*RHS
= E
->getRHS();
581 PrimType LHSElemT
= *this->classifyComplexElementType(LHS
->getType());
582 PrimType RHSElemT
= *this->classifyComplexElementType(RHS
->getType());
584 unsigned LHSOffset
= this->allocateLocalPrimitive(LHS
, PT_Ptr
, true, false);
585 unsigned RHSOffset
= this->allocateLocalPrimitive(RHS
, PT_Ptr
, true, false);
586 unsigned ResultOffset
= ~0u;
587 if (!this->DiscardResult
)
588 ResultOffset
= this->allocateLocalPrimitive(E
, PT_Ptr
, true, false);
590 assert(LHSElemT
== RHSElemT
);
592 // Save result pointer in ResultOffset
593 if (!this->DiscardResult
) {
594 if (!this->emitDupPtr(E
))
596 if (!this->emitSetLocal(PT_Ptr
, ResultOffset
, E
))
600 // Evaluate LHS and save value to LHSOffset.
601 if (!this->visit(LHS
))
603 if (!this->emitSetLocal(PT_Ptr
, LHSOffset
, E
))
607 if (!this->visit(RHS
))
609 if (!this->emitSetLocal(PT_Ptr
, RHSOffset
, E
))
612 // Now we can get pointers to the LHS and RHS from the offsets above.
613 BinaryOperatorKind Op
= E
->getOpcode();
614 for (unsigned ElemIndex
= 0; ElemIndex
!= 2; ++ElemIndex
) {
615 // Result pointer for the store later.
616 if (!this->DiscardResult
) {
617 if (!this->emitGetLocal(PT_Ptr
, ResultOffset
, E
))
621 if (!this->emitGetLocal(PT_Ptr
, LHSOffset
, E
))
623 if (!this->emitConstUint8(ElemIndex
, E
))
625 if (!this->emitArrayElemPtrPopUint8(E
))
627 if (!this->emitLoadPop(LHSElemT
, E
))
630 if (!this->emitGetLocal(PT_Ptr
, RHSOffset
, E
))
632 if (!this->emitConstUint8(ElemIndex
, E
))
634 if (!this->emitArrayElemPtrPopUint8(E
))
636 if (!this->emitLoadPop(RHSElemT
, E
))
639 // The actual operation.
642 if (LHSElemT
== PT_Float
) {
643 if (!this->emitAddf(getRoundingMode(E
), E
))
646 if (!this->emitAdd(LHSElemT
, E
))
651 if (LHSElemT
== PT_Float
) {
652 if (!this->emitSubf(getRoundingMode(E
), E
))
655 if (!this->emitSub(LHSElemT
, E
))
664 if (!this->DiscardResult
) {
665 // Initialize array element with the value we just computed.
666 if (!this->emitInitElemPop(LHSElemT
, ElemIndex
, E
))
669 if (!this->emitPop(LHSElemT
, E
))
676 template <class Emitter
>
677 bool ByteCodeExprGen
<Emitter
>::VisitImplicitValueInitExpr(const ImplicitValueInitExpr
*E
) {
678 QualType QT
= E
->getType();
680 if (std::optional
<PrimType
> T
= classify(QT
))
681 return this->visitZeroInitializer(*T
, QT
, E
);
683 if (QT
->isRecordType())
686 if (QT
->isIncompleteArrayType())
689 if (QT
->isArrayType()) {
690 const ArrayType
*AT
= QT
->getAsArrayTypeUnsafe();
692 const auto *CAT
= cast
<ConstantArrayType
>(AT
);
693 size_t NumElems
= CAT
->getSize().getZExtValue();
694 PrimType ElemT
= classifyPrim(CAT
->getElementType());
696 for (size_t I
= 0; I
!= NumElems
; ++I
) {
697 if (!this->visitZeroInitializer(ElemT
, CAT
->getElementType(), E
))
699 if (!this->emitInitElem(ElemT
, I
, E
))
709 template <class Emitter
>
710 bool ByteCodeExprGen
<Emitter
>::VisitArraySubscriptExpr(
711 const ArraySubscriptExpr
*E
) {
712 const Expr
*Base
= E
->getBase();
713 const Expr
*Index
= E
->getIdx();
716 return this->discard(Base
) && this->discard(Index
);
718 // Take pointer of LHS, add offset from RHS.
719 // What's left on the stack after this is a pointer.
720 if (!this->visit(Base
))
723 if (!this->visit(Index
))
726 PrimType IndexT
= classifyPrim(Index
->getType());
727 return this->emitArrayElemPtrPop(IndexT
, E
);
730 template <class Emitter
>
731 bool ByteCodeExprGen
<Emitter
>::visitInitList(ArrayRef
<const Expr
*> Inits
,
733 assert(E
->getType()->isRecordType());
734 const Record
*R
= getRecord(E
->getType());
736 unsigned InitIndex
= 0;
737 for (const Expr
*Init
: Inits
) {
738 if (!this->emitDupPtr(E
))
741 if (std::optional
<PrimType
> T
= classify(Init
)) {
742 const Record::Field
*FieldToInit
= R
->getField(InitIndex
);
743 if (!this->visit(Init
))
746 if (FieldToInit
->isBitField()) {
747 if (!this->emitInitBitField(*T
, FieldToInit
, E
))
750 if (!this->emitInitField(*T
, FieldToInit
->Offset
, E
))
754 if (!this->emitPopPtr(E
))
758 // Initializer for a direct base class.
759 if (const Record::Base
*B
= R
->getBase(Init
->getType())) {
760 if (!this->emitGetPtrBasePop(B
->Offset
, Init
))
763 if (!this->visitInitializer(Init
))
766 if (!this->emitInitPtrPop(E
))
768 // Base initializers don't increase InitIndex, since they don't count
769 // into the Record's fields.
771 const Record::Field
*FieldToInit
= R
->getField(InitIndex
);
772 // Non-primitive case. Get a pointer to the field-to-initialize
773 // on the stack and recurse into visitInitializer().
774 if (!this->emitGetPtrField(FieldToInit
->Offset
, Init
))
777 if (!this->visitInitializer(Init
))
780 if (!this->emitPopPtr(E
))
789 /// Pointer to the array(not the element!) must be on the stack when calling
791 template <class Emitter
>
792 bool ByteCodeExprGen
<Emitter
>::visitArrayElemInit(unsigned ElemIndex
,
794 if (std::optional
<PrimType
> T
= classify(Init
->getType())) {
795 // Visit the primitive element like normal.
796 if (!this->visit(Init
))
798 return this->emitInitElem(*T
, ElemIndex
, Init
);
801 // Advance the pointer currently on the stack to the given
803 if (!this->emitConstUint32(ElemIndex
, Init
))
805 if (!this->emitArrayElemPtrUint32(Init
))
807 if (!this->visitInitializer(Init
))
809 return this->emitPopPtr(Init
);
812 template <class Emitter
>
813 bool ByteCodeExprGen
<Emitter
>::VisitInitListExpr(const InitListExpr
*E
) {
814 // Handle discarding first.
816 for (const Expr
*Init
: E
->inits()) {
817 if (!this->discard(Init
))
824 if (std::optional
<PrimType
> T
= classify(E
->getType())) {
825 assert(!DiscardResult
);
826 if (E
->getNumInits() == 0)
827 return this->visitZeroInitializer(*T
, E
->getType(), E
);
828 assert(E
->getNumInits() == 1);
829 return this->delegate(E
->inits()[0]);
832 QualType T
= E
->getType();
833 if (T
->isRecordType())
834 return this->visitInitList(E
->inits(), E
);
836 if (T
->isArrayType()) {
837 // FIXME: Array fillers.
838 unsigned ElementIndex
= 0;
839 for (const Expr
*Init
: E
->inits()) {
840 if (!this->visitArrayElemInit(ElementIndex
, Init
))
847 if (T
->isAnyComplexType()) {
848 unsigned NumInits
= E
->getNumInits();
849 QualType ElemQT
= E
->getType()->getAs
<ComplexType
>()->getElementType();
850 PrimType ElemT
= classifyPrim(ElemQT
);
852 // Zero-initialize both elements.
853 for (unsigned I
= 0; I
< 2; ++I
) {
854 if (!this->visitZeroInitializer(ElemT
, ElemQT
, E
))
856 if (!this->emitInitElem(ElemT
, I
, E
))
859 } else if (NumInits
== 2) {
860 unsigned InitIndex
= 0;
861 for (const Expr
*Init
: E
->inits()) {
862 if (!this->visit(Init
))
865 if (!this->emitInitElem(ElemT
, InitIndex
, E
))
876 template <class Emitter
>
877 bool ByteCodeExprGen
<Emitter
>::VisitCXXParenListInitExpr(
878 const CXXParenListInitExpr
*E
) {
880 for (const Expr
*Init
: E
->getInitExprs()) {
881 if (!this->discard(Init
))
887 assert(E
->getType()->isRecordType());
888 return this->visitInitList(E
->getInitExprs(), E
);
891 template <class Emitter
>
892 bool ByteCodeExprGen
<Emitter
>::VisitSubstNonTypeTemplateParmExpr(
893 const SubstNonTypeTemplateParmExpr
*E
) {
894 return this->delegate(E
->getReplacement());
897 template <class Emitter
>
898 bool ByteCodeExprGen
<Emitter
>::VisitConstantExpr(const ConstantExpr
*E
) {
899 // Try to emit the APValue directly, without visiting the subexpr.
900 // This will only fail if we can't emit the APValue, so won't emit any
901 // diagnostics or any double values.
902 std::optional
<PrimType
> T
= classify(E
->getType());
903 if (T
&& E
->hasAPValueResult() &&
904 this->visitAPValue(E
->getAPValueResult(), *T
, E
))
907 return this->delegate(E
->getSubExpr());
910 static CharUnits
AlignOfType(QualType T
, const ASTContext
&ASTCtx
,
911 UnaryExprOrTypeTrait Kind
) {
912 bool AlignOfReturnsPreferred
=
913 ASTCtx
.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7
;
915 // C++ [expr.alignof]p3:
916 // When alignof is applied to a reference type, the result is the
917 // alignment of the referenced type.
918 if (const auto *Ref
= T
->getAs
<ReferenceType
>())
919 T
= Ref
->getPointeeType();
921 // __alignof is defined to return the preferred alignment.
922 // Before 8, clang returned the preferred alignment for alignof and
924 if (Kind
== UETT_PreferredAlignOf
|| AlignOfReturnsPreferred
)
925 return ASTCtx
.toCharUnitsFromBits(ASTCtx
.getPreferredTypeAlign(T
));
927 return ASTCtx
.getTypeAlignInChars(T
);
930 template <class Emitter
>
931 bool ByteCodeExprGen
<Emitter
>::VisitUnaryExprOrTypeTraitExpr(
932 const UnaryExprOrTypeTraitExpr
*E
) {
933 UnaryExprOrTypeTrait Kind
= E
->getKind();
934 ASTContext
&ASTCtx
= Ctx
.getASTContext();
936 if (Kind
== UETT_SizeOf
) {
937 QualType ArgType
= E
->getTypeOfArgument();
939 if (ArgType
->isVoidType() || ArgType
->isFunctionType())
940 Size
= CharUnits::One();
942 if (ArgType
->isDependentType() || !ArgType
->isConstantSizeType())
945 Size
= ASTCtx
.getTypeSizeInChars(ArgType
);
951 return this->emitConst(Size
.getQuantity(), E
);
954 if (Kind
== UETT_AlignOf
|| Kind
== UETT_PreferredAlignOf
) {
957 if (E
->isArgumentType()) {
958 QualType ArgType
= E
->getTypeOfArgument();
960 Size
= AlignOfType(ArgType
, ASTCtx
, Kind
);
962 // Argument is an expression, not a type.
963 const Expr
*Arg
= E
->getArgumentExpr()->IgnoreParens();
965 // The kinds of expressions that we have special-case logic here for
966 // should be kept up to date with the special checks for those
967 // expressions in Sema.
969 // alignof decl is always accepted, even if it doesn't make sense: we
970 // default to 1 in those cases.
971 if (const auto *DRE
= dyn_cast
<DeclRefExpr
>(Arg
))
972 Size
= ASTCtx
.getDeclAlign(DRE
->getDecl(),
973 /*RefAsPointee*/ true);
974 else if (const auto *ME
= dyn_cast
<MemberExpr
>(Arg
))
975 Size
= ASTCtx
.getDeclAlign(ME
->getMemberDecl(),
976 /*RefAsPointee*/ true);
978 Size
= AlignOfType(Arg
->getType(), ASTCtx
, Kind
);
984 return this->emitConst(Size
.getQuantity(), E
);
990 template <class Emitter
>
991 bool ByteCodeExprGen
<Emitter
>::VisitMemberExpr(const MemberExpr
*E
) {
993 const Expr
*Base
= E
->getBase();
996 return this->discard(Base
);
998 if (!this->visit(Base
))
1001 // Base above gives us a pointer on the stack.
1002 // TODO: Implement non-FieldDecl members.
1003 const ValueDecl
*Member
= E
->getMemberDecl();
1004 if (const auto *FD
= dyn_cast
<FieldDecl
>(Member
)) {
1005 const RecordDecl
*RD
= FD
->getParent();
1006 const Record
*R
= getRecord(RD
);
1007 const Record::Field
*F
= R
->getField(FD
);
1008 // Leave a pointer to the field on the stack.
1009 if (F
->Decl
->getType()->isReferenceType())
1010 return this->emitGetFieldPop(PT_Ptr
, F
->Offset
, E
);
1011 return this->emitGetPtrField(F
->Offset
, E
);
1017 template <class Emitter
>
1018 bool ByteCodeExprGen
<Emitter
>::VisitArrayInitIndexExpr(
1019 const ArrayInitIndexExpr
*E
) {
1020 // ArrayIndex might not be set if a ArrayInitIndexExpr is being evaluated
1021 // stand-alone, e.g. via EvaluateAsInt().
1024 return this->emitConst(*ArrayIndex
, E
);
1027 template <class Emitter
>
1028 bool ByteCodeExprGen
<Emitter
>::VisitArrayInitLoopExpr(
1029 const ArrayInitLoopExpr
*E
) {
1030 assert(Initializing
);
1031 assert(!DiscardResult
);
1032 // TODO: This compiles to quite a lot of bytecode if the array is larger.
1033 // Investigate compiling this to a loop.
1035 const Expr
*SubExpr
= E
->getSubExpr();
1036 const Expr
*CommonExpr
= E
->getCommonExpr();
1037 size_t Size
= E
->getArraySize().getZExtValue();
1039 // If the common expression is an opaque expression, we visit it
1040 // here once so we have its value cached.
1041 // FIXME: This might be necessary (or useful) for all expressions.
1042 if (isa
<OpaqueValueExpr
>(CommonExpr
)) {
1043 if (!this->discard(CommonExpr
))
1047 // So, every iteration, we execute an assignment here
1048 // where the LHS is on the stack (the target array)
1049 // and the RHS is our SubExpr.
1050 for (size_t I
= 0; I
!= Size
; ++I
) {
1051 ArrayIndexScope
<Emitter
> IndexScope(this, I
);
1052 BlockScope
<Emitter
> BS(this);
1054 if (!this->visitArrayElemInit(I
, SubExpr
))
1060 template <class Emitter
>
1061 bool ByteCodeExprGen
<Emitter
>::VisitOpaqueValueExpr(const OpaqueValueExpr
*E
) {
1063 return this->visitInitializer(E
->getSourceExpr());
1065 PrimType SubExprT
= classify(E
->getSourceExpr()).value_or(PT_Ptr
);
1066 if (auto It
= OpaqueExprs
.find(E
); It
!= OpaqueExprs
.end())
1067 return this->emitGetLocal(SubExprT
, It
->second
, E
);
1069 if (!this->visit(E
->getSourceExpr()))
1072 // At this point we either have the evaluated source expression or a pointer
1073 // to an object on the stack. We want to create a local variable that stores
1075 std::optional
<unsigned> LocalIndex
=
1076 allocateLocalPrimitive(E
, SubExprT
, /*IsConst=*/true);
1079 if (!this->emitSetLocal(SubExprT
, *LocalIndex
, E
))
1082 // Here the local variable is created but the value is removed from the stack,
1083 // so we put it back, because the caller might need it.
1084 if (!DiscardResult
) {
1085 if (!this->emitGetLocal(SubExprT
, *LocalIndex
, E
))
1089 // FIXME: Ideally the cached value should be cleaned up later.
1090 OpaqueExprs
.insert({E
, *LocalIndex
});
1095 template <class Emitter
>
1096 bool ByteCodeExprGen
<Emitter
>::VisitAbstractConditionalOperator(
1097 const AbstractConditionalOperator
*E
) {
1098 const Expr
*Condition
= E
->getCond();
1099 const Expr
*TrueExpr
= E
->getTrueExpr();
1100 const Expr
*FalseExpr
= E
->getFalseExpr();
1102 LabelTy LabelEnd
= this->getLabel(); // Label after the operator.
1103 LabelTy LabelFalse
= this->getLabel(); // Label for the false expr.
1105 if (!this->visitBool(Condition
))
1108 if (!this->jumpFalse(LabelFalse
))
1111 if (!this->delegate(TrueExpr
))
1113 if (!this->jump(LabelEnd
))
1116 this->emitLabel(LabelFalse
);
1118 if (!this->delegate(FalseExpr
))
1121 this->fallthrough(LabelEnd
);
1122 this->emitLabel(LabelEnd
);
1127 template <class Emitter
>
1128 bool ByteCodeExprGen
<Emitter
>::VisitStringLiteral(const StringLiteral
*E
) {
1132 if (!Initializing
) {
1133 unsigned StringIndex
= P
.createGlobalString(E
);
1134 return this->emitGetPtrGlobal(StringIndex
, E
);
1137 // We are initializing an array on the stack.
1138 const ConstantArrayType
*CAT
=
1139 Ctx
.getASTContext().getAsConstantArrayType(E
->getType());
1140 assert(CAT
&& "a string literal that's not a constant array?");
1142 // If the initializer string is too long, a diagnostic has already been
1143 // emitted. Read only the array length from the string literal.
1144 unsigned ArraySize
= CAT
->getSize().getZExtValue();
1145 unsigned N
= std::min(ArraySize
, E
->getLength());
1146 size_t CharWidth
= E
->getCharByteWidth();
1148 for (unsigned I
= 0; I
!= N
; ++I
) {
1149 uint32_t CodeUnit
= E
->getCodeUnit(I
);
1151 if (CharWidth
== 1) {
1152 this->emitConstSint8(CodeUnit
, E
);
1153 this->emitInitElemSint8(I
, E
);
1154 } else if (CharWidth
== 2) {
1155 this->emitConstUint16(CodeUnit
, E
);
1156 this->emitInitElemUint16(I
, E
);
1157 } else if (CharWidth
== 4) {
1158 this->emitConstUint32(CodeUnit
, E
);
1159 this->emitInitElemUint32(I
, E
);
1161 llvm_unreachable("unsupported character width");
1165 // Fill up the rest of the char array with NUL bytes.
1166 for (unsigned I
= N
; I
!= ArraySize
; ++I
) {
1167 if (CharWidth
== 1) {
1168 this->emitConstSint8(0, E
);
1169 this->emitInitElemSint8(I
, E
);
1170 } else if (CharWidth
== 2) {
1171 this->emitConstUint16(0, E
);
1172 this->emitInitElemUint16(I
, E
);
1173 } else if (CharWidth
== 4) {
1174 this->emitConstUint32(0, E
);
1175 this->emitInitElemUint32(I
, E
);
1177 llvm_unreachable("unsupported character width");
1184 template <class Emitter
>
1185 bool ByteCodeExprGen
<Emitter
>::VisitCharacterLiteral(
1186 const CharacterLiteral
*E
) {
1189 return this->emitConst(E
->getValue(), E
);
1192 template <class Emitter
>
1193 bool ByteCodeExprGen
<Emitter
>::VisitFloatCompoundAssignOperator(
1194 const CompoundAssignOperator
*E
) {
1196 const Expr
*LHS
= E
->getLHS();
1197 const Expr
*RHS
= E
->getRHS();
1198 QualType LHSType
= LHS
->getType();
1199 QualType LHSComputationType
= E
->getComputationLHSType();
1200 QualType ResultType
= E
->getComputationResultType();
1201 std::optional
<PrimType
> LT
= classify(LHSComputationType
);
1202 std::optional
<PrimType
> RT
= classify(ResultType
);
1204 assert(ResultType
->isFloatingType());
1209 PrimType LHST
= classifyPrim(LHSType
);
1211 // C++17 onwards require that we evaluate the RHS first.
1212 // Compute RHS and save it in a temporary variable so we can
1213 // load it again later.
1217 unsigned TempOffset
= this->allocateLocalPrimitive(E
, *RT
, /*IsConst=*/true);
1218 if (!this->emitSetLocal(*RT
, TempOffset
, E
))
1221 // First, visit LHS.
1224 if (!this->emitLoad(LHST
, E
))
1227 // If necessary, convert LHS to its computation type.
1228 if (!this->emitPrimCast(LHST
, classifyPrim(LHSComputationType
),
1229 LHSComputationType
, E
))
1233 if (!this->emitGetLocal(*RT
, TempOffset
, E
))
1236 llvm::RoundingMode RM
= getRoundingMode(E
);
1237 switch (E
->getOpcode()) {
1239 if (!this->emitAddf(RM
, E
))
1243 if (!this->emitSubf(RM
, E
))
1247 if (!this->emitMulf(RM
, E
))
1251 if (!this->emitDivf(RM
, E
))
1258 if (!this->emitPrimCast(classifyPrim(ResultType
), LHST
, LHS
->getType(), E
))
1262 return this->emitStorePop(LHST
, E
);
1263 return this->emitStore(LHST
, E
);
1266 template <class Emitter
>
1267 bool ByteCodeExprGen
<Emitter
>::VisitPointerCompoundAssignOperator(
1268 const CompoundAssignOperator
*E
) {
1269 BinaryOperatorKind Op
= E
->getOpcode();
1270 const Expr
*LHS
= E
->getLHS();
1271 const Expr
*RHS
= E
->getRHS();
1272 std::optional
<PrimType
> LT
= classify(LHS
->getType());
1273 std::optional
<PrimType
> RT
= classify(RHS
->getType());
1275 if (Op
!= BO_AddAssign
&& Op
!= BO_SubAssign
)
1280 assert(*LT
== PT_Ptr
);
1285 if (!this->emitLoadPtr(LHS
))
1291 if (Op
== BO_AddAssign
)
1292 this->emitAddOffset(*RT
, E
);
1294 this->emitSubOffset(*RT
, E
);
1297 return this->emitStorePopPtr(E
);
1298 return this->emitStorePtr(E
);
1301 template <class Emitter
>
1302 bool ByteCodeExprGen
<Emitter
>::VisitCompoundAssignOperator(
1303 const CompoundAssignOperator
*E
) {
1305 const Expr
*LHS
= E
->getLHS();
1306 const Expr
*RHS
= E
->getRHS();
1307 std::optional
<PrimType
> LHSComputationT
=
1308 classify(E
->getComputationLHSType());
1309 std::optional
<PrimType
> LT
= classify(LHS
->getType());
1310 std::optional
<PrimType
> RT
= classify(E
->getComputationResultType());
1311 std::optional
<PrimType
> ResultT
= classify(E
->getType());
1313 if (!LT
|| !RT
|| !ResultT
|| !LHSComputationT
)
1316 // Handle floating point operations separately here, since they
1317 // require special care.
1319 if (ResultT
== PT_Float
|| RT
== PT_Float
)
1320 return VisitFloatCompoundAssignOperator(E
);
1322 if (E
->getType()->isPointerType())
1323 return VisitPointerCompoundAssignOperator(E
);
1325 assert(!E
->getType()->isPointerType() && "Handled above");
1326 assert(!E
->getType()->isFloatingType() && "Handled above");
1328 // C++17 onwards require that we evaluate the RHS first.
1329 // Compute RHS and save it in a temporary variable so we can
1330 // load it again later.
1331 // FIXME: Compound assignments are unsequenced in C, so we might
1332 // have to figure out how to reject them.
1336 unsigned TempOffset
= this->allocateLocalPrimitive(E
, *RT
, /*IsConst=*/true);
1338 if (!this->emitSetLocal(*RT
, TempOffset
, E
))
1341 // Get LHS pointer, load its value and cast it to the
1342 // computation type if necessary.
1345 if (!this->emitLoad(*LT
, E
))
1347 if (*LT
!= *LHSComputationT
) {
1348 if (!this->emitCast(*LT
, *LHSComputationT
, E
))
1352 // Get the RHS value on the stack.
1353 if (!this->emitGetLocal(*RT
, TempOffset
, E
))
1356 // Perform operation.
1357 switch (E
->getOpcode()) {
1359 if (!this->emitAdd(*LHSComputationT
, E
))
1363 if (!this->emitSub(*LHSComputationT
, E
))
1367 if (!this->emitMul(*LHSComputationT
, E
))
1371 if (!this->emitDiv(*LHSComputationT
, E
))
1375 if (!this->emitRem(*LHSComputationT
, E
))
1379 if (!this->emitShl(*LHSComputationT
, *RT
, E
))
1383 if (!this->emitShr(*LHSComputationT
, *RT
, E
))
1387 if (!this->emitBitAnd(*LHSComputationT
, E
))
1391 if (!this->emitBitXor(*LHSComputationT
, E
))
1395 if (!this->emitBitOr(*LHSComputationT
, E
))
1399 llvm_unreachable("Unimplemented compound assign operator");
1402 // And now cast from LHSComputationT to ResultT.
1403 if (*ResultT
!= *LHSComputationT
) {
1404 if (!this->emitCast(*LHSComputationT
, *ResultT
, E
))
1408 // And store the result in LHS.
1409 if (DiscardResult
) {
1410 if (LHS
->refersToBitField())
1411 return this->emitStoreBitFieldPop(*ResultT
, E
);
1412 return this->emitStorePop(*ResultT
, E
);
1414 if (LHS
->refersToBitField())
1415 return this->emitStoreBitField(*ResultT
, E
);
1416 return this->emitStore(*ResultT
, E
);
1419 template <class Emitter
>
1420 bool ByteCodeExprGen
<Emitter
>::VisitExprWithCleanups(
1421 const ExprWithCleanups
*E
) {
1422 const Expr
*SubExpr
= E
->getSubExpr();
1424 assert(E
->getNumObjects() == 0 && "TODO: Implement cleanups");
1426 return this->delegate(SubExpr
);
1429 template <class Emitter
>
1430 bool ByteCodeExprGen
<Emitter
>::VisitMaterializeTemporaryExpr(
1431 const MaterializeTemporaryExpr
*E
) {
1432 const Expr
*SubExpr
= E
->getSubExpr();
1435 // We already have a value, just initialize that.
1436 return this->visitInitializer(SubExpr
);
1438 // If we don't end up using the materialized temporary anyway, don't
1439 // bother creating it.
1441 return this->discard(SubExpr
);
1443 // When we're initializing a global variable *or* the storage duration of
1444 // the temporary is explicitly static, create a global variable.
1445 std::optional
<PrimType
> SubExprT
= classify(SubExpr
);
1446 bool IsStatic
= E
->getStorageDuration() == SD_Static
;
1447 if (GlobalDecl
|| IsStatic
) {
1448 std::optional
<unsigned> GlobalIndex
= P
.createGlobal(E
);
1452 const LifetimeExtendedTemporaryDecl
*TempDecl
=
1453 E
->getLifetimeExtendedTemporaryDecl();
1458 if (!this->visit(SubExpr
))
1461 if (!this->emitInitGlobalTemp(*SubExprT
, *GlobalIndex
, TempDecl
, E
))
1464 if (!this->emitInitGlobal(*SubExprT
, *GlobalIndex
, E
))
1467 return this->emitGetPtrGlobal(*GlobalIndex
, E
);
1470 // Non-primitive values.
1471 if (!this->emitGetPtrGlobal(*GlobalIndex
, E
))
1473 if (!this->visitInitializer(SubExpr
))
1476 return this->emitInitGlobalTempComp(TempDecl
, E
);
1480 // For everyhing else, use local variables.
1482 if (std::optional
<unsigned> LocalIndex
= allocateLocalPrimitive(
1483 SubExpr
, *SubExprT
, /*IsConst=*/true, /*IsExtended=*/true)) {
1484 if (!this->visit(SubExpr
))
1486 this->emitSetLocal(*SubExprT
, *LocalIndex
, E
);
1487 return this->emitGetPtrLocal(*LocalIndex
, E
);
1490 if (std::optional
<unsigned> LocalIndex
=
1491 allocateLocal(SubExpr
, /*IsExtended=*/true)) {
1492 if (!this->emitGetPtrLocal(*LocalIndex
, E
))
1494 return this->visitInitializer(SubExpr
);
1500 template <class Emitter
>
1501 bool ByteCodeExprGen
<Emitter
>::VisitCXXBindTemporaryExpr(
1502 const CXXBindTemporaryExpr
*E
) {
1503 return this->delegate(E
->getSubExpr());
1506 template <class Emitter
>
1507 bool ByteCodeExprGen
<Emitter
>::VisitCompoundLiteralExpr(
1508 const CompoundLiteralExpr
*E
) {
1509 const Expr
*Init
= E
->getInitializer();
1511 // We already have a value, just initialize that.
1512 return this->visitInitializer(Init
);
1515 std::optional
<PrimType
> T
= classify(E
->getType());
1516 if (E
->isFileScope()) {
1517 if (std::optional
<unsigned> GlobalIndex
= P
.createGlobal(E
)) {
1518 if (classify(E
->getType()))
1519 return this->visit(Init
);
1520 if (!this->emitGetPtrGlobal(*GlobalIndex
, E
))
1522 return this->visitInitializer(Init
);
1526 // Otherwise, use a local variable.
1528 // For primitive types, we just visit the initializer.
1529 return this->delegate(Init
);
1531 if (std::optional
<unsigned> LocalIndex
= allocateLocal(Init
)) {
1532 if (!this->emitGetPtrLocal(*LocalIndex
, E
))
1534 if (!this->visitInitializer(Init
))
1537 return this->emitPopPtr(E
);
1545 template <class Emitter
>
1546 bool ByteCodeExprGen
<Emitter
>::VisitTypeTraitExpr(const TypeTraitExpr
*E
) {
1549 return this->emitConstBool(E
->getValue(), E
);
1552 template <class Emitter
>
1553 bool ByteCodeExprGen
<Emitter
>::VisitLambdaExpr(const LambdaExpr
*E
) {
1554 assert(Initializing
);
1555 const Record
*R
= P
.getOrCreateRecord(E
->getLambdaClass());
1557 auto *CaptureInitIt
= E
->capture_init_begin();
1558 // Initialize all fields (which represent lambda captures) of the
1559 // record with their initializers.
1560 for (const Record::Field
&F
: R
->fields()) {
1561 const Expr
*Init
= *CaptureInitIt
;
1564 if (std::optional
<PrimType
> T
= classify(Init
)) {
1565 if (!this->visit(Init
))
1568 if (!this->emitSetField(*T
, F
.Offset
, E
))
1571 if (!this->emitDupPtr(E
))
1574 if (!this->emitGetPtrField(F
.Offset
, E
))
1577 if (!this->visitInitializer(Init
))
1580 if (!this->emitPopPtr(E
))
1588 template <class Emitter
>
1589 bool ByteCodeExprGen
<Emitter
>::VisitPredefinedExpr(const PredefinedExpr
*E
) {
1593 assert(!Initializing
);
1594 return this->visit(E
->getFunctionName());
1597 template <class Emitter
>
1598 bool ByteCodeExprGen
<Emitter
>::VisitCXXThrowExpr(const CXXThrowExpr
*E
) {
1599 if (E
->getSubExpr() && !this->discard(E
->getSubExpr()))
1602 return this->emitInvalid(E
);
1605 template <class Emitter
>
1606 bool ByteCodeExprGen
<Emitter
>::VisitCXXReinterpretCastExpr(
1607 const CXXReinterpretCastExpr
*E
) {
1608 if (!this->discard(E
->getSubExpr()))
1611 return this->emitInvalidCast(CastKind::Reinterpret
, E
);
1614 template <class Emitter
>
1615 bool ByteCodeExprGen
<Emitter
>::VisitCXXNoexceptExpr(const CXXNoexceptExpr
*E
) {
1616 assert(E
->getType()->isBooleanType());
1620 return this->emitConstBool(E
->getValue(), E
);
1623 template <class Emitter
>
1624 bool ByteCodeExprGen
<Emitter
>::VisitCXXConstructExpr(
1625 const CXXConstructExpr
*E
) {
1626 QualType T
= E
->getType();
1627 assert(!classify(T
));
1629 if (T
->isRecordType()) {
1630 const CXXConstructorDecl
*Ctor
= E
->getConstructor();
1632 // Trivial zero initialization.
1633 if (E
->requiresZeroInitialization() && Ctor
->isTrivial()) {
1634 const Record
*R
= getRecord(E
->getType());
1635 return this->visitZeroRecordInitializer(R
, E
);
1638 const Function
*Func
= getFunction(Ctor
);
1643 assert(Func
->hasThisPointer());
1644 assert(!Func
->hasRVO());
1646 // If we're discarding a construct expression, we still need
1647 // to allocate a variable and call the constructor and destructor.
1648 if (DiscardResult
) {
1649 assert(!Initializing
);
1650 std::optional
<unsigned> LocalIndex
=
1651 allocateLocal(E
, /*IsExtended=*/true);
1656 if (!this->emitGetPtrLocal(*LocalIndex
, E
))
1660 // The This pointer is already on the stack because this is an initializer,
1661 // but we need to dup() so the call() below has its own copy.
1662 if (!this->emitDupPtr(E
))
1665 // Constructor arguments.
1666 for (const auto *Arg
: E
->arguments()) {
1667 if (!this->visit(Arg
))
1671 if (!this->emitCall(Func
, E
))
1674 // Immediately call the destructor if we have to.
1675 if (DiscardResult
) {
1676 if (!this->emitPopPtr(E
))
1682 if (T
->isArrayType()) {
1683 const ConstantArrayType
*CAT
=
1684 Ctx
.getASTContext().getAsConstantArrayType(E
->getType());
1686 size_t NumElems
= CAT
->getSize().getZExtValue();
1687 const Function
*Func
= getFunction(E
->getConstructor());
1688 if (!Func
|| !Func
->isConstexpr())
1691 // FIXME(perf): We're calling the constructor once per array element here,
1692 // in the old intepreter we had a special-case for trivial constructors.
1693 for (size_t I
= 0; I
!= NumElems
; ++I
) {
1694 if (!this->emitConstUint64(I
, E
))
1696 if (!this->emitArrayElemPtrUint64(E
))
1699 // Constructor arguments.
1700 for (const auto *Arg
: E
->arguments()) {
1701 if (!this->visit(Arg
))
1705 if (!this->emitCall(Func
, E
))
1714 template <class Emitter
>
1715 bool ByteCodeExprGen
<Emitter
>::VisitSourceLocExpr(const SourceLocExpr
*E
) {
1720 E
->EvaluateInContext(Ctx
.getASTContext(), SourceLocDefaultExpr
);
1722 // Things like __builtin_LINE().
1723 if (E
->getType()->isIntegerType()) {
1724 assert(Val
.isInt());
1725 const APSInt
&I
= Val
.getInt();
1726 return this->emitConst(I
, E
);
1728 // Otherwise, the APValue is an LValue, with only one element.
1729 // Theoretically, we don't need the APValue at all of course.
1730 assert(E
->getType()->isPointerType());
1731 assert(Val
.isLValue());
1732 const APValue::LValueBase
&Base
= Val
.getLValueBase();
1733 if (const Expr
*LValueExpr
= Base
.dyn_cast
<const Expr
*>())
1734 return this->visit(LValueExpr
);
1736 // Otherwise, we have a decl (which is the case for
1737 // __builtin_source_location).
1738 assert(Base
.is
<const ValueDecl
*>());
1739 assert(Val
.getLValuePath().size() == 0);
1740 const auto *BaseDecl
= Base
.dyn_cast
<const ValueDecl
*>();
1743 auto *UGCD
= cast
<UnnamedGlobalConstantDecl
>(BaseDecl
);
1745 std::optional
<unsigned> GlobalIndex
= P
.getOrCreateGlobal(UGCD
);
1749 if (!this->emitGetPtrGlobal(*GlobalIndex
, E
))
1752 const Record
*R
= getRecord(E
->getType());
1753 const APValue
&V
= UGCD
->getValue();
1754 for (unsigned I
= 0, N
= R
->getNumFields(); I
!= N
; ++I
) {
1755 const Record::Field
*F
= R
->getField(I
);
1756 const APValue
&FieldValue
= V
.getStructField(I
);
1758 PrimType FieldT
= classifyPrim(F
->Decl
->getType());
1760 if (!this->visitAPValue(FieldValue
, FieldT
, E
))
1762 if (!this->emitInitField(FieldT
, F
->Offset
, E
))
1766 // Leave the pointer to the global on the stack.
1770 template <class Emitter
>
1771 bool ByteCodeExprGen
<Emitter
>::VisitOffsetOfExpr(const OffsetOfExpr
*E
) {
1772 unsigned N
= E
->getNumComponents();
1776 for (unsigned I
= 0; I
!= N
; ++I
) {
1777 const OffsetOfNode
&Node
= E
->getComponent(I
);
1778 if (Node
.getKind() == OffsetOfNode::Array
) {
1779 const Expr
*ArrayIndexExpr
= E
->getIndexExpr(Node
.getArrayExprIndex());
1780 PrimType IndexT
= classifyPrim(ArrayIndexExpr
->getType());
1782 if (DiscardResult
) {
1783 if (!this->discard(ArrayIndexExpr
))
1788 if (!this->visit(ArrayIndexExpr
))
1791 if (IndexT
!= PT_Sint64
) {
1792 if (!this->emitCast(IndexT
, PT_Sint64
, E
))
1801 PrimType T
= classifyPrim(E
->getType());
1802 return this->emitOffsetOf(T
, E
, E
);
1805 template <class Emitter
>
1806 bool ByteCodeExprGen
<Emitter
>::VisitCXXScalarValueInitExpr(
1807 const CXXScalarValueInitExpr
*E
) {
1808 QualType Ty
= E
->getType();
1810 if (Ty
->isVoidType())
1813 return this->visitZeroInitializer(classifyPrim(Ty
), Ty
, E
);
1816 template <class Emitter
>
1817 bool ByteCodeExprGen
<Emitter
>::VisitSizeOfPackExpr(const SizeOfPackExpr
*E
) {
1818 return this->emitConst(E
->getPackLength(), E
);
1821 template <class Emitter
> bool ByteCodeExprGen
<Emitter
>::discard(const Expr
*E
) {
1822 if (E
->containsErrors())
1825 OptionScope
<Emitter
> Scope(this, /*NewDiscardResult=*/true,
1826 /*NewInitializing=*/false);
1827 return this->Visit(E
);
1830 template <class Emitter
>
1831 bool ByteCodeExprGen
<Emitter
>::delegate(const Expr
*E
) {
1832 if (E
->containsErrors())
1835 // We're basically doing:
1836 // OptionScope<Emitter> Scope(this, DicardResult, Initializing);
1837 // but that's unnecessary of course.
1838 return this->Visit(E
);
1841 template <class Emitter
> bool ByteCodeExprGen
<Emitter
>::visit(const Expr
*E
) {
1842 if (E
->containsErrors())
1845 if (E
->getType()->isVoidType())
1846 return this->discard(E
);
1848 // Create local variable to hold the return value.
1849 if (!E
->isGLValue() && !E
->getType()->isAnyComplexType() &&
1850 !classify(E
->getType())) {
1851 std::optional
<unsigned> LocalIndex
= allocateLocal(E
, /*IsExtended=*/true);
1855 if (!this->emitGetPtrLocal(*LocalIndex
, E
))
1857 return this->visitInitializer(E
);
1860 // Otherwise,we have a primitive return value, produce the value directly
1861 // and push it on the stack.
1862 OptionScope
<Emitter
> Scope(this, /*NewDiscardResult=*/false,
1863 /*NewInitializing=*/false);
1864 return this->Visit(E
);
1867 template <class Emitter
>
1868 bool ByteCodeExprGen
<Emitter
>::visitInitializer(const Expr
*E
) {
1869 assert(!classify(E
->getType()));
1871 if (E
->containsErrors())
1874 OptionScope
<Emitter
> Scope(this, /*NewDiscardResult=*/false,
1875 /*NewInitializing=*/true);
1876 return this->Visit(E
);
1879 template <class Emitter
>
1880 bool ByteCodeExprGen
<Emitter
>::visitBool(const Expr
*E
) {
1881 std::optional
<PrimType
> T
= classify(E
->getType());
1885 if (!this->visit(E
))
1891 // Convert pointers to bool.
1892 if (T
== PT_Ptr
|| T
== PT_FnPtr
) {
1893 if (!this->emitNull(*T
, E
))
1895 return this->emitNE(*T
, E
);
1900 return this->emitCastFloatingIntegralBool(E
);
1902 // Or anything else we can.
1903 return this->emitCast(*T
, PT_Bool
, E
);
1906 template <class Emitter
>
1907 bool ByteCodeExprGen
<Emitter
>::visitZeroInitializer(PrimType T
, QualType QT
,
1911 return this->emitZeroBool(E
);
1913 return this->emitZeroSint8(E
);
1915 return this->emitZeroUint8(E
);
1917 return this->emitZeroSint16(E
);
1919 return this->emitZeroUint16(E
);
1921 return this->emitZeroSint32(E
);
1923 return this->emitZeroUint32(E
);
1925 return this->emitZeroSint64(E
);
1927 return this->emitZeroUint64(E
);
1929 return this->emitZeroIntAP(Ctx
.getBitWidth(QT
), E
);
1931 return this->emitZeroIntAPS(Ctx
.getBitWidth(QT
), E
);
1933 return this->emitNullPtr(E
);
1935 return this->emitNullFnPtr(E
);
1937 return this->emitConstFloat(APFloat::getZero(Ctx
.getFloatSemantics(QT
)), E
);
1940 llvm_unreachable("unknown primitive type");
1943 template <class Emitter
>
1944 bool ByteCodeExprGen
<Emitter
>::visitZeroRecordInitializer(const Record
*R
,
1949 for (const Record::Field
&Field
: R
->fields()) {
1950 const Descriptor
*D
= Field
.Desc
;
1951 if (D
->isPrimitive()) {
1952 QualType QT
= D
->getType();
1953 PrimType T
= classifyPrim(D
->getType());
1954 if (!this->visitZeroInitializer(T
, QT
, E
))
1956 if (!this->emitInitField(T
, Field
.Offset
, E
))
1961 // TODO: Add GetPtrFieldPop and get rid of this dup.
1962 if (!this->emitDupPtr(E
))
1964 if (!this->emitGetPtrField(Field
.Offset
, E
))
1967 if (D
->isPrimitiveArray()) {
1968 QualType ET
= D
->getElemQualType();
1969 PrimType T
= classifyPrim(ET
);
1970 for (uint32_t I
= 0, N
= D
->getNumElems(); I
!= N
; ++I
) {
1971 if (!this->visitZeroInitializer(T
, ET
, E
))
1973 if (!this->emitInitElem(T
, I
, E
))
1976 } else if (D
->isCompositeArray()) {
1977 const Record
*ElemRecord
= D
->ElemDesc
->ElemRecord
;
1978 assert(D
->ElemDesc
->ElemRecord
);
1979 for (uint32_t I
= 0, N
= D
->getNumElems(); I
!= N
; ++I
) {
1980 if (!this->emitConstUint32(I
, E
))
1982 if (!this->emitArrayElemPtr(PT_Uint32
, E
))
1984 if (!this->visitZeroRecordInitializer(ElemRecord
, E
))
1986 if (!this->emitPopPtr(E
))
1989 } else if (D
->isRecord()) {
1990 if (!this->visitZeroRecordInitializer(D
->ElemRecord
, E
))
1996 if (!this->emitPopPtr(E
))
2000 for (const Record::Base
&B
: R
->bases()) {
2001 if (!this->emitGetPtrBase(B
.Offset
, E
))
2003 if (!this->visitZeroRecordInitializer(B
.R
, E
))
2005 if (!this->emitInitPtrPop(E
))
2009 // FIXME: Virtual bases.
2014 template <class Emitter
>
2015 bool ByteCodeExprGen
<Emitter
>::dereference(
2016 const Expr
*LV
, DerefKind AK
, llvm::function_ref
<bool(PrimType
)> Direct
,
2017 llvm::function_ref
<bool(PrimType
)> Indirect
) {
2018 if (std::optional
<PrimType
> T
= classify(LV
->getType())) {
2019 if (!LV
->refersToBitField()) {
2020 // Only primitive, non bit-field types can be dereferenced directly.
2021 if (const auto *DE
= dyn_cast
<DeclRefExpr
>(LV
)) {
2022 if (!DE
->getDecl()->getType()->isReferenceType()) {
2023 if (const auto *PD
= dyn_cast
<ParmVarDecl
>(DE
->getDecl()))
2024 return dereferenceParam(LV
, *T
, PD
, AK
, Direct
, Indirect
);
2025 if (const auto *VD
= dyn_cast
<VarDecl
>(DE
->getDecl()))
2026 return dereferenceVar(LV
, *T
, VD
, AK
, Direct
, Indirect
);
2033 return Indirect(*T
);
2036 if (LV
->getType()->isAnyComplexType())
2037 return this->delegate(LV
);
2042 template <class Emitter
>
2043 bool ByteCodeExprGen
<Emitter
>::dereferenceParam(
2044 const Expr
*LV
, PrimType T
, const ParmVarDecl
*PD
, DerefKind AK
,
2045 llvm::function_ref
<bool(PrimType
)> Direct
,
2046 llvm::function_ref
<bool(PrimType
)> Indirect
) {
2047 auto It
= this->Params
.find(PD
);
2048 if (It
!= this->Params
.end()) {
2049 unsigned Idx
= It
->second
.Offset
;
2051 case DerefKind::Read
:
2052 return DiscardResult
? true : this->emitGetParam(T
, Idx
, LV
);
2054 case DerefKind::Write
:
2057 if (!this->emitSetParam(T
, Idx
, LV
))
2059 return DiscardResult
? true : this->emitGetPtrParam(Idx
, LV
);
2061 case DerefKind::ReadWrite
:
2062 if (!this->emitGetParam(T
, Idx
, LV
))
2066 if (!this->emitSetParam(T
, Idx
, LV
))
2068 return DiscardResult
? true : this->emitGetPtrParam(Idx
, LV
);
2073 // If the param is a pointer, we can dereference a dummy value.
2074 if (!DiscardResult
&& T
== PT_Ptr
&& AK
== DerefKind::Read
) {
2075 if (auto Idx
= P
.getOrCreateDummy(PD
))
2076 return this->emitGetPtrGlobal(*Idx
, PD
);
2080 // Value cannot be produced - try to emit pointer and do stuff with it.
2081 return visit(LV
) && Indirect(T
);
2084 template <class Emitter
>
2085 bool ByteCodeExprGen
<Emitter
>::dereferenceVar(
2086 const Expr
*LV
, PrimType T
, const VarDecl
*VD
, DerefKind AK
,
2087 llvm::function_ref
<bool(PrimType
)> Direct
,
2088 llvm::function_ref
<bool(PrimType
)> Indirect
) {
2089 auto It
= Locals
.find(VD
);
2090 if (It
!= Locals
.end()) {
2091 const auto &L
= It
->second
;
2093 case DerefKind::Read
:
2094 if (!this->emitGetLocal(T
, L
.Offset
, LV
))
2096 return DiscardResult
? this->emitPop(T
, LV
) : true;
2098 case DerefKind::Write
:
2101 if (!this->emitSetLocal(T
, L
.Offset
, LV
))
2103 return DiscardResult
? true : this->emitGetPtrLocal(L
.Offset
, LV
);
2105 case DerefKind::ReadWrite
:
2106 if (!this->emitGetLocal(T
, L
.Offset
, LV
))
2110 if (!this->emitSetLocal(T
, L
.Offset
, LV
))
2112 return DiscardResult
? true : this->emitGetPtrLocal(L
.Offset
, LV
);
2114 } else if (auto Idx
= P
.getGlobal(VD
)) {
2116 case DerefKind::Read
:
2117 if (!this->emitGetGlobal(T
, *Idx
, LV
))
2119 return DiscardResult
? this->emitPop(T
, LV
) : true;
2121 case DerefKind::Write
:
2124 if (!this->emitSetGlobal(T
, *Idx
, LV
))
2126 return DiscardResult
? true : this->emitGetPtrGlobal(*Idx
, LV
);
2128 case DerefKind::ReadWrite
:
2129 if (!this->emitGetGlobal(T
, *Idx
, LV
))
2133 if (!this->emitSetGlobal(T
, *Idx
, LV
))
2135 return DiscardResult
? true : this->emitGetPtrGlobal(*Idx
, LV
);
2139 // If the declaration is a constant value, emit it here even
2140 // though the declaration was not evaluated in the current scope.
2141 // The access mode can only be read in this case.
2142 if (!DiscardResult
&& AK
== DerefKind::Read
) {
2143 if (VD
->hasLocalStorage() && VD
->hasInit() && !VD
->isConstexpr()) {
2144 QualType VT
= VD
->getType();
2145 if (VT
.isConstQualified() && VT
->isFundamentalType())
2146 return this->visit(VD
->getInit());
2150 // Value cannot be produced - try to emit pointer.
2151 return visit(LV
) && Indirect(T
);
2154 template <class Emitter
>
2155 template <typename T
>
2156 bool ByteCodeExprGen
<Emitter
>::emitConst(T Value
, PrimType Ty
, const Expr
*E
) {
2159 return this->emitConstSint8(Value
, E
);
2161 return this->emitConstUint8(Value
, E
);
2163 return this->emitConstSint16(Value
, E
);
2165 return this->emitConstUint16(Value
, E
);
2167 return this->emitConstSint32(Value
, E
);
2169 return this->emitConstUint32(Value
, E
);
2171 return this->emitConstSint64(Value
, E
);
2173 return this->emitConstUint64(Value
, E
);
2179 return this->emitConstBool(Value
, E
);
2183 llvm_unreachable("Invalid integral type");
2186 llvm_unreachable("unknown primitive type");
2189 template <class Emitter
>
2190 template <typename T
>
2191 bool ByteCodeExprGen
<Emitter
>::emitConst(T Value
, const Expr
*E
) {
2192 return this->emitConst(Value
, classifyPrim(E
->getType()), E
);
2195 template <class Emitter
>
2196 bool ByteCodeExprGen
<Emitter
>::emitConst(const APSInt
&Value
, PrimType Ty
,
2198 if (Value
.isSigned())
2199 return this->emitConst(Value
.getSExtValue(), Ty
, E
);
2200 return this->emitConst(Value
.getZExtValue(), Ty
, E
);
2203 template <class Emitter
>
2204 bool ByteCodeExprGen
<Emitter
>::emitConst(const APSInt
&Value
, const Expr
*E
) {
2205 return this->emitConst(Value
, classifyPrim(E
->getType()), E
);
2208 template <class Emitter
>
2209 unsigned ByteCodeExprGen
<Emitter
>::allocateLocalPrimitive(DeclTy
&&Src
,
2213 // Make sure we don't accidentally register the same decl twice.
2214 if (const auto *VD
=
2215 dyn_cast_if_present
<ValueDecl
>(Src
.dyn_cast
<const Decl
*>())) {
2216 assert(!P
.getGlobal(VD
));
2217 assert(!Locals
.contains(VD
));
2220 // FIXME: There are cases where Src.is<Expr*>() is wrong, e.g.
2221 // (int){12} in C. Consider using Expr::isTemporaryObject() instead
2222 // or isa<MaterializeTemporaryExpr>().
2223 Descriptor
*D
= P
.createDescriptor(Src
, Ty
, Descriptor::InlineDescMD
, IsConst
,
2224 Src
.is
<const Expr
*>());
2225 Scope::Local Local
= this->createLocal(D
);
2226 if (auto *VD
= dyn_cast_if_present
<ValueDecl
>(Src
.dyn_cast
<const Decl
*>()))
2227 Locals
.insert({VD
, Local
});
2228 VarScope
->add(Local
, IsExtended
);
2229 return Local
.Offset
;
2232 template <class Emitter
>
2233 std::optional
<unsigned>
2234 ByteCodeExprGen
<Emitter
>::allocateLocal(DeclTy
&&Src
, bool IsExtended
) {
2235 // Make sure we don't accidentally register the same decl twice.
2236 if ([[maybe_unused
]] const auto *VD
=
2237 dyn_cast_if_present
<ValueDecl
>(Src
.dyn_cast
<const Decl
*>())) {
2238 assert(!P
.getGlobal(VD
));
2239 assert(!Locals
.contains(VD
));
2243 const ValueDecl
*Key
= nullptr;
2244 const Expr
*Init
= nullptr;
2245 bool IsTemporary
= false;
2246 if (auto *VD
= dyn_cast_if_present
<ValueDecl
>(Src
.dyn_cast
<const Decl
*>())) {
2250 if (const auto *VarD
= dyn_cast
<VarDecl
>(VD
))
2251 Init
= VarD
->getInit();
2253 if (auto *E
= Src
.dyn_cast
<const Expr
*>()) {
2258 Descriptor
*D
= P
.createDescriptor(
2259 Src
, Ty
.getTypePtr(), Descriptor::InlineDescMD
, Ty
.isConstQualified(),
2260 IsTemporary
, /*IsMutable=*/false, Init
);
2264 Scope::Local Local
= this->createLocal(D
);
2266 Locals
.insert({Key
, Local
});
2267 VarScope
->add(Local
, IsExtended
);
2268 return Local
.Offset
;
2271 template <class Emitter
>
2272 const RecordType
*ByteCodeExprGen
<Emitter
>::getRecordTy(QualType Ty
) {
2273 if (const PointerType
*PT
= dyn_cast
<PointerType
>(Ty
))
2274 return PT
->getPointeeType()->getAs
<RecordType
>();
2275 return Ty
->getAs
<RecordType
>();
2278 template <class Emitter
>
2279 Record
*ByteCodeExprGen
<Emitter
>::getRecord(QualType Ty
) {
2280 if (const auto *RecordTy
= getRecordTy(Ty
))
2281 return getRecord(RecordTy
->getDecl());
2285 template <class Emitter
>
2286 Record
*ByteCodeExprGen
<Emitter
>::getRecord(const RecordDecl
*RD
) {
2287 return P
.getOrCreateRecord(RD
);
2290 template <class Emitter
>
2291 const Function
*ByteCodeExprGen
<Emitter
>::getFunction(const FunctionDecl
*FD
) {
2292 return Ctx
.getOrCreateFunction(FD
);
2295 template <class Emitter
>
2296 bool ByteCodeExprGen
<Emitter
>::visitExpr(const Expr
*E
) {
2297 ExprScope
<Emitter
> RootScope(this);
2298 // Void expressions.
2299 if (E
->getType()->isVoidType()) {
2302 return this->emitRetVoid(E
);
2305 // Expressions with a primitive return type.
2306 if (std::optional
<PrimType
> T
= classify(E
)) {
2309 return this->emitRet(*T
, E
);
2312 // Expressions with a composite return type.
2313 // For us, that means everything we don't
2314 // have a PrimType for.
2315 if (std::optional
<unsigned> LocalOffset
= this->allocateLocal(E
)) {
2316 if (!this->visitLocalInitializer(E
, *LocalOffset
))
2319 if (!this->emitGetPtrLocal(*LocalOffset
, E
))
2321 return this->emitRetValue(E
);
2327 /// Toplevel visitDecl().
2328 /// We get here from evaluateAsInitializer().
2329 /// We need to evaluate the initializer and return its value.
2330 template <class Emitter
>
2331 bool ByteCodeExprGen
<Emitter
>::visitDecl(const VarDecl
*VD
) {
2332 assert(!VD
->isInvalidDecl() && "Trying to constant evaluate an invalid decl");
2334 // Create and initialize the variable.
2335 if (!this->visitVarDecl(VD
))
2338 std::optional
<PrimType
> VarT
= classify(VD
->getType());
2339 // Get a pointer to the variable
2340 if (Context::shouldBeGloballyIndexed(VD
)) {
2341 auto GlobalIndex
= P
.getGlobal(VD
);
2342 assert(GlobalIndex
); // visitVarDecl() didn't return false.
2344 if (!this->emitGetGlobalUnchecked(*VarT
, *GlobalIndex
, VD
))
2347 if (!this->emitGetPtrGlobal(*GlobalIndex
, VD
))
2351 auto Local
= Locals
.find(VD
);
2352 assert(Local
!= Locals
.end()); // Same here.
2354 if (!this->emitGetLocal(*VarT
, Local
->second
.Offset
, VD
))
2357 if (!this->emitGetPtrLocal(Local
->second
.Offset
, VD
))
2364 return this->emitRet(*VarT
, VD
);
2365 return this->emitRetValue(VD
);
2368 template <class Emitter
>
2369 bool ByteCodeExprGen
<Emitter
>::visitVarDecl(const VarDecl
*VD
) {
2370 // We don't know what to do with these, so just return false.
2371 if (VD
->getType().isNull())
2374 const Expr
*Init
= VD
->getInit();
2375 std::optional
<PrimType
> VarT
= classify(VD
->getType());
2377 if (Context::shouldBeGloballyIndexed(VD
)) {
2378 // We've already seen and initialized this global.
2379 if (P
.getGlobal(VD
))
2382 std::optional
<unsigned> GlobalIndex
= P
.createGlobal(VD
, Init
);
2385 return this->bail(VD
);
2389 DeclScope
<Emitter
> LocalScope(this, VD
);
2392 if (!this->visit(Init
))
2394 return this->emitInitGlobal(*VarT
, *GlobalIndex
, VD
);
2396 return this->visitGlobalInitializer(Init
, *GlobalIndex
);
2399 VariableScope
<Emitter
> LocalScope(this);
2401 unsigned Offset
= this->allocateLocalPrimitive(
2402 VD
, *VarT
, VD
->getType().isConstQualified());
2404 // Compile the initializer in its own scope.
2405 ExprScope
<Emitter
> Scope(this);
2406 if (!this->visit(Init
))
2409 return this->emitSetLocal(*VarT
, Offset
, VD
);
2412 if (std::optional
<unsigned> Offset
= this->allocateLocal(VD
)) {
2414 return this->visitLocalInitializer(Init
, *Offset
);
2423 template <class Emitter
>
2424 bool ByteCodeExprGen
<Emitter
>::visitAPValue(const APValue
&Val
,
2425 PrimType ValType
, const Expr
*E
) {
2426 assert(!DiscardResult
);
2428 return this->emitConst(Val
.getInt(), ValType
, E
);
2430 if (Val
.isLValue()) {
2431 APValue::LValueBase Base
= Val
.getLValueBase();
2432 if (const Expr
*BaseExpr
= Base
.dyn_cast
<const Expr
*>())
2433 return this->visit(BaseExpr
);
2439 template <class Emitter
>
2440 bool ByteCodeExprGen
<Emitter
>::VisitBuiltinCallExpr(const CallExpr
*E
) {
2441 const Function
*Func
= getFunction(E
->getDirectCallee());
2445 if (!Func
->isUnevaluatedBuiltin()) {
2446 // Put arguments on the stack.
2447 for (const auto *Arg
: E
->arguments()) {
2448 if (!this->visit(Arg
))
2453 if (!this->emitCallBI(Func
, E
, E
))
2456 QualType ReturnType
= E
->getCallReturnType(Ctx
.getASTContext());
2457 if (DiscardResult
&& !ReturnType
->isVoidType()) {
2458 PrimType T
= classifyPrim(ReturnType
);
2459 return this->emitPop(T
, E
);
2465 template <class Emitter
>
2466 bool ByteCodeExprGen
<Emitter
>::VisitCallExpr(const CallExpr
*E
) {
2467 if (E
->getBuiltinCallee())
2468 return VisitBuiltinCallExpr(E
);
2470 QualType ReturnType
= E
->getCallReturnType(Ctx
.getASTContext());
2471 std::optional
<PrimType
> T
= classify(ReturnType
);
2472 bool HasRVO
= !ReturnType
->isVoidType() && !T
;
2475 if (DiscardResult
) {
2476 // If we need to discard the return value but the function returns its
2477 // value via an RVO pointer, we need to create one such pointer just
2479 if (std::optional
<unsigned> LocalIndex
= allocateLocal(E
)) {
2480 if (!this->emitGetPtrLocal(*LocalIndex
, E
))
2484 assert(Initializing
);
2485 if (!this->emitDupPtr(E
))
2490 // Add the (optional, implicit) This pointer.
2491 if (const auto *MC
= dyn_cast
<CXXMemberCallExpr
>(E
)) {
2492 if (!this->visit(MC
->getImplicitObjectArgument()))
2496 // Put arguments on the stack.
2497 for (const auto *Arg
: E
->arguments()) {
2498 if (!this->visit(Arg
))
2502 if (const FunctionDecl
*FuncDecl
= E
->getDirectCallee()) {
2503 const Function
*Func
= getFunction(FuncDecl
);
2506 // If the function is being compiled right now, this is a recursive call.
2507 // In that case, the function can't be valid yet, even though it will be
2509 // If the function is already fully compiled but not constexpr, it was
2510 // found to be faulty earlier on, so bail out.
2511 if (Func
->isFullyCompiled() && !Func
->isConstexpr())
2514 assert(HasRVO
== Func
->hasRVO());
2516 bool HasQualifier
= false;
2517 if (const auto *ME
= dyn_cast
<MemberExpr
>(E
->getCallee()))
2518 HasQualifier
= ME
->hasQualifier();
2520 bool IsVirtual
= false;
2521 if (const auto *MD
= dyn_cast
<CXXMethodDecl
>(FuncDecl
))
2522 IsVirtual
= MD
->isVirtual();
2524 // In any case call the function. The return value will end up on the stack
2525 // and if the function has RVO, we already have the pointer on the stack to
2526 // write the result into.
2527 if (IsVirtual
&& !HasQualifier
) {
2528 if (!this->emitCallVirt(Func
, E
))
2531 if (!this->emitCall(Func
, E
))
2535 // Indirect call. Visit the callee, which will leave a FunctionPointer on
2536 // the stack. Cleanup of the returned value if necessary will be done after
2537 // the function call completed.
2538 if (!this->visit(E
->getCallee()))
2541 if (!this->emitCallPtr(E
))
2545 // Cleanup for discarded return values.
2546 if (DiscardResult
&& !ReturnType
->isVoidType() && T
)
2547 return this->emitPop(*T
, E
);
2552 template <class Emitter
>
2553 bool ByteCodeExprGen
<Emitter
>::VisitCXXDefaultInitExpr(
2554 const CXXDefaultInitExpr
*E
) {
2555 SourceLocScope
<Emitter
> SLS(this, E
);
2557 return this->visitInitializer(E
->getExpr());
2559 assert(classify(E
->getType()));
2560 return this->visit(E
->getExpr());
2563 template <class Emitter
>
2564 bool ByteCodeExprGen
<Emitter
>::VisitCXXDefaultArgExpr(
2565 const CXXDefaultArgExpr
*E
) {
2566 SourceLocScope
<Emitter
> SLS(this, E
);
2568 const Expr
*SubExpr
= E
->getExpr();
2569 if (std::optional
<PrimType
> T
= classify(E
->getExpr()))
2570 return this->visit(SubExpr
);
2572 assert(Initializing
);
2573 return this->visitInitializer(SubExpr
);
2576 template <class Emitter
>
2577 bool ByteCodeExprGen
<Emitter
>::VisitCXXBoolLiteralExpr(
2578 const CXXBoolLiteralExpr
*E
) {
2582 return this->emitConstBool(E
->getValue(), E
);
2585 template <class Emitter
>
2586 bool ByteCodeExprGen
<Emitter
>::VisitCXXNullPtrLiteralExpr(
2587 const CXXNullPtrLiteralExpr
*E
) {
2591 return this->emitNullPtr(E
);
2594 template <class Emitter
>
2595 bool ByteCodeExprGen
<Emitter
>::VisitGNUNullExpr(const GNUNullExpr
*E
) {
2599 assert(E
->getType()->isIntegerType());
2601 PrimType T
= classifyPrim(E
->getType());
2602 return this->emitZero(T
, E
);
2605 template <class Emitter
>
2606 bool ByteCodeExprGen
<Emitter
>::VisitCXXThisExpr(const CXXThisExpr
*E
) {
2610 if (this->LambdaThisCapture
> 0)
2611 return this->emitGetThisFieldPtr(this->LambdaThisCapture
, E
);
2613 return this->emitThis(E
);
2616 template <class Emitter
>
2617 bool ByteCodeExprGen
<Emitter
>::VisitUnaryOperator(const UnaryOperator
*E
) {
2618 const Expr
*SubExpr
= E
->getSubExpr();
2619 std::optional
<PrimType
> T
= classify(SubExpr
->getType());
2621 switch (E
->getOpcode()) {
2622 case UO_PostInc
: { // x++
2623 if (!this->visit(SubExpr
))
2627 if (!this->emitIncPtr(E
))
2630 return DiscardResult
? this->emitPopPtr(E
) : true;
2633 if (T
== PT_Float
) {
2634 return DiscardResult
? this->emitIncfPop(getRoundingMode(E
), E
)
2635 : this->emitIncf(getRoundingMode(E
), E
);
2638 return DiscardResult
? this->emitIncPop(*T
, E
) : this->emitInc(*T
, E
);
2640 case UO_PostDec
: { // x--
2641 if (!this->visit(SubExpr
))
2645 if (!this->emitDecPtr(E
))
2648 return DiscardResult
? this->emitPopPtr(E
) : true;
2651 if (T
== PT_Float
) {
2652 return DiscardResult
? this->emitDecfPop(getRoundingMode(E
), E
)
2653 : this->emitDecf(getRoundingMode(E
), E
);
2656 return DiscardResult
? this->emitDecPop(*T
, E
) : this->emitDec(*T
, E
);
2658 case UO_PreInc
: { // ++x
2659 if (!this->visit(SubExpr
))
2663 if (!this->emitLoadPtr(E
))
2665 if (!this->emitConstUint8(1, E
))
2667 if (!this->emitAddOffsetUint8(E
))
2669 return DiscardResult
? this->emitStorePopPtr(E
) : this->emitStorePtr(E
);
2672 // Post-inc and pre-inc are the same if the value is to be discarded.
2673 if (DiscardResult
) {
2675 return this->emitIncfPop(getRoundingMode(E
), E
);
2676 return this->emitIncPop(*T
, E
);
2679 if (T
== PT_Float
) {
2680 const auto &TargetSemantics
= Ctx
.getFloatSemantics(E
->getType());
2681 if (!this->emitLoadFloat(E
))
2683 if (!this->emitConstFloat(llvm::APFloat(TargetSemantics
, 1), E
))
2685 if (!this->emitAddf(getRoundingMode(E
), E
))
2687 return this->emitStoreFloat(E
);
2689 if (!this->emitLoad(*T
, E
))
2691 if (!this->emitConst(1, E
))
2693 if (!this->emitAdd(*T
, E
))
2695 return this->emitStore(*T
, E
);
2697 case UO_PreDec
: { // --x
2698 if (!this->visit(SubExpr
))
2702 if (!this->emitLoadPtr(E
))
2704 if (!this->emitConstUint8(1, E
))
2706 if (!this->emitSubOffsetUint8(E
))
2708 return DiscardResult
? this->emitStorePopPtr(E
) : this->emitStorePtr(E
);
2711 // Post-dec and pre-dec are the same if the value is to be discarded.
2712 if (DiscardResult
) {
2714 return this->emitDecfPop(getRoundingMode(E
), E
);
2715 return this->emitDecPop(*T
, E
);
2718 if (T
== PT_Float
) {
2719 const auto &TargetSemantics
= Ctx
.getFloatSemantics(E
->getType());
2720 if (!this->emitLoadFloat(E
))
2722 if (!this->emitConstFloat(llvm::APFloat(TargetSemantics
, 1), E
))
2724 if (!this->emitSubf(getRoundingMode(E
), E
))
2726 return this->emitStoreFloat(E
);
2728 if (!this->emitLoad(*T
, E
))
2730 if (!this->emitConst(1, E
))
2732 if (!this->emitSub(*T
, E
))
2734 return this->emitStore(*T
, E
);
2738 return this->discard(SubExpr
);
2740 if (!this->visitBool(SubExpr
))
2743 if (!this->emitInvBool(E
))
2746 if (PrimType ET
= classifyPrim(E
->getType()); ET
!= PT_Bool
)
2747 return this->emitCast(PT_Bool
, ET
, E
);
2749 case UO_Minus
: // -x
2750 if (!this->visit(SubExpr
))
2752 return DiscardResult
? this->emitPop(*T
, E
) : this->emitNeg(*T
, E
);
2754 if (!this->visit(SubExpr
)) // noop
2756 return DiscardResult
? this->emitPop(*T
, E
) : true;
2757 case UO_AddrOf
: // &x
2758 // We should already have a pointer when we get here.
2759 return this->delegate(SubExpr
);
2760 case UO_Deref
: // *x
2762 SubExpr
, DerefKind::Read
,
2764 llvm_unreachable("Dereferencing requires a pointer");
2767 [this, E
](PrimType T
) {
2768 return DiscardResult
? this->emitPop(T
, E
) : true;
2771 if (!this->visit(SubExpr
))
2773 return DiscardResult
? this->emitPop(*T
, E
) : this->emitComp(*T
, E
);
2774 case UO_Real
: // __real x
2776 return this->delegate(SubExpr
);
2777 return this->emitComplexReal(SubExpr
);
2778 case UO_Imag
: { // __imag x
2780 if (!this->discard(SubExpr
))
2782 return this->visitZeroInitializer(*T
, SubExpr
->getType(), SubExpr
);
2784 if (!this->visit(SubExpr
))
2786 if (!this->emitConstUint8(1, E
))
2788 if (!this->emitArrayElemPtrPopUint8(E
))
2791 // Since our _Complex implementation does not map to a primitive type,
2792 // we sometimes have to do the lvalue-to-rvalue conversion here manually.
2793 if (!SubExpr
->isLValue())
2794 return this->emitLoadPop(classifyPrim(E
->getType()), E
);
2798 return this->delegate(SubExpr
);
2800 assert(false && "Unhandled opcode");
2806 template <class Emitter
>
2807 bool ByteCodeExprGen
<Emitter
>::VisitDeclRefExpr(const DeclRefExpr
*E
) {
2811 const auto *D
= E
->getDecl();
2813 if (const auto *ECD
= dyn_cast
<EnumConstantDecl
>(D
)) {
2814 return this->emitConst(ECD
->getInitVal(), E
);
2815 } else if (const auto *BD
= dyn_cast
<BindingDecl
>(D
)) {
2816 return this->visit(BD
->getBinding());
2817 } else if (const auto *FuncDecl
= dyn_cast
<FunctionDecl
>(D
)) {
2818 const Function
*F
= getFunction(FuncDecl
);
2819 return F
&& this->emitGetFnPtr(F
, E
);
2822 // References are implemented via pointers, so when we see a DeclRefExpr
2823 // pointing to a reference, we need to get its value directly (i.e. the
2824 // pointer to the actual value) instead of a pointer to the pointer to the
2826 bool IsReference
= D
->getType()->isReferenceType();
2828 // Check for local/global variables and parameters.
2829 if (auto It
= Locals
.find(D
); It
!= Locals
.end()) {
2830 const unsigned Offset
= It
->second
.Offset
;
2833 return this->emitGetLocal(PT_Ptr
, Offset
, E
);
2834 return this->emitGetPtrLocal(Offset
, E
);
2835 } else if (auto GlobalIndex
= P
.getGlobal(D
)) {
2837 return this->emitGetGlobalPtr(*GlobalIndex
, E
);
2839 return this->emitGetPtrGlobal(*GlobalIndex
, E
);
2840 } else if (const auto *PVD
= dyn_cast
<ParmVarDecl
>(D
)) {
2841 if (auto It
= this->Params
.find(PVD
); It
!= this->Params
.end()) {
2842 if (IsReference
|| !It
->second
.IsPtr
)
2843 return this->emitGetParamPtr(It
->second
.Offset
, E
);
2845 return this->emitGetPtrParam(It
->second
.Offset
, E
);
2849 // Handle lambda captures.
2850 if (auto It
= this->LambdaCaptures
.find(D
);
2851 It
!= this->LambdaCaptures
.end()) {
2852 auto [Offset
, IsPtr
] = It
->second
;
2855 return this->emitGetThisFieldPtr(Offset
, E
);
2856 return this->emitGetPtrThisField(Offset
, E
);
2859 // Lazily visit global declarations we haven't seen yet.
2860 // This happens in C.
2861 if (!Ctx
.getLangOpts().CPlusPlus
) {
2862 if (const auto *VD
= dyn_cast
<VarDecl
>(D
);
2863 VD
&& VD
->hasGlobalStorage() && VD
->getAnyInitializer() &&
2864 VD
->getType().isConstQualified()) {
2865 if (!this->visitVarDecl(VD
))
2868 return this->VisitDeclRefExpr(E
);
2871 if (std::optional
<unsigned> I
= P
.getOrCreateDummy(D
))
2872 return this->emitGetPtrGlobal(*I
, E
);
2875 return this->emitInvalidDeclRef(E
, E
);
2878 template <class Emitter
>
2879 void ByteCodeExprGen
<Emitter
>::emitCleanup() {
2880 for (VariableScope
<Emitter
> *C
= VarScope
; C
; C
= C
->getParent())
2881 C
->emitDestruction();
2884 template <class Emitter
>
2886 ByteCodeExprGen
<Emitter
>::collectBaseOffset(const RecordType
*BaseType
,
2887 const RecordType
*DerivedType
) {
2888 const auto *FinalDecl
= cast
<CXXRecordDecl
>(BaseType
->getDecl());
2889 const RecordDecl
*CurDecl
= DerivedType
->getDecl();
2890 const Record
*CurRecord
= getRecord(CurDecl
);
2891 assert(CurDecl
&& FinalDecl
);
2893 unsigned OffsetSum
= 0;
2895 assert(CurRecord
->getNumBases() > 0);
2897 for (const Record::Base
&B
: CurRecord
->bases()) {
2898 const auto *BaseDecl
= cast
<CXXRecordDecl
>(B
.Decl
);
2900 if (BaseDecl
== FinalDecl
|| BaseDecl
->isDerivedFrom(FinalDecl
)) {
2901 OffsetSum
+= B
.Offset
;
2907 if (CurDecl
== FinalDecl
)
2911 assert(OffsetSum
> 0);
2915 /// Emit casts from a PrimType to another PrimType.
2916 template <class Emitter
>
2917 bool ByteCodeExprGen
<Emitter
>::emitPrimCast(PrimType FromT
, PrimType ToT
,
2918 QualType ToQT
, const Expr
*E
) {
2920 if (FromT
== PT_Float
) {
2921 // Floating to floating.
2922 if (ToT
== PT_Float
) {
2923 const llvm::fltSemantics
*ToSem
= &Ctx
.getFloatSemantics(ToQT
);
2924 return this->emitCastFP(ToSem
, getRoundingMode(E
), E
);
2927 // Float to integral.
2928 if (isIntegralType(ToT
) || ToT
== PT_Bool
)
2929 return this->emitCastFloatingIntegral(ToT
, E
);
2932 if (isIntegralType(FromT
) || FromT
== PT_Bool
) {
2933 // Integral to integral.
2934 if (isIntegralType(ToT
) || ToT
== PT_Bool
)
2935 return FromT
!= ToT
? this->emitCast(FromT
, ToT
, E
) : true;
2937 if (ToT
== PT_Float
) {
2938 // Integral to floating.
2939 const llvm::fltSemantics
*ToSem
= &Ctx
.getFloatSemantics(ToQT
);
2940 return this->emitCastIntegralFloating(FromT
, ToSem
, getRoundingMode(E
),
2948 /// Emits __real(SubExpr)
2949 template <class Emitter
>
2950 bool ByteCodeExprGen
<Emitter
>::emitComplexReal(const Expr
*SubExpr
) {
2951 assert(SubExpr
->getType()->isAnyComplexType());
2954 return this->discard(SubExpr
);
2956 if (!this->visit(SubExpr
))
2958 if (!this->emitConstUint8(0, SubExpr
))
2960 if (!this->emitArrayElemPtrPopUint8(SubExpr
))
2963 // Since our _Complex implementation does not map to a primitive type,
2964 // we sometimes have to do the lvalue-to-rvalue conversion here manually.
2965 if (!SubExpr
->isLValue())
2966 return this->emitLoadPop(*classifyComplexElementType(SubExpr
->getType()),
2971 /// When calling this, we have a pointer of the local-to-destroy
2973 /// Emit destruction of record types (or arrays of record types).
2974 template <class Emitter
>
2975 bool ByteCodeExprGen
<Emitter
>::emitRecordDestruction(const Descriptor
*Desc
) {
2977 assert(!Desc
->isPrimitive());
2978 assert(!Desc
->isPrimitiveArray());
2981 if (Desc
->isArray()) {
2982 const Descriptor
*ElemDesc
= Desc
->ElemDesc
;
2985 // Don't need to do anything for these.
2986 if (ElemDesc
->isPrimitiveArray())
2987 return this->emitPopPtr(SourceInfo
{});
2989 // If this is an array of record types, check if we need
2990 // to call the element destructors at all. If not, try
2991 // to save the work.
2992 if (const Record
*ElemRecord
= ElemDesc
->ElemRecord
) {
2993 if (const CXXDestructorDecl
*Dtor
= ElemRecord
->getDestructor();
2994 !Dtor
|| Dtor
->isTrivial())
2995 return this->emitPopPtr(SourceInfo
{});
2998 for (ssize_t I
= Desc
->getNumElems() - 1; I
>= 0; --I
) {
2999 if (!this->emitConstUint64(I
, SourceInfo
{}))
3001 if (!this->emitArrayElemPtrUint64(SourceInfo
{}))
3003 if (!this->emitRecordDestruction(ElemDesc
))
3006 return this->emitPopPtr(SourceInfo
{});
3009 const Record
*R
= Desc
->ElemRecord
;
3011 // First, destroy all fields.
3012 for (const Record::Field
&Field
: llvm::reverse(R
->fields())) {
3013 const Descriptor
*D
= Field
.Desc
;
3014 if (!D
->isPrimitive() && !D
->isPrimitiveArray()) {
3015 if (!this->emitDupPtr(SourceInfo
{}))
3017 if (!this->emitGetPtrField(Field
.Offset
, SourceInfo
{}))
3019 if (!this->emitRecordDestruction(D
))
3024 // FIXME: Unions need to be handled differently here. We don't want to
3025 // call the destructor of its members.
3027 // Now emit the destructor and recurse into base classes.
3028 if (const CXXDestructorDecl
*Dtor
= R
->getDestructor();
3029 Dtor
&& !Dtor
->isTrivial()) {
3030 if (const Function
*DtorFunc
= getFunction(Dtor
)) {
3031 assert(DtorFunc
->hasThisPointer());
3032 assert(DtorFunc
->getNumParams() == 1);
3033 if (!this->emitDupPtr(SourceInfo
{}))
3035 if (!this->emitCall(DtorFunc
, SourceInfo
{}))
3040 for (const Record::Base
&Base
: llvm::reverse(R
->bases())) {
3041 if (!this->emitGetPtrBase(Base
.Offset
, SourceInfo
{}))
3043 if (!this->emitRecordDestruction(Base
.Desc
))
3046 // FIXME: Virtual bases.
3048 // Remove the instance pointer.
3049 return this->emitPopPtr(SourceInfo
{});
3055 template class ByteCodeExprGen
<ByteCodeEmitter
>;
3056 template class ByteCodeExprGen
<EvalEmitter
>;
3058 } // namespace interp
3059 } // namespace clang