clang 20.0.0git
Compiler.cpp
Go to the documentation of this file.
1//===--- Compiler.cpp - Code generator for expressions ---*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
9#include "Compiler.h"
10#include "ByteCodeEmitter.h"
11#include "Context.h"
12#include "Floating.h"
13#include "Function.h"
14#include "InterpShared.h"
15#include "PrimType.h"
16#include "Program.h"
17#include "clang/AST/Attr.h"
18
19using namespace clang;
20using namespace clang::interp;
21
22using APSInt = llvm::APSInt;
23
24namespace clang {
25namespace interp {
26
27/// Scope used to handle temporaries in toplevel variable declarations.
28template <class Emitter> class DeclScope final : public LocalScope<Emitter> {
29public:
31 : LocalScope<Emitter>(Ctx, VD), Scope(Ctx->P, VD),
32 OldInitializingDecl(Ctx->InitializingDecl) {
33 Ctx->InitializingDecl = VD;
34 Ctx->InitStack.push_back(InitLink::Decl(VD));
35 }
36
37 void addExtended(const Scope::Local &Local) override {
38 return this->addLocal(Local);
39 }
40
42 this->Ctx->InitializingDecl = OldInitializingDecl;
43 this->Ctx->InitStack.pop_back();
44 }
45
46private:
48 const ValueDecl *OldInitializingDecl;
49};
50
51/// Scope used to handle initialization methods.
52template <class Emitter> class OptionScope final {
53public:
54 /// Root constructor, compiling or discarding primitives.
55 OptionScope(Compiler<Emitter> *Ctx, bool NewDiscardResult,
56 bool NewInitializing)
57 : Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult),
58 OldInitializing(Ctx->Initializing) {
59 Ctx->DiscardResult = NewDiscardResult;
60 Ctx->Initializing = NewInitializing;
61 }
62
64 Ctx->DiscardResult = OldDiscardResult;
65 Ctx->Initializing = OldInitializing;
66 }
67
68private:
69 /// Parent context.
71 /// Old discard flag to restore.
72 bool OldDiscardResult;
73 bool OldInitializing;
74};
75
76template <class Emitter>
77bool InitLink::emit(Compiler<Emitter> *Ctx, const Expr *E) const {
78 switch (Kind) {
79 case K_This:
80 return Ctx->emitThis(E);
81 case K_Field:
82 // We're assuming there's a base pointer on the stack already.
83 return Ctx->emitGetPtrFieldPop(Offset, E);
84 case K_Temp:
85 return Ctx->emitGetPtrLocal(Offset, E);
86 case K_Decl:
87 return Ctx->visitDeclRef(D, E);
88 case K_Elem:
89 if (!Ctx->emitConstUint32(Offset, E))
90 return false;
91 return Ctx->emitArrayElemPtrPopUint32(E);
92 default:
93 llvm_unreachable("Unhandled InitLink kind");
94 }
95 return true;
96}
97
98/// Scope managing label targets.
99template <class Emitter> class LabelScope {
100public:
101 virtual ~LabelScope() {}
102
103protected:
105 /// Compiler instance.
107};
108
109/// Sets the context for break/continue statements.
110template <class Emitter> class LoopScope final : public LabelScope<Emitter> {
111public:
114
115 LoopScope(Compiler<Emitter> *Ctx, LabelTy BreakLabel, LabelTy ContinueLabel)
116 : LabelScope<Emitter>(Ctx), OldBreakLabel(Ctx->BreakLabel),
117 OldContinueLabel(Ctx->ContinueLabel) {
118 this->Ctx->BreakLabel = BreakLabel;
119 this->Ctx->ContinueLabel = ContinueLabel;
120 }
121
123 this->Ctx->BreakLabel = OldBreakLabel;
124 this->Ctx->ContinueLabel = OldContinueLabel;
125 }
126
127private:
128 OptLabelTy OldBreakLabel;
129 OptLabelTy OldContinueLabel;
130};
131
132// Sets the context for a switch scope, mapping labels.
133template <class Emitter> class SwitchScope final : public LabelScope<Emitter> {
134public:
138
139 SwitchScope(Compiler<Emitter> *Ctx, CaseMap &&CaseLabels, LabelTy BreakLabel,
140 OptLabelTy DefaultLabel)
141 : LabelScope<Emitter>(Ctx), OldBreakLabel(Ctx->BreakLabel),
142 OldDefaultLabel(this->Ctx->DefaultLabel),
143 OldCaseLabels(std::move(this->Ctx->CaseLabels)) {
144 this->Ctx->BreakLabel = BreakLabel;
145 this->Ctx->DefaultLabel = DefaultLabel;
146 this->Ctx->CaseLabels = std::move(CaseLabels);
147 }
148
150 this->Ctx->BreakLabel = OldBreakLabel;
151 this->Ctx->DefaultLabel = OldDefaultLabel;
152 this->Ctx->CaseLabels = std::move(OldCaseLabels);
153 }
154
155private:
156 OptLabelTy OldBreakLabel;
157 OptLabelTy OldDefaultLabel;
158 CaseMap OldCaseLabels;
159};
160
161template <class Emitter> class StmtExprScope final {
162public:
163 StmtExprScope(Compiler<Emitter> *Ctx) : Ctx(Ctx), OldFlag(Ctx->InStmtExpr) {
164 Ctx->InStmtExpr = true;
165 }
166
167 ~StmtExprScope() { Ctx->InStmtExpr = OldFlag; }
168
169private:
171 bool OldFlag;
172};
173
174} // namespace interp
175} // namespace clang
176
177template <class Emitter>
179 const Expr *SubExpr = CE->getSubExpr();
180 switch (CE->getCastKind()) {
181
182 case CK_LValueToRValue: {
183 if (DiscardResult)
184 return this->discard(SubExpr);
185
186 std::optional<PrimType> SubExprT = classify(SubExpr->getType());
187 // Prepare storage for the result.
188 if (!Initializing && !SubExprT) {
189 std::optional<unsigned> LocalIndex = allocateLocal(SubExpr);
190 if (!LocalIndex)
191 return false;
192 if (!this->emitGetPtrLocal(*LocalIndex, CE))
193 return false;
194 }
195
196 if (!this->visit(SubExpr))
197 return false;
198
199 if (SubExprT)
200 return this->emitLoadPop(*SubExprT, CE);
201
202 // If the subexpr type is not primitive, we need to perform a copy here.
203 // This happens for example in C when dereferencing a pointer of struct
204 // type.
205 return this->emitMemcpy(CE);
206 }
207
208 case CK_DerivedToBaseMemberPointer: {
209 assert(classifyPrim(CE->getType()) == PT_MemberPtr);
210 assert(classifyPrim(SubExpr->getType()) == PT_MemberPtr);
211 const auto *FromMP = SubExpr->getType()->getAs<MemberPointerType>();
212 const auto *ToMP = CE->getType()->getAs<MemberPointerType>();
213
214 unsigned DerivedOffset = collectBaseOffset(QualType(ToMP->getClass(), 0),
215 QualType(FromMP->getClass(), 0));
216
217 if (!this->visit(SubExpr))
218 return false;
219
220 return this->emitGetMemberPtrBasePop(DerivedOffset, CE);
221 }
222
223 case CK_BaseToDerivedMemberPointer: {
224 assert(classifyPrim(CE) == PT_MemberPtr);
225 assert(classifyPrim(SubExpr) == PT_MemberPtr);
226 const auto *FromMP = SubExpr->getType()->getAs<MemberPointerType>();
227 const auto *ToMP = CE->getType()->getAs<MemberPointerType>();
228
229 unsigned DerivedOffset = collectBaseOffset(QualType(FromMP->getClass(), 0),
230 QualType(ToMP->getClass(), 0));
231
232 if (!this->visit(SubExpr))
233 return false;
234 return this->emitGetMemberPtrBasePop(-DerivedOffset, CE);
235 }
236
237 case CK_UncheckedDerivedToBase:
238 case CK_DerivedToBase: {
239 if (!this->visit(SubExpr))
240 return false;
241
242 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
243 if (const auto *PT = dyn_cast<PointerType>(Ty))
244 return PT->getPointeeType()->getAsCXXRecordDecl();
245 return Ty->getAsCXXRecordDecl();
246 };
247
248 // FIXME: We can express a series of non-virtual casts as a single
249 // GetPtrBasePop op.
250 QualType CurType = SubExpr->getType();
251 for (const CXXBaseSpecifier *B : CE->path()) {
252 if (B->isVirtual()) {
253 if (!this->emitGetPtrVirtBasePop(extractRecordDecl(B->getType()), CE))
254 return false;
255 CurType = B->getType();
256 } else {
257 unsigned DerivedOffset = collectBaseOffset(B->getType(), CurType);
258 if (!this->emitGetPtrBasePop(DerivedOffset, CE))
259 return false;
260 CurType = B->getType();
261 }
262 }
263
264 return true;
265 }
266
267 case CK_BaseToDerived: {
268 if (!this->visit(SubExpr))
269 return false;
270
271 unsigned DerivedOffset =
272 collectBaseOffset(SubExpr->getType(), CE->getType());
273
274 return this->emitGetPtrDerivedPop(DerivedOffset, CE);
275 }
276
277 case CK_FloatingCast: {
278 // HLSL uses CK_FloatingCast to cast between vectors.
279 if (!SubExpr->getType()->isFloatingType() ||
280 !CE->getType()->isFloatingType())
281 return false;
282 if (DiscardResult)
283 return this->discard(SubExpr);
284 if (!this->visit(SubExpr))
285 return false;
286 const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
287 return this->emitCastFP(TargetSemantics, getRoundingMode(CE), CE);
288 }
289
290 case CK_IntegralToFloating: {
291 if (DiscardResult)
292 return this->discard(SubExpr);
293 std::optional<PrimType> FromT = classify(SubExpr->getType());
294 if (!FromT)
295 return false;
296
297 if (!this->visit(SubExpr))
298 return false;
299
300 const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
301 llvm::RoundingMode RM = getRoundingMode(CE);
302 return this->emitCastIntegralFloating(*FromT, TargetSemantics, RM, CE);
303 }
304
305 case CK_FloatingToBoolean:
306 case CK_FloatingToIntegral: {
307 if (DiscardResult)
308 return this->discard(SubExpr);
309
310 std::optional<PrimType> ToT = classify(CE->getType());
311
312 if (!ToT)
313 return false;
314
315 if (!this->visit(SubExpr))
316 return false;
317
318 if (ToT == PT_IntAP)
319 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(CE->getType()),
320 CE);
321 if (ToT == PT_IntAPS)
322 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(CE->getType()),
323 CE);
324
325 return this->emitCastFloatingIntegral(*ToT, CE);
326 }
327
328 case CK_NullToPointer:
329 case CK_NullToMemberPointer: {
330 if (DiscardResult)
331 return true;
332
333 const Descriptor *Desc = nullptr;
334 const QualType PointeeType = CE->getType()->getPointeeType();
335 if (!PointeeType.isNull()) {
336 if (std::optional<PrimType> T = classify(PointeeType))
337 Desc = P.createDescriptor(SubExpr, *T);
338 else
339 Desc = P.createDescriptor(SubExpr, PointeeType.getTypePtr(),
340 std::nullopt, true, false,
341 /*IsMutable=*/false, nullptr);
342 }
343 return this->emitNull(classifyPrim(CE->getType()), Desc, CE);
344 }
345
346 case CK_PointerToIntegral: {
347 if (DiscardResult)
348 return this->discard(SubExpr);
349
350 if (!this->visit(SubExpr))
351 return false;
352
353 // If SubExpr doesn't result in a pointer, make it one.
354 if (PrimType FromT = classifyPrim(SubExpr->getType()); FromT != PT_Ptr) {
355 assert(isPtrType(FromT));
356 if (!this->emitDecayPtr(FromT, PT_Ptr, CE))
357 return false;
358 }
359
360 PrimType T = classifyPrim(CE->getType());
361 if (T == PT_IntAP)
362 return this->emitCastPointerIntegralAP(Ctx.getBitWidth(CE->getType()),
363 CE);
364 if (T == PT_IntAPS)
365 return this->emitCastPointerIntegralAPS(Ctx.getBitWidth(CE->getType()),
366 CE);
367 return this->emitCastPointerIntegral(T, CE);
368 }
369
370 case CK_ArrayToPointerDecay: {
371 if (!this->visit(SubExpr))
372 return false;
373 if (!this->emitArrayDecay(CE))
374 return false;
375 if (DiscardResult)
376 return this->emitPopPtr(CE);
377 return true;
378 }
379
380 case CK_IntegralToPointer: {
381 QualType IntType = SubExpr->getType();
382 assert(IntType->isIntegralOrEnumerationType());
383 if (!this->visit(SubExpr))
384 return false;
385 // FIXME: I think the discard is wrong since the int->ptr cast might cause a
386 // diagnostic.
387 PrimType T = classifyPrim(IntType);
388 if (DiscardResult)
389 return this->emitPop(T, CE);
390
391 QualType PtrType = CE->getType();
392 assert(PtrType->isPointerType());
393
394 const Descriptor *Desc;
395 if (std::optional<PrimType> T = classify(PtrType->getPointeeType()))
396 Desc = P.createDescriptor(SubExpr, *T);
397 else if (PtrType->getPointeeType()->isVoidType())
398 Desc = nullptr;
399 else
400 Desc = P.createDescriptor(CE, PtrType->getPointeeType().getTypePtr(),
401 Descriptor::InlineDescMD, true, false,
402 /*IsMutable=*/false, nullptr);
403
404 if (!this->emitGetIntPtr(T, Desc, CE))
405 return false;
406
407 PrimType DestPtrT = classifyPrim(PtrType);
408 if (DestPtrT == PT_Ptr)
409 return true;
410
411 // In case we're converting the integer to a non-Pointer.
412 return this->emitDecayPtr(PT_Ptr, DestPtrT, CE);
413 }
414
415 case CK_AtomicToNonAtomic:
416 case CK_ConstructorConversion:
417 case CK_FunctionToPointerDecay:
418 case CK_NonAtomicToAtomic:
419 case CK_NoOp:
420 case CK_UserDefinedConversion:
421 case CK_AddressSpaceConversion:
422 return this->delegate(SubExpr);
423
424 case CK_BitCast: {
425 // Reject bitcasts to atomic types.
426 if (CE->getType()->isAtomicType()) {
427 if (!this->discard(SubExpr))
428 return false;
429 return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, CE);
430 }
431
432 if (DiscardResult)
433 return this->discard(SubExpr);
434
435 QualType SubExprTy = SubExpr->getType();
436 std::optional<PrimType> FromT = classify(SubExprTy);
437 std::optional<PrimType> ToT = classify(CE->getType());
438 if (!FromT || !ToT)
439 return false;
440
441 assert(isPtrType(*FromT));
442 assert(isPtrType(*ToT));
443 if (FromT == ToT) {
444 if (CE->getType()->isVoidPointerType())
445 return this->delegate(SubExpr);
446
447 if (!this->visit(SubExpr))
448 return false;
449 if (FromT == PT_Ptr)
450 return this->emitPtrPtrCast(SubExprTy->isVoidPointerType(), CE);
451 return true;
452 }
453
454 if (!this->visit(SubExpr))
455 return false;
456 return this->emitDecayPtr(*FromT, *ToT, CE);
457 }
458
459 case CK_IntegralToBoolean:
460 case CK_BooleanToSignedIntegral:
461 case CK_IntegralCast: {
462 if (DiscardResult)
463 return this->discard(SubExpr);
464 std::optional<PrimType> FromT = classify(SubExpr->getType());
465 std::optional<PrimType> ToT = classify(CE->getType());
466
467 if (!FromT || !ToT)
468 return false;
469
470 if (!this->visit(SubExpr))
471 return false;
472
473 // Possibly diagnose casts to enum types if the target type does not
474 // have a fixed size.
475 if (Ctx.getLangOpts().CPlusPlus && CE->getType()->isEnumeralType()) {
476 if (const auto *ET = CE->getType().getCanonicalType()->getAs<EnumType>();
477 ET && !ET->getDecl()->isFixed()) {
478 if (!this->emitCheckEnumValue(*FromT, ET->getDecl(), CE))
479 return false;
480 }
481 }
482
483 auto maybeNegate = [&]() -> bool {
484 if (CE->getCastKind() == CK_BooleanToSignedIntegral)
485 return this->emitNeg(*ToT, CE);
486 return true;
487 };
488
489 if (ToT == PT_IntAP)
490 return this->emitCastAP(*FromT, Ctx.getBitWidth(CE->getType()), CE) &&
491 maybeNegate();
492 if (ToT == PT_IntAPS)
493 return this->emitCastAPS(*FromT, Ctx.getBitWidth(CE->getType()), CE) &&
494 maybeNegate();
495
496 if (FromT == ToT)
497 return true;
498 if (!this->emitCast(*FromT, *ToT, CE))
499 return false;
500
501 return maybeNegate();
502 }
503
504 case CK_PointerToBoolean:
505 case CK_MemberPointerToBoolean: {
506 PrimType PtrT = classifyPrim(SubExpr->getType());
507
508 // Just emit p != nullptr for this.
509 if (!this->visit(SubExpr))
510 return false;
511
512 if (!this->emitNull(PtrT, nullptr, CE))
513 return false;
514
515 return this->emitNE(PtrT, CE);
516 }
517
518 case CK_IntegralComplexToBoolean:
519 case CK_FloatingComplexToBoolean: {
520 if (DiscardResult)
521 return this->discard(SubExpr);
522 if (!this->visit(SubExpr))
523 return false;
524 return this->emitComplexBoolCast(SubExpr);
525 }
526
527 case CK_IntegralComplexToReal:
528 case CK_FloatingComplexToReal:
529 return this->emitComplexReal(SubExpr);
530
531 case CK_IntegralRealToComplex:
532 case CK_FloatingRealToComplex: {
533 // We're creating a complex value here, so we need to
534 // allocate storage for it.
535 if (!Initializing) {
536 std::optional<unsigned> LocalIndex = allocateLocal(CE);
537 if (!LocalIndex)
538 return false;
539 if (!this->emitGetPtrLocal(*LocalIndex, CE))
540 return false;
541 }
542
543 // Init the complex value to {SubExpr, 0}.
544 if (!this->visitArrayElemInit(0, SubExpr))
545 return false;
546 // Zero-init the second element.
547 PrimType T = classifyPrim(SubExpr->getType());
548 if (!this->visitZeroInitializer(T, SubExpr->getType(), SubExpr))
549 return false;
550 return this->emitInitElem(T, 1, SubExpr);
551 }
552
553 case CK_IntegralComplexCast:
554 case CK_FloatingComplexCast:
555 case CK_IntegralComplexToFloatingComplex:
556 case CK_FloatingComplexToIntegralComplex: {
557 assert(CE->getType()->isAnyComplexType());
558 assert(SubExpr->getType()->isAnyComplexType());
559 if (DiscardResult)
560 return this->discard(SubExpr);
561
562 if (!Initializing) {
563 std::optional<unsigned> LocalIndex = allocateLocal(CE);
564 if (!LocalIndex)
565 return false;
566 if (!this->emitGetPtrLocal(*LocalIndex, CE))
567 return false;
568 }
569
570 // Location for the SubExpr.
571 // Since SubExpr is of complex type, visiting it results in a pointer
572 // anyway, so we just create a temporary pointer variable.
573 unsigned SubExprOffset = allocateLocalPrimitive(
574 SubExpr, PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false);
575 if (!this->visit(SubExpr))
576 return false;
577 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, CE))
578 return false;
579
580 PrimType SourceElemT = classifyComplexElementType(SubExpr->getType());
581 QualType DestElemType =
582 CE->getType()->getAs<ComplexType>()->getElementType();
583 PrimType DestElemT = classifyPrim(DestElemType);
584 // Cast both elements individually.
585 for (unsigned I = 0; I != 2; ++I) {
586 if (!this->emitGetLocal(PT_Ptr, SubExprOffset, CE))
587 return false;
588 if (!this->emitArrayElemPop(SourceElemT, I, CE))
589 return false;
590
591 // Do the cast.
592 if (!this->emitPrimCast(SourceElemT, DestElemT, DestElemType, CE))
593 return false;
594
595 // Save the value.
596 if (!this->emitInitElem(DestElemT, I, CE))
597 return false;
598 }
599 return true;
600 }
601
602 case CK_VectorSplat: {
603 assert(!classify(CE->getType()));
604 assert(classify(SubExpr->getType()));
605 assert(CE->getType()->isVectorType());
606
607 if (DiscardResult)
608 return this->discard(SubExpr);
609
610 if (!Initializing) {
611 std::optional<unsigned> LocalIndex = allocateLocal(CE);
612 if (!LocalIndex)
613 return false;
614 if (!this->emitGetPtrLocal(*LocalIndex, CE))
615 return false;
616 }
617
618 const auto *VT = CE->getType()->getAs<VectorType>();
619 PrimType ElemT = classifyPrim(SubExpr->getType());
620 unsigned ElemOffset = allocateLocalPrimitive(
621 SubExpr, ElemT, /*IsConst=*/true, /*IsExtended=*/false);
622
623 // Prepare a local variable for the scalar value.
624 if (!this->visit(SubExpr))
625 return false;
626 if (classifyPrim(SubExpr) == PT_Ptr && !this->emitLoadPop(ElemT, CE))
627 return false;
628
629 if (!this->emitSetLocal(ElemT, ElemOffset, CE))
630 return false;
631
632 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
633 if (!this->emitGetLocal(ElemT, ElemOffset, CE))
634 return false;
635 if (!this->emitInitElem(ElemT, I, CE))
636 return false;
637 }
638
639 return true;
640 }
641
642 case CK_ToVoid:
643 return discard(SubExpr);
644
645 default:
646 return this->emitInvalid(CE);
647 }
648 llvm_unreachable("Unhandled clang::CastKind enum");
649}
650
651template <class Emitter>
653 if (DiscardResult)
654 return true;
655
656 return this->emitConst(LE->getValue(), LE);
657}
658
659template <class Emitter>
661 if (DiscardResult)
662 return true;
663
664 return this->emitConstFloat(E->getValue(), E);
665}
666
667template <class Emitter>
669 assert(E->getType()->isAnyComplexType());
670 if (DiscardResult)
671 return true;
672
673 if (!Initializing) {
674 std::optional<unsigned> LocalIndex = allocateLocal(E);
675 if (!LocalIndex)
676 return false;
677 if (!this->emitGetPtrLocal(*LocalIndex, E))
678 return false;
679 }
680
681 const Expr *SubExpr = E->getSubExpr();
682 PrimType SubExprT = classifyPrim(SubExpr->getType());
683
684 if (!this->visitZeroInitializer(SubExprT, SubExpr->getType(), SubExpr))
685 return false;
686 if (!this->emitInitElem(SubExprT, 0, SubExpr))
687 return false;
688 return this->visitArrayElemInit(1, SubExpr);
689}
690
691template <class Emitter>
693 return this->delegate(E->getSubExpr());
694}
695
696template <class Emitter>
698 // Need short-circuiting for these.
699 if (BO->isLogicalOp())
700 return this->VisitLogicalBinOp(BO);
701
702 const Expr *LHS = BO->getLHS();
703 const Expr *RHS = BO->getRHS();
704
705 // Handle comma operators. Just discard the LHS
706 // and delegate to RHS.
707 if (BO->isCommaOp()) {
708 if (!this->discard(LHS))
709 return false;
710 if (RHS->getType()->isVoidType())
711 return this->discard(RHS);
712
713 return this->delegate(RHS);
714 }
715
716 if (BO->getType()->isAnyComplexType())
717 return this->VisitComplexBinOp(BO);
718 if ((LHS->getType()->isAnyComplexType() ||
719 RHS->getType()->isAnyComplexType()) &&
720 BO->isComparisonOp())
721 return this->emitComplexComparison(LHS, RHS, BO);
722
723 if (BO->isPtrMemOp()) {
724 if (!this->visit(LHS))
725 return false;
726
727 if (!this->visit(RHS))
728 return false;
729
730 if (!this->emitToMemberPtr(BO))
731 return false;
732
733 if (classifyPrim(BO) == PT_MemberPtr)
734 return true;
735
736 if (!this->emitCastMemberPtrPtr(BO))
737 return false;
738 return DiscardResult ? this->emitPopPtr(BO) : true;
739 }
740
741 // Typecheck the args.
742 std::optional<PrimType> LT = classify(LHS);
743 std::optional<PrimType> RT = classify(RHS);
744 std::optional<PrimType> T = classify(BO->getType());
745
746 // Special case for C++'s three-way/spaceship operator <=>, which
747 // returns a std::{strong,weak,partial}_ordering (which is a class, so doesn't
748 // have a PrimType).
749 if (!T && BO->getOpcode() == BO_Cmp) {
750 if (DiscardResult)
751 return true;
752 const ComparisonCategoryInfo *CmpInfo =
753 Ctx.getASTContext().CompCategories.lookupInfoForType(BO->getType());
754 assert(CmpInfo);
755
756 // We need a temporary variable holding our return value.
757 if (!Initializing) {
758 std::optional<unsigned> ResultIndex = this->allocateLocal(BO);
759 if (!this->emitGetPtrLocal(*ResultIndex, BO))
760 return false;
761 }
762
763 if (!visit(LHS) || !visit(RHS))
764 return false;
765
766 return this->emitCMP3(*LT, CmpInfo, BO);
767 }
768
769 if (!LT || !RT || !T)
770 return false;
771
772 // Pointer arithmetic special case.
773 if (BO->getOpcode() == BO_Add || BO->getOpcode() == BO_Sub) {
774 if (isPtrType(*T) || (isPtrType(*LT) && isPtrType(*RT)))
775 return this->VisitPointerArithBinOp(BO);
776 }
777
778 // Assignmentes require us to evalute the RHS first.
779 if (BO->getOpcode() == BO_Assign) {
780 if (!visit(RHS) || !visit(LHS))
781 return false;
782 if (!this->emitFlip(*LT, *RT, BO))
783 return false;
784 } else {
785 if (!visit(LHS) || !visit(RHS))
786 return false;
787 }
788
789 // For languages such as C, cast the result of one
790 // of our comparision opcodes to T (which is usually int).
791 auto MaybeCastToBool = [this, T, BO](bool Result) {
792 if (!Result)
793 return false;
794 if (DiscardResult)
795 return this->emitPop(*T, BO);
796 if (T != PT_Bool)
797 return this->emitCast(PT_Bool, *T, BO);
798 return true;
799 };
800
801 auto Discard = [this, T, BO](bool Result) {
802 if (!Result)
803 return false;
804 return DiscardResult ? this->emitPop(*T, BO) : true;
805 };
806
807 switch (BO->getOpcode()) {
808 case BO_EQ:
809 return MaybeCastToBool(this->emitEQ(*LT, BO));
810 case BO_NE:
811 return MaybeCastToBool(this->emitNE(*LT, BO));
812 case BO_LT:
813 return MaybeCastToBool(this->emitLT(*LT, BO));
814 case BO_LE:
815 return MaybeCastToBool(this->emitLE(*LT, BO));
816 case BO_GT:
817 return MaybeCastToBool(this->emitGT(*LT, BO));
818 case BO_GE:
819 return MaybeCastToBool(this->emitGE(*LT, BO));
820 case BO_Sub:
821 if (BO->getType()->isFloatingType())
822 return Discard(this->emitSubf(getRoundingMode(BO), BO));
823 return Discard(this->emitSub(*T, BO));
824 case BO_Add:
825 if (BO->getType()->isFloatingType())
826 return Discard(this->emitAddf(getRoundingMode(BO), BO));
827 return Discard(this->emitAdd(*T, BO));
828 case BO_Mul:
829 if (BO->getType()->isFloatingType())
830 return Discard(this->emitMulf(getRoundingMode(BO), BO));
831 return Discard(this->emitMul(*T, BO));
832 case BO_Rem:
833 return Discard(this->emitRem(*T, BO));
834 case BO_Div:
835 if (BO->getType()->isFloatingType())
836 return Discard(this->emitDivf(getRoundingMode(BO), BO));
837 return Discard(this->emitDiv(*T, BO));
838 case BO_Assign:
839 if (DiscardResult)
840 return LHS->refersToBitField() ? this->emitStoreBitFieldPop(*T, BO)
841 : this->emitStorePop(*T, BO);
842 if (LHS->refersToBitField()) {
843 if (!this->emitStoreBitField(*T, BO))
844 return false;
845 } else {
846 if (!this->emitStore(*T, BO))
847 return false;
848 }
849 // Assignments aren't necessarily lvalues in C.
850 // Load from them in that case.
851 if (!BO->isLValue())
852 return this->emitLoadPop(*T, BO);
853 return true;
854 case BO_And:
855 return Discard(this->emitBitAnd(*T, BO));
856 case BO_Or:
857 return Discard(this->emitBitOr(*T, BO));
858 case BO_Shl:
859 return Discard(this->emitShl(*LT, *RT, BO));
860 case BO_Shr:
861 return Discard(this->emitShr(*LT, *RT, BO));
862 case BO_Xor:
863 return Discard(this->emitBitXor(*T, BO));
864 case BO_LOr:
865 case BO_LAnd:
866 llvm_unreachable("Already handled earlier");
867 default:
868 return false;
869 }
870
871 llvm_unreachable("Unhandled binary op");
872}
873
874/// Perform addition/subtraction of a pointer and an integer or
875/// subtraction of two pointers.
876template <class Emitter>
878 BinaryOperatorKind Op = E->getOpcode();
879 const Expr *LHS = E->getLHS();
880 const Expr *RHS = E->getRHS();
881
882 if ((Op != BO_Add && Op != BO_Sub) ||
883 (!LHS->getType()->isPointerType() && !RHS->getType()->isPointerType()))
884 return false;
885
886 std::optional<PrimType> LT = classify(LHS);
887 std::optional<PrimType> RT = classify(RHS);
888
889 if (!LT || !RT)
890 return false;
891
892 if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) {
893 if (Op != BO_Sub)
894 return false;
895
896 assert(E->getType()->isIntegerType());
897 if (!visit(RHS) || !visit(LHS))
898 return false;
899
900 return this->emitSubPtr(classifyPrim(E->getType()), E);
901 }
902
903 PrimType OffsetType;
904 if (LHS->getType()->isIntegerType()) {
905 if (!visit(RHS) || !visit(LHS))
906 return false;
907 OffsetType = *LT;
908 } else if (RHS->getType()->isIntegerType()) {
909 if (!visit(LHS) || !visit(RHS))
910 return false;
911 OffsetType = *RT;
912 } else {
913 return false;
914 }
915
916 if (Op == BO_Add)
917 return this->emitAddOffset(OffsetType, E);
918 else if (Op == BO_Sub)
919 return this->emitSubOffset(OffsetType, E);
920
921 return false;
922}
923
924template <class Emitter>
926 assert(E->isLogicalOp());
927 BinaryOperatorKind Op = E->getOpcode();
928 const Expr *LHS = E->getLHS();
929 const Expr *RHS = E->getRHS();
930 std::optional<PrimType> T = classify(E->getType());
931
932 if (Op == BO_LOr) {
933 // Logical OR. Visit LHS and only evaluate RHS if LHS was FALSE.
934 LabelTy LabelTrue = this->getLabel();
935 LabelTy LabelEnd = this->getLabel();
936
937 if (!this->visitBool(LHS))
938 return false;
939 if (!this->jumpTrue(LabelTrue))
940 return false;
941
942 if (!this->visitBool(RHS))
943 return false;
944 if (!this->jump(LabelEnd))
945 return false;
946
947 this->emitLabel(LabelTrue);
948 this->emitConstBool(true, E);
949 this->fallthrough(LabelEnd);
950 this->emitLabel(LabelEnd);
951
952 } else {
953 assert(Op == BO_LAnd);
954 // Logical AND.
955 // Visit LHS. Only visit RHS if LHS was TRUE.
956 LabelTy LabelFalse = this->getLabel();
957 LabelTy LabelEnd = this->getLabel();
958
959 if (!this->visitBool(LHS))
960 return false;
961 if (!this->jumpFalse(LabelFalse))
962 return false;
963
964 if (!this->visitBool(RHS))
965 return false;
966 if (!this->jump(LabelEnd))
967 return false;
968
969 this->emitLabel(LabelFalse);
970 this->emitConstBool(false, E);
971 this->fallthrough(LabelEnd);
972 this->emitLabel(LabelEnd);
973 }
974
975 if (DiscardResult)
976 return this->emitPopBool(E);
977
978 // For C, cast back to integer type.
979 assert(T);
980 if (T != PT_Bool)
981 return this->emitCast(PT_Bool, *T, E);
982 return true;
983}
984
985template <class Emitter>
987 // Prepare storage for result.
988 if (!Initializing) {
989 std::optional<unsigned> LocalIndex = allocateLocal(E);
990 if (!LocalIndex)
991 return false;
992 if (!this->emitGetPtrLocal(*LocalIndex, E))
993 return false;
994 }
995
996 // Both LHS and RHS might _not_ be of complex type, but one of them
997 // needs to be.
998 const Expr *LHS = E->getLHS();
999 const Expr *RHS = E->getRHS();
1000
1001 PrimType ResultElemT = this->classifyComplexElementType(E->getType());
1002 unsigned ResultOffset = ~0u;
1003 if (!DiscardResult)
1004 ResultOffset = this->allocateLocalPrimitive(E, PT_Ptr, true, false);
1005
1006 // Save result pointer in ResultOffset
1007 if (!this->DiscardResult) {
1008 if (!this->emitDupPtr(E))
1009 return false;
1010 if (!this->emitSetLocal(PT_Ptr, ResultOffset, E))
1011 return false;
1012 }
1013 QualType LHSType = LHS->getType();
1014 if (const auto *AT = LHSType->getAs<AtomicType>())
1015 LHSType = AT->getValueType();
1016 QualType RHSType = RHS->getType();
1017 if (const auto *AT = RHSType->getAs<AtomicType>())
1018 RHSType = AT->getValueType();
1019
1020 bool LHSIsComplex = LHSType->isAnyComplexType();
1021 unsigned LHSOffset;
1022 bool RHSIsComplex = RHSType->isAnyComplexType();
1023
1024 // For ComplexComplex Mul, we have special ops to make their implementation
1025 // easier.
1026 BinaryOperatorKind Op = E->getOpcode();
1027 if (Op == BO_Mul && LHSIsComplex && RHSIsComplex) {
1028 assert(classifyPrim(LHSType->getAs<ComplexType>()->getElementType()) ==
1029 classifyPrim(RHSType->getAs<ComplexType>()->getElementType()));
1030 PrimType ElemT =
1031 classifyPrim(LHSType->getAs<ComplexType>()->getElementType());
1032 if (!this->visit(LHS))
1033 return false;
1034 if (!this->visit(RHS))
1035 return false;
1036 return this->emitMulc(ElemT, E);
1037 }
1038
1039 if (Op == BO_Div && RHSIsComplex) {
1040 QualType ElemQT = RHSType->getAs<ComplexType>()->getElementType();
1041 PrimType ElemT = classifyPrim(ElemQT);
1042 // If the LHS is not complex, we still need to do the full complex
1043 // division, so just stub create a complex value and stub it out with
1044 // the LHS and a zero.
1045
1046 if (!LHSIsComplex) {
1047 // This is using the RHS type for the fake-complex LHS.
1048 if (auto LHSO = allocateLocal(RHS))
1049 LHSOffset = *LHSO;
1050 else
1051 return false;
1052
1053 if (!this->emitGetPtrLocal(LHSOffset, E))
1054 return false;
1055
1056 if (!this->visit(LHS))
1057 return false;
1058 // real is LHS
1059 if (!this->emitInitElem(ElemT, 0, E))
1060 return false;
1061 // imag is zero
1062 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1063 return false;
1064 if (!this->emitInitElem(ElemT, 1, E))
1065 return false;
1066 } else {
1067 if (!this->visit(LHS))
1068 return false;
1069 }
1070
1071 if (!this->visit(RHS))
1072 return false;
1073 return this->emitDivc(ElemT, E);
1074 }
1075
1076 // Evaluate LHS and save value to LHSOffset.
1077 if (LHSType->isAnyComplexType()) {
1078 LHSOffset = this->allocateLocalPrimitive(LHS, PT_Ptr, true, false);
1079 if (!this->visit(LHS))
1080 return false;
1081 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
1082 return false;
1083 } else {
1084 PrimType LHST = classifyPrim(LHSType);
1085 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, true, false);
1086 if (!this->visit(LHS))
1087 return false;
1088 if (!this->emitSetLocal(LHST, LHSOffset, E))
1089 return false;
1090 }
1091
1092 // Same with RHS.
1093 unsigned RHSOffset;
1094 if (RHSType->isAnyComplexType()) {
1095 RHSOffset = this->allocateLocalPrimitive(RHS, PT_Ptr, true, false);
1096 if (!this->visit(RHS))
1097 return false;
1098 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
1099 return false;
1100 } else {
1101 PrimType RHST = classifyPrim(RHSType);
1102 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, true, false);
1103 if (!this->visit(RHS))
1104 return false;
1105 if (!this->emitSetLocal(RHST, RHSOffset, E))
1106 return false;
1107 }
1108
1109 // For both LHS and RHS, either load the value from the complex pointer, or
1110 // directly from the local variable. For index 1 (i.e. the imaginary part),
1111 // just load 0 and do the operation anyway.
1112 auto loadComplexValue = [this](bool IsComplex, bool LoadZero,
1113 unsigned ElemIndex, unsigned Offset,
1114 const Expr *E) -> bool {
1115 if (IsComplex) {
1116 if (!this->emitGetLocal(PT_Ptr, Offset, E))
1117 return false;
1118 return this->emitArrayElemPop(classifyComplexElementType(E->getType()),
1119 ElemIndex, E);
1120 }
1121 if (ElemIndex == 0 || !LoadZero)
1122 return this->emitGetLocal(classifyPrim(E->getType()), Offset, E);
1123 return this->visitZeroInitializer(classifyPrim(E->getType()), E->getType(),
1124 E);
1125 };
1126
1127 // Now we can get pointers to the LHS and RHS from the offsets above.
1128 for (unsigned ElemIndex = 0; ElemIndex != 2; ++ElemIndex) {
1129 // Result pointer for the store later.
1130 if (!this->DiscardResult) {
1131 if (!this->emitGetLocal(PT_Ptr, ResultOffset, E))
1132 return false;
1133 }
1134
1135 // The actual operation.
1136 switch (Op) {
1137 case BO_Add:
1138 if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1139 return false;
1140
1141 if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1142 return false;
1143 if (ResultElemT == PT_Float) {
1144 if (!this->emitAddf(getRoundingMode(E), E))
1145 return false;
1146 } else {
1147 if (!this->emitAdd(ResultElemT, E))
1148 return false;
1149 }
1150 break;
1151 case BO_Sub:
1152 if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1153 return false;
1154
1155 if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1156 return false;
1157 if (ResultElemT == PT_Float) {
1158 if (!this->emitSubf(getRoundingMode(E), E))
1159 return false;
1160 } else {
1161 if (!this->emitSub(ResultElemT, E))
1162 return false;
1163 }
1164 break;
1165 case BO_Mul:
1166 if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1167 return false;
1168
1169 if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1170 return false;
1171
1172 if (ResultElemT == PT_Float) {
1173 if (!this->emitMulf(getRoundingMode(E), E))
1174 return false;
1175 } else {
1176 if (!this->emitMul(ResultElemT, E))
1177 return false;
1178 }
1179 break;
1180 case BO_Div:
1181 assert(!RHSIsComplex);
1182 if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1183 return false;
1184
1185 if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1186 return false;
1187
1188 if (ResultElemT == PT_Float) {
1189 if (!this->emitDivf(getRoundingMode(E), E))
1190 return false;
1191 } else {
1192 if (!this->emitDiv(ResultElemT, E))
1193 return false;
1194 }
1195 break;
1196
1197 default:
1198 return false;
1199 }
1200
1201 if (!this->DiscardResult) {
1202 // Initialize array element with the value we just computed.
1203 if (!this->emitInitElemPop(ResultElemT, ElemIndex, E))
1204 return false;
1205 } else {
1206 if (!this->emitPop(ResultElemT, E))
1207 return false;
1208 }
1209 }
1210 return true;
1211}
1212
1213template <class Emitter>
1215 const ImplicitValueInitExpr *E) {
1216 QualType QT = E->getType();
1217
1218 if (std::optional<PrimType> T = classify(QT))
1219 return this->visitZeroInitializer(*T, QT, E);
1220
1221 if (QT->isRecordType()) {
1222 const RecordDecl *RD = QT->getAsRecordDecl();
1223 assert(RD);
1224 if (RD->isInvalidDecl())
1225 return false;
1226 if (RD->isUnion()) {
1227 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
1228 // object's first non-static named data member is zero-initialized
1229 // FIXME
1230 return false;
1231 }
1232
1233 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1234 CXXRD && CXXRD->getNumVBases() > 0) {
1235 // TODO: Diagnose.
1236 return false;
1237 }
1238
1239 const Record *R = getRecord(QT);
1240 if (!R)
1241 return false;
1242
1243 assert(Initializing);
1244 return this->visitZeroRecordInitializer(R, E);
1245 }
1246
1247 if (QT->isIncompleteArrayType())
1248 return true;
1249
1250 if (QT->isArrayType()) {
1251 const ArrayType *AT = QT->getAsArrayTypeUnsafe();
1252 assert(AT);
1253 const auto *CAT = cast<ConstantArrayType>(AT);
1254 size_t NumElems = CAT->getZExtSize();
1255 PrimType ElemT = classifyPrim(CAT->getElementType());
1256
1257 for (size_t I = 0; I != NumElems; ++I) {
1258 if (!this->visitZeroInitializer(ElemT, CAT->getElementType(), E))
1259 return false;
1260 if (!this->emitInitElem(ElemT, I, E))
1261 return false;
1262 }
1263
1264 return true;
1265 }
1266
1267 if (const auto *ComplexTy = E->getType()->getAs<ComplexType>()) {
1268 assert(Initializing);
1269 QualType ElemQT = ComplexTy->getElementType();
1270 PrimType ElemT = classifyPrim(ElemQT);
1271 for (unsigned I = 0; I < 2; ++I) {
1272 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1273 return false;
1274 if (!this->emitInitElem(ElemT, I, E))
1275 return false;
1276 }
1277 return true;
1278 }
1279
1280 if (const auto *VecT = E->getType()->getAs<VectorType>()) {
1281 unsigned NumVecElements = VecT->getNumElements();
1282 QualType ElemQT = VecT->getElementType();
1283 PrimType ElemT = classifyPrim(ElemQT);
1284
1285 for (unsigned I = 0; I < NumVecElements; ++I) {
1286 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1287 return false;
1288 if (!this->emitInitElem(ElemT, I, E))
1289 return false;
1290 }
1291 return true;
1292 }
1293
1294 return false;
1295}
1296
1297template <class Emitter>
1299 const Expr *LHS = E->getLHS();
1300 const Expr *RHS = E->getRHS();
1301 const Expr *Index = E->getIdx();
1302
1303 if (DiscardResult)
1304 return this->discard(LHS) && this->discard(RHS);
1305
1306 // C++17's rules require us to evaluate the LHS first, regardless of which
1307 // side is the base.
1308 bool Success = true;
1309 for (const Expr *SubExpr : {LHS, RHS}) {
1310 if (!this->visit(SubExpr))
1311 Success = false;
1312 }
1313
1314 if (!Success)
1315 return false;
1316
1317 PrimType IndexT = classifyPrim(Index->getType());
1318 // If the index is first, we need to change that.
1319 if (LHS == Index) {
1320 if (!this->emitFlip(PT_Ptr, IndexT, E))
1321 return false;
1322 }
1323
1324 return this->emitArrayElemPtrPop(IndexT, E);
1325}
1326
1327template <class Emitter>
1329 const Expr *ArrayFiller, const Expr *E) {
1330
1331 QualType QT = E->getType();
1332
1333 if (const auto *AT = QT->getAs<AtomicType>())
1334 QT = AT->getValueType();
1335
1336 if (QT->isVoidType())
1337 return this->emitInvalid(E);
1338
1339 // Handle discarding first.
1340 if (DiscardResult) {
1341 for (const Expr *Init : Inits) {
1342 if (!this->discard(Init))
1343 return false;
1344 }
1345 return true;
1346 }
1347
1348 // Primitive values.
1349 if (std::optional<PrimType> T = classify(QT)) {
1350 assert(!DiscardResult);
1351 if (Inits.size() == 0)
1352 return this->visitZeroInitializer(*T, QT, E);
1353 assert(Inits.size() == 1);
1354 return this->delegate(Inits[0]);
1355 }
1356
1357 if (QT->isRecordType()) {
1358 const Record *R = getRecord(QT);
1359
1360 if (Inits.size() == 1 && E->getType() == Inits[0]->getType())
1361 return this->delegate(Inits[0]);
1362
1363 auto initPrimitiveField = [=](const Record::Field *FieldToInit,
1364 const Expr *Init, PrimType T) -> bool {
1365 InitStackScope<Emitter> ISS(this, isa<CXXDefaultInitExpr>(Init));
1366 if (!this->visit(Init))
1367 return false;
1368
1369 if (FieldToInit->isBitField())
1370 return this->emitInitBitField(T, FieldToInit, E);
1371 return this->emitInitField(T, FieldToInit->Offset, E);
1372 };
1373
1374 auto initCompositeField = [=](const Record::Field *FieldToInit,
1375 const Expr *Init) -> bool {
1376 InitStackScope<Emitter> ISS(this, isa<CXXDefaultInitExpr>(Init));
1377 InitLinkScope<Emitter> ILS(this, InitLink::Field(FieldToInit->Offset));
1378 // Non-primitive case. Get a pointer to the field-to-initialize
1379 // on the stack and recurse into visitInitializer().
1380 if (!this->emitGetPtrField(FieldToInit->Offset, Init))
1381 return false;
1382 if (!this->visitInitializer(Init))
1383 return false;
1384 return this->emitPopPtr(E);
1385 };
1386
1387 if (R->isUnion()) {
1388 if (Inits.size() == 0) {
1389 if (!this->visitZeroRecordInitializer(R, E))
1390 return false;
1391 } else {
1392 const Expr *Init = Inits[0];
1393 const FieldDecl *FToInit = nullptr;
1394 if (const auto *ILE = dyn_cast<InitListExpr>(E))
1395 FToInit = ILE->getInitializedFieldInUnion();
1396 else
1397 FToInit = cast<CXXParenListInitExpr>(E)->getInitializedFieldInUnion();
1398
1399 const Record::Field *FieldToInit = R->getField(FToInit);
1400 if (std::optional<PrimType> T = classify(Init)) {
1401 if (!initPrimitiveField(FieldToInit, Init, *T))
1402 return false;
1403 } else {
1404 if (!initCompositeField(FieldToInit, Init))
1405 return false;
1406 }
1407 }
1408 return this->emitFinishInit(E);
1409 }
1410
1411 assert(!R->isUnion());
1412 unsigned InitIndex = 0;
1413 for (const Expr *Init : Inits) {
1414 // Skip unnamed bitfields.
1415 while (InitIndex < R->getNumFields() &&
1416 R->getField(InitIndex)->Decl->isUnnamedBitField())
1417 ++InitIndex;
1418
1419 if (std::optional<PrimType> T = classify(Init)) {
1420 const Record::Field *FieldToInit = R->getField(InitIndex);
1421 if (!initPrimitiveField(FieldToInit, Init, *T))
1422 return false;
1423 ++InitIndex;
1424 } else {
1425 // Initializer for a direct base class.
1426 if (const Record::Base *B = R->getBase(Init->getType())) {
1427 if (!this->emitGetPtrBase(B->Offset, Init))
1428 return false;
1429
1430 if (!this->visitInitializer(Init))
1431 return false;
1432
1433 if (!this->emitFinishInitPop(E))
1434 return false;
1435 // Base initializers don't increase InitIndex, since they don't count
1436 // into the Record's fields.
1437 } else {
1438 const Record::Field *FieldToInit = R->getField(InitIndex);
1439 if (!initCompositeField(FieldToInit, Init))
1440 return false;
1441 ++InitIndex;
1442 }
1443 }
1444 }
1445 return this->emitFinishInit(E);
1446 }
1447
1448 if (QT->isArrayType()) {
1449 if (Inits.size() == 1 && QT == Inits[0]->getType())
1450 return this->delegate(Inits[0]);
1451
1452 unsigned ElementIndex = 0;
1453 for (const Expr *Init : Inits) {
1454 if (const auto *EmbedS =
1455 dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
1456 PrimType TargetT = classifyPrim(Init->getType());
1457
1458 auto Eval = [&](const Expr *Init, unsigned ElemIndex) {
1459 PrimType InitT = classifyPrim(Init->getType());
1460 if (!this->visit(Init))
1461 return false;
1462 if (InitT != TargetT) {
1463 if (!this->emitCast(InitT, TargetT, E))
1464 return false;
1465 }
1466 return this->emitInitElem(TargetT, ElemIndex, Init);
1467 };
1468 if (!EmbedS->doForEachDataElement(Eval, ElementIndex))
1469 return false;
1470 } else {
1471 if (!this->visitArrayElemInit(ElementIndex, Init))
1472 return false;
1473 ++ElementIndex;
1474 }
1475 }
1476
1477 // Expand the filler expression.
1478 // FIXME: This should go away.
1479 if (ArrayFiller) {
1480 const ConstantArrayType *CAT =
1481 Ctx.getASTContext().getAsConstantArrayType(QT);
1482 uint64_t NumElems = CAT->getZExtSize();
1483
1484 for (; ElementIndex != NumElems; ++ElementIndex) {
1485 if (!this->visitArrayElemInit(ElementIndex, ArrayFiller))
1486 return false;
1487 }
1488 }
1489
1490 return this->emitFinishInit(E);
1491 }
1492
1493 if (const auto *ComplexTy = QT->getAs<ComplexType>()) {
1494 unsigned NumInits = Inits.size();
1495
1496 if (NumInits == 1)
1497 return this->delegate(Inits[0]);
1498
1499 QualType ElemQT = ComplexTy->getElementType();
1500 PrimType ElemT = classifyPrim(ElemQT);
1501 if (NumInits == 0) {
1502 // Zero-initialize both elements.
1503 for (unsigned I = 0; I < 2; ++I) {
1504 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1505 return false;
1506 if (!this->emitInitElem(ElemT, I, E))
1507 return false;
1508 }
1509 } else if (NumInits == 2) {
1510 unsigned InitIndex = 0;
1511 for (const Expr *Init : Inits) {
1512 if (!this->visit(Init))
1513 return false;
1514
1515 if (!this->emitInitElem(ElemT, InitIndex, E))
1516 return false;
1517 ++InitIndex;
1518 }
1519 }
1520 return true;
1521 }
1522
1523 if (const auto *VecT = QT->getAs<VectorType>()) {
1524 unsigned NumVecElements = VecT->getNumElements();
1525 assert(NumVecElements >= Inits.size());
1526
1527 QualType ElemQT = VecT->getElementType();
1528 PrimType ElemT = classifyPrim(ElemQT);
1529
1530 // All initializer elements.
1531 unsigned InitIndex = 0;
1532 for (const Expr *Init : Inits) {
1533 if (!this->visit(Init))
1534 return false;
1535
1536 // If the initializer is of vector type itself, we have to deconstruct
1537 // that and initialize all the target fields from the initializer fields.
1538 if (const auto *InitVecT = Init->getType()->getAs<VectorType>()) {
1539 if (!this->emitCopyArray(ElemT, 0, InitIndex,
1540 InitVecT->getNumElements(), E))
1541 return false;
1542 InitIndex += InitVecT->getNumElements();
1543 } else {
1544 if (!this->emitInitElem(ElemT, InitIndex, E))
1545 return false;
1546 ++InitIndex;
1547 }
1548 }
1549
1550 assert(InitIndex <= NumVecElements);
1551
1552 // Fill the rest with zeroes.
1553 for (; InitIndex != NumVecElements; ++InitIndex) {
1554 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1555 return false;
1556 if (!this->emitInitElem(ElemT, InitIndex, E))
1557 return false;
1558 }
1559 return true;
1560 }
1561
1562 return false;
1563}
1564
1565/// Pointer to the array(not the element!) must be on the stack when calling
1566/// this.
1567template <class Emitter>
1569 const Expr *Init) {
1570 if (std::optional<PrimType> T = classify(Init->getType())) {
1571 // Visit the primitive element like normal.
1572 if (!this->visit(Init))
1573 return false;
1574 return this->emitInitElem(*T, ElemIndex, Init);
1575 }
1576
1577 InitLinkScope<Emitter> ILS(this, InitLink::Elem(ElemIndex));
1578 // Advance the pointer currently on the stack to the given
1579 // dimension.
1580 if (!this->emitConstUint32(ElemIndex, Init))
1581 return false;
1582 if (!this->emitArrayElemPtrUint32(Init))
1583 return false;
1584 if (!this->visitInitializer(Init))
1585 return false;
1586 return this->emitFinishInitPop(Init);
1587}
1588
1589template <class Emitter>
1591 return this->visitInitList(E->inits(), E->getArrayFiller(), E);
1592}
1593
1594template <class Emitter>
1596 const CXXParenListInitExpr *E) {
1597 return this->visitInitList(E->getInitExprs(), E->getArrayFiller(), E);
1598}
1599
1600template <class Emitter>
1603 return this->delegate(E->getReplacement());
1604}
1605
1606template <class Emitter>
1608 std::optional<PrimType> T = classify(E->getType());
1609 if (T && E->hasAPValueResult()) {
1610 // Try to emit the APValue directly, without visiting the subexpr.
1611 // This will only fail if we can't emit the APValue, so won't emit any
1612 // diagnostics or any double values.
1613 if (DiscardResult)
1614 return true;
1615
1616 if (this->visitAPValue(E->getAPValueResult(), *T, E))
1617 return true;
1618 }
1619 return this->delegate(E->getSubExpr());
1620}
1621
1622template <class Emitter>
1624 auto It = E->begin();
1625 return this->visit(*It);
1626}
1627
1629 UnaryExprOrTypeTrait Kind) {
1630 bool AlignOfReturnsPreferred =
1631 ASTCtx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
1632
1633 // C++ [expr.alignof]p3:
1634 // When alignof is applied to a reference type, the result is the
1635 // alignment of the referenced type.
1636 if (const auto *Ref = T->getAs<ReferenceType>())
1637 T = Ref->getPointeeType();
1638
1639 if (T.getQualifiers().hasUnaligned())
1640 return CharUnits::One();
1641
1642 // __alignof is defined to return the preferred alignment.
1643 // Before 8, clang returned the preferred alignment for alignof and
1644 // _Alignof as well.
1645 if (Kind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
1646 return ASTCtx.toCharUnitsFromBits(ASTCtx.getPreferredTypeAlign(T));
1647
1648 return ASTCtx.getTypeAlignInChars(T);
1649}
1650
1651template <class Emitter>
1653 const UnaryExprOrTypeTraitExpr *E) {
1654 UnaryExprOrTypeTrait Kind = E->getKind();
1655 const ASTContext &ASTCtx = Ctx.getASTContext();
1656
1657 if (Kind == UETT_SizeOf || Kind == UETT_DataSizeOf) {
1658 QualType ArgType = E->getTypeOfArgument();
1659
1660 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1661 // the result is the size of the referenced type."
1662 if (const auto *Ref = ArgType->getAs<ReferenceType>())
1663 ArgType = Ref->getPointeeType();
1664
1665 CharUnits Size;
1666 if (ArgType->isVoidType() || ArgType->isFunctionType())
1667 Size = CharUnits::One();
1668 else {
1669 if (ArgType->isDependentType() || !ArgType->isConstantSizeType())
1670 return false;
1671
1672 if (Kind == UETT_SizeOf)
1673 Size = ASTCtx.getTypeSizeInChars(ArgType);
1674 else
1675 Size = ASTCtx.getTypeInfoDataSizeInChars(ArgType).Width;
1676 }
1677
1678 if (DiscardResult)
1679 return true;
1680
1681 return this->emitConst(Size.getQuantity(), E);
1682 }
1683
1684 if (Kind == UETT_AlignOf || Kind == UETT_PreferredAlignOf) {
1685 CharUnits Size;
1686
1687 if (E->isArgumentType()) {
1688 QualType ArgType = E->getTypeOfArgument();
1689
1690 Size = AlignOfType(ArgType, ASTCtx, Kind);
1691 } else {
1692 // Argument is an expression, not a type.
1693 const Expr *Arg = E->getArgumentExpr()->IgnoreParens();
1694
1695 // The kinds of expressions that we have special-case logic here for
1696 // should be kept up to date with the special checks for those
1697 // expressions in Sema.
1698
1699 // alignof decl is always accepted, even if it doesn't make sense: we
1700 // default to 1 in those cases.
1701 if (const auto *DRE = dyn_cast<DeclRefExpr>(Arg))
1702 Size = ASTCtx.getDeclAlign(DRE->getDecl(),
1703 /*RefAsPointee*/ true);
1704 else if (const auto *ME = dyn_cast<MemberExpr>(Arg))
1705 Size = ASTCtx.getDeclAlign(ME->getMemberDecl(),
1706 /*RefAsPointee*/ true);
1707 else
1708 Size = AlignOfType(Arg->getType(), ASTCtx, Kind);
1709 }
1710
1711 if (DiscardResult)
1712 return true;
1713
1714 return this->emitConst(Size.getQuantity(), E);
1715 }
1716
1717 if (Kind == UETT_VectorElements) {
1718 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>())
1719 return this->emitConst(VT->getNumElements(), E);
1720 assert(E->getTypeOfArgument()->isSizelessVectorType());
1721 return this->emitSizelessVectorElementSize(E);
1722 }
1723
1724 if (Kind == UETT_VecStep) {
1725 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>()) {
1726 unsigned N = VT->getNumElements();
1727
1728 // The vec_step built-in functions that take a 3-component
1729 // vector return 4. (OpenCL 1.1 spec 6.11.12)
1730 if (N == 3)
1731 N = 4;
1732
1733 return this->emitConst(N, E);
1734 }
1735 return this->emitConst(1, E);
1736 }
1737
1738 return false;
1739}
1740
1741template <class Emitter>
1743 // 'Base.Member'
1744 const Expr *Base = E->getBase();
1745 const ValueDecl *Member = E->getMemberDecl();
1746
1747 if (DiscardResult)
1748 return this->discard(Base);
1749
1750 // MemberExprs are almost always lvalues, in which case we don't need to
1751 // do the load. But sometimes they aren't.
1752 const auto maybeLoadValue = [&]() -> bool {
1753 if (E->isGLValue())
1754 return true;
1755 if (std::optional<PrimType> T = classify(E))
1756 return this->emitLoadPop(*T, E);
1757 return false;
1758 };
1759
1760 if (const auto *VD = dyn_cast<VarDecl>(Member)) {
1761 // I am almost confident in saying that a var decl must be static
1762 // and therefore registered as a global variable. But this will probably
1763 // turn out to be wrong some time in the future, as always.
1764 if (auto GlobalIndex = P.getGlobal(VD))
1765 return this->emitGetPtrGlobal(*GlobalIndex, E) && maybeLoadValue();
1766 return false;
1767 }
1768
1769 if (!isa<FieldDecl>(Member))
1770 return this->discard(Base) && this->visitDeclRef(Member, E);
1771
1772 if (Initializing) {
1773 if (!this->delegate(Base))
1774 return false;
1775 } else {
1776 if (!this->visit(Base))
1777 return false;
1778 }
1779
1780 // Base above gives us a pointer on the stack.
1781 const auto *FD = cast<FieldDecl>(Member);
1782 const RecordDecl *RD = FD->getParent();
1783 const Record *R = getRecord(RD);
1784 if (!R)
1785 return false;
1786 const Record::Field *F = R->getField(FD);
1787 // Leave a pointer to the field on the stack.
1788 if (F->Decl->getType()->isReferenceType())
1789 return this->emitGetFieldPop(PT_Ptr, F->Offset, E) && maybeLoadValue();
1790 return this->emitGetPtrFieldPop(F->Offset, E) && maybeLoadValue();
1791}
1792
1793template <class Emitter>
1795 // ArrayIndex might not be set if a ArrayInitIndexExpr is being evaluated
1796 // stand-alone, e.g. via EvaluateAsInt().
1797 if (!ArrayIndex)
1798 return false;
1799 return this->emitConst(*ArrayIndex, E);
1800}
1801
1802template <class Emitter>
1804 assert(Initializing);
1805 assert(!DiscardResult);
1806
1807 // We visit the common opaque expression here once so we have its value
1808 // cached.
1809 if (!this->discard(E->getCommonExpr()))
1810 return false;
1811
1812 // TODO: This compiles to quite a lot of bytecode if the array is larger.
1813 // Investigate compiling this to a loop.
1814 const Expr *SubExpr = E->getSubExpr();
1815 size_t Size = E->getArraySize().getZExtValue();
1816
1817 // So, every iteration, we execute an assignment here
1818 // where the LHS is on the stack (the target array)
1819 // and the RHS is our SubExpr.
1820 for (size_t I = 0; I != Size; ++I) {
1821 ArrayIndexScope<Emitter> IndexScope(this, I);
1822 BlockScope<Emitter> BS(this);
1823
1824 if (!this->visitArrayElemInit(I, SubExpr))
1825 return false;
1826 if (!BS.destroyLocals())
1827 return false;
1828 }
1829 return true;
1830}
1831
1832template <class Emitter>
1834 const Expr *SourceExpr = E->getSourceExpr();
1835 if (!SourceExpr)
1836 return false;
1837
1838 if (Initializing)
1839 return this->visitInitializer(SourceExpr);
1840
1841 PrimType SubExprT = classify(SourceExpr).value_or(PT_Ptr);
1842 if (auto It = OpaqueExprs.find(E); It != OpaqueExprs.end())
1843 return this->emitGetLocal(SubExprT, It->second, E);
1844
1845 if (!this->visit(SourceExpr))
1846 return false;
1847
1848 // At this point we either have the evaluated source expression or a pointer
1849 // to an object on the stack. We want to create a local variable that stores
1850 // this value.
1851 unsigned LocalIndex = allocateLocalPrimitive(E, SubExprT, /*IsConst=*/true);
1852 if (!this->emitSetLocal(SubExprT, LocalIndex, E))
1853 return false;
1854
1855 // Here the local variable is created but the value is removed from the stack,
1856 // so we put it back if the caller needs it.
1857 if (!DiscardResult) {
1858 if (!this->emitGetLocal(SubExprT, LocalIndex, E))
1859 return false;
1860 }
1861
1862 // This is cleaned up when the local variable is destroyed.
1863 OpaqueExprs.insert({E, LocalIndex});
1864
1865 return true;
1866}
1867
1868template <class Emitter>
1871 const Expr *Condition = E->getCond();
1872 const Expr *TrueExpr = E->getTrueExpr();
1873 const Expr *FalseExpr = E->getFalseExpr();
1874
1875 LabelTy LabelEnd = this->getLabel(); // Label after the operator.
1876 LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
1877
1878 if (!this->visitBool(Condition))
1879 return false;
1880
1881 if (!this->jumpFalse(LabelFalse))
1882 return false;
1883
1884 if (!this->delegate(TrueExpr))
1885 return false;
1886 if (!this->jump(LabelEnd))
1887 return false;
1888
1889 this->emitLabel(LabelFalse);
1890
1891 if (!this->delegate(FalseExpr))
1892 return false;
1893
1894 this->fallthrough(LabelEnd);
1895 this->emitLabel(LabelEnd);
1896
1897 return true;
1898}
1899
1900template <class Emitter>
1902 if (DiscardResult)
1903 return true;
1904
1905 if (!Initializing) {
1906 unsigned StringIndex = P.createGlobalString(E);
1907 return this->emitGetPtrGlobal(StringIndex, E);
1908 }
1909
1910 // We are initializing an array on the stack.
1911 const ConstantArrayType *CAT =
1912 Ctx.getASTContext().getAsConstantArrayType(E->getType());
1913 assert(CAT && "a string literal that's not a constant array?");
1914
1915 // If the initializer string is too long, a diagnostic has already been
1916 // emitted. Read only the array length from the string literal.
1917 unsigned ArraySize = CAT->getZExtSize();
1918 unsigned N = std::min(ArraySize, E->getLength());
1919 size_t CharWidth = E->getCharByteWidth();
1920
1921 for (unsigned I = 0; I != N; ++I) {
1922 uint32_t CodeUnit = E->getCodeUnit(I);
1923
1924 if (CharWidth == 1) {
1925 this->emitConstSint8(CodeUnit, E);
1926 this->emitInitElemSint8(I, E);
1927 } else if (CharWidth == 2) {
1928 this->emitConstUint16(CodeUnit, E);
1929 this->emitInitElemUint16(I, E);
1930 } else if (CharWidth == 4) {
1931 this->emitConstUint32(CodeUnit, E);
1932 this->emitInitElemUint32(I, E);
1933 } else {
1934 llvm_unreachable("unsupported character width");
1935 }
1936 }
1937
1938 // Fill up the rest of the char array with NUL bytes.
1939 for (unsigned I = N; I != ArraySize; ++I) {
1940 if (CharWidth == 1) {
1941 this->emitConstSint8(0, E);
1942 this->emitInitElemSint8(I, E);
1943 } else if (CharWidth == 2) {
1944 this->emitConstUint16(0, E);
1945 this->emitInitElemUint16(I, E);
1946 } else if (CharWidth == 4) {
1947 this->emitConstUint32(0, E);
1948 this->emitInitElemUint32(I, E);
1949 } else {
1950 llvm_unreachable("unsupported character width");
1951 }
1952 }
1953
1954 return true;
1955}
1956
1957template <class Emitter>
1959 return this->delegate(E->getString());
1960}
1961
1962template <class Emitter>
1964 auto &A = Ctx.getASTContext();
1965 std::string Str;
1966 A.getObjCEncodingForType(E->getEncodedType(), Str);
1967 StringLiteral *SL =
1968 StringLiteral::Create(A, Str, StringLiteralKind::Ordinary,
1969 /*Pascal=*/false, E->getType(), E->getAtLoc());
1970 return this->delegate(SL);
1971}
1972
1973template <class Emitter>
1975 const SYCLUniqueStableNameExpr *E) {
1976 if (DiscardResult)
1977 return true;
1978
1979 assert(!Initializing);
1980
1981 auto &A = Ctx.getASTContext();
1982 std::string ResultStr = E->ComputeName(A);
1983
1984 QualType CharTy = A.CharTy.withConst();
1985 APInt Size(A.getTypeSize(A.getSizeType()), ResultStr.size() + 1);
1986 QualType ArrayTy = A.getConstantArrayType(CharTy, Size, nullptr,
1987 ArraySizeModifier::Normal, 0);
1988
1989 StringLiteral *SL =
1990 StringLiteral::Create(A, ResultStr, StringLiteralKind::Ordinary,
1991 /*Pascal=*/false, ArrayTy, E->getLocation());
1992
1993 unsigned StringIndex = P.createGlobalString(SL);
1994 return this->emitGetPtrGlobal(StringIndex, E);
1995}
1996
1997template <class Emitter>
1999 if (DiscardResult)
2000 return true;
2001 return this->emitConst(E->getValue(), E);
2002}
2003
2004template <class Emitter>
2006 const CompoundAssignOperator *E) {
2007
2008 const Expr *LHS = E->getLHS();
2009 const Expr *RHS = E->getRHS();
2010 QualType LHSType = LHS->getType();
2011 QualType LHSComputationType = E->getComputationLHSType();
2012 QualType ResultType = E->getComputationResultType();
2013 std::optional<PrimType> LT = classify(LHSComputationType);
2014 std::optional<PrimType> RT = classify(ResultType);
2015
2016 assert(ResultType->isFloatingType());
2017
2018 if (!LT || !RT)
2019 return false;
2020
2021 PrimType LHST = classifyPrim(LHSType);
2022
2023 // C++17 onwards require that we evaluate the RHS first.
2024 // Compute RHS and save it in a temporary variable so we can
2025 // load it again later.
2026 if (!visit(RHS))
2027 return false;
2028
2029 unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
2030 if (!this->emitSetLocal(*RT, TempOffset, E))
2031 return false;
2032
2033 // First, visit LHS.
2034 if (!visit(LHS))
2035 return false;
2036 if (!this->emitLoad(LHST, E))
2037 return false;
2038
2039 // If necessary, convert LHS to its computation type.
2040 if (!this->emitPrimCast(LHST, classifyPrim(LHSComputationType),
2041 LHSComputationType, E))
2042 return false;
2043
2044 // Now load RHS.
2045 if (!this->emitGetLocal(*RT, TempOffset, E))
2046 return false;
2047
2048 llvm::RoundingMode RM = getRoundingMode(E);
2049 switch (E->getOpcode()) {
2050 case BO_AddAssign:
2051 if (!this->emitAddf(RM, E))
2052 return false;
2053 break;
2054 case BO_SubAssign:
2055 if (!this->emitSubf(RM, E))
2056 return false;
2057 break;
2058 case BO_MulAssign:
2059 if (!this->emitMulf(RM, E))
2060 return false;
2061 break;
2062 case BO_DivAssign:
2063 if (!this->emitDivf(RM, E))
2064 return false;
2065 break;
2066 default:
2067 return false;
2068 }
2069
2070 if (!this->emitPrimCast(classifyPrim(ResultType), LHST, LHS->getType(), E))
2071 return false;
2072
2073 if (DiscardResult)
2074 return this->emitStorePop(LHST, E);
2075 return this->emitStore(LHST, E);
2076}
2077
2078template <class Emitter>
2080 const CompoundAssignOperator *E) {
2081 BinaryOperatorKind Op = E->getOpcode();
2082 const Expr *LHS = E->getLHS();
2083 const Expr *RHS = E->getRHS();
2084 std::optional<PrimType> LT = classify(LHS->getType());
2085 std::optional<PrimType> RT = classify(RHS->getType());
2086
2087 if (Op != BO_AddAssign && Op != BO_SubAssign)
2088 return false;
2089
2090 if (!LT || !RT)
2091 return false;
2092
2093 if (!visit(LHS))
2094 return false;
2095
2096 if (!this->emitLoad(*LT, LHS))
2097 return false;
2098
2099 if (!visit(RHS))
2100 return false;
2101
2102 if (Op == BO_AddAssign) {
2103 if (!this->emitAddOffset(*RT, E))
2104 return false;
2105 } else {
2106 if (!this->emitSubOffset(*RT, E))
2107 return false;
2108 }
2109
2110 if (DiscardResult)
2111 return this->emitStorePopPtr(E);
2112 return this->emitStorePtr(E);
2113}
2114
2115template <class Emitter>
2117 const CompoundAssignOperator *E) {
2118
2119 const Expr *LHS = E->getLHS();
2120 const Expr *RHS = E->getRHS();
2121 std::optional<PrimType> LHSComputationT =
2122 classify(E->getComputationLHSType());
2123 std::optional<PrimType> LT = classify(LHS->getType());
2124 std::optional<PrimType> RT = classify(RHS->getType());
2125 std::optional<PrimType> ResultT = classify(E->getType());
2126
2127 if (!Ctx.getLangOpts().CPlusPlus14)
2128 return this->visit(RHS) && this->visit(LHS) && this->emitError(E);
2129
2130 if (!LT || !RT || !ResultT || !LHSComputationT)
2131 return false;
2132
2133 // Handle floating point operations separately here, since they
2134 // require special care.
2135
2136 if (ResultT == PT_Float || RT == PT_Float)
2137 return VisitFloatCompoundAssignOperator(E);
2138
2139 if (E->getType()->isPointerType())
2140 return VisitPointerCompoundAssignOperator(E);
2141
2142 assert(!E->getType()->isPointerType() && "Handled above");
2143 assert(!E->getType()->isFloatingType() && "Handled above");
2144
2145 // C++17 onwards require that we evaluate the RHS first.
2146 // Compute RHS and save it in a temporary variable so we can
2147 // load it again later.
2148 // FIXME: Compound assignments are unsequenced in C, so we might
2149 // have to figure out how to reject them.
2150 if (!visit(RHS))
2151 return false;
2152
2153 unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
2154
2155 if (!this->emitSetLocal(*RT, TempOffset, E))
2156 return false;
2157
2158 // Get LHS pointer, load its value and cast it to the
2159 // computation type if necessary.
2160 if (!visit(LHS))
2161 return false;
2162 if (!this->emitLoad(*LT, E))
2163 return false;
2164 if (LT != LHSComputationT) {
2165 if (!this->emitCast(*LT, *LHSComputationT, E))
2166 return false;
2167 }
2168
2169 // Get the RHS value on the stack.
2170 if (!this->emitGetLocal(*RT, TempOffset, E))
2171 return false;
2172
2173 // Perform operation.
2174 switch (E->getOpcode()) {
2175 case BO_AddAssign:
2176 if (!this->emitAdd(*LHSComputationT, E))
2177 return false;
2178 break;
2179 case BO_SubAssign:
2180 if (!this->emitSub(*LHSComputationT, E))
2181 return false;
2182 break;
2183 case BO_MulAssign:
2184 if (!this->emitMul(*LHSComputationT, E))
2185 return false;
2186 break;
2187 case BO_DivAssign:
2188 if (!this->emitDiv(*LHSComputationT, E))
2189 return false;
2190 break;
2191 case BO_RemAssign:
2192 if (!this->emitRem(*LHSComputationT, E))
2193 return false;
2194 break;
2195 case BO_ShlAssign:
2196 if (!this->emitShl(*LHSComputationT, *RT, E))
2197 return false;
2198 break;
2199 case BO_ShrAssign:
2200 if (!this->emitShr(*LHSComputationT, *RT, E))
2201 return false;
2202 break;
2203 case BO_AndAssign:
2204 if (!this->emitBitAnd(*LHSComputationT, E))
2205 return false;
2206 break;
2207 case BO_XorAssign:
2208 if (!this->emitBitXor(*LHSComputationT, E))
2209 return false;
2210 break;
2211 case BO_OrAssign:
2212 if (!this->emitBitOr(*LHSComputationT, E))
2213 return false;
2214 break;
2215 default:
2216 llvm_unreachable("Unimplemented compound assign operator");
2217 }
2218
2219 // And now cast from LHSComputationT to ResultT.
2220 if (ResultT != LHSComputationT) {
2221 if (!this->emitCast(*LHSComputationT, *ResultT, E))
2222 return false;
2223 }
2224
2225 // And store the result in LHS.
2226 if (DiscardResult) {
2227 if (LHS->refersToBitField())
2228 return this->emitStoreBitFieldPop(*ResultT, E);
2229 return this->emitStorePop(*ResultT, E);
2230 }
2231 if (LHS->refersToBitField())
2232 return this->emitStoreBitField(*ResultT, E);
2233 return this->emitStore(*ResultT, E);
2234}
2235
2236template <class Emitter>
2238 LocalScope<Emitter> ES(this);
2239 const Expr *SubExpr = E->getSubExpr();
2240
2241 assert(E->getNumObjects() == 0 && "TODO: Implement cleanups");
2242
2243 return this->delegate(SubExpr) && ES.destroyLocals(E);
2244}
2245
2246template <class Emitter>
2248 const MaterializeTemporaryExpr *E) {
2249 const Expr *SubExpr = E->getSubExpr();
2250
2251 if (Initializing) {
2252 // We already have a value, just initialize that.
2253 return this->delegate(SubExpr);
2254 }
2255 // If we don't end up using the materialized temporary anyway, don't
2256 // bother creating it.
2257 if (DiscardResult)
2258 return this->discard(SubExpr);
2259
2260 // When we're initializing a global variable *or* the storage duration of
2261 // the temporary is explicitly static, create a global variable.
2262 std::optional<PrimType> SubExprT = classify(SubExpr);
2263 bool IsStatic = E->getStorageDuration() == SD_Static;
2264 if (IsStatic) {
2265 std::optional<unsigned> GlobalIndex = P.createGlobal(E);
2266 if (!GlobalIndex)
2267 return false;
2268
2269 const LifetimeExtendedTemporaryDecl *TempDecl =
2270 E->getLifetimeExtendedTemporaryDecl();
2271 if (IsStatic)
2272 assert(TempDecl);
2273
2274 if (SubExprT) {
2275 if (!this->visit(SubExpr))
2276 return false;
2277 if (IsStatic) {
2278 if (!this->emitInitGlobalTemp(*SubExprT, *GlobalIndex, TempDecl, E))
2279 return false;
2280 } else {
2281 if (!this->emitInitGlobal(*SubExprT, *GlobalIndex, E))
2282 return false;
2283 }
2284 return this->emitGetPtrGlobal(*GlobalIndex, E);
2285 }
2286
2287 // Non-primitive values.
2288 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2289 return false;
2290 if (!this->visitInitializer(SubExpr))
2291 return false;
2292 if (IsStatic)
2293 return this->emitInitGlobalTempComp(TempDecl, E);
2294 return true;
2295 }
2296
2297 // For everyhing else, use local variables.
2298 if (SubExprT) {
2299 unsigned LocalIndex = allocateLocalPrimitive(
2300 SubExpr, *SubExprT, /*IsConst=*/true, /*IsExtended=*/true);
2301 if (!this->visit(SubExpr))
2302 return false;
2303 if (!this->emitSetLocal(*SubExprT, LocalIndex, E))
2304 return false;
2305 return this->emitGetPtrLocal(LocalIndex, E);
2306 } else {
2307 const Expr *Inner = E->getSubExpr()->skipRValueSubobjectAdjustments();
2308 if (std::optional<unsigned> LocalIndex =
2309 allocateLocal(Inner, E->getExtendingDecl())) {
2310 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
2311 if (!this->emitGetPtrLocal(*LocalIndex, E))
2312 return false;
2313 return this->visitInitializer(SubExpr);
2314 }
2315 }
2316 return false;
2317}
2318
2319template <class Emitter>
2321 const CXXBindTemporaryExpr *E) {
2322 return this->delegate(E->getSubExpr());
2323}
2324
2325template <class Emitter>
2327 const Expr *Init = E->getInitializer();
2328 if (Initializing) {
2329 // We already have a value, just initialize that.
2330 return this->visitInitializer(Init) && this->emitFinishInit(E);
2331 }
2332
2333 std::optional<PrimType> T = classify(E->getType());
2334 if (E->isFileScope()) {
2335 // Avoid creating a variable if this is a primitive RValue anyway.
2336 if (T && !E->isLValue())
2337 return this->delegate(Init);
2338
2339 if (std::optional<unsigned> GlobalIndex = P.createGlobal(E)) {
2340 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2341 return false;
2342
2343 if (T) {
2344 if (!this->visit(Init))
2345 return false;
2346 return this->emitInitGlobal(*T, *GlobalIndex, E);
2347 }
2348
2349 return this->visitInitializer(Init) && this->emitFinishInit(E);
2350 }
2351
2352 return false;
2353 }
2354
2355 // Otherwise, use a local variable.
2356 if (T && !E->isLValue()) {
2357 // For primitive types, we just visit the initializer.
2358 return this->delegate(Init);
2359 } else {
2360 unsigned LocalIndex;
2361
2362 if (T)
2363 LocalIndex = this->allocateLocalPrimitive(Init, *T, false, false);
2364 else if (std::optional<unsigned> MaybeIndex = this->allocateLocal(Init))
2365 LocalIndex = *MaybeIndex;
2366 else
2367 return false;
2368
2369 if (!this->emitGetPtrLocal(LocalIndex, E))
2370 return false;
2371
2372 if (T) {
2373 if (!this->visit(Init)) {
2374 return false;
2375 }
2376 return this->emitInit(*T, E);
2377 } else {
2378 if (!this->visitInitializer(Init) || !this->emitFinishInit(E))
2379 return false;
2380 }
2381
2382 if (DiscardResult)
2383 return this->emitPopPtr(E);
2384 return true;
2385 }
2386
2387 return false;
2388}
2389
2390template <class Emitter>
2392 if (DiscardResult)
2393 return true;
2394 if (E->getType()->isBooleanType())
2395 return this->emitConstBool(E->getValue(), E);
2396 return this->emitConst(E->getValue(), E);
2397}
2398
2399template <class Emitter>
2401 if (DiscardResult)
2402 return true;
2403 return this->emitConst(E->getValue(), E);
2404}
2405
2406template <class Emitter>
2408 if (DiscardResult)
2409 return true;
2410
2411 assert(Initializing);
2412 const Record *R = P.getOrCreateRecord(E->getLambdaClass());
2413
2414 auto *CaptureInitIt = E->capture_init_begin();
2415 // Initialize all fields (which represent lambda captures) of the
2416 // record with their initializers.
2417 for (const Record::Field &F : R->fields()) {
2418 const Expr *Init = *CaptureInitIt;
2419 ++CaptureInitIt;
2420
2421 if (!Init)
2422 continue;
2423
2424 if (std::optional<PrimType> T = classify(Init)) {
2425 if (!this->visit(Init))
2426 return false;
2427
2428 if (!this->emitInitField(*T, F.Offset, E))
2429 return false;
2430 } else {
2431 if (!this->emitGetPtrField(F.Offset, E))
2432 return false;
2433
2434 if (!this->visitInitializer(Init))
2435 return false;
2436
2437 if (!this->emitPopPtr(E))
2438 return false;
2439 }
2440 }
2441
2442 return true;
2443}
2444
2445template <class Emitter>
2447 if (DiscardResult)
2448 return true;
2449
2450 return this->delegate(E->getFunctionName());
2451}
2452
2453template <class Emitter>
2455 if (E->getSubExpr() && !this->discard(E->getSubExpr()))
2456 return false;
2457
2458 return this->emitInvalid(E);
2459}
2460
2461template <class Emitter>
2463 const CXXReinterpretCastExpr *E) {
2464 const Expr *SubExpr = E->getSubExpr();
2465
2466 bool TypesMatch = classify(E) == classify(SubExpr);
2467 if (!this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/!TypesMatch, E))
2468 return false;
2469
2470 return this->delegate(SubExpr);
2471}
2472
2473template <class Emitter>
2475 assert(E->getType()->isBooleanType());
2476
2477 if (DiscardResult)
2478 return true;
2479 return this->emitConstBool(E->getValue(), E);
2480}
2481
2482template <class Emitter>
2484 QualType T = E->getType();
2485 assert(!classify(T));
2486
2487 if (T->isRecordType()) {
2488 const CXXConstructorDecl *Ctor = E->getConstructor();
2489
2490 // Trivial copy/move constructor. Avoid copy.
2491 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
2492 Ctor->isTrivial() &&
2493 E->getArg(0)->isTemporaryObject(Ctx.getASTContext(),
2495 return this->visitInitializer(E->getArg(0));
2496
2497 // If we're discarding a construct expression, we still need
2498 // to allocate a variable and call the constructor and destructor.
2499 if (DiscardResult) {
2500 if (Ctor->isTrivial())
2501 return true;
2502 assert(!Initializing);
2503 std::optional<unsigned> LocalIndex = allocateLocal(E);
2504
2505 if (!LocalIndex)
2506 return false;
2507
2508 if (!this->emitGetPtrLocal(*LocalIndex, E))
2509 return false;
2510 }
2511
2512 // Zero initialization.
2513 if (E->requiresZeroInitialization()) {
2514 const Record *R = getRecord(E->getType());
2515
2516 if (!this->visitZeroRecordInitializer(R, E))
2517 return false;
2518
2519 // If the constructor is trivial anyway, we're done.
2520 if (Ctor->isTrivial())
2521 return true;
2522 }
2523
2524 const Function *Func = getFunction(Ctor);
2525
2526 if (!Func)
2527 return false;
2528
2529 assert(Func->hasThisPointer());
2530 assert(!Func->hasRVO());
2531
2532 // The This pointer is already on the stack because this is an initializer,
2533 // but we need to dup() so the call() below has its own copy.
2534 if (!this->emitDupPtr(E))
2535 return false;
2536
2537 // Constructor arguments.
2538 for (const auto *Arg : E->arguments()) {
2539 if (!this->visit(Arg))
2540 return false;
2541 }
2542
2543 if (Func->isVariadic()) {
2544 uint32_t VarArgSize = 0;
2545 unsigned NumParams = Func->getNumWrittenParams();
2546 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) {
2547 VarArgSize +=
2548 align(primSize(classify(E->getArg(I)->getType()).value_or(PT_Ptr)));
2549 }
2550 if (!this->emitCallVar(Func, VarArgSize, E))
2551 return false;
2552 } else {
2553 if (!this->emitCall(Func, 0, E))
2554 return false;
2555 }
2556
2557 if (DiscardResult)
2558 return this->emitPopPtr(E);
2559 return true;
2560 }
2561
2562 if (T->isArrayType()) {
2563 const ConstantArrayType *CAT =
2564 Ctx.getASTContext().getAsConstantArrayType(E->getType());
2565 if (!CAT)
2566 return false;
2567
2568 size_t NumElems = CAT->getZExtSize();
2569 const Function *Func = getFunction(E->getConstructor());
2570 if (!Func || !Func->isConstexpr())
2571 return false;
2572
2573 // FIXME(perf): We're calling the constructor once per array element here,
2574 // in the old intepreter we had a special-case for trivial constructors.
2575 for (size_t I = 0; I != NumElems; ++I) {
2576 if (!this->emitConstUint64(I, E))
2577 return false;
2578 if (!this->emitArrayElemPtrUint64(E))
2579 return false;
2580
2581 // Constructor arguments.
2582 for (const auto *Arg : E->arguments()) {
2583 if (!this->visit(Arg))
2584 return false;
2585 }
2586
2587 if (!this->emitCall(Func, 0, E))
2588 return false;
2589 }
2590 return true;
2591 }
2592
2593 return false;
2594}
2595
2596template <class Emitter>
2598 if (DiscardResult)
2599 return true;
2600
2601 const APValue Val =
2602 E->EvaluateInContext(Ctx.getASTContext(), SourceLocDefaultExpr);
2603
2604 // Things like __builtin_LINE().
2605 if (E->getType()->isIntegerType()) {
2606 assert(Val.isInt());
2607 const APSInt &I = Val.getInt();
2608 return this->emitConst(I, E);
2609 }
2610 // Otherwise, the APValue is an LValue, with only one element.
2611 // Theoretically, we don't need the APValue at all of course.
2612 assert(E->getType()->isPointerType());
2613 assert(Val.isLValue());
2614 const APValue::LValueBase &Base = Val.getLValueBase();
2615 if (const Expr *LValueExpr = Base.dyn_cast<const Expr *>())
2616 return this->visit(LValueExpr);
2617
2618 // Otherwise, we have a decl (which is the case for
2619 // __builtin_source_location).
2620 assert(Base.is<const ValueDecl *>());
2621 assert(Val.getLValuePath().size() == 0);
2622 const auto *BaseDecl = Base.dyn_cast<const ValueDecl *>();
2623 assert(BaseDecl);
2624
2625 auto *UGCD = cast<UnnamedGlobalConstantDecl>(BaseDecl);
2626
2627 std::optional<unsigned> GlobalIndex = P.getOrCreateGlobal(UGCD);
2628 if (!GlobalIndex)
2629 return false;
2630
2631 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2632 return false;
2633
2634 const Record *R = getRecord(E->getType());
2635 const APValue &V = UGCD->getValue();
2636 for (unsigned I = 0, N = R->getNumFields(); I != N; ++I) {
2637 const Record::Field *F = R->getField(I);
2638 const APValue &FieldValue = V.getStructField(I);
2639
2640 PrimType FieldT = classifyPrim(F->Decl->getType());
2641
2642 if (!this->visitAPValue(FieldValue, FieldT, E))
2643 return false;
2644 if (!this->emitInitField(FieldT, F->Offset, E))
2645 return false;
2646 }
2647
2648 // Leave the pointer to the global on the stack.
2649 return true;
2650}
2651
2652template <class Emitter>
2654 unsigned N = E->getNumComponents();
2655 if (N == 0)
2656 return false;
2657
2658 for (unsigned I = 0; I != N; ++I) {
2659 const OffsetOfNode &Node = E->getComponent(I);
2660 if (Node.getKind() == OffsetOfNode::Array) {
2661 const Expr *ArrayIndexExpr = E->getIndexExpr(Node.getArrayExprIndex());
2662 PrimType IndexT = classifyPrim(ArrayIndexExpr->getType());
2663
2664 if (DiscardResult) {
2665 if (!this->discard(ArrayIndexExpr))
2666 return false;
2667 continue;
2668 }
2669
2670 if (!this->visit(ArrayIndexExpr))
2671 return false;
2672 // Cast to Sint64.
2673 if (IndexT != PT_Sint64) {
2674 if (!this->emitCast(IndexT, PT_Sint64, E))
2675 return false;
2676 }
2677 }
2678 }
2679
2680 if (DiscardResult)
2681 return true;
2682
2683 PrimType T = classifyPrim(E->getType());
2684 return this->emitOffsetOf(T, E, E);
2685}
2686
2687template <class Emitter>
2689 const CXXScalarValueInitExpr *E) {
2690 QualType Ty = E->getType();
2691
2692 if (DiscardResult || Ty->isVoidType())
2693 return true;
2694
2695 if (std::optional<PrimType> T = classify(Ty))
2696 return this->visitZeroInitializer(*T, Ty, E);
2697
2698 if (const auto *CT = Ty->getAs<ComplexType>()) {
2699 if (!Initializing) {
2700 std::optional<unsigned> LocalIndex = allocateLocal(E);
2701 if (!LocalIndex)
2702 return false;
2703 if (!this->emitGetPtrLocal(*LocalIndex, E))
2704 return false;
2705 }
2706
2707 // Initialize both fields to 0.
2708 QualType ElemQT = CT->getElementType();
2709 PrimType ElemT = classifyPrim(ElemQT);
2710
2711 for (unsigned I = 0; I != 2; ++I) {
2712 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2713 return false;
2714 if (!this->emitInitElem(ElemT, I, E))
2715 return false;
2716 }
2717 return true;
2718 }
2719
2720 if (const auto *VT = Ty->getAs<VectorType>()) {
2721 // FIXME: Code duplication with the _Complex case above.
2722 if (!Initializing) {
2723 std::optional<unsigned> LocalIndex = allocateLocal(E);
2724 if (!LocalIndex)
2725 return false;
2726 if (!this->emitGetPtrLocal(*LocalIndex, E))
2727 return false;
2728 }
2729
2730 // Initialize all fields to 0.
2731 QualType ElemQT = VT->getElementType();
2732 PrimType ElemT = classifyPrim(ElemQT);
2733
2734 for (unsigned I = 0, N = VT->getNumElements(); I != N; ++I) {
2735 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2736 return false;
2737 if (!this->emitInitElem(ElemT, I, E))
2738 return false;
2739 }
2740 return true;
2741 }
2742
2743 return false;
2744}
2745
2746template <class Emitter>
2748 return this->emitConst(E->getPackLength(), E);
2749}
2750
2751template <class Emitter>
2753 const GenericSelectionExpr *E) {
2754 return this->delegate(E->getResultExpr());
2755}
2756
2757template <class Emitter>
2759 return this->delegate(E->getChosenSubExpr());
2760}
2761
2762template <class Emitter>
2764 if (DiscardResult)
2765 return true;
2766
2767 return this->emitConst(E->getValue(), E);
2768}
2769
2770template <class Emitter>
2772 const CXXInheritedCtorInitExpr *E) {
2773 const CXXConstructorDecl *Ctor = E->getConstructor();
2774 assert(!Ctor->isTrivial() &&
2775 "Trivial CXXInheritedCtorInitExpr, implement. (possible?)");
2776 const Function *F = this->getFunction(Ctor);
2777 assert(F);
2778 assert(!F->hasRVO());
2779 assert(F->hasThisPointer());
2780
2781 if (!this->emitDupPtr(SourceInfo{}))
2782 return false;
2783
2784 // Forward all arguments of the current function (which should be a
2785 // constructor itself) to the inherited ctor.
2786 // This is necessary because the calling code has pushed the pointer
2787 // of the correct base for us already, but the arguments need
2788 // to come after.
2789 unsigned Offset = align(primSize(PT_Ptr)); // instance pointer.
2790 for (const ParmVarDecl *PD : Ctor->parameters()) {
2791 PrimType PT = this->classify(PD->getType()).value_or(PT_Ptr);
2792
2793 if (!this->emitGetParam(PT, Offset, E))
2794 return false;
2795 Offset += align(primSize(PT));
2796 }
2797
2798 return this->emitCall(F, 0, E);
2799}
2800
2801template <class Emitter>
2803 assert(classifyPrim(E->getType()) == PT_Ptr);
2804 const Expr *Init = E->getInitializer();
2805 QualType ElementType = E->getAllocatedType();
2806 std::optional<PrimType> ElemT = classify(ElementType);
2807 unsigned PlacementArgs = E->getNumPlacementArgs();
2808 bool IsNoThrow = false;
2809
2810 // FIXME: Better diagnostic. diag::note_constexpr_new_placement
2811 if (PlacementArgs != 0) {
2812 // The only new-placement list we support is of the form (std::nothrow).
2813 //
2814 // FIXME: There is no restriction on this, but it's not clear that any
2815 // other form makes any sense. We get here for cases such as:
2816 //
2817 // new (std::align_val_t{N}) X(int)
2818 //
2819 // (which should presumably be valid only if N is a multiple of
2820 // alignof(int), and in any case can't be deallocated unless N is
2821 // alignof(X) and X has new-extended alignment).
2822 if (PlacementArgs != 1 || !E->getPlacementArg(0)->getType()->isNothrowT())
2823 return this->emitInvalid(E);
2824
2825 if (!this->discard(E->getPlacementArg(0)))
2826 return false;
2827 IsNoThrow = true;
2828 }
2829
2830 const Descriptor *Desc;
2831 if (ElemT) {
2832 if (E->isArray())
2833 Desc = nullptr; // We're not going to use it in this case.
2834 else
2835 Desc = P.createDescriptor(E, *ElemT, Descriptor::InlineDescMD,
2836 /*IsConst=*/false, /*IsTemporary=*/false,
2837 /*IsMutable=*/false);
2838 } else {
2839 Desc = P.createDescriptor(
2840 E, ElementType.getTypePtr(),
2841 E->isArray() ? std::nullopt : Descriptor::InlineDescMD,
2842 /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false, Init);
2843 }
2844
2845 if (E->isArray()) {
2846 std::optional<const Expr *> ArraySizeExpr = E->getArraySize();
2847 if (!ArraySizeExpr)
2848 return false;
2849
2850 const Expr *Stripped = *ArraySizeExpr;
2851 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
2852 Stripped = ICE->getSubExpr())
2853 if (ICE->getCastKind() != CK_NoOp &&
2854 ICE->getCastKind() != CK_IntegralCast)
2855 break;
2856
2857 PrimType SizeT = classifyPrim(Stripped->getType());
2858
2859 if (!this->visit(Stripped))
2860 return false;
2861
2862 if (ElemT) {
2863 // N primitive elements.
2864 if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E))
2865 return false;
2866 } else {
2867 // N Composite elements.
2868 if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E))
2869 return false;
2870 }
2871
2872 if (Init && !this->visitInitializer(Init))
2873 return false;
2874
2875 } else {
2876 // Allocate just one element.
2877 if (!this->emitAlloc(Desc, E))
2878 return false;
2879
2880 if (Init) {
2881 if (ElemT) {
2882 if (!this->visit(Init))
2883 return false;
2884
2885 if (!this->emitInit(*ElemT, E))
2886 return false;
2887 } else {
2888 // Composite.
2889 if (!this->visitInitializer(Init))
2890 return false;
2891 }
2892 }
2893 }
2894
2895 if (DiscardResult)
2896 return this->emitPopPtr(E);
2897
2898 return true;
2899}
2900
2901template <class Emitter>
2903 const Expr *Arg = E->getArgument();
2904
2905 // Arg must be an lvalue.
2906 if (!this->visit(Arg))
2907 return false;
2908
2909 return this->emitFree(E->isArrayForm(), E);
2910}
2911
2912template <class Emitter>
2914 assert(Ctx.getLangOpts().CPlusPlus);
2915 return this->emitConstBool(E->getValue(), E);
2916}
2917
2918template <class Emitter>
2920 if (DiscardResult)
2921 return true;
2922 assert(!Initializing);
2923
2924 const MSGuidDecl *GuidDecl = E->getGuidDecl();
2925 const RecordDecl *RD = GuidDecl->getType()->getAsRecordDecl();
2926 assert(RD);
2927 // If the definiton of the result type is incomplete, just return a dummy.
2928 // If (and when) that is read from, we will fail, but not now.
2929 if (!RD->isCompleteDefinition()) {
2930 if (std::optional<unsigned> I = P.getOrCreateDummy(GuidDecl))
2931 return this->emitGetPtrGlobal(*I, E);
2932 return false;
2933 }
2934
2935 std::optional<unsigned> GlobalIndex = P.getOrCreateGlobal(GuidDecl);
2936 if (!GlobalIndex)
2937 return false;
2938 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2939 return false;
2940
2941 assert(this->getRecord(E->getType()));
2942
2943 const APValue &V = GuidDecl->getAsAPValue();
2944 if (V.getKind() == APValue::None)
2945 return true;
2946
2947 assert(V.isStruct());
2948 assert(V.getStructNumBases() == 0);
2949 if (!this->visitAPValueInitializer(V, E))
2950 return false;
2951
2952 return this->emitFinishInit(E);
2953}
2954
2955template <class Emitter>
2957 assert(classifyPrim(E->getType()) == PT_Bool);
2958 if (DiscardResult)
2959 return true;
2960 return this->emitConstBool(E->isSatisfied(), E);
2961}
2962
2963template <class Emitter>
2966 assert(classifyPrim(E->getType()) == PT_Bool);
2967 if (DiscardResult)
2968 return true;
2969 return this->emitConstBool(E->isSatisfied(), E);
2970}
2971
2972template <class Emitter>
2975 return this->delegate(E->getSemanticForm());
2976}
2977
2978template <class Emitter>
2980
2981 for (const Expr *SemE : E->semantics()) {
2982 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
2983 if (SemE == E->getResultExpr())
2984 return false;
2985
2986 if (OVE->isUnique())
2987 continue;
2988
2989 if (!this->discard(OVE))
2990 return false;
2991 } else if (SemE == E->getResultExpr()) {
2992 if (!this->delegate(SemE))
2993 return false;
2994 } else {
2995 if (!this->discard(SemE))
2996 return false;
2997 }
2998 }
2999 return true;
3000}
3001
3002template <class Emitter>
3004 return this->delegate(E->getSelectedExpr());
3005}
3006
3007template <class Emitter>
3009 return this->emitError(E);
3010}
3011
3012template <class Emitter>
3014 assert(E->getType()->isVoidPointerType());
3015
3016 unsigned Offset = allocateLocalPrimitive(
3017 E->getLabel(), PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false);
3018
3019 return this->emitGetLocal(PT_Ptr, Offset, E);
3020}
3021
3022template <class Emitter>
3024 assert(Initializing);
3025 const auto *VT = E->getType()->castAs<VectorType>();
3026 QualType ElemType = VT->getElementType();
3027 PrimType ElemT = classifyPrim(ElemType);
3028 const Expr *Src = E->getSrcExpr();
3029 PrimType SrcElemT =
3030 classifyPrim(Src->getType()->castAs<VectorType>()->getElementType());
3031
3032 unsigned SrcOffset = this->allocateLocalPrimitive(Src, PT_Ptr, true, false);
3033 if (!this->visit(Src))
3034 return false;
3035 if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
3036 return false;
3037
3038 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
3039 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
3040 return false;
3041 if (!this->emitArrayElemPop(SrcElemT, I, E))
3042 return false;
3043 if (SrcElemT != ElemT) {
3044 if (!this->emitPrimCast(SrcElemT, ElemT, ElemType, E))
3045 return false;
3046 }
3047 if (!this->emitInitElem(ElemT, I, E))
3048 return false;
3049 }
3050
3051 return true;
3052}
3053
3054template <class Emitter>
3056 assert(Initializing);
3057 assert(E->getNumSubExprs() > 2);
3058
3059 const Expr *Vecs[] = {E->getExpr(0), E->getExpr(1)};
3060 const VectorType *VT = Vecs[0]->getType()->castAs<VectorType>();
3061 PrimType ElemT = classifyPrim(VT->getElementType());
3062 unsigned NumInputElems = VT->getNumElements();
3063 unsigned NumOutputElems = E->getNumSubExprs() - 2;
3064 assert(NumOutputElems > 0);
3065
3066 // Save both input vectors to a local variable.
3067 unsigned VectorOffsets[2];
3068 for (unsigned I = 0; I != 2; ++I) {
3069 VectorOffsets[I] = this->allocateLocalPrimitive(
3070 Vecs[I], PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false);
3071 if (!this->visit(Vecs[I]))
3072 return false;
3073 if (!this->emitSetLocal(PT_Ptr, VectorOffsets[I], E))
3074 return false;
3075 }
3076 for (unsigned I = 0; I != NumOutputElems; ++I) {
3077 APSInt ShuffleIndex = E->getShuffleMaskIdx(Ctx.getASTContext(), I);
3078 if (ShuffleIndex == -1)
3079 return this->emitInvalid(E); // FIXME: Better diagnostic.
3080
3081 assert(ShuffleIndex < (NumInputElems * 2));
3082 if (!this->emitGetLocal(PT_Ptr,
3083 VectorOffsets[ShuffleIndex >= NumInputElems], E))
3084 return false;
3085 unsigned InputVectorIndex = ShuffleIndex.getZExtValue() % NumInputElems;
3086 if (!this->emitArrayElemPop(ElemT, InputVectorIndex, E))
3087 return false;
3088
3089 if (!this->emitInitElem(ElemT, I, E))
3090 return false;
3091 }
3092
3093 return true;
3094}
3095
3096template <class Emitter>
3098 const ExtVectorElementExpr *E) {
3099 const Expr *Base = E->getBase();
3100 assert(
3101 Base->getType()->isVectorType() ||
3102 Base->getType()->getAs<PointerType>()->getPointeeType()->isVectorType());
3103
3105 E->getEncodedElementAccess(Indices);
3106
3107 if (Indices.size() == 1) {
3108 if (!this->visit(Base))
3109 return false;
3110
3111 if (E->isGLValue()) {
3112 if (!this->emitConstUint32(Indices[0], E))
3113 return false;
3114 return this->emitArrayElemPtrPop(PT_Uint32, E);
3115 }
3116 // Else, also load the value.
3117 return this->emitArrayElemPop(classifyPrim(E->getType()), Indices[0], E);
3118 }
3119
3120 // Create a local variable for the base.
3121 unsigned BaseOffset = allocateLocalPrimitive(Base, PT_Ptr, /*IsConst=*/true,
3122 /*IsExtended=*/false);
3123 if (!this->visit(Base))
3124 return false;
3125 if (!this->emitSetLocal(PT_Ptr, BaseOffset, E))
3126 return false;
3127
3128 // Now the vector variable for the return value.
3129 if (!Initializing) {
3130 std::optional<unsigned> ResultIndex;
3131 ResultIndex = allocateLocal(E);
3132 if (!ResultIndex)
3133 return false;
3134 if (!this->emitGetPtrLocal(*ResultIndex, E))
3135 return false;
3136 }
3137
3138 assert(Indices.size() == E->getType()->getAs<VectorType>()->getNumElements());
3139
3140 PrimType ElemT =
3141 classifyPrim(E->getType()->getAs<VectorType>()->getElementType());
3142 uint32_t DstIndex = 0;
3143 for (uint32_t I : Indices) {
3144 if (!this->emitGetLocal(PT_Ptr, BaseOffset, E))
3145 return false;
3146 if (!this->emitArrayElemPop(ElemT, I, E))
3147 return false;
3148 if (!this->emitInitElem(ElemT, DstIndex, E))
3149 return false;
3150 ++DstIndex;
3151 }
3152
3153 // Leave the result pointer on the stack.
3154 assert(!DiscardResult);
3155 return true;
3156}
3157
3158template <class Emitter>
3160 const Expr *SubExpr = E->getSubExpr();
3161 if (!E->isExpressibleAsConstantInitializer())
3162 return this->discard(SubExpr) && this->emitInvalid(E);
3163
3164 return this->delegate(SubExpr);
3165}
3166
3167template <class Emitter>
3170 const Expr *SubExpr = E->getSubExpr();
3172 Ctx.getASTContext().getAsConstantArrayType(SubExpr->getType());
3173 const Record *R = getRecord(E->getType());
3174 assert(Initializing);
3175 assert(SubExpr->isGLValue());
3176
3177 if (!this->visit(SubExpr))
3178 return false;
3179 if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E))
3180 return false;
3181
3182 PrimType SecondFieldT = classifyPrim(R->getField(1u)->Decl->getType());
3183 if (isIntegralType(SecondFieldT)) {
3184 if (!this->emitConst(static_cast<APSInt>(ArrayType->getSize()),
3185 SecondFieldT, E))
3186 return false;
3187 return this->emitInitField(SecondFieldT, R->getField(1u)->Offset, E);
3188 }
3189 assert(SecondFieldT == PT_Ptr);
3190
3191 if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E))
3192 return false;
3193 if (!this->emitConst(static_cast<APSInt>(ArrayType->getSize()), PT_Uint64, E))
3194 return false;
3195 if (!this->emitArrayElemPtrPop(PT_Uint64, E))
3196 return false;
3197 return this->emitInitFieldPtr(R->getField(1u)->Offset, E);
3198}
3199
3200template <class Emitter>
3202 BlockScope<Emitter> BS(this);
3203 StmtExprScope<Emitter> SS(this);
3204
3205 const CompoundStmt *CS = E->getSubStmt();
3206 const Stmt *Result = CS->getStmtExprResult();
3207 for (const Stmt *S : CS->body()) {
3208 if (S != Result) {
3209 if (!this->visitStmt(S))
3210 return false;
3211 continue;
3212 }
3213
3214 assert(S == Result);
3215 if (const Expr *ResultExpr = dyn_cast<Expr>(S))
3216 return this->delegate(ResultExpr);
3217 return this->emitUnsupported(E);
3218 }
3219
3220 return BS.destroyLocals();
3221}
3222
3223template <class Emitter> bool Compiler<Emitter>::discard(const Expr *E) {
3224 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true,
3225 /*NewInitializing=*/false);
3226 return this->Visit(E);
3227}
3228
3229template <class Emitter> bool Compiler<Emitter>::delegate(const Expr *E) {
3230 if (E->containsErrors())
3231 return this->emitError(E);
3232
3233 // We're basically doing:
3234 // OptionScope<Emitter> Scope(this, DicardResult, Initializing);
3235 // but that's unnecessary of course.
3236 return this->Visit(E);
3237}
3238
3239template <class Emitter> bool Compiler<Emitter>::visit(const Expr *E) {
3240 if (E->getType().isNull())
3241 return false;
3242
3243 if (E->getType()->isVoidType())
3244 return this->discard(E);
3245
3246 // Create local variable to hold the return value.
3247 if (!E->isGLValue() && !E->getType()->isAnyComplexType() &&
3248 !classify(E->getType())) {
3249 std::optional<unsigned> LocalIndex = allocateLocal(E);
3250 if (!LocalIndex)
3251 return false;
3252
3253 if (!this->emitGetPtrLocal(*LocalIndex, E))
3254 return false;
3255 return this->visitInitializer(E);
3256 }
3257
3258 // Otherwise,we have a primitive return value, produce the value directly
3259 // and push it on the stack.
3260 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
3261 /*NewInitializing=*/false);
3262 return this->Visit(E);
3263}
3264
3265template <class Emitter>
3267 assert(!classify(E->getType()));
3268
3269 if (E->containsErrors())
3270 return this->emitError(E);
3271
3272 if (!this->checkLiteralType(E))
3273 return false;
3274
3275 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
3276 /*NewInitializing=*/true);
3277 return this->Visit(E);
3278}
3279
3280template <class Emitter> bool Compiler<Emitter>::visitBool(const Expr *E) {
3281 std::optional<PrimType> T = classify(E->getType());
3282 if (!T) {
3283 // Convert complex values to bool.
3284 if (E->getType()->isAnyComplexType()) {
3285 if (!this->visit(E))
3286 return false;
3287 return this->emitComplexBoolCast(E);
3288 }
3289 return false;
3290 }
3291
3292 if (!this->visit(E))
3293 return false;
3294
3295 if (T == PT_Bool)
3296 return true;
3297
3298 // Convert pointers to bool.
3299 if (T == PT_Ptr || T == PT_FnPtr) {
3300 if (!this->emitNull(*T, nullptr, E))
3301 return false;
3302 return this->emitNE(*T, E);
3303 }
3304
3305 // Or Floats.
3306 if (T == PT_Float)
3307 return this->emitCastFloatingIntegralBool(E);
3308
3309 // Or anything else we can.
3310 return this->emitCast(*T, PT_Bool, E);
3311}
3312
3313template <class Emitter>
3315 const Expr *E) {
3316 switch (T) {
3317 case PT_Bool:
3318 return this->emitZeroBool(E);
3319 case PT_Sint8:
3320 return this->emitZeroSint8(E);
3321 case PT_Uint8:
3322 return this->emitZeroUint8(E);
3323 case PT_Sint16:
3324 return this->emitZeroSint16(E);
3325 case PT_Uint16:
3326 return this->emitZeroUint16(E);
3327 case PT_Sint32:
3328 return this->emitZeroSint32(E);
3329 case PT_Uint32:
3330 return this->emitZeroUint32(E);
3331 case PT_Sint64:
3332 return this->emitZeroSint64(E);
3333 case PT_Uint64:
3334 return this->emitZeroUint64(E);
3335 case PT_IntAP:
3336 return this->emitZeroIntAP(Ctx.getBitWidth(QT), E);
3337 case PT_IntAPS:
3338 return this->emitZeroIntAPS(Ctx.getBitWidth(QT), E);
3339 case PT_Ptr:
3340 return this->emitNullPtr(nullptr, E);
3341 case PT_FnPtr:
3342 return this->emitNullFnPtr(nullptr, E);
3343 case PT_MemberPtr:
3344 return this->emitNullMemberPtr(nullptr, E);
3345 case PT_Float: {
3346 return this->emitConstFloat(APFloat::getZero(Ctx.getFloatSemantics(QT)), E);
3347 }
3348 }
3349 llvm_unreachable("unknown primitive type");
3350}
3351
3352template <class Emitter>
3354 const Expr *E) {
3355 assert(E);
3356 assert(R);
3357 // Fields
3358 for (const Record::Field &Field : R->fields()) {
3359 if (Field.Decl->isUnnamedBitField())
3360 continue;
3361
3362 const Descriptor *D = Field.Desc;
3363 if (D->isPrimitive()) {
3364 QualType QT = D->getType();
3365 PrimType T = classifyPrim(D->getType());
3366 if (!this->visitZeroInitializer(T, QT, E))
3367 return false;
3368 if (!this->emitInitField(T, Field.Offset, E))
3369 return false;
3370 if (R->isUnion())
3371 break;
3372 continue;
3373 }
3374
3375 if (!this->emitGetPtrField(Field.Offset, E))
3376 return false;
3377
3378 if (D->isPrimitiveArray()) {
3379 QualType ET = D->getElemQualType();
3380 PrimType T = classifyPrim(ET);
3381 for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
3382 if (!this->visitZeroInitializer(T, ET, E))
3383 return false;
3384 if (!this->emitInitElem(T, I, E))
3385 return false;
3386 }
3387 } else if (D->isCompositeArray()) {
3388 const Record *ElemRecord = D->ElemDesc->ElemRecord;
3389 assert(D->ElemDesc->ElemRecord);
3390 for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
3391 if (!this->emitConstUint32(I, E))
3392 return false;
3393 if (!this->emitArrayElemPtr(PT_Uint32, E))
3394 return false;
3395 if (!this->visitZeroRecordInitializer(ElemRecord, E))
3396 return false;
3397 if (!this->emitPopPtr(E))
3398 return false;
3399 }
3400 } else if (D->isRecord()) {
3401 if (!this->visitZeroRecordInitializer(D->ElemRecord, E))
3402 return false;
3403 } else {
3404 assert(false);
3405 }
3406
3407 if (!this->emitFinishInitPop(E))
3408 return false;
3409
3410 if (R->isUnion())
3411 break;
3412 }
3413
3414 for (const Record::Base &B : R->bases()) {
3415 if (!this->emitGetPtrBase(B.Offset, E))
3416 return false;
3417 if (!this->visitZeroRecordInitializer(B.R, E))
3418 return false;
3419 if (!this->emitFinishInitPop(E))
3420 return false;
3421 }
3422
3423 // FIXME: Virtual bases.
3424
3425 return true;
3426}
3427
3428template <class Emitter>
3429template <typename T>
3431 switch (Ty) {
3432 case PT_Sint8:
3433 return this->emitConstSint8(Value, E);
3434 case PT_Uint8:
3435 return this->emitConstUint8(Value, E);
3436 case PT_Sint16:
3437 return this->emitConstSint16(Value, E);
3438 case PT_Uint16:
3439 return this->emitConstUint16(Value, E);
3440 case PT_Sint32:
3441 return this->emitConstSint32(Value, E);
3442 case PT_Uint32:
3443 return this->emitConstUint32(Value, E);
3444 case PT_Sint64:
3445 return this->emitConstSint64(Value, E);
3446 case PT_Uint64:
3447 return this->emitConstUint64(Value, E);
3448 case PT_Bool:
3449 return this->emitConstBool(Value, E);
3450 case PT_Ptr:
3451 case PT_FnPtr:
3452 case PT_MemberPtr:
3453 case PT_Float:
3454 case PT_IntAP:
3455 case PT_IntAPS:
3456 llvm_unreachable("Invalid integral type");
3457 break;
3458 }
3459 llvm_unreachable("unknown primitive type");
3460}
3461
3462template <class Emitter>
3463template <typename T>
3465 return this->emitConst(Value, classifyPrim(E->getType()), E);
3466}
3467
3468template <class Emitter>
3470 const Expr *E) {
3471 if (Ty == PT_IntAPS)
3472 return this->emitConstIntAPS(Value, E);
3473 if (Ty == PT_IntAP)
3474 return this->emitConstIntAP(Value, E);
3475
3476 if (Value.isSigned())
3477 return this->emitConst(Value.getSExtValue(), Ty, E);
3478 return this->emitConst(Value.getZExtValue(), Ty, E);
3479}
3480
3481template <class Emitter>
3482bool Compiler<Emitter>::emitConst(const APSInt &Value, const Expr *E) {
3483 return this->emitConst(Value, classifyPrim(E->getType()), E);
3484}
3485
3486template <class Emitter>
3488 bool IsConst,
3489 bool IsExtended) {
3490 // Make sure we don't accidentally register the same decl twice.
3491 if (const auto *VD =
3492 dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
3493 assert(!P.getGlobal(VD));
3494 assert(!Locals.contains(VD));
3495 (void)VD;
3496 }
3497
3498 // FIXME: There are cases where Src.is<Expr*>() is wrong, e.g.
3499 // (int){12} in C. Consider using Expr::isTemporaryObject() instead
3500 // or isa<MaterializeTemporaryExpr>().
3501 Descriptor *D = P.createDescriptor(Src, Ty, Descriptor::InlineDescMD, IsConst,
3502 Src.is<const Expr *>());
3503 Scope::Local Local = this->createLocal(D);
3504 if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>()))
3505 Locals.insert({VD, Local});
3506 VarScope->add(Local, IsExtended);
3507 return Local.Offset;
3508}
3509
3510template <class Emitter>
3511std::optional<unsigned>
3513 // Make sure we don't accidentally register the same decl twice.
3514 if ([[maybe_unused]] const auto *VD =
3515 dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
3516 assert(!P.getGlobal(VD));
3517 assert(!Locals.contains(VD));
3518 }
3519
3520 QualType Ty;
3521 const ValueDecl *Key = nullptr;
3522 const Expr *Init = nullptr;
3523 bool IsTemporary = false;
3524 if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
3525 Key = VD;
3526 Ty = VD->getType();
3527
3528 if (const auto *VarD = dyn_cast<VarDecl>(VD))
3529 Init = VarD->getInit();
3530 }
3531 if (auto *E = Src.dyn_cast<const Expr *>()) {
3532 IsTemporary = true;
3533 Ty = E->getType();
3534 }
3535
3536 Descriptor *D = P.createDescriptor(
3538 IsTemporary, /*IsMutable=*/false, Init);
3539 if (!D)
3540 return std::nullopt;
3541
3542 Scope::Local Local = this->createLocal(D);
3543 if (Key)
3544 Locals.insert({Key, Local});
3545 if (ExtendingDecl)
3546 VarScope->addExtended(Local, ExtendingDecl);
3547 else
3548 VarScope->add(Local, false);
3549 return Local.Offset;
3550}
3551
3552template <class Emitter>
3554 if (const PointerType *PT = dyn_cast<PointerType>(Ty))
3555 return PT->getPointeeType()->getAs<RecordType>();
3556 return Ty->getAs<RecordType>();
3557}
3558
3559template <class Emitter> Record *Compiler<Emitter>::getRecord(QualType Ty) {
3560 if (const auto *RecordTy = getRecordTy(Ty))
3561 return getRecord(RecordTy->getDecl());
3562 return nullptr;
3563}
3564
3565template <class Emitter>
3567 return P.getOrCreateRecord(RD);
3568}
3569
3570template <class Emitter>
3572 return Ctx.getOrCreateFunction(FD);
3573}
3574
3575template <class Emitter> bool Compiler<Emitter>::visitExpr(const Expr *E) {
3576 LocalScope<Emitter> RootScope(this);
3577 // Void expressions.
3578 if (E->getType()->isVoidType()) {
3579 if (!visit(E))
3580 return false;
3581 return this->emitRetVoid(E) && RootScope.destroyLocals();
3582 }
3583
3584 // Expressions with a primitive return type.
3585 if (std::optional<PrimType> T = classify(E)) {
3586 if (!visit(E))
3587 return false;
3588 return this->emitRet(*T, E) && RootScope.destroyLocals();
3589 }
3590
3591 // Expressions with a composite return type.
3592 // For us, that means everything we don't
3593 // have a PrimType for.
3594 if (std::optional<unsigned> LocalOffset = this->allocateLocal(E)) {
3595 if (!this->emitGetPtrLocal(*LocalOffset, E))
3596 return false;
3597
3598 if (!visitInitializer(E))
3599 return false;
3600
3601 if (!this->emitFinishInit(E))
3602 return false;
3603 // We are destroying the locals AFTER the Ret op.
3604 // The Ret op needs to copy the (alive) values, but the
3605 // destructors may still turn the entire expression invalid.
3606 return this->emitRetValue(E) && RootScope.destroyLocals();
3607 }
3608
3609 RootScope.destroyLocals();
3610 return false;
3611}
3612
3613template <class Emitter>
3615
3616 auto R = this->visitVarDecl(VD, /*Toplevel=*/true);
3617
3618 if (R.notCreated())
3619 return R;
3620
3621 if (R)
3622 return true;
3623
3624 if (!R && Context::shouldBeGloballyIndexed(VD)) {
3625 if (auto GlobalIndex = P.getGlobal(VD)) {
3626 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
3628 *reinterpret_cast<GlobalInlineDescriptor *>(GlobalBlock->rawData());
3629
3630 GD.InitState = GlobalInitState::InitializerFailed;
3631 GlobalBlock->invokeDtor();
3632 }
3633 }
3634
3635 return R;
3636}
3637
3638/// Toplevel visitDeclAndReturn().
3639/// We get here from evaluateAsInitializer().
3640/// We need to evaluate the initializer and return its value.
3641template <class Emitter>
3643 bool ConstantContext) {
3644 std::optional<PrimType> VarT = classify(VD->getType());
3645
3646 // We only create variables if we're evaluating in a constant context.
3647 // Otherwise, just evaluate the initializer and return it.
3648 if (!ConstantContext) {
3649 DeclScope<Emitter> LS(this, VD);
3650 if (!this->visit(VD->getAnyInitializer()))
3651 return false;
3652 return this->emitRet(VarT.value_or(PT_Ptr), VD) && LS.destroyLocals();
3653 }
3654
3655 LocalScope<Emitter> VDScope(this, VD);
3656 if (!this->visitVarDecl(VD, /*Toplevel=*/true))
3657 return false;
3658
3660 auto GlobalIndex = P.getGlobal(VD);
3661 assert(GlobalIndex); // visitVarDecl() didn't return false.
3662 if (VarT) {
3663 if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
3664 return false;
3665 } else {
3666 if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
3667 return false;
3668 }
3669 } else {
3670 auto Local = Locals.find(VD);
3671 assert(Local != Locals.end()); // Same here.
3672 if (VarT) {
3673 if (!this->emitGetLocal(*VarT, Local->second.Offset, VD))
3674 return false;
3675 } else {
3676 if (!this->emitGetPtrLocal(Local->second.Offset, VD))
3677 return false;
3678 }
3679 }
3680
3681 // Return the value.
3682 if (!this->emitRet(VarT.value_or(PT_Ptr), VD)) {
3683 // If the Ret above failed and this is a global variable, mark it as
3684 // uninitialized, even everything else succeeded.
3686 auto GlobalIndex = P.getGlobal(VD);
3687 assert(GlobalIndex);
3688 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
3690 *reinterpret_cast<GlobalInlineDescriptor *>(GlobalBlock->rawData());
3691
3692 GD.InitState = GlobalInitState::InitializerFailed;
3693 GlobalBlock->invokeDtor();
3694 }
3695 return false;
3696 }
3697
3698 return VDScope.destroyLocals();
3699}
3700
3701template <class Emitter>
3703 // We don't know what to do with these, so just return false.
3704 if (VD->getType().isNull())
3705 return false;
3706
3707 // This case is EvalEmitter-only. If we won't create any instructions for the
3708 // initializer anyway, don't bother creating the variable in the first place.
3709 if (!this->isActive())
3711
3712 const Expr *Init = VD->getInit();
3713 std::optional<PrimType> VarT = classify(VD->getType());
3714
3715 if (Init && Init->isValueDependent())
3716 return false;
3717
3719 auto checkDecl = [&]() -> bool {
3720 bool NeedsOp = !Toplevel && VD->isLocalVarDecl() && VD->isStaticLocal();
3721 return !NeedsOp || this->emitCheckDecl(VD, VD);
3722 };
3723
3724 auto initGlobal = [&](unsigned GlobalIndex) -> bool {
3725 assert(Init);
3727
3728 if (VarT) {
3729 if (!this->visit(Init))
3730 return checkDecl() && false;
3731
3732 return checkDecl() && this->emitInitGlobal(*VarT, GlobalIndex, VD);
3733 }
3734
3735 if (!checkDecl())
3736 return false;
3737
3738 if (!this->emitGetPtrGlobal(GlobalIndex, Init))
3739 return false;
3740
3741 if (!visitInitializer(Init))
3742 return false;
3743
3744 if (!this->emitFinishInit(Init))
3745 return false;
3746
3747 return this->emitPopPtr(Init);
3748 };
3749
3750 // We've already seen and initialized this global.
3751 if (std::optional<unsigned> GlobalIndex = P.getGlobal(VD)) {
3752 if (P.getPtrGlobal(*GlobalIndex).isInitialized())
3753 return checkDecl();
3754
3755 // The previous attempt at initialization might've been unsuccessful,
3756 // so let's try this one.
3757 return Init && checkDecl() && initGlobal(*GlobalIndex);
3758 }
3759
3760 std::optional<unsigned> GlobalIndex = P.createGlobal(VD, Init);
3761
3762 if (!GlobalIndex)
3763 return false;
3764
3765 return !Init || (checkDecl() && initGlobal(*GlobalIndex));
3766 } else {
3768
3769 if (VarT) {
3770 unsigned Offset = this->allocateLocalPrimitive(
3771 VD, *VarT, VD->getType().isConstQualified());
3772 if (Init) {
3773 // If this is a toplevel declaration, create a scope for the
3774 // initializer.
3775 if (Toplevel) {
3777 if (!this->visit(Init))
3778 return false;
3779 return this->emitSetLocal(*VarT, Offset, VD) && Scope.destroyLocals();
3780 } else {
3781 if (!this->visit(Init))
3782 return false;
3783 return this->emitSetLocal(*VarT, Offset, VD);
3784 }
3785 }
3786 } else {
3787 if (std::optional<unsigned> Offset = this->allocateLocal(VD)) {
3788 if (!Init)
3789 return true;
3790
3791 if (!this->emitGetPtrLocal(*Offset, Init))
3792 return false;
3793
3794 if (!visitInitializer(Init))
3795 return false;
3796
3797 if (!this->emitFinishInit(Init))
3798 return false;
3799
3800 return this->emitPopPtr(Init);
3801 }
3802 return false;
3803 }
3804 return true;
3805 }
3806
3807 return false;
3808}
3809
3810template <class Emitter>
3812 const Expr *E) {
3813 assert(!DiscardResult);
3814 if (Val.isInt())
3815 return this->emitConst(Val.getInt(), ValType, E);
3816 else if (Val.isFloat())
3817 return this->emitConstFloat(Val.getFloat(), E);
3818
3819 if (Val.isLValue()) {
3820 if (Val.isNullPointer())
3821 return this->emitNull(ValType, nullptr, E);
3823 if (const Expr *BaseExpr = Base.dyn_cast<const Expr *>())
3824 return this->visit(BaseExpr);
3825 else if (const auto *VD = Base.dyn_cast<const ValueDecl *>()) {
3826 return this->visitDeclRef(VD, E);
3827 }
3828 } else if (Val.isMemberPointer()) {
3829 if (const ValueDecl *MemberDecl = Val.getMemberPointerDecl())
3830 return this->emitGetMemberPtr(MemberDecl, E);
3831 return this->emitNullMemberPtr(nullptr, E);
3832 }
3833
3834 return false;
3835}
3836
3837template <class Emitter>
3839 const Expr *E) {
3840
3841 if (Val.isStruct()) {
3842 const Record *R = this->getRecord(E->getType());
3843 assert(R);
3844 for (unsigned I = 0, N = Val.getStructNumFields(); I != N; ++I) {
3845 const APValue &F = Val.getStructField(I);
3846 const Record::Field *RF = R->getField(I);
3847
3848 if (F.isInt() || F.isFloat() || F.isLValue() || F.isMemberPointer()) {
3849 PrimType T = classifyPrim(RF->Decl->getType());
3850 if (!this->visitAPValue(F, T, E))
3851 return false;
3852 if (!this->emitInitField(T, RF->Offset, E))
3853 return false;
3854 } else if (F.isArray()) {
3855 assert(RF->Desc->isPrimitiveArray());
3856 const auto *ArrType = RF->Decl->getType()->getAsArrayTypeUnsafe();
3857 PrimType ElemT = classifyPrim(ArrType->getElementType());
3858 assert(ArrType);
3859
3860 if (!this->emitGetPtrField(RF->Offset, E))
3861 return false;
3862
3863 for (unsigned A = 0, AN = F.getArraySize(); A != AN; ++A) {
3864 if (!this->visitAPValue(F.getArrayInitializedElt(A), ElemT, E))
3865 return false;
3866 if (!this->emitInitElem(ElemT, A, E))
3867 return false;
3868 }
3869
3870 if (!this->emitPopPtr(E))
3871 return false;
3872 } else if (F.isStruct() || F.isUnion()) {
3873 if (!this->emitGetPtrField(RF->Offset, E))
3874 return false;
3875 if (!this->visitAPValueInitializer(F, E))
3876 return false;
3877 if (!this->emitPopPtr(E))
3878 return false;
3879 } else {
3880 assert(false && "I don't think this should be possible");
3881 }
3882 }
3883 return true;
3884 } else if (Val.isUnion()) {
3885 const FieldDecl *UnionField = Val.getUnionField();
3886 const Record *R = this->getRecord(UnionField->getParent());
3887 assert(R);
3888 const APValue &F = Val.getUnionValue();
3889 const Record::Field *RF = R->getField(UnionField);
3890 PrimType T = classifyPrim(RF->Decl->getType());
3891 if (!this->visitAPValue(F, T, E))
3892 return false;
3893 return this->emitInitField(T, RF->Offset, E);
3894 }
3895 // TODO: Other types.
3896
3897 return false;
3898}
3899
3900template <class Emitter>
3902 const Function *Func = getFunction(E->getDirectCallee());
3903 if (!Func)
3904 return false;
3905
3906 // For these, we're expected to ultimately return an APValue pointing
3907 // to the CallExpr. This is needed to get the correct codegen.
3908 unsigned Builtin = E->getBuiltinCallee();
3909 if (Builtin == Builtin::BI__builtin___CFStringMakeConstantString ||
3910 Builtin == Builtin::BI__builtin___NSStringMakeConstantString ||
3911 Builtin == Builtin::BI__builtin_ptrauth_sign_constant ||
3912 Builtin == Builtin::BI__builtin_function_start) {
3913 if (std::optional<unsigned> GlobalOffset = P.createGlobal(E)) {
3914 if (!this->emitGetPtrGlobal(*GlobalOffset, E))
3915 return false;
3916
3917 if (PrimType PT = classifyPrim(E); PT != PT_Ptr && isPtrType(PT))
3918 return this->emitDecayPtr(PT_Ptr, PT, E);
3919 return true;
3920 }
3921 return false;
3922 }
3923
3924 QualType ReturnType = E->getType();
3925 std::optional<PrimType> ReturnT = classify(E);
3926
3927 // Non-primitive return type. Prepare storage.
3928 if (!Initializing && !ReturnT && !ReturnType->isVoidType()) {
3929 std::optional<unsigned> LocalIndex = allocateLocal(E);
3930 if (!LocalIndex)
3931 return false;
3932 if (!this->emitGetPtrLocal(*LocalIndex, E))
3933 return false;
3934 }
3935
3936 if (!Func->isUnevaluatedBuiltin()) {
3937 // Put arguments on the stack.
3938 for (const auto *Arg : E->arguments()) {
3939 if (!this->visit(Arg))
3940 return false;
3941 }
3942 }
3943
3944 if (!this->emitCallBI(Func, E, E))
3945 return false;
3946
3947 if (DiscardResult && !ReturnType->isVoidType()) {
3948 assert(ReturnT);
3949 return this->emitPop(*ReturnT, E);
3950 }
3951
3952 return true;
3953}
3954
3955template <class Emitter>
3957 if (E->getBuiltinCallee())
3958 return VisitBuiltinCallExpr(E);
3959
3960 QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
3961 std::optional<PrimType> T = classify(ReturnType);
3962 bool HasRVO = !ReturnType->isVoidType() && !T;
3963 const FunctionDecl *FuncDecl = E->getDirectCallee();
3964
3965 if (HasRVO) {
3966 if (DiscardResult) {
3967 // If we need to discard the return value but the function returns its
3968 // value via an RVO pointer, we need to create one such pointer just
3969 // for this call.
3970 if (std::optional<unsigned> LocalIndex = allocateLocal(E)) {
3971 if (!this->emitGetPtrLocal(*LocalIndex, E))
3972 return false;
3973 }
3974 } else {
3975 // We need the result. Prepare a pointer to return or
3976 // dup the current one.
3977 if (!Initializing) {
3978 if (std::optional<unsigned> LocalIndex = allocateLocal(E)) {
3979 if (!this->emitGetPtrLocal(*LocalIndex, E))
3980 return false;
3981 }
3982 }
3983 if (!this->emitDupPtr(E))
3984 return false;
3985 }
3986 }
3987
3989 llvm::ArrayRef(E->getArgs(), E->getNumArgs()));
3990
3991 bool IsAssignmentOperatorCall = false;
3992 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
3993 OCE && OCE->isAssignmentOp()) {
3994 // Just like with regular assignments, we need to special-case assignment
3995 // operators here and evaluate the RHS (the second arg) before the LHS (the
3996 // first arg. We fix this by using a Flip op later.
3997 assert(Args.size() == 2);
3998 IsAssignmentOperatorCall = true;
3999 std::reverse(Args.begin(), Args.end());
4000 }
4001 // Calling a static operator will still
4002 // pass the instance, but we don't need it.
4003 // Discard it here.
4004 if (isa<CXXOperatorCallExpr>(E)) {
4005 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl);
4006 MD && MD->isStatic()) {
4007 if (!this->discard(E->getArg(0)))
4008 return false;
4009 // Drop first arg.
4010 Args.erase(Args.begin());
4011 }
4012 }
4013
4014 std::optional<unsigned> CalleeOffset;
4015 // Add the (optional, implicit) This pointer.
4016 if (const auto *MC = dyn_cast<CXXMemberCallExpr>(E)) {
4017 if (!FuncDecl && classifyPrim(E->getCallee()) == PT_MemberPtr) {
4018 // If we end up creating a CallPtr op for this, we need the base of the
4019 // member pointer as the instance pointer, and later extract the function
4020 // decl as the function pointer.
4021 const Expr *Callee = E->getCallee();
4022 CalleeOffset =
4023 this->allocateLocalPrimitive(Callee, PT_MemberPtr, true, false);
4024 if (!this->visit(Callee))
4025 return false;
4026 if (!this->emitSetLocal(PT_MemberPtr, *CalleeOffset, E))
4027 return false;
4028 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
4029 return false;
4030 if (!this->emitGetMemberPtrBase(E))
4031 return false;
4032 } else if (!this->visit(MC->getImplicitObjectArgument())) {
4033 return false;
4034 }
4035 } else if (!FuncDecl) {
4036 const Expr *Callee = E->getCallee();
4037 CalleeOffset = this->allocateLocalPrimitive(Callee, PT_FnPtr, true, false);
4038 if (!this->visit(Callee))
4039 return false;
4040 if (!this->emitSetLocal(PT_FnPtr, *CalleeOffset, E))
4041 return false;
4042 }
4043
4044 llvm::BitVector NonNullArgs = collectNonNullArgs(FuncDecl, Args);
4045 // Put arguments on the stack.
4046 unsigned ArgIndex = 0;
4047 for (const auto *Arg : Args) {
4048 if (!this->visit(Arg))
4049 return false;
4050
4051 // If we know the callee already, check the known parametrs for nullability.
4052 if (FuncDecl && NonNullArgs[ArgIndex]) {
4053 PrimType ArgT = classify(Arg).value_or(PT_Ptr);
4054 if (ArgT == PT_Ptr || ArgT == PT_FnPtr) {
4055 if (!this->emitCheckNonNullArg(ArgT, Arg))
4056 return false;
4057 }
4058 }
4059 ++ArgIndex;
4060 }
4061
4062 // Undo the argument reversal we did earlier.
4063 if (IsAssignmentOperatorCall) {
4064 assert(Args.size() == 2);
4065 PrimType Arg1T = classify(Args[0]).value_or(PT_Ptr);
4066 PrimType Arg2T = classify(Args[1]).value_or(PT_Ptr);
4067 if (!this->emitFlip(Arg2T, Arg1T, E))
4068 return false;
4069 }
4070
4071 if (FuncDecl) {
4072 const Function *Func = getFunction(FuncDecl);
4073 if (!Func)
4074 return false;
4075 assert(HasRVO == Func->hasRVO());
4076
4077 bool HasQualifier = false;
4078 if (const auto *ME = dyn_cast<MemberExpr>(E->getCallee()))
4079 HasQualifier = ME->hasQualifier();
4080
4081 bool IsVirtual = false;
4082 if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl))
4083 IsVirtual = MD->isVirtual();
4084
4085 // In any case call the function. The return value will end up on the stack
4086 // and if the function has RVO, we already have the pointer on the stack to
4087 // write the result into.
4088 if (IsVirtual && !HasQualifier) {
4089 uint32_t VarArgSize = 0;
4090 unsigned NumParams =
4091 Func->getNumWrittenParams() + isa<CXXOperatorCallExpr>(E);
4092 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
4093 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
4094
4095 if (!this->emitCallVirt(Func, VarArgSize, E))
4096 return false;
4097 } else if (Func->isVariadic()) {
4098 uint32_t VarArgSize = 0;
4099 unsigned NumParams =
4100 Func->getNumWrittenParams() + isa<CXXOperatorCallExpr>(E);
4101 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
4102 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
4103 if (!this->emitCallVar(Func, VarArgSize, E))
4104 return false;
4105 } else {
4106 if (!this->emitCall(Func, 0, E))
4107 return false;
4108 }
4109 } else {
4110 // Indirect call. Visit the callee, which will leave a FunctionPointer on
4111 // the stack. Cleanup of the returned value if necessary will be done after
4112 // the function call completed.
4113
4114 // Sum the size of all args from the call expr.
4115 uint32_t ArgSize = 0;
4116 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
4117 ArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
4118
4119 // Get the callee, either from a member pointer or function pointer saved in
4120 // CalleeOffset.
4121 if (isa<CXXMemberCallExpr>(E) && CalleeOffset) {
4122 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
4123 return false;
4124 if (!this->emitGetMemberPtrDecl(E))
4125 return false;
4126 } else {
4127 if (!this->emitGetLocal(PT_FnPtr, *CalleeOffset, E))
4128 return false;
4129 }
4130 if (!this->emitCallPtr(ArgSize, E, E))
4131 return false;
4132 }
4133
4134 // Cleanup for discarded return values.
4135 if (DiscardResult && !ReturnType->isVoidType() && T)
4136 return this->emitPop(*T, E);
4137
4138 return true;
4139}
4140
4141template <class Emitter>
4143 SourceLocScope<Emitter> SLS(this, E);
4144
4145 return this->delegate(E->getExpr());
4146}
4147
4148template <class Emitter>
4150 SourceLocScope<Emitter> SLS(this, E);
4151
4152 const Expr *SubExpr = E->getExpr();
4153 if (std::optional<PrimType> T = classify(E->getExpr()))
4154 return this->visit(SubExpr);
4155
4156 assert(Initializing);
4157 return this->visitInitializer(SubExpr);
4158}
4159
4160template <class Emitter>
4162 if (DiscardResult)
4163 return true;
4164
4165 return this->emitConstBool(E->getValue(), E);
4166}
4167
4168template <class Emitter>
4170 const CXXNullPtrLiteralExpr *E) {
4171 if (DiscardResult)
4172 return true;
4173
4174 return this->emitNullPtr(nullptr, E);
4175}
4176
4177template <class Emitter>
4179 if (DiscardResult)
4180 return true;
4181
4182 assert(E->getType()->isIntegerType());
4183
4184 PrimType T = classifyPrim(E->getType());
4185 return this->emitZero(T, E);
4186}
4187
4188template <class Emitter>
4190 if (DiscardResult)
4191 return true;
4192
4193 if (this->LambdaThisCapture.Offset > 0) {
4194 if (this->LambdaThisCapture.IsPtr)
4195 return this->emitGetThisFieldPtr(this->LambdaThisCapture.Offset, E);
4196 return this->emitGetPtrThisField(this->LambdaThisCapture.Offset, E);
4197 }
4198
4199 // In some circumstances, the 'this' pointer does not actually refer to the
4200 // instance pointer of the current function frame, but e.g. to the declaration
4201 // currently being initialized. Here we emit the necessary instruction(s) for
4202 // this scenario.
4203 if (!InitStackActive || !E->isImplicit())
4204 return this->emitThis(E);
4205
4206 if (InitStackActive && !InitStack.empty()) {
4207 unsigned StartIndex = 0;
4208 for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) {
4209 if (InitStack[StartIndex].Kind != InitLink::K_Field &&
4210 InitStack[StartIndex].Kind != InitLink::K_Elem)
4211 break;
4212 }
4213
4214 for (unsigned I = StartIndex, N = InitStack.size(); I != N; ++I) {
4215 if (!InitStack[I].template emit<Emitter>(this, E))
4216 return false;
4217 }
4218 return true;
4219 }
4220 return this->emitThis(E);
4221}
4222
4223template <class Emitter> bool Compiler<Emitter>::visitStmt(const Stmt *S) {
4224 switch (S->getStmtClass()) {
4225 case Stmt::CompoundStmtClass:
4226 return visitCompoundStmt(cast<CompoundStmt>(S));
4227 case Stmt::DeclStmtClass:
4228 return visitDeclStmt(cast<DeclStmt>(S));
4229 case Stmt::ReturnStmtClass:
4230 return visitReturnStmt(cast<ReturnStmt>(S));
4231 case Stmt::IfStmtClass:
4232 return visitIfStmt(cast<IfStmt>(S));
4233 case Stmt::WhileStmtClass:
4234 return visitWhileStmt(cast<WhileStmt>(S));
4235 case Stmt::DoStmtClass:
4236 return visitDoStmt(cast<DoStmt>(S));
4237 case Stmt::ForStmtClass:
4238 return visitForStmt(cast<ForStmt>(S));
4239 case Stmt::CXXForRangeStmtClass:
4240 return visitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
4241 case Stmt::BreakStmtClass:
4242 return visitBreakStmt(cast<BreakStmt>(S));
4243 case Stmt::ContinueStmtClass:
4244 return visitContinueStmt(cast<ContinueStmt>(S));
4245 case Stmt::SwitchStmtClass:
4246 return visitSwitchStmt(cast<SwitchStmt>(S));
4247 case Stmt::CaseStmtClass:
4248 return visitCaseStmt(cast<CaseStmt>(S));
4249 case Stmt::DefaultStmtClass:
4250 return visitDefaultStmt(cast<DefaultStmt>(S));
4251 case Stmt::AttributedStmtClass:
4252 return visitAttributedStmt(cast<AttributedStmt>(S));
4253 case Stmt::CXXTryStmtClass:
4254 return visitCXXTryStmt(cast<CXXTryStmt>(S));
4255 case Stmt::NullStmtClass:
4256 return true;
4257 // Always invalid statements.
4258 case Stmt::GCCAsmStmtClass:
4259 case Stmt::MSAsmStmtClass:
4260 case Stmt::GotoStmtClass:
4261 return this->emitInvalid(S);
4262 case Stmt::LabelStmtClass:
4263 return this->visitStmt(cast<LabelStmt>(S)->getSubStmt());
4264 default: {
4265 if (const auto *E = dyn_cast<Expr>(S))
4266 return this->discard(E);
4267 return false;
4268 }
4269 }
4270}
4271
4272template <class Emitter>
4275 for (const auto *InnerStmt : S->body())
4276 if (!visitStmt(InnerStmt))
4277 return false;
4278 return Scope.destroyLocals();
4279}
4280
4281template <class Emitter>
4283 for (const auto *D : DS->decls()) {
4285 FunctionDecl>(D))
4286 continue;
4287
4288 const auto *VD = dyn_cast<VarDecl>(D);
4289 if (!VD)
4290 return false;
4291 if (!this->visitVarDecl(VD))
4292 return false;
4293 }
4294
4295 return true;
4296}
4297
4298template <class Emitter>
4300 if (this->InStmtExpr)
4301 return this->emitUnsupported(RS);
4302
4303 if (const Expr *RE = RS->getRetValue()) {
4304 LocalScope<Emitter> RetScope(this);
4305 if (ReturnType) {
4306 // Primitive types are simply returned.
4307 if (!this->visit(RE))
4308 return false;
4309 this->emitCleanup();
4310 return this->emitRet(*ReturnType, RS);
4311 } else if (RE->getType()->isVoidType()) {
4312 if (!this->visit(RE))
4313 return false;
4314 } else {
4315 // RVO - construct the value in the return location.
4316 if (!this->emitRVOPtr(RE))
4317 return false;
4318 if (!this->visitInitializer(RE))
4319 return false;
4320 if (!this->emitPopPtr(RE))
4321 return false;
4322
4323 this->emitCleanup();
4324 return this->emitRetVoid(RS);
4325 }
4326 }
4327
4328 // Void return.
4329 this->emitCleanup();
4330 return this->emitRetVoid(RS);
4331}
4332
4333template <class Emitter> bool Compiler<Emitter>::visitIfStmt(const IfStmt *IS) {
4334 if (IS->isNonNegatedConsteval())
4335 return visitStmt(IS->getThen());
4336 if (IS->isNegatedConsteval())
4337 return IS->getElse() ? visitStmt(IS->getElse()) : true;
4338
4339 if (auto *CondInit = IS->getInit())
4340 if (!visitStmt(CondInit))
4341 return false;
4342
4343 if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt())
4344 if (!visitDeclStmt(CondDecl))
4345 return false;
4346
4347 if (!this->visitBool(IS->getCond()))
4348 return false;
4349
4350 if (const Stmt *Else = IS->getElse()) {
4351 LabelTy LabelElse = this->getLabel();
4352 LabelTy LabelEnd = this->getLabel();
4353 if (!this->jumpFalse(LabelElse))
4354 return false;
4355 if (!visitStmt(IS->getThen()))
4356 return false;
4357 if (!this->jump(LabelEnd))
4358 return false;
4359 this->emitLabel(LabelElse);
4360 if (!visitStmt(Else))
4361 return false;
4362 this->emitLabel(LabelEnd);
4363 } else {
4364 LabelTy LabelEnd = this->getLabel();
4365 if (!this->jumpFalse(LabelEnd))
4366 return false;
4367 if (!visitStmt(IS->getThen()))
4368 return false;
4369 this->emitLabel(LabelEnd);
4370 }
4371
4372 return true;
4373}
4374
4375template <class Emitter>
4377 const Expr *Cond = S->getCond();
4378 const Stmt *Body = S->getBody();
4379
4380 LabelTy CondLabel = this->getLabel(); // Label before the condition.
4381 LabelTy EndLabel = this->getLabel(); // Label after the loop.
4382 LoopScope<Emitter> LS(this, EndLabel, CondLabel);
4383
4384 this->fallthrough(CondLabel);
4385 this->emitLabel(CondLabel);
4386
4387 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
4388 if (!visitDeclStmt(CondDecl))
4389 return false;
4390
4391 if (!this->visitBool(Cond))
4392 return false;
4393 if (!this->jumpFalse(EndLabel))
4394 return false;
4395
4396 if (!this->visitStmt(Body))
4397 return false;
4398
4399 if (!this->jump(CondLabel))
4400 return false;
4401 this->fallthrough(EndLabel);
4402 this->emitLabel(EndLabel);
4403
4404 return true;
4405}
4406
4407template <class Emitter> bool Compiler<Emitter>::visitDoStmt(const DoStmt *S) {
4408 const Expr *Cond = S->getCond();
4409 const Stmt *Body = S->getBody();
4410
4411 LabelTy StartLabel = this->getLabel();
4412 LabelTy EndLabel = this->getLabel();
4413 LabelTy CondLabel = this->getLabel();
4414 LoopScope<Emitter> LS(this, EndLabel, CondLabel);
4415
4416 this->fallthrough(StartLabel);
4417 this->emitLabel(StartLabel);
4418 {
4419 if (!this->visitStmt(Body))
4420 return false;
4421 this->fallthrough(CondLabel);
4422 this->emitLabel(CondLabel);
4423 if (!this->visitBool(Cond))
4424 return false;
4425 }
4426 if (!this->jumpTrue(StartLabel))
4427 return false;
4428
4429 this->fallthrough(EndLabel);
4430 this->emitLabel(EndLabel);
4431 return true;
4432}
4433
4434template <class Emitter>
4436 // for (Init; Cond; Inc) { Body }
4437 const Stmt *Init = S->getInit();
4438 const Expr *Cond = S->getCond();
4439 const Expr *Inc = S->getInc();
4440 const Stmt *Body = S->getBody();
4441
4442 LabelTy EndLabel = this->getLabel();
4443 LabelTy CondLabel = this->getLabel();
4444 LabelTy IncLabel = this->getLabel();
4445 LoopScope<Emitter> LS(this, EndLabel, IncLabel);
4446
4447 if (Init && !this->visitStmt(Init))
4448 return false;
4449
4450 this->fallthrough(CondLabel);
4451 this->emitLabel(CondLabel);
4452
4453 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
4454 if (!visitDeclStmt(CondDecl))
4455 return false;
4456
4457 if (Cond) {
4458 if (!this->visitBool(Cond))
4459 return false;
4460 if (!this->jumpFalse(EndLabel))
4461 return false;
4462 }
4463
4464 {
4465 if (Body && !this->visitStmt(Body))
4466 return false;
4467
4468 this->fallthrough(IncLabel);
4469 this->emitLabel(IncLabel);
4470 if (Inc && !this->discard(Inc))
4471 return false;
4472 }
4473
4474 if (!this->jump(CondLabel))
4475 return false;
4476 this->fallthrough(EndLabel);
4477 this->emitLabel(EndLabel);
4478 return true;
4479}
4480
4481template <class Emitter>
4483 const Stmt *Init = S->getInit();
4484 const Expr *Cond = S->getCond();
4485 const Expr *Inc = S->getInc();
4486 const Stmt *Body = S->getBody();
4487 const Stmt *BeginStmt = S->getBeginStmt();
4488 const Stmt *RangeStmt = S->getRangeStmt();
4489 const Stmt *EndStmt = S->getEndStmt();
4490 const VarDecl *LoopVar = S->getLoopVariable();
4491
4492 LabelTy EndLabel = this->getLabel();
4493 LabelTy CondLabel = this->getLabel();
4494 LabelTy IncLabel = this->getLabel();
4495 LoopScope<Emitter> LS(this, EndLabel, IncLabel);
4496
4497 // Emit declarations needed in the loop.
4498 if (Init && !this->visitStmt(Init))
4499 return false;
4500 if (!this->visitStmt(RangeStmt))
4501 return false;
4502 if (!this->visitStmt(BeginStmt))
4503 return false;
4504 if (!this->visitStmt(EndStmt))
4505 return false;
4506
4507 // Now the condition as well as the loop variable assignment.
4508 this->fallthrough(CondLabel);
4509 this->emitLabel(CondLabel);
4510 if (!this->visitBool(Cond))
4511 return false;
4512 if (!this->jumpFalse(EndLabel))
4513 return false;
4514
4515 if (!this->visitVarDecl(LoopVar))
4516 return false;
4517
4518 // Body.
4519 {
4520 if (!this->visitStmt(Body))
4521 return false;
4522
4523 this->fallthrough(IncLabel);
4524 this->emitLabel(IncLabel);
4525 if (!this->discard(Inc))
4526 return false;
4527 }
4528
4529 if (!this->jump(CondLabel))
4530 return false;
4531
4532 this->fallthrough(EndLabel);
4533 this->emitLabel(EndLabel);
4534 return true;
4535}
4536
4537template <class Emitter>
4539 if (!BreakLabel)
4540 return false;
4541
4542 this->emitCleanup();
4543 return this->jump(*BreakLabel);
4544}
4545
4546template <class Emitter>
4548 if (!ContinueLabel)
4549 return false;
4550
4551 this->emitCleanup();
4552 return this->jump(*ContinueLabel);
4553}
4554
4555template <class Emitter>
4557 const Expr *Cond = S->getCond();
4558 PrimType CondT = this->classifyPrim(Cond->getType());
4559
4560 LabelTy EndLabel = this->getLabel();
4561 OptLabelTy DefaultLabel = std::nullopt;
4562 unsigned CondVar = this->allocateLocalPrimitive(Cond, CondT, true, false);
4563
4564 if (const auto *CondInit = S->getInit())
4565 if (!visitStmt(CondInit))
4566 return false;
4567
4568 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
4569 if (!visitDeclStmt(CondDecl))
4570 return false;
4571
4572 // Initialize condition variable.
4573 if (!this->visit(Cond))
4574 return false;
4575 if (!this->emitSetLocal(CondT, CondVar, S))
4576 return false;
4577
4578 CaseMap CaseLabels;
4579 // Create labels and comparison ops for all case statements.
4580 for (const SwitchCase *SC = S->getSwitchCaseList(); SC;
4581 SC = SC->getNextSwitchCase()) {
4582 if (const auto *CS = dyn_cast<CaseStmt>(SC)) {
4583 // FIXME: Implement ranges.
4584 if (CS->caseStmtIsGNURange())
4585 return false;
4586 CaseLabels[SC] = this->getLabel();
4587
4588 const Expr *Value = CS->getLHS();
4589 PrimType ValueT = this->classifyPrim(Value->getType());
4590
4591 // Compare the case statement's value to the switch condition.
4592 if (!this->emitGetLocal(CondT, CondVar, CS))
4593 return false;
4594 if (!this->visit(Value))
4595 return false;
4596
4597 // Compare and jump to the case label.
4598 if (!this->emitEQ(ValueT, S))
4599 return false;
4600 if (!this->jumpTrue(CaseLabels[CS]))
4601 return false;
4602 } else {
4603 assert(!DefaultLabel);
4604 DefaultLabel = this->getLabel();
4605 }
4606 }
4607
4608 // If none of the conditions above were true, fall through to the default
4609 // statement or jump after the switch statement.
4610 if (DefaultLabel) {
4611 if (!this->jump(*DefaultLabel))
4612 return false;
4613 } else {
4614 if (!this->jump(EndLabel))
4615 return false;
4616 }
4617
4618 SwitchScope<Emitter> SS(this, std::move(CaseLabels), EndLabel, DefaultLabel);
4619 if (!this->visitStmt(S->getBody()))
4620 return false;
4621 this->emitLabel(EndLabel);
4622 return true;
4623}
4624
4625template <class Emitter>
4627 this->emitLabel(CaseLabels[S]);
4628 return this->visitStmt(S->getSubStmt());
4629}
4630
4631template <class Emitter>
4633 this->emitLabel(*DefaultLabel);
4634 return this->visitStmt(S->getSubStmt());
4635}
4636
4637template <class Emitter>
4639 if (this->Ctx.getLangOpts().CXXAssumptions &&
4640 !this->Ctx.getLangOpts().MSVCCompat) {
4641 for (const Attr *A : S->getAttrs()) {
4642 auto *AA = dyn_cast<CXXAssumeAttr>(A);
4643 if (!AA)
4644 continue;
4645
4646 assert(isa<NullStmt>(S->getSubStmt()));
4647
4648 const Expr *Assumption = AA->getAssumption();
4649 if (Assumption->isValueDependent())
4650 return false;
4651
4652 if (Assumption->HasSideEffects(this->Ctx.getASTContext()))
4653 continue;
4654
4655 // Evaluate assumption.
4656 if (!this->visitBool(Assumption))
4657 return false;
4658
4659 if (!this->emitAssume(Assumption))
4660 return false;
4661 }
4662 }
4663
4664 // Ignore other attributes.
4665 return this->visitStmt(S->getSubStmt());
4666}
4667
4668template <class Emitter>
4670 // Ignore all handlers.
4671 return this->visitStmt(S->getTryBlock());
4672}
4673
4674template <class Emitter>
4676 assert(MD->isLambdaStaticInvoker());
4677 assert(MD->hasBody());
4678 assert(cast<CompoundStmt>(MD->getBody())->body_empty());
4679
4680 const CXXRecordDecl *ClosureClass = MD->getParent();
4681 const CXXMethodDecl *LambdaCallOp = ClosureClass->getLambdaCallOperator();
4682 assert(ClosureClass->captures_begin() == ClosureClass->captures_end());
4683 const Function *Func = this->getFunction(LambdaCallOp);
4684 if (!Func)
4685 return false;
4686 assert(Func->hasThisPointer());
4687 assert(Func->getNumParams() == (MD->getNumParams() + 1 + Func->hasRVO()));
4688
4689 if (Func->hasRVO()) {
4690 if (!this->emitRVOPtr(MD))
4691 return false;
4692 }
4693
4694 // The lambda call operator needs an instance pointer, but we don't have
4695 // one here, and we don't need one either because the lambda cannot have
4696 // any captures, as verified above. Emit a null pointer. This is then
4697 // special-cased when interpreting to not emit any misleading diagnostics.
4698 if (!this->emitNullPtr(nullptr, MD))
4699 return false;
4700
4701 // Forward all arguments from the static invoker to the lambda call operator.
4702 for (const ParmVarDecl *PVD : MD->parameters()) {
4703 auto It = this->Params.find(PVD);
4704 assert(It != this->Params.end());
4705
4706 // We do the lvalue-to-rvalue conversion manually here, so no need
4707 // to care about references.
4708 PrimType ParamType = this->classify(PVD->getType()).value_or(PT_Ptr);
4709 if (!this->emitGetParam(ParamType, It->second.Offset, MD))
4710 return false;
4711 }
4712
4713 if (!this->emitCall(Func, 0, LambdaCallOp))
4714 return false;
4715
4716 this->emitCleanup();
4717 if (ReturnType)
4718 return this->emitRet(*ReturnType, MD);
4719
4720 // Nothing to do, since we emitted the RVO pointer above.
4721 return this->emitRetVoid(MD);
4722}
4723
4724template <class Emitter>
4726 if (Ctx.getLangOpts().CPlusPlus23)
4727 return true;
4728
4729 if (!E->isPRValue() || E->getType()->isLiteralType(Ctx.getASTContext()))
4730 return true;
4731
4732 return this->emitCheckLiteralType(E->getType().getTypePtr(), E);
4733}
4734
4735template <class Emitter>
4737 // Classify the return type.
4738 ReturnType = this->classify(F->getReturnType());
4739
4740 auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset,
4741 const Expr *InitExpr) -> bool {
4742 // We don't know what to do with these, so just return false.
4743 if (InitExpr->getType().isNull())
4744 return false;
4745
4746 if (std::optional<PrimType> T = this->classify(InitExpr)) {
4747 if (!this->visit(InitExpr))
4748 return false;
4749
4750 if (F->isBitField())
4751 return this->emitInitThisBitField(*T, F, FieldOffset, InitExpr);
4752 return this->emitInitThisField(*T, FieldOffset, InitExpr);
4753 }
4754 // Non-primitive case. Get a pointer to the field-to-initialize
4755 // on the stack and call visitInitialzer() for it.
4756 InitLinkScope<Emitter> FieldScope(this, InitLink::Field(F->Offset));
4757 if (!this->emitGetPtrThisField(FieldOffset, InitExpr))
4758 return false;
4759
4760 if (!this->visitInitializer(InitExpr))
4761 return false;
4762
4763 return this->emitFinishInitPop(InitExpr);
4764 };
4765
4766 // Emit custom code if this is a lambda static invoker.
4767 if (const auto *MD = dyn_cast<CXXMethodDecl>(F);
4768 MD && MD->isLambdaStaticInvoker())
4769 return this->emitLambdaStaticInvokerBody(MD);
4770
4771 // Constructor. Set up field initializers.
4772 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F)) {
4773 const RecordDecl *RD = Ctor->getParent();
4774 const Record *R = this->getRecord(RD);
4775 if (!R)
4776 return false;
4777
4778 if (R->isUnion() && Ctor->isCopyOrMoveConstructor()) {
4779 // union copy and move ctors are special.
4780 assert(cast<CompoundStmt>(Ctor->getBody())->body_empty());
4781 if (!this->emitThis(Ctor))
4782 return false;
4783
4784 auto PVD = Ctor->getParamDecl(0);
4785 ParamOffset PO = this->Params[PVD]; // Must exist.
4786
4787 if (!this->emitGetParam(PT_Ptr, PO.Offset, Ctor))
4788 return false;
4789
4790 return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) &&
4791 this->emitRetVoid(Ctor);
4792 }
4793
4795 for (const auto *Init : Ctor->inits()) {
4796 // Scope needed for the initializers.
4798
4799 const Expr *InitExpr = Init->getInit();
4800 if (const FieldDecl *Member = Init->getMember()) {
4801 const Record::Field *F = R->getField(Member);
4802
4803 if (!emitFieldInitializer(F, F->Offset, InitExpr))
4804 return false;
4805 } else if (const Type *Base = Init->getBaseClass()) {
4806 const auto *BaseDecl = Base->getAsCXXRecordDecl();
4807 assert(BaseDecl);
4808
4809 if (Init->isBaseVirtual()) {
4810 assert(R->getVirtualBase(BaseDecl));
4811 if (!this->emitGetPtrThisVirtBase(BaseDecl, InitExpr))
4812 return false;
4813
4814 } else {
4815 // Base class initializer.
4816 // Get This Base and call initializer on it.
4817 const Record::Base *B = R->getBase(BaseDecl);
4818 assert(B);
4819 if (!this->emitGetPtrThisBase(B->Offset, InitExpr))
4820 return false;
4821 }
4822
4823 if (!this->visitInitializer(InitExpr))
4824 return false;
4825 if (!this->emitFinishInitPop(InitExpr))
4826 return false;
4827 } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) {
4828 assert(IFD->getChainingSize() >= 2);
4829
4830 unsigned NestedFieldOffset = 0;
4831 const Record::Field *NestedField = nullptr;
4832 for (const NamedDecl *ND : IFD->chain()) {
4833 const auto *FD = cast<FieldDecl>(ND);
4834 const Record *FieldRecord =
4835 this->P.getOrCreateRecord(FD->getParent());
4836 assert(FieldRecord);
4837
4838 NestedField = FieldRecord->getField(FD);
4839 assert(NestedField);
4840
4841 NestedFieldOffset += NestedField->Offset;
4842 }
4843 assert(NestedField);
4844
4845 if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr))
4846 return false;
4847 } else {
4848 assert(Init->isDelegatingInitializer());
4849 if (!this->emitThis(InitExpr))
4850 return false;
4851 if (!this->visitInitializer(Init->getInit()))
4852 return false;
4853 if (!this->emitPopPtr(InitExpr))
4854 return false;
4855 }
4856
4857 if (!Scope.destroyLocals())
4858 return false;
4859 }
4860 }
4861
4862 if (const auto *Body = F->getBody())
4863 if (!visitStmt(Body))
4864 return false;
4865
4866 // Emit a guard return to protect against a code path missing one.
4867 if (F->getReturnType()->isVoidType())
4868 return this->emitRetVoid(SourceInfo{});
4869 return this->emitNoRet(SourceInfo{});
4870}
4871
4872template <class Emitter>
4874 const Expr *SubExpr = E->getSubExpr();
4875 if (SubExpr->getType()->isAnyComplexType())
4876 return this->VisitComplexUnaryOperator(E);
4877 std::optional<PrimType> T = classify(SubExpr->getType());
4878
4879 switch (E->getOpcode()) {
4880 case UO_PostInc: { // x++
4881 if (!Ctx.getLangOpts().CPlusPlus14)
4882 return this->emitInvalid(E);
4883 if (!T)
4884 return this->emitError(E);
4885
4886 if (!this->visit(SubExpr))
4887 return false;
4888
4889 if (T == PT_Ptr || T == PT_FnPtr) {
4890 if (!this->emitIncPtr(E))
4891 return false;
4892
4893 return DiscardResult ? this->emitPopPtr(E) : true;
4894 }
4895
4896 if (T == PT_Float) {
4897 return DiscardResult ? this->emitIncfPop(getRoundingMode(E), E)
4898 : this->emitIncf(getRoundingMode(E), E);
4899 }
4900
4901 return DiscardResult ? this->emitIncPop(*T, E) : this->emitInc(*T, E);
4902 }
4903 case UO_PostDec: { // x--
4904 if (!Ctx.getLangOpts().CPlusPlus14)
4905 return this->emitInvalid(E);
4906 if (!T)
4907 return this->emitError(E);
4908
4909 if (!this->visit(SubExpr))
4910 return false;
4911
4912 if (T == PT_Ptr || T == PT_FnPtr) {
4913 if (!this->emitDecPtr(E))
4914 return false;
4915
4916 return DiscardResult ? this->emitPopPtr(E) : true;
4917 }
4918
4919 if (T == PT_Float) {
4920 return DiscardResult ? this->emitDecfPop(getRoundingMode(E), E)
4921 : this->emitDecf(getRoundingMode(E), E);
4922 }
4923
4924 return DiscardResult ? this->emitDecPop(*T, E) : this->emitDec(*T, E);
4925 }
4926 case UO_PreInc: { // ++x
4927 if (!Ctx.getLangOpts().CPlusPlus14)
4928 return this->emitInvalid(E);
4929 if (!T)
4930 return this->emitError(E);
4931
4932 if (!this->visit(SubExpr))
4933 return false;
4934
4935 if (T == PT_Ptr || T == PT_FnPtr) {
4936 if (!this->emitLoadPtr(E))
4937 return false;
4938 if (!this->emitConstUint8(1, E))
4939 return false;
4940 if (!this->emitAddOffsetUint8(E))
4941 return false;
4942 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
4943 }
4944
4945 // Post-inc and pre-inc are the same if the value is to be discarded.
4946 if (DiscardResult) {
4947 if (T == PT_Float)
4948 return this->emitIncfPop(getRoundingMode(E), E);
4949 return this->emitIncPop(*T, E);
4950 }
4951
4952 if (T == PT_Float) {
4953 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
4954 if (!this->emitLoadFloat(E))
4955 return false;
4956 if (!this->emitConstFloat(llvm::APFloat(TargetSemantics, 1), E))
4957 return false;
4958 if (!this->emitAddf(getRoundingMode(E), E))
4959 return false;
4960 if (!this->emitStoreFloat(E))
4961 return false;
4962 } else {
4963 assert(isIntegralType(*T));
4964 if (!this->emitLoad(*T, E))
4965 return false;
4966 if (!this->emitConst(1, E))
4967 return false;
4968 if (!this->emitAdd(*T, E))
4969 return false;
4970 if (!this->emitStore(*T, E))
4971 return false;
4972 }
4973 return E->isGLValue() || this->emitLoadPop(*T, E);
4974 }
4975 case UO_PreDec: { // --x
4976 if (!Ctx.getLangOpts().CPlusPlus14)
4977 return this->emitInvalid(E);
4978 if (!T)
4979 return this->emitError(E);
4980
4981 if (!this->visit(SubExpr))
4982 return false;
4983
4984 if (T == PT_Ptr || T == PT_FnPtr) {
4985 if (!this->emitLoadPtr(E))
4986 return false;
4987 if (!this->emitConstUint8(1, E))
4988 return false;
4989 if (!this->emitSubOffsetUint8(E))
4990 return false;
4991 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
4992 }
4993
4994 // Post-dec and pre-dec are the same if the value is to be discarded.
4995 if (DiscardResult) {
4996 if (T == PT_Float)
4997 return this->emitDecfPop(getRoundingMode(E), E);
4998 return this->emitDecPop(*T, E);
4999 }
5000
5001 if (T == PT_Float) {
5002 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
5003 if (!this->emitLoadFloat(E))
5004 return false;
5005 if (!this->emitConstFloat(llvm::APFloat(TargetSemantics, 1), E))
5006 return false;
5007 if (!this->emitSubf(getRoundingMode(E), E))
5008 return false;
5009 if (!this->emitStoreFloat(E))
5010 return false;
5011 } else {
5012 assert(isIntegralType(*T));
5013 if (!this->emitLoad(*T, E))
5014 return false;
5015 if (!this->emitConst(1, E))
5016 return false;
5017 if (!this->emitSub(*T, E))
5018 return false;
5019 if (!this->emitStore(*T, E))
5020 return false;
5021 }
5022 return E->isGLValue() || this->emitLoadPop(*T, E);
5023 }
5024 case UO_LNot: // !x
5025 if (!T)
5026 return this->emitError(E);
5027
5028 if (DiscardResult)
5029 return this->discard(SubExpr);
5030
5031 if (!this->visitBool(SubExpr))
5032 return false;
5033
5034 if (!this->emitInvBool(E))
5035 return false;
5036
5037 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
5038 return this->emitCast(PT_Bool, ET, E);
5039 return true;
5040 case UO_Minus: // -x
5041 if (!T)
5042 return this->emitError(E);
5043
5044 if (!this->visit(SubExpr))
5045 return false;
5046 return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E);
5047 case UO_Plus: // +x
5048 if (!T)
5049 return this->emitError(E);
5050
5051 if (!this->visit(SubExpr)) // noop
5052 return false;
5053 return DiscardResult ? this->emitPop(*T, E) : true;
5054 case UO_AddrOf: // &x
5055 if (E->getType()->isMemberPointerType()) {
5056 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5057 // member can be formed.
5058 return this->emitGetMemberPtr(cast<DeclRefExpr>(SubExpr)->getDecl(), E);
5059 }
5060 // We should already have a pointer when we get here.
5061 return this->delegate(SubExpr);
5062 case UO_Deref: // *x
5063 if (DiscardResult)
5064 return this->discard(SubExpr);
5065 return this->visit(SubExpr);
5066 case UO_Not: // ~x
5067 if (!T)
5068 return this->emitError(E);
5069
5070 if (!this->visit(SubExpr))
5071 return false;
5072 return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
5073 case UO_Real: // __real x
5074 assert(T);
5075 return this->delegate(SubExpr);
5076 case UO_Imag: { // __imag x
5077 assert(T);
5078 if (!this->discard(SubExpr))
5079 return false;
5080 return this->visitZeroInitializer(*T, SubExpr->getType(), SubExpr);
5081 }
5082 case UO_Extension:
5083 return this->delegate(SubExpr);
5084 case UO_Coawait:
5085 assert(false && "Unhandled opcode");
5086 }
5087
5088 return false;
5089}
5090
5091template <class Emitter>
5093 const Expr *SubExpr = E->getSubExpr();
5094 assert(SubExpr->getType()->isAnyComplexType());
5095
5096 if (DiscardResult)
5097 return this->discard(SubExpr);
5098
5099 std::optional<PrimType> ResT = classify(E);
5100 auto prepareResult = [=]() -> bool {
5101 if (!ResT && !Initializing) {
5102 std::optional<unsigned> LocalIndex = allocateLocal(SubExpr);
5103 if (!LocalIndex)
5104 return false;
5105 return this->emitGetPtrLocal(*LocalIndex, E);
5106 }
5107
5108 return true;
5109 };
5110
5111 // The offset of the temporary, if we created one.
5112 unsigned SubExprOffset = ~0u;
5113 auto createTemp = [=, &SubExprOffset]() -> bool {
5114 SubExprOffset = this->allocateLocalPrimitive(SubExpr, PT_Ptr, true, false);
5115 if (!this->visit(SubExpr))
5116 return false;
5117 return this->emitSetLocal(PT_Ptr, SubExprOffset, E);
5118 };
5119
5120 PrimType ElemT = classifyComplexElementType(SubExpr->getType());
5121 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
5122 if (!this->emitGetLocal(PT_Ptr, Offset, E))
5123 return false;
5124 return this->emitArrayElemPop(ElemT, Index, E);
5125 };
5126
5127 switch (E->getOpcode()) {
5128 case UO_Minus:
5129 if (!prepareResult())
5130 return false;
5131 if (!createTemp())
5132 return false;
5133 for (unsigned I = 0; I != 2; ++I) {
5134 if (!getElem(SubExprOffset, I))
5135 return false;
5136 if (!this->emitNeg(ElemT, E))
5137 return false;
5138 if (!this->emitInitElem(ElemT, I, E))
5139 return false;
5140 }
5141 break;
5142
5143 case UO_Plus: // +x
5144 case UO_AddrOf: // &x
5145 case UO_Deref: // *x
5146 return this->delegate(SubExpr);
5147
5148 case UO_LNot:
5149 if (!this->visit(SubExpr))
5150 return false;
5151 if (!this->emitComplexBoolCast(SubExpr))
5152 return false;
5153 if (!this->emitInvBool(E))
5154 return false;
5155 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
5156 return this->emitCast(PT_Bool, ET, E);
5157 return true;
5158
5159 case UO_Real:
5160 return this->emitComplexReal(SubExpr);
5161
5162 case UO_Imag:
5163 if (!this->visit(SubExpr))
5164 return false;
5165
5166 if (SubExpr->isLValue()) {
5167 if (!this->emitConstUint8(1, E))
5168 return false;
5169 return this->emitArrayElemPtrPopUint8(E);
5170 }
5171
5172 // Since our _Complex implementation does not map to a primitive type,
5173 // we sometimes have to do the lvalue-to-rvalue conversion here manually.
5174 return this->emitArrayElemPop(classifyPrim(E->getType()), 1, E);
5175
5176 case UO_Not: // ~x
5177 if (!this->visit(SubExpr))
5178 return false;
5179 // Negate the imaginary component.
5180 if (!this->emitArrayElem(ElemT, 1, E))
5181 return false;
5182 if (!this->emitNeg(ElemT, E))
5183 return false;
5184 if (!this->emitInitElem(ElemT, 1, E))
5185 return false;
5186 return DiscardResult ? this->emitPopPtr(E) : true;
5187
5188 case UO_Extension:
5189 return this->delegate(SubExpr);
5190
5191 default:
5192 return this->emitInvalid(E);
5193 }
5194
5195 return true;
5196}
5197
5198template <class Emitter>
5200 if (DiscardResult)
5201 return true;
5202
5203 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
5204 return this->emitConst(ECD->getInitVal(), E);
5205 } else if (const auto *BD = dyn_cast<BindingDecl>(D)) {
5206 return this->visit(BD->getBinding());
5207 } else if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) {
5208 const Function *F = getFunction(FuncDecl);
5209 return F && this->emitGetFnPtr(F, E);
5210 } else if (const auto *TPOD = dyn_cast<TemplateParamObjectDecl>(D)) {
5211 if (std::optional<unsigned> Index = P.getOrCreateGlobal(D)) {
5212 if (!this->emitGetPtrGlobal(*Index, E))
5213 return false;
5214 if (std::optional<PrimType> T = classify(E->getType())) {
5215 if (!this->visitAPValue(TPOD->getValue(), *T, E))
5216 return false;
5217 return this->emitInitGlobal(*T, *Index, E);
5218 }
5219 return this->visitAPValueInitializer(TPOD->getValue(), E);
5220 }
5221 return false;
5222 }
5223
5224 // References are implemented via pointers, so when we see a DeclRefExpr
5225 // pointing to a reference, we need to get its value directly (i.e. the
5226 // pointer to the actual value) instead of a pointer to the pointer to the
5227 // value.
5228 bool IsReference = D->getType()->isReferenceType();
5229
5230 // Check for local/global variables and parameters.
5231 if (auto It = Locals.find(D); It != Locals.end()) {
5232 const unsigned Offset = It->second.Offset;
5233 if (IsReference)
5234 return this->emitGetLocal(PT_Ptr, Offset, E);
5235 return this->emitGetPtrLocal(Offset, E);
5236 } else if (auto GlobalIndex = P.getGlobal(D)) {
5237 if (IsReference) {
5238 if (!Ctx.getLangOpts().CPlusPlus11)
5239 return this->emitGetGlobal(classifyPrim(E), *GlobalIndex, E);
5240 return this->emitGetGlobalUnchecked(classifyPrim(E), *GlobalIndex, E);
5241 }
5242
5243 return this->emitGetPtrGlobal(*GlobalIndex, E);
5244 } else if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
5245 if (auto It = this->Params.find(PVD); It != this->Params.end()) {
5246 if (IsReference || !It->second.IsPtr)
5247 return this->emitGetParam(classifyPrim(E), It->second.Offset, E);
5248
5249 return this->emitGetPtrParam(It->second.Offset, E);
5250 }
5251 }
5252
5253 // In case we need to re-visit a declaration.
5254 auto revisit = [&](const VarDecl *VD) -> bool {
5255 auto VarState = this->visitDecl(VD);
5256
5257 if (VarState.notCreated())
5258 return true;
5259 if (!VarState)
5260 return false;
5261 // Retry.
5262 return this->visitDeclRef(D, E);
5263 };
5264
5265 // Handle lambda captures.
5266 if (auto It = this->LambdaCaptures.find(D);
5267 It != this->LambdaCaptures.end()) {
5268 auto [Offset, IsPtr] = It->second;
5269
5270 if (IsPtr)
5271 return this->emitGetThisFieldPtr(Offset, E);
5272 return this->emitGetPtrThisField(Offset, E);
5273 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(E);
5274 DRE && DRE->refersToEnclosingVariableOrCapture()) {
5275 if (const auto *VD = dyn_cast<VarDecl>(D); VD && VD->isInitCapture())
5276 return revisit(VD);
5277 }
5278
5279 if (D != InitializingDecl) {
5280 // Try to lazily visit (or emit dummy pointers for) declarations
5281 // we haven't seen yet.
5282 if (Ctx.getLangOpts().CPlusPlus) {
5283 if (const auto *VD = dyn_cast<VarDecl>(D)) {
5284 const auto typeShouldBeVisited = [&](QualType T) -> bool {
5285 if (T.isConstant(Ctx.getASTContext()))
5286 return true;
5287 if (const auto *RT = T->getAs<ReferenceType>())
5288 return RT->getPointeeType().isConstQualified();
5289 return false;
5290 };
5291
5292 // DecompositionDecls are just proxies for us.
5293 if (isa<DecompositionDecl>(VD))
5294 return revisit(VD);
5295
5296 // Visit local const variables like normal.
5297 if ((VD->hasGlobalStorage() || VD->isLocalVarDecl() ||
5298 VD->isStaticDataMember()) &&
5299 typeShouldBeVisited(VD->getType()))
5300 return revisit(VD);
5301 }
5302 } else {
5303 if (const auto *VD = dyn_cast<VarDecl>(D);
5304 VD && VD->getAnyInitializer() &&
5305 VD->getType().isConstant(Ctx.getASTContext()) && !VD->isWeak())
5306 return revisit(VD);
5307 }
5308 }
5309
5310 if (std::optional<unsigned> I = P.getOrCreateDummy(D)) {
5311 if (!this->emitGetPtrGlobal(*I, E))
5312 return false;
5313 if (E->getType()->isVoidType())
5314 return true;
5315 // Convert the dummy pointer to another pointer type if we have to.
5316 if (PrimType PT = classifyPrim(E); PT != PT_Ptr) {
5317 if (isPtrType(PT))
5318 return this->emitDecayPtr(PT_Ptr, PT, E);
5319 return false;
5320 }
5321 return true;
5322 }
5323
5324 if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
5325 return this->emitInvalidDeclRef(DRE, E);
5326 return false;
5327}
5328
5329template <class Emitter>
5331 const auto *D = E->getDecl();
5332 return this->visitDeclRef(D, E);
5333}
5334
5335template <class Emitter> void Compiler<Emitter>::emitCleanup() {
5336 for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent())
5337 C->emitDestruction();
5338}
5339
5340template <class Emitter>
5341unsigned Compiler<Emitter>::collectBaseOffset(const QualType BaseType,
5342 const QualType DerivedType) {
5343 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
5344 if (const auto *R = Ty->getPointeeCXXRecordDecl())
5345 return R;
5346 return Ty->getAsCXXRecordDecl();
5347 };
5348 const CXXRecordDecl *BaseDecl = extractRecordDecl(BaseType);
5349 const CXXRecordDecl *DerivedDecl = extractRecordDecl(DerivedType);
5350
5351 return Ctx.collectBaseOffset(BaseDecl, DerivedDecl);
5352}
5353
5354/// Emit casts from a PrimType to another PrimType.
5355template <class Emitter>
5357 QualType ToQT, const Expr *E) {
5358
5359 if (FromT == PT_Float) {
5360 // Floating to floating.
5361 if (ToT == PT_Float) {
5362 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
5363 return this->emitCastFP(ToSem, getRoundingMode(E), E);
5364 }
5365
5366 if (ToT == PT_IntAP)
5367 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(ToQT), E);
5368 if (ToT == PT_IntAPS)
5369 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(ToQT), E);
5370
5371 // Float to integral.
5372 if (isIntegralType(ToT) || ToT == PT_Bool)
5373 return this->emitCastFloatingIntegral(ToT, E);
5374 }
5375
5376 if (isIntegralType(FromT) || FromT == PT_Bool) {
5377 if (ToT == PT_IntAP)
5378 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
5379 if (ToT == PT_IntAPS)
5380 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
5381
5382 // Integral to integral.
5383 if (isIntegralType(ToT) || ToT == PT_Bool)
5384 return FromT != ToT ? this->emitCast(FromT, ToT, E) : true;
5385
5386 if (ToT == PT_Float) {
5387 // Integral to floating.
5388 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
5389 return this->emitCastIntegralFloating(FromT, ToSem, getRoundingMode(E),
5390 E);
5391 }
5392 }
5393
5394 return false;
5395}
5396
5397/// Emits __real(SubExpr)
5398template <class Emitter>
5399bool Compiler<Emitter>::emitComplexReal(const Expr *SubExpr) {
5400 assert(SubExpr->getType()->isAnyComplexType());
5401
5402 if (DiscardResult)
5403 return this->discard(SubExpr);
5404
5405 if (!this->visit(SubExpr))
5406 return false;
5407 if (SubExpr->isLValue()) {
5408 if (!this->emitConstUint8(0, SubExpr))
5409 return false;
5410 return this->emitArrayElemPtrPopUint8(SubExpr);
5411 }
5412
5413 // Rvalue, load the actual element.
5414 return this->emitArrayElemPop(classifyComplexElementType(SubExpr->getType()),
5415 0, SubExpr);
5416}
5417
5418template <class Emitter>
5420 assert(!DiscardResult);
5421 PrimType ElemT = classifyComplexElementType(E->getType());
5422 // We emit the expression (__real(E) != 0 || __imag(E) != 0)
5423 // for us, that means (bool)E[0] || (bool)E[1]
5424 if (!this->emitArrayElem(ElemT, 0, E))
5425 return false;
5426 if (ElemT == PT_Float) {
5427 if (!this->emitCastFloatingIntegral(PT_Bool, E))
5428 return false;
5429 } else {
5430 if (!this->emitCast(ElemT, PT_Bool, E))
5431 return false;
5432 }
5433
5434 // We now have the bool value of E[0] on the stack.
5435 LabelTy LabelTrue = this->getLabel();
5436 if (!this->jumpTrue(LabelTrue))
5437 return false;
5438
5439 if (!this->emitArrayElemPop(ElemT, 1, E))
5440 return false;
5441 if (ElemT == PT_Float) {
5442 if (!this->emitCastFloatingIntegral(PT_Bool, E))
5443 return false;
5444 } else {
5445 if (!this->emitCast(ElemT, PT_Bool, E))
5446 return false;
5447 }
5448 // Leave the boolean value of E[1] on the stack.
5449 LabelTy EndLabel = this->getLabel();
5450 this->jump(EndLabel);
5451
5452 this->emitLabel(LabelTrue);
5453 if (!this->emitPopPtr(E))
5454 return false;
5455 if (!this->emitConstBool(true, E))
5456 return false;
5457
5458 this->fallthrough(EndLabel);
5459 this->emitLabel(EndLabel);
5460
5461 return true;
5462}
5463
5464template <class Emitter>
5465bool Compiler<Emitter>::emitComplexComparison(const Expr *LHS, const Expr *RHS,
5466 const BinaryOperator *E) {
5467 assert(E->isComparisonOp());
5468 assert(!Initializing);
5469 assert(!DiscardResult);
5470
5471 PrimType ElemT;
5472 bool LHSIsComplex;
5473 unsigned LHSOffset;
5474 if (LHS->getType()->isAnyComplexType()) {
5475 LHSIsComplex = true;
5476 ElemT = classifyComplexElementType(LHS->getType());
5477 LHSOffset = allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true,
5478 /*IsExtended=*/false);
5479 if (!this->visit(LHS))
5480 return false;
5481 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
5482 return false;
5483 } else {
5484 LHSIsComplex = false;
5485 PrimType LHST = classifyPrim(LHS->getType());
5486 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, true, false);
5487 if (!this->visit(LHS))
5488 return false;
5489 if (!this->emitSetLocal(LHST, LHSOffset, E))
5490 return false;
5491 }
5492
5493 bool RHSIsComplex;
5494 unsigned RHSOffset;
5495 if (RHS->getType()->isAnyComplexType()) {
5496 RHSIsComplex = true;
5497 ElemT = classifyComplexElementType(RHS->getType());
5498 RHSOffset = allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true,
5499 /*IsExtended=*/false);
5500 if (!this->visit(RHS))
5501 return false;
5502 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
5503 return false;
5504 } else {
5505 RHSIsComplex = false;
5506 PrimType RHST = classifyPrim(RHS->getType());
5507 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, true, false);
5508 if (!this->visit(RHS))
5509 return false;
5510 if (!this->emitSetLocal(RHST, RHSOffset, E))
5511 return false;
5512 }
5513
5514 auto getElem = [&](unsigned LocalOffset, unsigned Index,
5515 bool IsComplex) -> bool {
5516 if (IsComplex) {
5517 if (!this->emitGetLocal(PT_Ptr, LocalOffset, E))
5518 return false;
5519 return this->emitArrayElemPop(ElemT, Index, E);
5520 }
5521 return this->emitGetLocal(ElemT, LocalOffset, E);
5522 };
5523
5524 for (unsigned I = 0; I != 2; ++I) {
5525 // Get both values.
5526 if (!getElem(LHSOffset, I, LHSIsComplex))
5527 return false;
5528 if (!getElem(RHSOffset, I, RHSIsComplex))
5529 return false;
5530 // And compare them.
5531 if (!this->emitEQ(ElemT, E))
5532 return false;
5533
5534 if (!this->emitCastBoolUint8(E))
5535 return false;
5536 }
5537
5538 // We now have two bool values on the stack. Compare those.
5539 if (!this->emitAddUint8(E))
5540 return false;
5541 if (!this->emitConstUint8(2, E))
5542 return false;
5543
5544 if (E->getOpcode() == BO_EQ) {
5545 if (!this->emitEQUint8(E))
5546 return false;
5547 } else if (E->getOpcode() == BO_NE) {
5548 if (!this->emitNEUint8(E))
5549 return false;
5550 } else
5551 return false;
5552
5553 // In C, this returns an int.
5554 if (PrimType ResT = classifyPrim(E->getType()); ResT != PT_Bool)
5555 return this->emitCast(PT_Bool, ResT, E);
5556 return true;
5557}
5558
5559/// When calling this, we have a pointer of the local-to-destroy
5560/// on the stack.
5561/// Emit destruction of record types (or arrays of record types).
5562template <class Emitter>
5564 assert(R);
5565 if (!R->isUnion()) {
5566 // First, destroy all fields.
5567 for (const Record::Field &Field : llvm::reverse(R->fields())) {
5568 const Descriptor *D = Field.Desc;
5569 if (!D->isPrimitive() && !D->isPrimitiveArray()) {
5570 if (!this->emitGetPtrField(Field.Offset, SourceInfo{}))
5571 return false;
5572 if (!this->emitDestruction(D))
5573 return false;
5574 if (!this->emitPopPtr(SourceInfo{}))
5575 return false;
5576 }
5577 }
5578 }
5579
5580 // Now emit the destructor and recurse into base classes.
5581 if (const CXXDestructorDecl *Dtor = R->getDestructor();
5582 Dtor && !Dtor->isTrivial()) {
5583 const Function *DtorFunc = getFunction(Dtor);
5584 if (!DtorFunc)
5585 return false;
5586 assert(DtorFunc->hasThisPointer());
5587 assert(DtorFunc->getNumParams() == 1);
5588 if (!this->emitDupPtr(SourceInfo{}))
5589 return false;
5590 if (!this->emitCall(DtorFunc, 0, SourceInfo{}))
5591 return false;
5592 }
5593
5594 for (const Record::Base &Base : llvm::reverse(R->bases())) {
5595 if (!this->emitGetPtrBase(Base.Offset, SourceInfo{}))
5596 return false;
5597 if (!this->emitRecordDestruction(Base.R))
5598 return false;
5599 if (!this->emitPopPtr(SourceInfo{}))
5600 return false;
5601 }
5602
5603 // FIXME: Virtual bases.
5604 return true;
5605}
5606/// When calling this, we have a pointer of the local-to-destroy
5607/// on the stack.
5608/// Emit destruction of record types (or arrays of record types).
5609template <class Emitter>
5611 assert(Desc);
5612 assert(!Desc->isPrimitive());
5613 assert(!Desc->isPrimitiveArray());
5614
5615 // Arrays.
5616 if (Desc->isArray()) {
5617 const Descriptor *ElemDesc = Desc->ElemDesc;
5618 assert(ElemDesc);
5619
5620 // Don't need to do anything for these.
5621 if (ElemDesc->isPrimitiveArray())
5622 return true;
5623
5624 // If this is an array of record types, check if we need
5625 // to call the element destructors at all. If not, try
5626 // to save the work.
5627 if (const Record *ElemRecord = ElemDesc->ElemRecord) {
5628 if (const CXXDestructorDecl *Dtor = ElemRecord->getDestructor();
5629 !Dtor || Dtor->isTrivial())
5630 return true;
5631 }
5632
5633 for (ssize_t I = Desc->getNumElems() - 1; I >= 0; --I) {
5634 if (!this->emitConstUint64(I, SourceInfo{}))
5635 return false;
5636 if (!this->emitArrayElemPtrUint64(SourceInfo{}))
5637 return false;
5638 if (!this->emitDestruction(ElemDesc))
5639 return false;
5640 if (!this->emitPopPtr(SourceInfo{}))
5641 return false;
5642 }
5643 return true;
5644 }
5645
5646 assert(Desc->ElemRecord);
5647 return this->emitRecordDestruction(Desc->ElemRecord);
5648}
5649
5650namespace clang {
5651namespace interp {
5652
5653template class Compiler<ByteCodeEmitter>;
5654template class Compiler<EvalEmitter>;
5655
5656} // namespace interp
5657} // namespace clang
#define V(N, I)
Definition: ASTContext.h:3340
ASTImporterLookupTable & LT
DynTypedNode Node
StringRef P
const Decl * D
Expr * E
static CharUnits AlignOfType(QualType T, const ASTContext &ASTCtx, UnaryExprOrTypeTrait Kind)
Definition: Compiler.cpp:1628
llvm::APSInt APSInt
Definition: Compiler.cpp:22
bool IsStatic
Definition: Format.cpp:3013
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
const LValueBase getLValueBase() const
Definition: APValue.cpp:974
APValue & getArrayInitializedElt(unsigned I)
Definition: APValue.h:510
ArrayRef< LValuePathEntry > getLValuePath() const
Definition: APValue.cpp:994
APSInt & getInt()
Definition: APValue.h:423
APValue & getStructField(unsigned i)
Definition: APValue.h:551
const FieldDecl * getUnionField() const
Definition: APValue.h:563
unsigned getStructNumFields() const
Definition: APValue.h:542
bool isArray() const
Definition: APValue.h:408
bool isFloat() const
Definition: APValue.h:402
const ValueDecl * getMemberPointerDecl() const
Definition: APValue.cpp:1057
APValue & getUnionValue()
Definition: APValue.h:567
bool isLValue() const
Definition: APValue.h:406
bool isMemberPointer() const
Definition: APValue.h:411
bool isInt() const
Definition: APValue.h:401
unsigned getArraySize() const
Definition: APValue.h:533
bool isUnion() const
Definition: APValue.h:410
@ None
There is no such object (it's outside its lifetime).
Definition: APValue.h:129
bool isStruct() const
Definition: APValue.h:409
bool isNullPointer() const
Definition: APValue.cpp:1010
APFloat & getFloat()
Definition: APValue.h:437
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:186
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
Definition: ASTContext.h:2484
const LangOptions & getLangOpts() const
Definition: ASTContext.h:796
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition: Expr.h:4165
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition: Expr.h:4362
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition: Expr.h:5746
Represents a loop initializing the elements of an array.
Definition: Expr.h:5693
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition: Expr.h:2674
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition: ExprCXX.h:2852
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition: Type.h:3566
Attr - This represents one attribute.
Definition: Attr.h:42
Represents an attribute applied to a statement.
Definition: Stmt.h:2085
A builtin binary operation expression such as "x + y" or "x <= y".
Definition: Expr.h:3860
static bool isLogicalOp(Opcode Opc)
Definition: Expr.h:3992
Expr * getLHS() const
Definition: Expr.h:3909
static bool isComparisonOp(Opcode Opc)
Definition: Expr.h:3959
static bool isCommaOp(Opcode Opc)
Definition: Expr.h:3962
Expr * getRHS() const
Definition: Expr.h:3911
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition: Expr.h:3936
Opcode getOpcode() const
Definition: Expr.h:3904
BreakStmt - This represents a break.
Definition: Stmt.h:2985
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
Represents binding an expression to a temporary.
Definition: ExprCXX.h:1491
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition: ExprCXX.h:720
Represents a call to a C++ constructor.
Definition: ExprCXX.h:1546
Represents a C++ constructor within a class.
Definition: DeclCXX.h:2538
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition: DeclCXX.cpp:2811
A default argument (C++ [dcl.fct.default]).
Definition: ExprCXX.h:1268
A use of a default initializer in a constructor or in aggregate initialization.
Definition: ExprCXX.h:1375
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition: ExprCXX.h:2497
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2802
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition: StmtCXX.h:135
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition: ExprCXX.h:1737
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2063
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2189
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition: DeclCXX.cpp:2639
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition: ExprCXX.h:2240
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition: ExprCXX.h:4125
The null pointer literal (C++11 [lex.nullptr])
Definition: ExprCXX.h:765
Represents a list-initialization with parenthesis.
Definition: ExprCXX.h:4953
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
capture_const_iterator captures_end() const
Definition: DeclCXX.h:1111
capture_const_iterator captures_begin() const
Definition: DeclCXX.h:1105
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition: DeclCXX.cpp:1633
A C++ reinterpret_cast expression (C++ [expr.reinterpret.cast]).
Definition: ExprCXX.h:523
A rewritten comparison expression that was originally written using operator syntax.
Definition: ExprCXX.h:283
An expression "T()" which creates a value-initialized rvalue of type T, which is a non-class type.
Definition: ExprCXX.h:2181
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition: ExprCXX.h:797
Represents the this expression in C++.
Definition: ExprCXX.h:1152
A C++ throw-expression (C++ [except.throw]).
Definition: ExprCXX.h:1206
CXXTryStmt - A C++ try block, including all handlers.
Definition: StmtCXX.h:69
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition: ExprCXX.h:1066
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition: Expr.h:2830
CaseStmt - Represent a case statement.
Definition: Stmt.h:1806
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition: Expr.h:3498
CastKind getCastKind() const
Definition: Expr.h:3542
llvm::iterator_range< path_iterator > path()
Path through the class hierarchy taken by casts between base and derived classes (see implementation ...
Definition: Expr.h:3585
Expr * getSubExpr()
Definition: Expr.h:3548
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition: CharUnits.h:58
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition: Expr.h:4582
Complex values, per C99 6.2.5p11.
Definition: Type.h:3134
QualType getElementType() const
Definition: Type.h:3144
CompoundAssignOperator - For compound assignments (e.g.
Definition: Expr.h:4112
CompoundLiteralExpr - [C99 6.5.2.5].
Definition: Expr.h:3428
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition: Stmt.h:1606
body_range body()
Definition: Stmt.h:1669
Stmt * getStmtExprResult()
Definition: Stmt.h:1728
Represents the specialization of a concept - evaluates to a prvalue of type bool.
Definition: ExprConcepts.h:42
Represents the canonical version of C arrays with a specified constant size.
Definition: Type.h:3604
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition: Type.h:3680
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition: Expr.h:1077
ContinueStmt - This represents a continue.
Definition: Stmt.h:2955
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition: Expr.h:4523
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition: DeclBase.h:2089
A reference to a declared variable, function, enum, etc.
Definition: Expr.h:1265
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition: Stmt.h:1497
decl_range decls()
Definition: Stmt.h:1545
Decl - This represents one declaration (or definition), e.g.
Definition: DeclBase.h:86
bool isInvalidDecl() const
Definition: DeclBase.h:594
DoStmt - This represents a 'do/while' stmt.
Definition: Stmt.h:2730
Represents a reference to #emded data.
Definition: Expr.h:4857
bool isFixed() const
Returns true if this is an Objective-C, C++11, or Microsoft-style enumeration with a fixed underlying...
Definition: Decl.h:4054
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of enums.
Definition: Type.h:5991
EnumDecl * getDecl() const
Definition: Type.h:5998
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition: ExprCXX.h:3473
This represents one expression.
Definition: Expr.h:110
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition: Expr.cpp:82
bool isGLValue() const
Definition: Expr.h:280
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition: Expr.h:175
bool containsErrors() const
Whether this expression contains subexpressions which had errors, e.g.
Definition: Expr.h:245
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition: Expr.cpp:3066
bool isPRValue() const
Definition: Expr.h:278
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition: Expr.h:277
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition: Expr.cpp:3567
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition: Expr.cpp:3204
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition: Expr.h:469
QualType getType() const
Definition: Expr.h:142
An expression trait intrinsic.
Definition: ExprCXX.h:2923
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition: Expr.h:6295
Represents a member of a struct/union/class.
Definition: Decl.h:3030
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition: Decl.h:3243
bool isUnnamedBitField() const
Determines whether this is an unnamed bitfield.
Definition: Decl.h:3124
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition: Stmt.h:2786
Represents a function declaration or definition.
Definition: Decl.h:1932
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition: Decl.cpp:3224
QualType getReturnType() const
Definition: Decl.h:2717
ArrayRef< ParmVarDecl * > parameters() const
Definition: Decl.h:2646
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition: Decl.h:2302
bool isDefaulted() const
Whether this function is defaulted.
Definition: Decl.h:2310
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition: Decl.cpp:3678
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition: Decl.cpp:3144
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition: Expr.h:4657
Represents a C11 generic selection.
Definition: Expr.h:5907
IfStmt - This represents an if/then/else.
Definition: Stmt.h:2143
Stmt * getThen()
Definition: Stmt.h:2232
Stmt * getInit()
Definition: Stmt.h:2293
bool isNonNegatedConsteval() const
Definition: Stmt.h:2328
Expr * getCond()
Definition: Stmt.h:2220
bool isNegatedConsteval() const
Definition: Stmt.h:2332
Stmt * getElse()
Definition: Stmt.h:2241
DeclStmt * getConditionVariableDeclStmt()
If this IfStmt has a condition variable, return the faux DeclStmt associated with the creation of tha...
Definition: Stmt.h:2276
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition: Expr.h:1717
Represents an implicitly-generated value initialization of an object of a given type.
Definition: Expr.h:5782
Represents a field injected from an anonymous union/struct into the parent scope.
Definition: Decl.h:3314
Describes an C or C++ initializer list.
Definition: Expr.h:5029
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition: ExprCXX.h:1954
Implicit declaration of a temporary that was materialized by a MaterializeTemporaryExpr and lifetime-...
Definition: DeclCXX.h:3232
A global _GUID constant.
Definition: DeclCXX.h:4292
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
Definition: DeclCXX.cpp:3508
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition: ExprCXX.h:4727
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition: Expr.h:3187
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition: Type.h:3508
const Type * getClass() const
Definition: Type.h:3538
This represents a decl that may have a name.
Definition: Decl.h:249
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition: ExprObjC.h:87
ObjCBoxedExpr - used for generalized expression boxing.
Definition: ExprObjC.h:127
ObjCEncodeExpr, used for @encode in Objective-C.
Definition: ExprObjC.h:410
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition: ExprObjC.h:51
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition: Expr.h:2475
Helper class for OffsetOfExpr.
Definition: Expr.h:2369
@ Array
An index into an array.
Definition: Expr.h:2374
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition: Expr.h:1173
ParenExpr - This represents a parenthesized expression, e.g.
Definition: Expr.h:2135
Represents a parameter to a function.
Definition: Decl.h:1722
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition: Type.h:3187
QualType getPointeeType() const
Definition: Type.h:3197
[C99 6.4.2.2] - A predefined identifier such as func.
Definition: Expr.h:1991
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition: Expr.h:6487
A (possibly-)qualified type.
Definition: Type.h:941
QualType withConst() const
Definition: Type.h:1166
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition: Type.h:1008
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition: Type.h:7750
QualType getCanonicalType() const
Definition: Type.h:7802
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition: Type.h:7823
Represents a struct/union/class.
Definition: Decl.h:4141
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5965
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition: Expr.h:7091
Base for LValueReferenceType and RValueReferenceType.
Definition: Type.h:3428
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
Definition: ExprConcepts.h:510
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition: Stmt.h:3024
Expr * getRetValue()
Definition: Stmt.h:3055
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition: Expr.h:4455
Represents an expression that computes the length of a parameter pack.
Definition: ExprCXX.h:4257
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition: Expr.h:4751
Represents a C++11 static_assert declaration.
Definition: DeclCXX.h:4061
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition: Expr.h:4407
Stmt - This represents one statement.
Definition: Stmt.h:84
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1778
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, const SourceLocation *Loc, unsigned NumConcatenated)
This is the "fully general" constructor that allows representation of strings formed from multiple co...
Definition: Expr.cpp:1191
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition: ExprCXX.h:4483
SwitchStmt - This represents a 'switch' stmt.
Definition: Stmt.h:2393
Represents the declaration of a struct/union/class/enum.
Definition: Decl.h:3557
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition: Decl.h:3660
bool isUnion() const
Definition: Decl.h:3763
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition: ExprCXX.h:2767
The base class of the type hierarchy.
Definition: Type.h:1829
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1882
bool isVoidType() const
Definition: Type.h:8319
bool isBooleanType() const
Definition: Type.h:8447
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition: Type.cpp:2892
bool isIncompleteArrayType() const
Definition: Type.h:8083
bool isNothrowT() const
Definition: Type.cpp:3061
bool isVoidPointerType() const
Definition: Type.cpp:665
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition: Type.cpp:2352
bool isArrayType() const
Definition: Type.h:8075
bool isPointerType() const
Definition: Type.h:8003
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition: Type.h:8359
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8607
bool isEnumeralType() const
Definition: Type.h:8107
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition: Type.cpp:705
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition: Type.h:8434
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition: Type.h:2695
bool isAnyComplexType() const
Definition: Type.h:8111
bool isMemberPointerType() const
Definition: Type.h:8057
bool isAtomicType() const
Definition: Type.h:8158
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition: Type.h:8593
bool isFunctionType() const
Definition: Type.h:7999
bool isVectorType() const
Definition: Type.h:8115
bool isFloatingType() const
Definition: Type.cpp:2249
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8540
bool isRecordType() const
Definition: Type.h:8103
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition: Type.cpp:1886
Base class for declarations which introduce a typedef-name.
Definition: Decl.h:3405
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition: Expr.h:2578
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition: Expr.h:2188
Represents a C++ using-enum-declaration.
Definition: DeclCXX.h:3716
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:667
QualType getType() const
Definition: Decl.h:678
QualType getType() const
Definition: Value.cpp:234
Represents a variable declaration or definition.
Definition: Decl.h:879
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition: Decl.h:1156
const Expr * getInit() const
Definition: Decl.h:1316
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition: Decl.h:1201
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition: Decl.h:1306
Represents a GCC generic vector type.
Definition: Type.h:4021
unsigned getNumElements() const
Definition: Type.h:4036
QualType getElementType() const
Definition: Type.h:4035
WhileStmt - This represents a 'while' stmt.
Definition: Stmt.h:2589
Scope for storage declared in a compound statement.
Definition: Compiler.h:559
A memory block, either on the stack or in the heap.
Definition: InterpBlock.h:49
void invokeDtor()
Invokes the Destructor.
Definition: InterpBlock.h:121
std::byte * rawData()
Returns a pointer to the raw data, including metadata.
Definition: InterpBlock.h:102
Compilation context for expressions.
Definition: Compiler.h:104
OptLabelTy BreakLabel
Point to break to.
Definition: Compiler.h:399
bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E)
Definition: Compiler.cpp:1794
bool VisitCXXDeleteExpr(const CXXDeleteExpr *E)
Definition: Compiler.cpp:2902
bool VisitOffsetOfExpr(const OffsetOfExpr *E)
Definition: Compiler.cpp:2653
bool visitContinueStmt(const ContinueStmt *S)
Definition: Compiler.cpp:4547
bool VisitCharacterLiteral(const CharacterLiteral *E)
Definition: Compiler.cpp:1998
bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E)
Definition: Compiler.cpp:1595
bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E)
Definition: Compiler.cpp:2964
bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
Definition: Compiler.cpp:2326
bool visitBool(const Expr *E)
Visits an expression and converts it to a boolean.
Definition: Compiler.cpp:3280
bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
Definition: Compiler.cpp:4142
bool visitDeclAndReturn(const VarDecl *VD, bool ConstantContext) override
Toplevel visitDeclAndReturn().
Definition: Compiler.cpp:3642
bool visitExpr(const Expr *E) override
Definition: Compiler.cpp:3575
bool VisitTypeTraitExpr(const TypeTraitExpr *E)
Definition: Compiler.cpp:2391
bool VisitLambdaExpr(const LambdaExpr *E)
Definition: Compiler.cpp:2407
bool VisitMemberExpr(const MemberExpr *E)
Definition: Compiler.cpp:1742
bool VisitBinaryOperator(const BinaryOperator *E)
Definition: Compiler.cpp:697
bool visitAttributedStmt(const AttributedStmt *S)
Definition: Compiler.cpp:4638
bool VisitPackIndexingExpr(const PackIndexingExpr *E)
Definition: Compiler.cpp:3003
bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
Definition: Compiler.cpp:1298
bool VisitCallExpr(const CallExpr *E)
Definition: Compiler.cpp:3956
bool VisitPseudoObjectExpr(const PseudoObjectExpr *E)
Definition: Compiler.cpp:2979
bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E)
Definition: Compiler.cpp:2462
const Function * getFunction(const FunctionDecl *FD)
Returns a function for the given FunctionDecl.
Definition: Compiler.cpp:3571
void emitCleanup()
Emits scope cleanup instructions.
Definition: Compiler.cpp:5335
bool VisitCastExpr(const CastExpr *E)
Definition: Compiler.cpp:178
bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E)
Definition: Compiler.cpp:1963
bool VisitComplexUnaryOperator(const UnaryOperator *E)
Definition: Compiler.cpp:5092
llvm::DenseMap< const SwitchCase *, LabelTy > CaseMap
Definition: Compiler.h:110
bool visitDeclStmt(const DeclStmt *DS)
Definition: Compiler.cpp:4282
bool visitAPValue(const APValue &Val, PrimType ValType, const Expr *E)
Visit an APValue.
Definition: Compiler.cpp:3811
bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E)
Definition: Compiler.cpp:2688
bool VisitLogicalBinOp(const BinaryOperator *E)
Definition: Compiler.cpp:925
bool visitCompoundStmt(const CompoundStmt *S)
Definition: Compiler.cpp:4273
bool visitDeclRef(const ValueDecl *D, const Expr *E)
Visit the given decl as if we have a reference to it.
Definition: Compiler.cpp:5199
bool visitBreakStmt(const BreakStmt *S)
Definition: Compiler.cpp:4538
bool visitForStmt(const ForStmt *S)
Definition: Compiler.cpp:4435
bool VisitDeclRefExpr(const DeclRefExpr *E)
Definition: Compiler.cpp:5330
bool VisitOpaqueValueExpr(const OpaqueValueExpr *E)
Definition: Compiler.cpp:1833
bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E)
Definition: Compiler.cpp:1803
OptLabelTy DefaultLabel
Default case label.
Definition: Compiler.h:403
bool VisitStmtExpr(const StmtExpr *E)
Definition: Compiler.cpp:3201
bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E)
Definition: Compiler.cpp:4161
bool VisitCXXNewExpr(const CXXNewExpr *E)
Definition: Compiler.cpp:2802
bool VisitCompoundAssignOperator(const CompoundAssignOperator *E)
Definition: Compiler.cpp:2116
bool visitArrayElemInit(unsigned ElemIndex, const Expr *Init)
Pointer to the array(not the element!) must be on the stack when calling this.
Definition: Compiler.cpp:1568
bool delegate(const Expr *E)
Just pass evaluation on to E.
Definition: Compiler.cpp:3229
bool discard(const Expr *E)
Evaluates an expression for side effects and discards the result.
Definition: Compiler.cpp:3223
bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
Definition: Compiler.cpp:4149
CaseMap CaseLabels
Switch case mapping.
Definition: Compiler.h:396
Record * getRecord(QualType Ty)
Returns a record from a record or pointer type.
Definition: Compiler.cpp:3559
bool visit(const Expr *E)
Evaluates an expression and places the result on the stack.
Definition: Compiler.cpp:3239
const RecordType * getRecordTy(QualType Ty)
Returns a record type from a record or pointer type.
Definition: Compiler.cpp:3553
bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E)
Definition: Compiler.cpp:3168
std::optional< unsigned > allocateLocal(DeclTy &&Decl, const ValueDecl *ExtendingDecl=nullptr)
Allocates a space storing a local given its type.
Definition: Compiler.cpp:3512
bool visitInitList(ArrayRef< const Expr * > Inits, const Expr *ArrayFiller, const Expr *E)
Definition: Compiler.cpp:1328
bool VisitSizeOfPackExpr(const SizeOfPackExpr *E)
Definition: Compiler.cpp:2747
bool VisitPredefinedExpr(const PredefinedExpr *E)
Definition: Compiler.cpp:2446
bool VisitSourceLocExpr(const SourceLocExpr *E)
Definition: Compiler.cpp:2597
bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E)
Definition: Compiler.cpp:3097
bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
Definition: Compiler.cpp:1958
bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E)
Definition: Compiler.cpp:2400
bool visitInitializer(const Expr *E)
Compiles an initializer.
Definition: Compiler.cpp:3266
bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E)
Definition: Compiler.cpp:2320
bool VisitPointerArithBinOp(const BinaryOperator *E)
Perform addition/subtraction of a pointer and an integer or subtraction of two pointers.
Definition: Compiler.cpp:877
bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E)
Definition: Compiler.cpp:2763
bool visitDefaultStmt(const DefaultStmt *S)
Definition: Compiler.cpp:4632
typename Emitter::LabelTy LabelTy
Definition: Compiler.h:107
VarCreationState visitDecl(const VarDecl *VD)
Definition: Compiler.cpp:3614
bool visitStmt(const Stmt *S)
Definition: Compiler.cpp:4223
bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E)
Definition: Compiler.cpp:2913
bool visitAPValueInitializer(const APValue &Val, const Expr *E)
Definition: Compiler.cpp:3838
bool VisitCXXConstructExpr(const CXXConstructExpr *E)
Definition: Compiler.cpp:2483
bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
Definition: Compiler.cpp:4169
bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
Definition: Compiler.cpp:3159
bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E)
Definition: Compiler.cpp:2771
bool VisitRecoveryExpr(const RecoveryExpr *E)
Definition: Compiler.cpp:3008
bool VisitRequiresExpr(const RequiresExpr *E)
Definition: Compiler.cpp:2956
bool Initializing
Flag inidicating if we're initializing an already created variable.
Definition: Compiler.h:386
bool visitReturnStmt(const ReturnStmt *RS)
Definition: Compiler.cpp:4299
bool VisitCXXThrowExpr(const CXXThrowExpr *E)
Definition: Compiler.cpp:2454
bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
Definition: Compiler.cpp:1601
bool VisitChooseExpr(const ChooseExpr *E)
Definition: Compiler.cpp:2758
bool visitFunc(const FunctionDecl *F) override
Definition: Compiler.cpp:4736
bool visitCXXForRangeStmt(const CXXForRangeStmt *S)
Definition: Compiler.cpp:4482
bool visitCaseStmt(const CaseStmt *S)
Definition: Compiler.cpp:4626
bool VisitComplexBinOp(const BinaryOperator *E)
Definition: Compiler.cpp:986
bool VisitAbstractConditionalOperator(const AbstractConditionalOperator *E)
Definition: Compiler.cpp:1869
OptLabelTy ContinueLabel
Point to continue to.
Definition: Compiler.h:401
bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
Definition: Compiler.cpp:1214
bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E)
Definition: Compiler.cpp:2973
bool VisitUnaryOperator(const UnaryOperator *E)
Definition: Compiler.cpp:4873
bool VisitFloatCompoundAssignOperator(const CompoundAssignOperator *E)
Definition: Compiler.cpp:2005
bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
Definition: Compiler.cpp:2752
bool visitDoStmt(const DoStmt *S)
Definition: Compiler.cpp:4407
bool VisitIntegerLiteral(const IntegerLiteral *E)
Definition: Compiler.cpp:652
bool VisitInitListExpr(const InitListExpr *E)
Definition: Compiler.cpp:1590
bool VisitStringLiteral(const StringLiteral *E)
Definition: Compiler.cpp:1901
bool VisitParenExpr(const ParenExpr *E)
Definition: Compiler.cpp:692
bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E)
Definition: Compiler.cpp:2474
bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E)
Definition: Compiler.cpp:3055
bool VisitPointerCompoundAssignOperator(const CompoundAssignOperator *E)
Definition: Compiler.cpp:2079
std::optional< LabelTy > OptLabelTy
Definition: Compiler.h:109
bool DiscardResult
Flag indicating if return value is to be discarded.
Definition: Compiler.h:380
bool VisitEmbedExpr(const EmbedExpr *E)
Definition: Compiler.cpp:1623
bool VisitConvertVectorExpr(const ConvertVectorExpr *E)
Definition: Compiler.cpp:3023
bool VisitCXXThisExpr(const CXXThisExpr *E)
Definition: Compiler.cpp:4189
bool VisitConstantExpr(const ConstantExpr *E)
Definition: Compiler.cpp:1607
bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
Definition: Compiler.cpp:1652
bool visitSwitchStmt(const SwitchStmt *S)
Definition: Compiler.cpp:4556
bool VisitCXXUuidofExpr(const CXXUuidofExpr *E)
Definition: Compiler.cpp:2919
unsigned allocateLocalPrimitive(DeclTy &&Decl, PrimType Ty, bool IsConst, bool IsExtended=false)
Creates a local primitive value.
Definition: Compiler.cpp:3487
bool VisitExprWithCleanups(const ExprWithCleanups *E)
Definition: Compiler.cpp:2237
bool visitWhileStmt(const WhileStmt *S)
Definition: Compiler.cpp:4376
bool visitIfStmt(const IfStmt *IS)
Definition: Compiler.cpp:4333
bool VisitAddrLabelExpr(const AddrLabelExpr *E)
Definition: Compiler.cpp:3013
bool VisitFloatingLiteral(const FloatingLiteral *E)
Definition: Compiler.cpp:660
bool VisitBuiltinCallExpr(const CallExpr *E)
Definition: Compiler.cpp:3901
bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E)
Definition: Compiler.cpp:2247
bool VisitGNUNullExpr(const GNUNullExpr *E)
Definition: Compiler.cpp:4178
bool VisitImaginaryLiteral(const ImaginaryLiteral *E)
Definition: Compiler.cpp:668
bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E)
Definition: Compiler.cpp:1974
VarCreationState visitVarDecl(const VarDecl *VD, bool Toplevel=false)
Creates and initializes a variable from the given decl.
Definition: Compiler.cpp:3702
bool visitCXXTryStmt(const CXXTryStmt *S)
Definition: Compiler.cpp:4669
static bool shouldBeGloballyIndexed(const ValueDecl *VD)
Returns whether we should create a global variable for the given ValueDecl.
Definition: Context.h:97
Scope used to handle temporaries in toplevel variable declarations.
Definition: Compiler.cpp:28
void addExtended(const Scope::Local &Local) override
Definition: Compiler.cpp:37
DeclScope(Compiler< Emitter > *Ctx, const ValueDecl *VD)
Definition: Compiler.cpp:30
Bytecode function.
Definition: Function.h:77
unsigned getNumParams() const
Definition: Function.h:187
bool hasThisPointer() const
Definition: Function.h:171
bool hasRVO() const
Checks if the first argument is a RVO pointer.
Definition: Function.h:110
Scope managing label targets.
Definition: Compiler.cpp:99
LabelScope(Compiler< Emitter > *Ctx)
Definition: Compiler.cpp:104
Compiler< Emitter > * Ctx
Compiler instance.
Definition: Compiler.cpp:106
Generic scope for local variables.
Definition: Compiler.h:471
bool destroyLocals(const Expr *E=nullptr) override
Explicit destruction of local variables.
Definition: Compiler.h:495
void addLocal(const Scope::Local &Local) override
Definition: Compiler.h:505
Sets the context for break/continue statements.
Definition: Compiler.cpp:110
typename Compiler< Emitter >::LabelTy LabelTy
Definition: Compiler.cpp:112
LoopScope(Compiler< Emitter > *Ctx, LabelTy BreakLabel, LabelTy ContinueLabel)
Definition: Compiler.cpp:115
typename Compiler< Emitter >::OptLabelTy OptLabelTy
Definition: Compiler.cpp:113
Scope used to handle initialization methods.
Definition: Compiler.cpp:52
OptionScope(Compiler< Emitter > *Ctx, bool NewDiscardResult, bool NewInitializing)
Root constructor, compiling or discarding primitives.
Definition: Compiler.cpp:55
Context to manage declaration lifetimes.
Definition: Program.h:133
Structure/Class descriptor.
Definition: Record.h:25
bool isUnion() const
Checks if the record is a union.
Definition: Record.h:56
const CXXDestructorDecl * getDestructor() const
Returns the destructor of the record, if any.
Definition: Record.h:70
const Field * getField(const FieldDecl *FD) const
Returns a field.
Definition: Record.cpp:39
llvm::iterator_range< const_base_iter > bases() const
Definition: Record.h:85
const Base * getVirtualBase(const RecordDecl *RD) const
Returns a virtual base descriptor.
Definition: Record.cpp:59
unsigned getNumFields() const
Definition: Record.h:81
llvm::iterator_range< const_field_iter > fields() const
Definition: Record.h:77
const Base * getBase(const RecordDecl *FD) const
Returns a base descriptor.
Definition: Record.cpp:45
Describes a scope block.
Definition: Function.h:35
Describes the statement/declaration an opcode was generated from.
Definition: Source.h:77
StmtExprScope(Compiler< Emitter > *Ctx)
Definition: Compiler.cpp:163
typename Compiler< Emitter >::LabelTy LabelTy
Definition: Compiler.cpp:135
typename Compiler< Emitter >::OptLabelTy OptLabelTy
Definition: Compiler.cpp:136
SwitchScope(Compiler< Emitter > *Ctx, CaseMap &&CaseLabels, LabelTy BreakLabel, OptLabelTy DefaultLabel)
Definition: Compiler.cpp:139
typename Compiler< Emitter >::CaseMap CaseMap
Definition: Compiler.cpp:137
Scope chain managing the variable lifetimes.
Definition: Compiler.h:410
Compiler< Emitter > * Ctx
Compiler instance.
Definition: Compiler.h:464
llvm::APInt APInt
Definition: Integral.h:29
constexpr bool isPtrType(PrimType T)
Definition: PrimType.h:51
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition: PrimType.h:104
bool InitScope(InterpState &S, CodePtr OpPC, uint32_t I)
Definition: Interp.h:2021
bool LE(InterpState &S, CodePtr OpPC)
Definition: Interp.h:1109
PrimType
Enumeration of the primitive types of the VM.
Definition: PrimType.h:33
llvm::BitVector collectNonNullArgs(const FunctionDecl *F, const llvm::ArrayRef< const Expr * > &Args)
size_t primSize(PrimType Type)
Returns the size of a primitive type in bytes.
Definition: PrimType.cpp:23
llvm::APSInt APSInt
Definition: Floating.h:24
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
Definition: Descriptor.h:28
constexpr bool isIntegralType(PrimType T)
Definition: PrimType.h:72
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition: Address.h:328
BinaryOperatorKind
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition: TypeTraits.h:51
@ SD_Static
Static storage duration.
Definition: Specifiers.h:331
const FunctionProtoType * T
@ Success
Template argument deduction was successful.
#define true
Definition: stdbool.h:25
Describes a memory block created by an allocation site.
Definition: Descriptor.h:111
unsigned getNumElems() const
Returns the number of elements stored in the block.
Definition: Descriptor.h:237
bool isPrimitive() const
Checks if the descriptor is of a primitive.
Definition: Descriptor.h:251
const Descriptor *const ElemDesc
Descriptor of the array element.
Definition: Descriptor.h:143
static constexpr MetadataSize InlineDescMD
Definition: Descriptor.h:132
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition: Descriptor.h:242
const Record *const ElemRecord
Pointer to the record, if block contains records.
Definition: Descriptor.h:141
bool isArray() const
Checks if the descriptor is of an array.
Definition: Descriptor.h:254
Descriptor used for global variables.
Definition: Descriptor.h:58
const FieldDecl * Decl
Definition: Record.h:29
Information about a local's storage.
Definition: Function.h:38
State encapsulating if a the variable creation has been successful, unsuccessful, or no variable has ...
Definition: Compiler.h:91
static VarCreationState NotCreated()
Definition: Compiler.h:95