clang 24.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 "../ExprConstShared.h"
11#include "ByteCodeEmitter.h"
12#include "Context.h"
13#include "FixedPoint.h"
14#include "Floating.h"
15#include "Function.h"
16#include "InterpShared.h"
17#include "PrimType.h"
18#include "Program.h"
19#include "clang/AST/Attr.h"
21#include "llvm/Support/SaveAndRestore.h"
22
23using namespace clang;
24using namespace clang::interp;
25
26using APSInt = llvm::APSInt;
27
28namespace clang {
29namespace interp {
30
31static std::optional<bool> getBoolValue(const Expr *E) {
32 if (const auto *CE = dyn_cast_if_present<ConstantExpr>(E);
33 CE && CE->hasAPValueResult() &&
34 CE->getResultAPValueKind() == APValue::ValueKind::Int) {
35 return CE->getResultAsAPSInt().getBoolValue();
36 }
37
38 return std::nullopt;
39}
40
41/// Check if \c E has side-effects. This is used to avoid some temporary
42/// variables and is supposed to be a quick check, not exhaustive. That's why
43/// we're not using Expr::HasSideEffects().
44static bool isSideEffectFree(const Expr *E) {
47 return true;
48 if (isa<DeclRefExpr>(E))
49 return true;
50
51 return false;
52}
53
54/// Whether the CheckArraySize op rejects an array with \p NumElems elements.
55static bool exceedsArraySizeLimit(const LangOptions &LangOpts,
56 uint64_t NumElems) {
57 if (NumElems > std::numeric_limits<unsigned>::max())
58 return true;
59 uint64_t Limit = LangOpts.ConstexprStepLimit;
60 return Limit != 0 && NumElems > Limit;
61}
62
63/// Scope chain managing the variable lifetimes.
64template <class Emitter> class VariableScope {
65public:
67 : Ctx(Ctx), Parent(Ctx->VarScope), Kind(Kind) {
68 if (Parent)
69 this->LocalsAlwaysEnabled = Parent->LocalsAlwaysEnabled;
70 Ctx->VarScope = this;
71 }
72
73 virtual ~VariableScope() { Ctx->VarScope = this->Parent; }
74
75 virtual void addLocal(Scope::Local Local) {
76 llvm_unreachable("Shouldn't be called");
77 }
78 /// Like addExtended, but adds to the nearest scope of the given kind.
80 VariableScope *P = this;
81 while (P) {
82 // We found the right scope kind.
83 if (P->Kind == Kind) {
84 P->addLocal(Local);
85 return;
86 }
87 // If we reached the root scope and we're looking for a Block scope,
88 // attach it to the root instead of the current scope.
89 if (!P->Parent && Kind == ScopeKind::Block) {
90 P->addLocal(Local);
91 return;
92 }
93 P = P->Parent;
94 if (!P)
95 break;
96 }
97
98 // Add to this scope.
99 this->addLocal(Local);
100 }
101
102 virtual bool emitDestructors(const Expr *E = nullptr) { return true; }
103 virtual bool destroyLocals(const Expr *E = nullptr) { return true; }
104 VariableScope *getParent() const { return Parent; }
105 ScopeKind getKind() const { return Kind; }
106
107 /// Whether locals added to this scope are enabled by default.
108 /// This is almost always true, except for the two branches
109 /// of a conditional operator.
111
112protected:
113 /// Compiler instance.
115 /// Link to the parent scope.
118};
119
120/// Generic scope for local variables.
121template <class Emitter> class LocalScope : public VariableScope<Emitter> {
122public:
125
126 /// Emit a Destroy op for this scope.
127 ~LocalScope() override {
128 if (!Idx || ExplicitlyDestroyed)
129 return;
130 this->Ctx->emitDestroy(*Idx, SourceInfo{});
132 }
133 /// Explicit destruction of local variables.
134 bool destroyLocals(const Expr *E = nullptr) override {
135 if (!Idx)
136 return true;
137
138 // NB: We are *not* resetting Idx here as to allow multiple
139 // calls to destroyLocals().
140 bool Success = this->emitDestructors(E);
141 this->Ctx->emitDestroy(*Idx, E);
142 ExplicitlyDestroyed = true;
143 return Success;
144 }
145
146 void addLocal(Scope::Local Local) override {
147 if (!Idx) {
148 Idx = static_cast<unsigned>(this->Ctx->Descriptors.size());
149 this->Ctx->Descriptors.emplace_back();
150 }
151
152 Local.EnabledByDefault = this->LocalsAlwaysEnabled;
153 this->Ctx->Descriptors[*Idx].emplace_back(Local);
154 }
155
156 bool emitDestructors(const Expr *E = nullptr) override {
157 if (!Idx)
158 return true;
159
160 // Emit destructor calls for local variables of record
161 // type with a destructor.
162 for (Scope::Local &Local : llvm::reverse(this->Ctx->Descriptors[*Idx])) {
163 if (Local.Desc->hasTrivialDtor())
164 continue;
165
166 if (!Local.EnabledByDefault) {
167 typename Emitter::LabelTy EndLabel = this->Ctx->getLabel();
168 if (!this->Ctx->emitGetLocalEnabled(Local.Offset, E))
169 return false;
170 if (!this->Ctx->jumpFalse(EndLabel, E))
171 return false;
172
173 if (!this->Ctx->emitGetPtrLocal(Local.Offset, E))
174 return false;
175
176 if (!this->Ctx->emitDestructionPop(Local.Desc, Local.Desc->getLoc()))
177 return false;
178
179 this->Ctx->fallthrough(EndLabel);
180 this->Ctx->emitLabel(EndLabel);
181 } else {
182 if (!this->Ctx->emitGetPtrLocal(Local.Offset, E))
183 return false;
184 if (!this->Ctx->emitDestructionPop(Local.Desc, Local.Desc->getLoc()))
185 return false;
186 }
187
189 }
190 return true;
191 }
192
194 if (!Idx)
195 return;
196
197 for (const Scope::Local &Local : this->Ctx->Descriptors[*Idx]) {
199 }
200 }
201
203 if (const auto *OVE =
204 llvm::dyn_cast_if_present<OpaqueValueExpr>(Local.Desc->asExpr())) {
205 this->Ctx->OpaqueExprs.erase(OVE);
206 };
207 }
208
209 /// Index of the scope in the chain.
210 UnsignedOrNone Idx = std::nullopt;
212};
213
214template <class Emitter> class ArrayIndexScope final {
215public:
216 ArrayIndexScope(Compiler<Emitter> *Ctx, uint64_t Index) : Ctx(Ctx) {
217 OldArrayIndex = Ctx->ArrayIndex;
218 Ctx->ArrayIndex = Index;
219 }
220
221 ~ArrayIndexScope() { Ctx->ArrayIndex = OldArrayIndex; }
222
223private:
225 std::optional<uint64_t> OldArrayIndex;
226};
227
228template <class Emitter> class SourceLocScope final {
229public:
230 SourceLocScope(Compiler<Emitter> *Ctx, const Expr *DefaultExpr) : Ctx(Ctx) {
231 assert(DefaultExpr);
232 // We only switch if the current SourceLocDefaultExpr is null.
233 if (!Ctx->SourceLocDefaultExpr) {
234 Enabled = true;
235 Ctx->SourceLocDefaultExpr = DefaultExpr;
236 }
237 }
238
240 if (Enabled)
241 Ctx->SourceLocDefaultExpr = nullptr;
242 }
243
244private:
246 bool Enabled = false;
247};
248
249template <class Emitter> class InitLinkScope final {
250public:
252 Ctx->InitStack.push_back(std::move(Link));
253 }
254
255 ~InitLinkScope() { this->Ctx->InitStack.pop_back(); }
256
257public:
259};
260
261template <class Emitter> class InitStackScope final {
262public:
264 : Ctx(Ctx), OldValue(Ctx->InitStackActive), Active(Active) {
265 // An explicit initializer nested in a default member initializer still
266 // needs the surrounding default initializer's `this` reconstruction.
267 Ctx->InitStackActive = OldValue || Active;
268 if (Active)
269 Ctx->InitStack.push_back(InitLink::DIE());
270 }
271
273 this->Ctx->InitStackActive = OldValue;
274 if (Active)
275 Ctx->InitStack.pop_back();
276 }
277
278private:
280 bool OldValue;
281 bool Active;
282};
283
284/// Scope used to handle temporaries in toplevel variable declarations.
285template <class Emitter> class DeclScope final : public LocalScope<Emitter> {
286public:
288 : LocalScope<Emitter>(Ctx), Scope(Ctx->P),
289 OldInitializingDecl(Ctx->InitializingDecl) {
290 Ctx->InitializingDecl = VD;
291 Ctx->InitStack.push_back(InitLink::Decl(VD));
292 }
293
295 this->Ctx->InitializingDecl = OldInitializingDecl;
296 this->Ctx->InitStack.pop_back();
297 }
298
299private:
301 const VarDecl *OldInitializingDecl;
302};
303
304/// Scope used to handle initialization methods.
305template <class Emitter> class OptionScope final {
306public:
307 /// Root constructor, compiling or discarding primitives.
308 OptionScope(Compiler<Emitter> *Ctx, bool NewDiscardResult,
309 bool NewInitializing, bool NewToLValue)
310 : Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult),
311 OldInitializing(Ctx->Initializing), OldToLValue(Ctx->ToLValue) {
312 Ctx->DiscardResult = NewDiscardResult;
313 Ctx->Initializing = NewInitializing;
314 Ctx->ToLValue = NewToLValue;
315 }
316
318 Ctx->DiscardResult = OldDiscardResult;
319 Ctx->Initializing = OldInitializing;
320 Ctx->ToLValue = OldToLValue;
321 }
322
323private:
324 /// Parent context.
326 /// Old discard flag to restore.
327 bool OldDiscardResult;
328 bool OldInitializing;
329 bool OldToLValue;
330};
331
332template <class Emitter>
333bool InitLink::emit(Compiler<Emitter> *Ctx, const Expr *E) const {
334 switch (Kind) {
335 case K_This:
336 return Ctx->emitThis(E);
337 case K_Field:
338 // We're assuming there's a base pointer on the stack already.
339 return Ctx->emitGetPtrFieldPop(Offset, E);
340 case K_Base:
341 return Ctx->emitGetPtrBasePop(Offset, false, E);
342 case K_Temp:
343 return Ctx->emitGetPtrLocal(Offset, E);
344 case K_Decl:
345 return Ctx->visitDeclRef(D, E);
346 case K_Elem:
347 if (!Ctx->emitConstUint32(Offset, E))
348 return false;
349 return Ctx->emitArrayElemPtrPopUint32(E);
350 case K_RVO:
351 return Ctx->emitRVOPtr(E);
352 case K_InitList:
353 return true;
354 default:
355 llvm_unreachable("Unhandled InitLink kind");
356 }
357 return true;
358}
359
360/// Sets the context for break/continue statements.
361template <class Emitter> class LoopScope final {
362public:
366
367 LoopScope(Compiler<Emitter> *Ctx, const Stmt *Name, LabelTy BreakLabel,
368 LabelTy ContinueLabel)
369 : Ctx(Ctx) {
370#ifndef NDEBUG
371 for (const LabelInfo &LI : Ctx->LabelInfoStack)
372 assert(LI.Name != Name);
373#endif
374
375 this->Ctx->LabelInfoStack.emplace_back(Name, BreakLabel, ContinueLabel,
376 /*DefaultLabel=*/std::nullopt,
377 Ctx->VarScope);
378 }
379
380 ~LoopScope() { this->Ctx->LabelInfoStack.pop_back(); }
381
382private:
384};
385
386// Sets the context for a switch scope, mapping labels.
387template <class Emitter> class SwitchScope final {
388public:
393
394 SwitchScope(Compiler<Emitter> *Ctx, const Stmt *Name, CaseMap &&CaseLabels,
395 LabelTy BreakLabel, OptLabelTy DefaultLabel)
396 : Ctx(Ctx), OldCaseLabels(std::move(this->Ctx->CaseLabels)) {
397#ifndef NDEBUG
398 for (const LabelInfo &LI : Ctx->LabelInfoStack)
399 assert(LI.Name != Name);
400#endif
401
402 this->Ctx->CaseLabels = std::move(CaseLabels);
403 this->Ctx->LabelInfoStack.emplace_back(Name, BreakLabel,
404 /*ContinueLabel=*/std::nullopt,
405 DefaultLabel, Ctx->VarScope);
406 }
407
409 this->Ctx->CaseLabels = std::move(OldCaseLabels);
410 this->Ctx->LabelInfoStack.pop_back();
411 }
412
413private:
415 CaseMap OldCaseLabels;
416};
417
418/// When generating code for e.g. implicit field initializers in constructors,
419/// we don't have anything to point to in case the initializer causes an error.
420/// In that case, we need to disable location tracking for the initializer so
421/// we later point to the call range instead.
422template <class Emitter> class LocOverrideScope final {
423public:
425 bool Enabled = true)
426 : Ctx(Ctx), OldFlag(Ctx->LocOverride), Enabled(Enabled) {
427
428 if (Enabled)
429 Ctx->LocOverride = NewValue;
430 }
431
433 if (Enabled)
434 Ctx->LocOverride = OldFlag;
435 }
436
437private:
439 std::optional<SourceInfo> OldFlag;
440 bool Enabled;
441};
442
443} // namespace interp
444} // namespace clang
445
446template <class Emitter>
448 const Expr *SubExpr = E->getSubExpr();
449
450 if (DiscardResult)
451 return this->delegate(SubExpr);
452
453 switch (E->getCastKind()) {
454 case CK_LValueToRValue: {
455 // This *could* work I guess, but the current interpreter rejects (via
456 // checkLiteralType).
457 if (!Ctx.getLangOpts().HLSL && E->getType()->isConstantMatrixType())
458 return false;
459
460 if (ToLValue && E->getType()->isPointerType()) {
461 assert(!DiscardResult);
462 if (!this->visit(SubExpr))
463 return false;
464 return this->emitLoadPopL(E);
465 }
466
467 if (SubExpr->getType().isVolatileQualified())
468 return this->emitInvalidCast(CastKind::Volatile, /*Fatal=*/true, E);
469
470 OptPrimType SubExprT = classify(SubExpr->getType());
471 // Try to load the value directly. This is purely a performance
472 // optimization.
473 if (SubExprT) {
474 if (const auto *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
475 const ValueDecl *D = DRE->getDecl();
476 bool IsReference = D->getType()->isReferenceType();
477
478 if (!IsReference) {
480 if (auto GlobalIndex = P.getGlobal(D))
481 return this->emitGetGlobal(*SubExprT, *GlobalIndex, E);
482 } else if (auto It = Locals.find(D); It != Locals.end()) {
483 return this->emitGetLocal(*SubExprT, It->second.Offset, E);
484 } else if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
485 if (auto It = this->Params.find(PVD); It != this->Params.end()) {
486 return this->emitGetParam(*SubExprT, It->second.Index, E);
487 }
488 }
489 }
490 }
491 }
492
493 // Prepare storage for the result.
494 if (!Initializing && !SubExprT) {
495 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
496 if (!LocalIndex)
497 return false;
498 if (!this->emitGetPtrLocal(*LocalIndex, E))
499 return false;
500 }
501
502 if (!this->visit(SubExpr))
503 return false;
504
505 if (SubExprT)
506 return this->emitLoadPop(*SubExprT, E);
507
508 // If the subexpr type is not primitive, we need to perform a copy here.
509 // This happens for example in C when dereferencing a pointer of struct
510 // type.
511 return this->emitMemcpy(E);
512 }
513
514 case CK_DerivedToBaseMemberPointer: {
515 if (E->containsErrors())
516 return false;
517 assert(classifyPrim(E) == PT_MemberPtr);
518 assert(classifyPrim(SubExpr) == PT_MemberPtr);
519
520 if (!this->delegate(SubExpr))
521 return false;
522
523 const CXXRecordDecl *CurDecl = SubExpr->getType()
525 ->getMostRecentCXXRecordDecl();
526 for (const CXXBaseSpecifier *B : E->path()) {
527 const CXXRecordDecl *ToDecl = B->getType()->getAsCXXRecordDecl();
528 unsigned DerivedOffset = Ctx.collectBaseOffset(ToDecl, CurDecl);
529
530 if (!this->emitCastMemberPtrBasePop(DerivedOffset, ToDecl, E))
531 return false;
532 CurDecl = ToDecl;
533 }
534
535 return true;
536 }
537
538 case CK_BaseToDerivedMemberPointer: {
539 if (E->containsErrors())
540 return false;
541 assert(classifyPrim(E) == PT_MemberPtr);
542 assert(classifyPrim(SubExpr) == PT_MemberPtr);
543
544 if (!this->delegate(SubExpr))
545 return false;
546
547 const CXXRecordDecl *CurDecl = SubExpr->getType()
549 ->getMostRecentCXXRecordDecl();
550 // Base-to-derived member pointer casts store the path in derived-to-base
551 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
552 // the wrong end of the derived->base arc, so stagger the path by one class.
553 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
554 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
555 PathI != PathE; ++PathI) {
556 const CXXRecordDecl *ToDecl = (*PathI)->getType()->getAsCXXRecordDecl();
557 unsigned DerivedOffset = Ctx.collectBaseOffset(CurDecl, ToDecl);
558
559 if (!this->emitCastMemberPtrDerivedPop(-DerivedOffset, ToDecl, E))
560 return false;
561 CurDecl = ToDecl;
562 }
563
564 const CXXRecordDecl *ToDecl =
565 E->getType()->castAs<MemberPointerType>()->getMostRecentCXXRecordDecl();
566 assert(ToDecl != CurDecl);
567 unsigned DerivedOffset = Ctx.collectBaseOffset(CurDecl, ToDecl);
568
569 if (!this->emitCastMemberPtrDerivedPop(-DerivedOffset, ToDecl, E))
570 return false;
571
572 return true;
573 }
574
575 case CK_UncheckedDerivedToBase:
576 case CK_DerivedToBase: {
577 if (!this->delegate(SubExpr))
578 return false;
579
580 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
581 if (const auto *PT = dyn_cast<PointerType>(Ty))
582 return PT->getPointeeType()->getAsCXXRecordDecl();
583 return Ty->getAsCXXRecordDecl();
584 };
585
586 // FIXME: We can express a series of non-virtual casts as a single
587 // GetPtrBasePop op.
588 QualType CurType = SubExpr->getType();
589 for (const CXXBaseSpecifier *B : E->path()) {
590 if (B->isVirtual()) {
591 if (!this->emitGetPtrVirtBasePop(extractRecordDecl(B->getType()), E))
592 return false;
593 CurType = B->getType();
594 } else {
595 unsigned DerivedOffset = collectBaseOffset(B->getType(), CurType);
596 if (!this->emitGetPtrBasePop(
597 DerivedOffset, /*NullOK=*/E->getType()->isPointerType(), E))
598 return false;
599 CurType = B->getType();
600 }
601 }
602
603 return true;
604 }
605
606 case CK_BaseToDerived: {
607 if (!this->delegate(SubExpr))
608 return false;
609
610 auto unwrapPointerType = [](const Type *T) -> const Type * {
611 if (T->isPointerOrReferenceType())
612 return T->getPointeeType().getTypePtr();
613 return T;
614 };
615
616 bool NullOK = false;
617 const Type *FinalType = E->getType().getTypePtr();
618 if (FinalType->isPointerOrReferenceType()) {
619 NullOK = true;
620 FinalType = FinalType->getPointeeType().getTypePtr();
621 }
622
623 for (const CXXBaseSpecifier *B :
624 llvm::drop_begin(llvm::reverse(E->path()))) {
625 const Type *TargetType = unwrapPointerType(B->getType().getTypePtr());
626 if (!this->emitGetPtrDerivedPop(NullOK, TargetType, FinalType, E))
627 return false;
628 }
629
630 return this->emitGetPtrDerivedPop(NullOK, FinalType, FinalType, E);
631 }
632
633 case CK_FloatingCast: {
634 // HLSL uses CK_FloatingCast to cast between vectors.
635 if (E->getType()->isVectorType())
636 return this->emitVectorConversion(E->getSubExpr(), E);
637 if (!SubExpr->getType()->isFloatingType() ||
638 !E->getType()->isFloatingType())
639 return false;
640 if (!this->visit(SubExpr))
641 return false;
642 const auto *TargetSemantics = &Ctx.getFloatSemantics(E->getType());
643 return this->emitCastFP(TargetSemantics, getRoundingMode(E), E);
644 }
645
646 case CK_IntegralToFloating: {
647 if (E->getType()->isVectorType())
648 return this->emitVectorConversion(E->getSubExpr(), E);
649 if (!E->getType()->isRealFloatingType())
650 return false;
651 if (!this->visit(SubExpr))
652 return false;
653 const auto *TargetSemantics = &Ctx.getFloatSemantics(E->getType());
654 return this->emitCastIntegralFloating(classifyPrim(SubExpr),
655 TargetSemantics, getFPOptions(E), E);
656 }
657
658 case CK_FloatingToBoolean: {
659 if (E->getType()->isVectorType())
660 return this->emitVectorConversion(E->getSubExpr(), E);
661 if (!SubExpr->getType()->isRealFloatingType() ||
663 return false;
664 if (const auto *FL = dyn_cast<FloatingLiteral>(SubExpr))
665 return this->emitConstBool(FL->getValue().isNonZero(), E);
666 if (!this->visit(SubExpr))
667 return false;
668 return this->emitCastFloatingIntegralBool(getFPOptions(E), E);
669 }
670
671 case CK_FloatingToIntegral: {
672 if (E->getType()->isVectorType())
673 return this->emitVectorConversion(E->getSubExpr(), E);
675 return false;
676 if (!this->visit(SubExpr))
677 return false;
678 PrimType ToT = classifyPrim(E);
679 if (ToT == PT_IntAP)
680 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(E->getType()),
681 getFPOptions(E), E);
682 if (ToT == PT_IntAPS)
683 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(E->getType()),
684 getFPOptions(E), E);
685
686 return this->emitCastFloatingIntegral(ToT, getFPOptions(E), E);
687 }
688
689 case CK_NullToPointer:
690 case CK_NullToMemberPointer: {
691 if (!this->discard(SubExpr))
692 return false;
693 uint64_t Val = Ctx.getASTContext().getTargetNullPointerValue(E->getType());
694 return this->emitNull(classifyPrim(E->getType()), Val,
695 E->getType().getTypePtr(), E);
696 }
697
698 case CK_PointerToIntegral: {
699 if (!this->visit(SubExpr))
700 return false;
701
702 // If SubExpr doesn't result in a pointer, make it one.
703 if (PrimType FromT = classifyPrim(SubExpr->getType()); FromT != PT_Ptr) {
704 assert(isPtrType(FromT));
705 if (!this->emitDecayPtr(FromT, PT_Ptr, E))
706 return false;
707 }
708
710 if (T == PT_IntAP)
711 return this->emitCastPointerIntegralAP(Ctx.getBitWidth(E->getType()), E);
712 if (T == PT_IntAPS)
713 return this->emitCastPointerIntegralAPS(Ctx.getBitWidth(E->getType()), E);
714 return this->emitCastPointerIntegral(T, E);
715 }
716
717 case CK_ArrayToPointerDecay: {
718 if (!this->visit(SubExpr))
719 return false;
720 return this->emitArrayDecay(E);
721 }
722
723 case CK_IntegralToPointer: {
724 QualType IntType = SubExpr->getType();
725 assert(IntType->isIntegralOrEnumerationType());
726 if (!this->visit(SubExpr))
727 return false;
728 // FIXME: I think the discard is wrong since the int->ptr cast might cause a
729 // diagnostic.
730 PrimType T = classifyPrim(IntType);
731 if (!this->emitGetIntPtr(T, E->getType().getTypePtr(), E))
732 return false;
733
734 QualType PtrType = E->getType();
735 PrimType DestPtrT = classifyPrim(PtrType);
736 if (DestPtrT == PT_Ptr)
737 return true;
738
739 // In case we're converting the integer to a non-Pointer.
740 return this->emitDecayPtr(PT_Ptr, DestPtrT, E);
741 }
742
743 case CK_AtomicToNonAtomic:
744 case CK_ConstructorConversion:
745 case CK_FunctionToPointerDecay:
746 case CK_NonAtomicToAtomic:
747 case CK_NoOp:
748 case CK_UserDefinedConversion:
749 case CK_CPointerToObjCPointerCast:
750 return this->delegate(SubExpr);
751
752 case CK_AddressSpaceConversion: {
753 if (E->containsErrors())
754 return false;
755
756 if (!this->visit(SubExpr))
757 return false;
758
759 uint64_t Val;
760 if (E->getType()->isPointerType())
761 Val = Ctx.getASTContext().getTargetNullPointerValue(E->getType());
762 else
763 Val = 0;
764
765 if (!this->emitCastAddressSpace(Val, E->getType().getTypePtr(), E))
766 return false;
767 if (DiscardResult)
768 return this->emitPopPtr(E);
769 return true;
770 }
771
772 case CK_BitCast: {
773 if (E->containsErrors())
774 return false;
775 QualType ETy = E->getType();
776 // Reject bitcasts to atomic types.
777 if (ETy->isAtomicType()) {
778 if (!this->discard(SubExpr))
779 return false;
780 return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, E);
781 }
782 QualType SubExprTy = SubExpr->getType();
783 OptPrimType FromT = classify(SubExprTy);
784 // Casts between vectors and integers of the same same size.
785 if (ETy->isVectorType() || SubExprTy->isVectorType())
786 return this->emitBuiltinBitCast(E);
787
788 OptPrimType ToT = classify(E->getType());
789 if (!FromT || !ToT)
790 return false;
791
792 assert(isPtrType(*FromT));
793 assert(isPtrType(*ToT));
794 bool SrcIsVoidPtr = SubExprTy->isVoidPointerType();
795 if (FromT == ToT) {
796 if (E->getType()->isVoidPointerType() &&
797 !SubExprTy->isFunctionPointerType()) {
798 return this->delegate(SubExpr);
799 }
800
801 if (!this->visit(SubExpr))
802 return false;
803 if (!this->emitCheckBitCast(ETy->getPointeeType().getTypePtr(),
804 SrcIsVoidPtr, E))
805 return false;
806
807 if (E->getType()->isFunctionPointerType() ||
808 SubExprTy->isFunctionPointerType()) {
809 return this->emitFnPtrCast(E);
810 }
811 if (FromT == PT_Ptr)
812 return this->emitPtrPtrCast(SubExprTy->isVoidPointerType(),
813 E->getType().getTypePtr(), E);
814 return true;
815 }
816
817 if (!this->visit(SubExpr))
818 return false;
819 return this->emitDecayPtr(*FromT, *ToT, E);
820 }
821 case CK_IntegralToBoolean:
822 case CK_FixedPointToBoolean: {
823 if (E->getType()->isVectorType())
824 return this->emitVectorConversion(E->getSubExpr(), E);
825 // HLSL uses this to cast to one-element vectors.
826 OptPrimType FromT = classify(SubExpr->getType());
827 if (!FromT)
828 return false;
829
830 if (const auto *IL = dyn_cast<IntegerLiteral>(SubExpr))
831 return this->emitConst(IL->getValue(), E);
832 if (!this->visit(SubExpr))
833 return false;
834 return this->emitCast(*FromT, classifyPrim(E), E);
835 }
836
837 case CK_IntegralCast:
838 if (E->getType()->isVectorType())
839 return this->emitVectorConversion(E->getSubExpr(), E);
840 [[fallthrough]];
841 case CK_BooleanToSignedIntegral: {
842 OptPrimType FromT = classify(SubExpr->getType());
843 OptPrimType ToT = classify(E->getType());
844 if (!FromT || !ToT)
845 return false;
846
847 // Try to emit a casted known constant value directly.
848 if (const auto *IL = dyn_cast<IntegerLiteral>(SubExpr)) {
849 if (ToT != PT_IntAP && ToT != PT_IntAPS && FromT != PT_IntAP &&
850 FromT != PT_IntAPS && !E->getType()->isEnumeralType())
851 return this->emitConst(APSInt(IL->getValue(), !isSignedType(*FromT)),
852 E);
853 if (!this->emitConst(IL->getValue(), SubExpr))
854 return false;
855 } else {
856 if (!this->visit(SubExpr))
857 return false;
858 }
859
860 // Possibly diagnose casts to enum types if the target type does not
861 // have a fixed size.
862 if (Ctx.getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) {
863 const auto *ED = E->getType()->castAsEnumDecl();
864 if (!ED->isFixed()) {
865 if (!this->emitCheckEnumValue(*FromT, ED, E))
866 return false;
867 }
868 }
869
870 if (ToT == PT_IntAP) {
871 if (!this->emitCastAP(*FromT, Ctx.getBitWidth(E->getType()), E))
872 return false;
873 } else if (ToT == PT_IntAPS) {
874 if (!this->emitCastAPS(*FromT, Ctx.getBitWidth(E->getType()), E))
875 return false;
876 } else {
877 if (FromT == ToT)
878 return true;
879 if (!this->emitCast(*FromT, *ToT, E))
880 return false;
881 }
882 if (E->getCastKind() == CK_BooleanToSignedIntegral)
883 return this->emitNeg(*ToT, E);
884 return true;
885 }
886
887 case CK_PointerToBoolean:
888 if (!this->visit(SubExpr))
889 return false;
890 return this->emitIsNonNullPtr(E);
891
892 case CK_MemberPointerToBoolean:
893 if (!this->visit(SubExpr))
894 return false;
895 return this->emitIsNonNullMemberPtr(E);
896
897 case CK_IntegralComplexToBoolean:
898 case CK_FloatingComplexToBoolean: {
899 if (!this->visit(SubExpr))
900 return false;
901 return this->emitComplexBoolCast(SubExpr);
902 }
903
904 case CK_IntegralComplexToReal:
905 case CK_FloatingComplexToReal:
906 return this->emitComplexReal(SubExpr);
907
908 case CK_IntegralRealToComplex:
909 case CK_FloatingRealToComplex: {
910 // We're creating a complex value here, so we need to
911 // allocate storage for it.
912 if (!Initializing) {
913 UnsignedOrNone LocalIndex = allocateTemporary(E);
914 if (!LocalIndex)
915 return false;
916 if (!this->emitGetPtrLocal(*LocalIndex, E))
917 return false;
918 }
919
920 PrimType T = classifyPrim(SubExpr->getType());
921 // Init the complex value to {SubExpr, 0}.
922 if (!this->visitArrayElemInit(0, SubExpr, T))
923 return false;
924 // Zero-init the second element.
925 if (!this->visitZeroInitializer(T, SubExpr->getType(), SubExpr))
926 return false;
927 return this->emitInitElem(T, 1, SubExpr);
928 }
929
930 case CK_IntegralComplexCast:
931 case CK_FloatingComplexCast:
932 case CK_IntegralComplexToFloatingComplex:
933 case CK_FloatingComplexToIntegralComplex: {
934 assert(E->getType()->isAnyComplexType());
935 assert(SubExpr->getType()->isAnyComplexType());
936 if (!Initializing) {
937 UnsignedOrNone LocalIndex = allocateLocal(E);
938 if (!LocalIndex)
939 return false;
940 if (!this->emitGetPtrLocal(*LocalIndex, E))
941 return false;
942 }
943
944 // Location for the SubExpr.
945 // Since SubExpr is of complex type, visiting it results in a pointer
946 // anyway, so we just create a temporary pointer variable.
947 unsigned SubExprOffset =
948 allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
949 if (!this->visit(SubExpr))
950 return false;
951 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E))
952 return false;
953
954 PrimType SourceElemT = classifyComplexElementType(SubExpr->getType());
955 QualType DestElemType =
956 E->getType()->getAs<ComplexType>()->getElementType();
957 PrimType DestElemT = classifyPrim(DestElemType);
958 // Cast both elements individually.
959 for (unsigned I = 0; I != 2; ++I) {
960 if (!this->emitGetLocal(PT_Ptr, SubExprOffset, E))
961 return false;
962 if (!this->emitArrayElemPop(SourceElemT, I, E))
963 return false;
964
965 // Do the cast.
966 if (!this->emitPrimCast(SourceElemT, DestElemT, DestElemType, E))
967 return false;
968
969 // Save the value.
970 if (!this->emitInitElem(DestElemT, I, E))
971 return false;
972 }
973 return true;
974 }
975
976 case CK_VectorSplat: {
977 assert(!canClassify(E->getType()));
978 assert(E->getType()->isVectorType());
979
980 if (!canClassify(SubExpr->getType()))
981 return false;
982
983 if (!Initializing) {
984 UnsignedOrNone LocalIndex = allocateLocal(E);
985 if (!LocalIndex)
986 return false;
987 if (!this->emitGetPtrLocal(*LocalIndex, E))
988 return false;
989 }
990
991 const auto *VT = E->getType()->getAs<VectorType>();
992 PrimType ElemT = classifyPrim(SubExpr->getType());
993 unsigned ElemOffset =
994 allocateLocalPrimitive(SubExpr, ElemT, /*IsConst=*/true);
995
996 // Prepare a local variable for the scalar value.
997 if (!this->visit(SubExpr))
998 return false;
999 if (classifyPrim(SubExpr) == PT_Ptr && !this->emitLoadPop(ElemT, E))
1000 return false;
1001
1002 if (!this->emitSetLocal(ElemT, ElemOffset, E))
1003 return false;
1004
1005 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
1006 if (!this->emitGetLocal(ElemT, ElemOffset, E))
1007 return false;
1008 if (!this->emitInitElem(ElemT, I, E))
1009 return false;
1010 }
1011
1012 return true;
1013 }
1014
1015 case CK_HLSLVectorTruncation: {
1016 assert(SubExpr->getType()->isVectorType());
1017 if (OptPrimType ResultT = classify(E)) {
1018 assert(!DiscardResult);
1019 // Result must be either a float or integer. Take the first element.
1020 if (!this->visit(SubExpr))
1021 return false;
1022 return this->emitArrayElemPop(*ResultT, 0, E);
1023 }
1024 // Otherwise, this truncates from one vector type to another.
1025 assert(E->getType()->isVectorType());
1026
1027 if (!Initializing) {
1028 UnsignedOrNone LocalIndex = allocateTemporary(E);
1029 if (!LocalIndex)
1030 return false;
1031 if (!this->emitGetPtrLocal(*LocalIndex, E))
1032 return false;
1033 }
1034 unsigned ToSize = E->getType()->getAs<VectorType>()->getNumElements();
1035 assert(SubExpr->getType()->getAs<VectorType>()->getNumElements() > ToSize);
1036 if (!this->visit(SubExpr))
1037 return false;
1038 return this->emitCopyArray(classifyVectorElementType(E->getType()), 0, 0,
1039 ToSize, E);
1040 };
1041
1042 case CK_IntegralToFixedPoint: {
1043 if (!this->visit(SubExpr))
1044 return false;
1045
1046 auto Sem =
1047 Ctx.getASTContext().getFixedPointSemantics(E->getType()).toOpaqueInt();
1048 if (!this->emitCastIntegralFixedPoint(classifyPrim(SubExpr->getType()), Sem,
1049 E))
1050 return false;
1051 if (DiscardResult)
1052 return this->emitPopFixedPoint(E);
1053 return true;
1054 }
1055 case CK_FloatingToFixedPoint: {
1056 if (!this->visit(SubExpr))
1057 return false;
1058
1059 auto Sem =
1060 Ctx.getASTContext().getFixedPointSemantics(E->getType()).toOpaqueInt();
1061 if (!this->emitCastFloatingFixedPoint(Sem, E))
1062 return false;
1063 if (DiscardResult)
1064 return this->emitPopFixedPoint(E);
1065 return true;
1066 }
1067 case CK_FixedPointToFloating: {
1068 if (!this->visit(SubExpr))
1069 return false;
1070 const auto *TargetSemantics = &Ctx.getFloatSemantics(E->getType());
1071 if (!this->emitCastFixedPointFloating(TargetSemantics, E))
1072 return false;
1073 if (DiscardResult)
1074 return this->emitPopFloat(E);
1075 return true;
1076 }
1077 case CK_FixedPointToIntegral: {
1078 if (!this->visit(SubExpr))
1079 return false;
1080 PrimType IntegralT = classifyPrim(E->getType());
1081 if (!this->emitCastFixedPointIntegral(IntegralT, E))
1082 return false;
1083 if (DiscardResult)
1084 return this->emitPop(IntegralT, E);
1085 return true;
1086 }
1087 case CK_FixedPointCast: {
1088 if (!this->visit(SubExpr))
1089 return false;
1090 auto Sem =
1091 Ctx.getASTContext().getFixedPointSemantics(E->getType()).toOpaqueInt();
1092 if (!this->emitCastFixedPoint(Sem, E))
1093 return false;
1094 if (DiscardResult)
1095 return this->emitPopFixedPoint(E);
1096 return true;
1097 }
1098
1099 case CK_ToVoid:
1100 return discard(SubExpr);
1101
1102 case CK_Dynamic:
1103 llvm_unreachable("CXXDynamicCastExpr has its own function");
1104
1105 case CK_LValueBitCast:
1106 if (!this->emitInvalidCast(CastKind::ReinterpretLike, /*Fatal=*/false, E))
1107 return false;
1108 return this->delegate(SubExpr);
1109
1110 case CK_HLSLArrayRValue: {
1111 // Non-decaying array rvalue cast - creates an rvalue copy of an lvalue
1112 // array, similar to LValueToRValue for composite types.
1113 if (!Initializing) {
1114 UnsignedOrNone LocalIndex = allocateLocal(E);
1115 if (!LocalIndex)
1116 return false;
1117 if (!this->emitGetPtrLocal(*LocalIndex, E))
1118 return false;
1119 }
1120 if (!this->visit(SubExpr))
1121 return false;
1122 return this->emitMemcpy(E);
1123 }
1124
1125 case CK_HLSLMatrixTruncation: {
1126 assert(SubExpr->getType()->isConstantMatrixType());
1127 if (OptPrimType ResultT = classify(E)) {
1128 assert(!DiscardResult);
1129 // Result must be either a float or integer. Take the first element.
1130 if (!this->visit(SubExpr))
1131 return false;
1132 return this->emitArrayElemPop(*ResultT, 0, E);
1133 }
1134 // Otherwise, this truncates to a a constant matrix type.
1135 assert(E->getType()->isConstantMatrixType());
1136
1137 if (!Initializing) {
1138 UnsignedOrNone LocalIndex = allocateTemporary(E);
1139 if (!LocalIndex)
1140 return false;
1141 if (!this->emitGetPtrLocal(*LocalIndex, E))
1142 return false;
1143 }
1144 unsigned ToSize =
1145 E->getType()->getAs<ConstantMatrixType>()->getNumElementsFlattened();
1146 if (!this->visit(SubExpr))
1147 return false;
1148 return this->emitCopyArray(classifyMatrixElementType(SubExpr->getType()), 0,
1149 0, ToSize, E);
1150 }
1151
1152 case CK_HLSLAggregateSplatCast: {
1153 // Aggregate splat cast: convert a scalar value to one of an aggregate type
1154 // by replicating and casting the scalar to every element of the destination
1155 // aggregate (vector, matrix, array, or struct).
1156 assert(canClassify(SubExpr->getType()));
1157
1158 if (!Initializing) {
1159 UnsignedOrNone LocalIndex = allocateLocal(E);
1160 if (!LocalIndex)
1161 return false;
1162 if (!this->emitGetPtrLocal(*LocalIndex, E))
1163 return false;
1164 }
1165
1166 // The scalar to be splatted is stored in a local to be repeatedly loaded
1167 // once for every scalar element of the destination.
1168 PrimType SrcElemT = classifyPrim(SubExpr->getType());
1169 unsigned SrcOffset =
1170 allocateLocalPrimitive(SubExpr, SrcElemT, /*IsConst=*/true);
1171
1172 if (!this->visit(SubExpr))
1173 return false;
1174 if (!this->emitSetLocal(SrcElemT, SrcOffset, E))
1175 return false;
1176
1177 // Recursively splat the scalar into every element of the destination.
1178 return emitHLSLAggregateSplat(SrcElemT, SrcOffset, E->getType(), E);
1179 }
1180
1181 case CK_HLSLElementwiseCast: {
1182 // Elementwise cast: flatten the elements of one aggregate source type and
1183 // store to a destination scalar or aggregate type of the same or fewer
1184 // number of elements. Casts are inserted element-wise to convert each
1185 // source scalar element to its corresponding destination scalar element.
1186 QualType SrcType = SubExpr->getType();
1187 QualType DestType = E->getType();
1188
1189 if (OptPrimType DestT = classify(DestType)) {
1190 // When the destination is a scalar, we only need the first scalar
1191 // element of the source.
1192 unsigned SrcPtrOffset =
1193 allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
1194 if (!this->visit(SubExpr))
1195 return false;
1196 if (!this->emitSetLocal(PT_Ptr, SrcPtrOffset, E))
1197 return false;
1198
1200 if (!emitHLSLFlattenAggregate(SrcType, SrcPtrOffset, Elements, 1, E))
1201 return false;
1202 if (Elements.empty())
1203 return false;
1204
1205 const HLSLFlatElement &Src = Elements[0];
1206 if (!this->emitGetLocal(Src.Type, Src.LocalOffset, E))
1207 return false;
1208 return this->emitPrimCast(Src.Type, *DestT, DestType, E);
1209 }
1210
1211 if (!Initializing) {
1212 UnsignedOrNone LocalIndex = allocateLocal(E);
1213 if (!LocalIndex)
1214 return false;
1215 if (!this->emitGetPtrLocal(*LocalIndex, E))
1216 return false;
1217 }
1218
1219 unsigned SrcOffset =
1220 allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
1221 if (!this->visit(SubExpr))
1222 return false;
1223 if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
1224 return false;
1225
1226 // Only flatten as many source elements as the destination requires.
1227 unsigned ElemCount = countHLSLFlatElements(DestType);
1228
1230 Elements.reserve(ElemCount);
1231 if (!emitHLSLFlattenAggregate(SrcType, SrcOffset, Elements, ElemCount, E))
1232 return false;
1233
1234 // Sema is expected to reject an elementwise cast whose source has fewer
1235 // scalar elements than the destination.
1236 assert(Elements.size() == ElemCount &&
1237 "Source type has fewer scalar elements than the destination type");
1238
1239 return emitHLSLConstructAggregate(DestType, Elements, E);
1240 }
1241
1242 case CK_ToUnion: {
1243 const FieldDecl *UnionField = E->getTargetUnionField();
1244 const Record *R = this->getRecord(E->getType());
1245 assert(R);
1246 const Record::Field *RF = R->getField(UnionField);
1247
1248 if (OptPrimType PT = RF->T) {
1249 if (!this->visit(SubExpr))
1250 return false;
1251 if (RF->isBitField())
1252 return this->emitInitBitFieldActivate(*PT, RF->Offset, RF->bitWidth(),
1253 E);
1254 return this->emitInitFieldActivate(*PT, RF->Offset, E);
1255 }
1256
1257 if (!this->emitGetPtrField(RF->Offset, E))
1258 return false;
1259 if (!this->emitActivate(E))
1260 return false;
1261 return this->visitInitializerPop(SubExpr);
1262 }
1263
1264 default:
1265 return this->emitInvalid(E);
1266 }
1267 llvm_unreachable("Unhandled clang::CastKind enum");
1268}
1269
1270template <class Emitter>
1272 return this->emitBuiltinBitCast(E);
1273}
1274
1275template <class Emitter>
1277 if (DiscardResult)
1278 return true;
1279
1280 return this->emitConst(LE->getValue(), LE);
1281}
1282
1283template <class Emitter>
1285 if (DiscardResult)
1286 return true;
1287
1288 APFloat F = E->getValue();
1289 return this->emitFloat(F, E);
1290}
1291
1292template <class Emitter>
1294 assert(E->getType()->isAnyComplexType());
1295 if (DiscardResult)
1296 return true;
1297
1298 if (!Initializing) {
1299 UnsignedOrNone LocalIndex = allocateTemporary(E);
1300 if (!LocalIndex)
1301 return false;
1302 if (!this->emitGetPtrLocal(*LocalIndex, E))
1303 return false;
1304 }
1305
1306 const Expr *SubExpr = E->getSubExpr();
1307 PrimType SubExprT = classifyPrim(SubExpr->getType());
1308
1309 if (!this->visitZeroInitializer(SubExprT, SubExpr->getType(), SubExpr))
1310 return false;
1311 if (!this->emitInitElem(SubExprT, 0, SubExpr))
1312 return false;
1313 if (!this->visitArrayElemInit(1, SubExpr, SubExprT))
1314 return false;
1315 return this->emitFinishInit(E);
1316}
1317
1318template <class Emitter>
1320 assert(E->getType()->isFixedPointType());
1321 assert(classifyPrim(E) == PT_FixedPoint);
1322
1323 if (DiscardResult)
1324 return true;
1325
1326 auto Sem = Ctx.getASTContext().getFixedPointSemantics(E->getType());
1327 APInt Value = E->getValue();
1328 return this->emitConstFixedPoint(FixedPoint(Value, Sem), E);
1329}
1330
1331template <class Emitter>
1333 return this->delegate(E->getSubExpr());
1334}
1335
1336template <class Emitter>
1338 // Need short-circuiting for these.
1339 if (E->isLogicalOp() && !E->getType()->isVectorType())
1340 return this->VisitLogicalBinOp(E);
1341
1342 const Expr *LHS = E->getLHS();
1343 const Expr *RHS = E->getRHS();
1344
1345 // Handle comma operators. Just discard the LHS
1346 // and delegate to RHS.
1347 if (E->isCommaOp()) {
1348 if (!this->discard(LHS))
1349 return false;
1350 if (RHS->getType()->isVoidType())
1351 return this->discard(RHS);
1352
1353 return this->delegate(RHS);
1354 }
1355
1356 if (E->getType()->isAnyComplexType())
1357 return this->VisitComplexBinOp(E);
1358 if (E->getType()->isVectorType())
1359 return this->VisitVectorBinOp(E);
1360 if ((LHS->getType()->isAnyComplexType() ||
1361 RHS->getType()->isAnyComplexType()) &&
1362 E->isComparisonOp())
1363 return this->emitComplexComparison(LHS, RHS, E);
1364 if (LHS->getType()->isFixedPointType() || RHS->getType()->isFixedPointType())
1365 return this->VisitFixedPointBinOp(E);
1366
1367 if (E->isPtrMemOp()) {
1368 if (E->containsErrors())
1369 return false;
1370
1371 if (!this->visit(LHS))
1372 return false;
1373
1374 if (!this->visit(RHS))
1375 return false;
1376
1377 if (!this->emitToMemberPtr(E))
1378 return false;
1379
1380 if (classifyPrim(E) == PT_MemberPtr)
1381 return true;
1382
1383 if (!this->emitCastMemberPtrPtr(E))
1384 return false;
1385 return DiscardResult ? this->emitPopPtr(E) : true;
1386 }
1387
1388 // Typecheck the args.
1389 OptPrimType LT = classify(LHS);
1390 OptPrimType RT = classify(RHS);
1391 OptPrimType T = classify(E->getType());
1392
1393 // Special case for C++'s three-way/spaceship operator <=>, which
1394 // returns a std::{strong,weak,partial}_ordering (which is a class, so doesn't
1395 // have a PrimType).
1396 if (!T && E->getOpcode() == BO_Cmp) {
1397 if (DiscardResult)
1398 return true;
1399 const ComparisonCategoryInfo *CmpInfo =
1400 Ctx.getASTContext().CompCategories.lookupInfoForType(E->getType());
1401 assert(CmpInfo);
1402
1403 // We need a temporary variable holding our return value.
1404 if (!Initializing) {
1405 UnsignedOrNone ResultIndex = this->allocateLocal(E);
1406 if (!this->emitGetPtrLocal(*ResultIndex, E))
1407 return false;
1408 }
1409
1410 if (!visit(LHS) || !visit(RHS))
1411 return false;
1412
1413 return this->emitCMP3(*LT, CmpInfo, E);
1414 }
1415
1416 if (!LT || !RT || !T)
1417 return false;
1418
1419 // Pointer arithmetic special case.
1420 if (E->getOpcode() == BO_Add || E->getOpcode() == BO_Sub) {
1421 if (isPtrType(*T) || (isPtrType(*LT) && isPtrType(*RT)))
1422 return this->VisitPointerArithBinOp(E);
1423 }
1424
1425 if (E->getOpcode() == BO_Assign)
1426 return this->visitAssignment(LHS, RHS, E);
1427
1428 if (!visit(LHS) || !visit(RHS))
1429 return false;
1430
1431 // For languages such as C, cast the result of one
1432 // of our comparision opcodes to T (which is usually int).
1433 auto MaybeCastToBool = [this, T, E](bool Result) {
1434 if (!Result)
1435 return false;
1436 if (DiscardResult)
1437 return this->emitPopBool(E);
1438 if (T != PT_Bool)
1439 return this->emitCast(PT_Bool, *T, E);
1440 return true;
1441 };
1442
1443 auto Discard = [this, T, E](bool Result) {
1444 if (!Result)
1445 return false;
1446 return DiscardResult ? this->emitPop(*T, E) : true;
1447 };
1448
1449 switch (E->getOpcode()) {
1450 case BO_EQ:
1451 return MaybeCastToBool(this->emitEQ(*LT, E));
1452 case BO_NE:
1453 return MaybeCastToBool(this->emitNE(*LT, E));
1454 case BO_LT:
1455 return MaybeCastToBool(this->emitLT(*LT, E));
1456 case BO_LE:
1457 return MaybeCastToBool(this->emitLE(*LT, E));
1458 case BO_GT:
1459 return MaybeCastToBool(this->emitGT(*LT, E));
1460 case BO_GE:
1461 return MaybeCastToBool(this->emitGE(*LT, E));
1462 case BO_Sub:
1463 if (E->getType()->isFloatingType())
1464 return Discard(this->emitSubf(getFPOptions(E), E));
1465 return Discard(this->emitSub(*T, E));
1466 case BO_Add:
1467 if (E->getType()->isFloatingType())
1468 return Discard(this->emitAddf(getFPOptions(E), E));
1469 return Discard(this->emitAdd(*T, E));
1470 case BO_Mul:
1471 if (E->getType()->isFloatingType())
1472 return Discard(this->emitMulf(getFPOptions(E), E));
1473 return Discard(this->emitMul(*T, E));
1474 case BO_Rem:
1475 return Discard(this->emitRem(*T, E));
1476 case BO_Div:
1477 if (E->getType()->isFloatingType())
1478 return Discard(this->emitDivf(getFPOptions(E), E));
1479 return Discard(this->emitDiv(*T, E));
1480 case BO_And:
1481 return Discard(this->emitBitAnd(*T, E));
1482 case BO_Or:
1483 return Discard(this->emitBitOr(*T, E));
1484 case BO_Shl:
1485 return Discard(this->emitShl(*LT, *RT, E));
1486 case BO_Shr:
1487 return Discard(this->emitShr(*LT, *RT, E));
1488 case BO_Xor:
1489 return Discard(this->emitBitXor(*T, E));
1490 case BO_LOr:
1491 case BO_LAnd:
1492 llvm_unreachable("Already handled earlier");
1493 default:
1494 return false;
1495 }
1496
1497 llvm_unreachable("Unhandled binary op");
1498}
1499
1500/// Perform addition/subtraction of a pointer and an integer or
1501/// subtraction of two pointers.
1502template <class Emitter>
1504 BinaryOperatorKind Op = E->getOpcode();
1505 const Expr *LHS = E->getLHS();
1506 const Expr *RHS = E->getRHS();
1507
1508 if ((Op != BO_Add && Op != BO_Sub) ||
1509 (!LHS->getType()->isPointerType() && !RHS->getType()->isPointerType()))
1510 return false;
1511
1512 OptPrimType LT = classify(LHS);
1513 OptPrimType RT = classify(RHS);
1514
1515 if (!LT || !RT)
1516 return false;
1517
1518 // Visit the given pointer expression and optionally convert to a PT_Ptr.
1519 auto visitAsPointer = [&](const Expr *E, PrimType T) -> bool {
1520 if (!this->visit(E))
1521 return false;
1522 if (T != PT_Ptr)
1523 return this->emitDecayPtr(T, PT_Ptr, E);
1524 return true;
1525 };
1526
1527 if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) {
1528 if (Op != BO_Sub)
1529 return false;
1530
1531 assert(E->getType()->isIntegerType());
1532 if (!visitAsPointer(RHS, *RT) || !visitAsPointer(LHS, *LT))
1533 return false;
1534
1535 QualType ElemType = LHS->getType()->getPointeeType();
1536 CharUnits ElemTypeSize;
1537 if (ElemType->isVoidType() || ElemType->isFunctionType())
1538 ElemTypeSize = CharUnits::One();
1539 else
1540 ElemTypeSize = Ctx.getASTContext().getTypeSizeInChars(ElemType);
1541
1542 PrimType IntT = classifyPrim(E->getType());
1543 if (!this->emitSubPtr(IntT, ElemTypeSize.getQuantity(), E))
1544 return false;
1545 return DiscardResult ? this->emitPop(IntT, E) : true;
1546 }
1547
1548 PrimType OffsetType;
1549 if (LHS->getType()->isIntegerType()) {
1550 if (!visitAsPointer(RHS, *RT))
1551 return false;
1552 if (!this->visit(LHS))
1553 return false;
1554 OffsetType = *LT;
1555 } else if (RHS->getType()->isIntegerType()) {
1556 if (!visitAsPointer(LHS, *LT))
1557 return false;
1558 if (!this->visit(RHS))
1559 return false;
1560 OffsetType = *RT;
1561 } else {
1562 return false;
1563 }
1564
1565 // Do the operation and optionally transform to
1566 // result pointer type.
1567 switch (Op) {
1568 case BO_Add:
1569 if (!this->emitAddOffset(OffsetType, E))
1570 return false;
1571 break;
1572 case BO_Sub:
1573 if (!this->emitSubOffset(OffsetType, E))
1574 return false;
1575 break;
1576 default:
1577 return false;
1578 }
1579
1580 PrimType ExprT = classifyPrim(E);
1581 if (ExprT != PT_Ptr) {
1582 if (!this->emitDecayPtr(PT_Ptr, ExprT, E))
1583 return false;
1584 }
1585
1586 if (DiscardResult)
1587 return this->emitPop(ExprT, E);
1588 return true;
1589}
1590
1591template <class Emitter>
1593 assert(E->isLogicalOp());
1594 BinaryOperatorKind Op = E->getOpcode();
1595 const Expr *LHS = E->getLHS();
1596 const Expr *RHS = E->getRHS();
1597
1598 if (Op == BO_LOr) {
1599 // Logical OR. Visit LHS and only evaluate RHS if LHS was FALSE.
1600 LabelTy LabelTrue = this->getLabel();
1601 LabelTy LabelEnd = this->getLabel();
1602
1603 if (!this->visitBool(LHS))
1604 return false;
1605 if (!this->jumpTrue(LabelTrue, E))
1606 return false;
1607
1608 if (!this->visitBool(RHS))
1609 return false;
1610 if (!this->jump(LabelEnd, E))
1611 return false;
1612
1613 this->emitLabel(LabelTrue);
1614 this->emitConstBool(true, E);
1615 this->fallthrough(LabelEnd);
1616 this->emitLabel(LabelEnd);
1617
1618 } else {
1619 assert(Op == BO_LAnd);
1620 // Logical AND.
1621 // Visit LHS. Only visit RHS if LHS was TRUE.
1622 LabelTy LabelFalse = this->getLabel();
1623 LabelTy LabelEnd = this->getLabel();
1624
1625 if (!this->visitBool(LHS))
1626 return false;
1627 if (!this->jumpFalse(LabelFalse, E))
1628 return false;
1629
1630 if (!this->visitBool(RHS))
1631 return false;
1632 if (!this->jump(LabelEnd, E))
1633 return false;
1634
1635 this->emitLabel(LabelFalse);
1636 this->emitConstBool(false, E);
1637 this->fallthrough(LabelEnd);
1638 this->emitLabel(LabelEnd);
1639 }
1640
1641 if (DiscardResult)
1642 return this->emitPopBool(E);
1643
1644 // For C, cast back to integer type.
1645 if (!E->getType()->isBooleanType()) {
1647 return this->emitCast(PT_Bool, T, E);
1648 }
1649 return true;
1650}
1651
1652template <class Emitter>
1654 // Prepare storage for result.
1655 if (!Initializing) {
1656 UnsignedOrNone LocalIndex = allocateTemporary(E);
1657 if (!LocalIndex)
1658 return false;
1659 if (!this->emitGetPtrLocal(*LocalIndex, E))
1660 return false;
1661 }
1662
1663 // Both LHS and RHS might _not_ be of complex type, but one of them
1664 // needs to be.
1665 const Expr *LHS = E->getLHS();
1666 const Expr *RHS = E->getRHS();
1667
1668 PrimType ResultElemT = this->classifyComplexElementType(E->getType());
1669 unsigned ResultOffset = ~0u;
1670 if (!DiscardResult)
1671 ResultOffset = this->allocateLocalPrimitive(E, PT_Ptr, /*IsConst=*/true);
1672
1673 // Save result pointer in ResultOffset
1674 if (!this->DiscardResult) {
1675 if (!this->emitDupPtr(E))
1676 return false;
1677 if (!this->emitSetLocal(PT_Ptr, ResultOffset, E))
1678 return false;
1679 }
1680 QualType LHSType = LHS->getType();
1681 if (const auto *AT = LHSType->getAs<AtomicType>())
1682 LHSType = AT->getValueType();
1683 QualType RHSType = RHS->getType();
1684 if (const auto *AT = RHSType->getAs<AtomicType>())
1685 RHSType = AT->getValueType();
1686
1687 bool LHSIsComplex = LHSType->isAnyComplexType();
1688 unsigned LHSOffset;
1689 bool RHSIsComplex = RHSType->isAnyComplexType();
1690
1691 // For ComplexComplex Mul, we have special ops to make their implementation
1692 // easier.
1693 BinaryOperatorKind Op = E->getOpcode();
1694 if (Op == BO_Mul && LHSIsComplex && RHSIsComplex) {
1695 assert(classifyPrim(LHSType->getAs<ComplexType>()->getElementType()) ==
1697 PrimType ElemT =
1699 if (!this->visit(LHS))
1700 return false;
1701 if (!this->visit(RHS))
1702 return false;
1703 if (!this->emitMulc(ElemT, E))
1704 return false;
1705 if (DiscardResult)
1706 return this->emitPopPtr(E);
1707 return true;
1708 }
1709
1710 if (Op == BO_Div && RHSIsComplex) {
1711 QualType ElemQT = RHSType->getAs<ComplexType>()->getElementType();
1712 PrimType ElemT = classifyPrim(ElemQT);
1713 // If the LHS is not complex, we still need to do the full complex
1714 // division, so just stub create a complex value and stub it out with
1715 // the LHS and a zero.
1716
1717 if (!LHSIsComplex) {
1718 // This is using the RHS type for the fake-complex LHS.
1719 UnsignedOrNone LocalIndex = allocateTemporary(RHS);
1720 if (!LocalIndex)
1721 return false;
1722 LHSOffset = *LocalIndex;
1723
1724 if (!this->emitGetPtrLocal(LHSOffset, E))
1725 return false;
1726
1727 if (!this->visit(LHS))
1728 return false;
1729 // real is LHS
1730 if (!this->emitInitElem(ElemT, 0, E))
1731 return false;
1732 // imag is zero
1733 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1734 return false;
1735 if (!this->emitInitElem(ElemT, 1, E))
1736 return false;
1737 } else {
1738 if (!this->visit(LHS))
1739 return false;
1740 }
1741
1742 if (!this->visit(RHS))
1743 return false;
1744 if (!this->emitDivc(ElemT, E))
1745 return false;
1746 if (DiscardResult)
1747 return this->emitPopPtr(E);
1748 return true;
1749 }
1750
1751 // Evaluate LHS and save value to LHSOffset.
1752 if (LHSType->isAnyComplexType()) {
1753 LHSOffset = this->allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
1754 if (!this->visit(LHS))
1755 return false;
1756 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
1757 return false;
1758 } else {
1759 PrimType LHST = classifyPrim(LHSType);
1760 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, /*IsConst=*/true);
1761 if (!this->visit(LHS))
1762 return false;
1763 if (!this->emitSetLocal(LHST, LHSOffset, E))
1764 return false;
1765 }
1766
1767 // Same with RHS.
1768 unsigned RHSOffset;
1769 if (RHSType->isAnyComplexType()) {
1770 RHSOffset = this->allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
1771 if (!this->visit(RHS))
1772 return false;
1773 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
1774 return false;
1775 } else {
1776 PrimType RHST = classifyPrim(RHSType);
1777 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, /*IsConst=*/true);
1778 if (!this->visit(RHS))
1779 return false;
1780 if (!this->emitSetLocal(RHST, RHSOffset, E))
1781 return false;
1782 }
1783
1784 // For both LHS and RHS, either load the value from the complex pointer, or
1785 // directly from the local variable. For index 1 (i.e. the imaginary part),
1786 // just load 0 and do the operation anyway.
1787 auto loadComplexValue = [this](bool IsComplex, bool LoadZero,
1788 unsigned ElemIndex, unsigned Offset,
1789 const Expr *E) -> bool {
1790 if (IsComplex) {
1791 if (!this->emitGetLocal(PT_Ptr, Offset, E))
1792 return false;
1793 return this->emitArrayElemPop(classifyComplexElementType(E->getType()),
1794 ElemIndex, E);
1795 }
1796 if (ElemIndex == 0 || !LoadZero)
1797 return this->emitGetLocal(classifyPrim(E->getType()), Offset, E);
1798 return this->visitZeroInitializer(classifyPrim(E->getType()), E->getType(),
1799 E);
1800 };
1801
1802 // Now we can get pointers to the LHS and RHS from the offsets above.
1803 for (unsigned ElemIndex = 0; ElemIndex != 2; ++ElemIndex) {
1804 // Result pointer for the store later.
1805 if (!this->DiscardResult) {
1806 if (!this->emitGetLocal(PT_Ptr, ResultOffset, E))
1807 return false;
1808 }
1809
1810 // The actual operation.
1811 switch (Op) {
1812 case BO_Add:
1813 if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1814 return false;
1815
1816 if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1817 return false;
1818 if (ResultElemT == PT_Float) {
1819 if (!this->emitAddf(getFPOptions(E), E))
1820 return false;
1821 } else {
1822 if (!this->emitAdd(ResultElemT, E))
1823 return false;
1824 }
1825 break;
1826 case BO_Sub:
1827 if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1828 return false;
1829
1830 if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1831 return false;
1832 if (ResultElemT == PT_Float) {
1833 if (!this->emitSubf(getFPOptions(E), E))
1834 return false;
1835 } else {
1836 if (!this->emitSub(ResultElemT, E))
1837 return false;
1838 }
1839 break;
1840 case BO_Mul:
1841 if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1842 return false;
1843
1844 if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1845 return false;
1846
1847 if (ResultElemT == PT_Float) {
1848 if (!this->emitMulf(getFPOptions(E), E))
1849 return false;
1850 } else {
1851 if (!this->emitMul(ResultElemT, E))
1852 return false;
1853 }
1854 break;
1855 case BO_Div:
1856 assert(!RHSIsComplex);
1857 if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1858 return false;
1859
1860 if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1861 return false;
1862
1863 if (ResultElemT == PT_Float) {
1864 if (!this->emitDivf(getFPOptions(E), E))
1865 return false;
1866 } else {
1867 if (!this->emitDiv(ResultElemT, E))
1868 return false;
1869 }
1870 break;
1871
1872 default:
1873 return false;
1874 }
1875
1876 if (!this->DiscardResult) {
1877 // Initialize array element with the value we just computed.
1878 if (!this->emitInitElemPop(ResultElemT, ElemIndex, E))
1879 return false;
1880 } else {
1881 if (!this->emitPop(ResultElemT, E))
1882 return false;
1883 // Remove the Complex temporary pointer we created ourselves at the
1884 // beginning of this function.
1885 if (!Initializing)
1886 return this->emitPopPtr(E);
1887 }
1888 }
1889 return this->emitFinishInit(E);
1890}
1891
1892template <class Emitter>
1894 const Expr *LHS = E->getLHS();
1895 const Expr *RHS = E->getRHS();
1896 assert(!E->isCommaOp() &&
1897 "Comma op should be handled in VisitBinaryOperator");
1898
1899 QualType LHSType = LHS->getType();
1900 if (const auto *AT = LHSType->getAs<AtomicType>())
1901 LHSType = AT->getValueType();
1902 QualType RHSType = RHS->getType();
1903 if (const auto *AT = RHSType->getAs<AtomicType>())
1904 RHSType = AT->getValueType();
1905 assert(E->getType()->isVectorType());
1906 assert(LHSType->isVectorType());
1907 assert(RHSType->isVectorType());
1908
1909 // We can only handle vectors with primitive element types.
1910 if (!canClassify(LHSType->castAs<VectorType>()->getElementType()))
1911 return false;
1912
1913 // Prepare storage for result.
1914 if (!Initializing && !E->isCompoundAssignmentOp() && !E->isAssignmentOp()) {
1915 UnsignedOrNone LocalIndex = allocateTemporary(E);
1916 if (!LocalIndex)
1917 return false;
1918 if (!this->emitGetPtrLocal(*LocalIndex, E))
1919 return false;
1920 }
1921
1922 const auto *VecTy = E->getType()->getAs<VectorType>();
1923 auto Op = E->isCompoundAssignmentOp()
1925 : E->getOpcode();
1926
1927 PrimType ElemT = this->classifyVectorElementType(LHSType);
1928 PrimType RHSElemT = this->classifyVectorElementType(RHSType);
1929 PrimType ResultElemT = this->classifyVectorElementType(E->getType());
1930
1931 if (E->getOpcode() == BO_Assign) {
1932 assert(Ctx.getASTContext().hasSameUnqualifiedType(
1933 LHSType->castAs<VectorType>()->getElementType(),
1934 RHSType->castAs<VectorType>()->getElementType()));
1935 if (!this->visit(LHS))
1936 return false;
1937 if (!this->visit(RHS))
1938 return false;
1939 if (!this->emitCopyArray(ElemT, 0, 0, VecTy->getNumElements(), E))
1940 return false;
1941 if (DiscardResult)
1942 return this->emitPopPtr(E);
1943 return true;
1944 }
1945
1946 // Evaluate LHS and save value to LHSOffset.
1947 unsigned LHSOffset =
1948 this->allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
1949 if (!this->visit(LHS))
1950 return false;
1951 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
1952 return false;
1953
1954 // Evaluate RHS and save value to RHSOffset.
1955 unsigned RHSOffset =
1956 this->allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
1957 if (!this->visit(RHS))
1958 return false;
1959 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
1960 return false;
1961
1962 if (E->isCompoundAssignmentOp() && !this->emitGetLocal(PT_Ptr, LHSOffset, E))
1963 return false;
1964
1965 // BitAdd/BitOr/BitXor/Shl/Shr doesn't support bool type, we need perform the
1966 // integer promotion.
1967 bool NeedIntPromot = ElemT == PT_Bool && (E->isBitwiseOp() || E->isShiftOp());
1968 QualType PromotTy;
1969 PrimType PromotT = PT_Bool;
1970 PrimType OpT = ElemT;
1971 if (NeedIntPromot) {
1972 PromotTy =
1973 Ctx.getASTContext().getPromotedIntegerType(Ctx.getASTContext().BoolTy);
1974 PromotT = classifyPrim(PromotTy);
1975 OpT = PromotT;
1976 }
1977
1978 auto getElem = [=](unsigned Offset, PrimType ElemT, unsigned Index) {
1979 if (!this->emitGetLocal(PT_Ptr, Offset, E))
1980 return false;
1981 if (!this->emitArrayElemPop(ElemT, Index, E))
1982 return false;
1983 if (E->isLogicalOp()) {
1984 if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
1985 return false;
1986 if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), E))
1987 return false;
1988 } else if (NeedIntPromot) {
1989 if (!this->emitPrimCast(ElemT, PromotT, PromotTy, E))
1990 return false;
1991 }
1992 return true;
1993 };
1994
1995#define EMIT_ARITH_OP(OP) \
1996 { \
1997 if (ElemT == PT_Float) { \
1998 if (!this->emit##OP##f(getFPOptions(E), E)) \
1999 return false; \
2000 } else { \
2001 if (!this->emit##OP(ElemT, E)) \
2002 return false; \
2003 } \
2004 break; \
2005 }
2006
2007 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
2008 if (!getElem(LHSOffset, ElemT, I))
2009 return false;
2010 if (!getElem(RHSOffset, RHSElemT, I))
2011 return false;
2012 switch (Op) {
2013 case BO_Add:
2015 case BO_Sub:
2017 case BO_Mul:
2019 case BO_Div:
2021 case BO_Rem:
2022 if (!this->emitRem(ElemT, E))
2023 return false;
2024 break;
2025 case BO_And:
2026 if (!this->emitBitAnd(OpT, E))
2027 return false;
2028 break;
2029 case BO_Or:
2030 if (!this->emitBitOr(OpT, E))
2031 return false;
2032 break;
2033 case BO_Xor:
2034 if (!this->emitBitXor(OpT, E))
2035 return false;
2036 break;
2037 case BO_Shl:
2038 if (!this->emitShl(OpT, RHSElemT, E))
2039 return false;
2040 break;
2041 case BO_Shr:
2042 if (!this->emitShr(OpT, RHSElemT, E))
2043 return false;
2044 break;
2045 case BO_EQ:
2046 if (!this->emitEQ(ElemT, E))
2047 return false;
2048 break;
2049 case BO_NE:
2050 if (!this->emitNE(ElemT, E))
2051 return false;
2052 break;
2053 case BO_LE:
2054 if (!this->emitLE(ElemT, E))
2055 return false;
2056 break;
2057 case BO_LT:
2058 if (!this->emitLT(ElemT, E))
2059 return false;
2060 break;
2061 case BO_GE:
2062 if (!this->emitGE(ElemT, E))
2063 return false;
2064 break;
2065 case BO_GT:
2066 if (!this->emitGT(ElemT, E))
2067 return false;
2068 break;
2069 case BO_LAnd:
2070 // a && b is equivalent to a!=0 & b!=0
2071 if (!this->emitBitAnd(ResultElemT, E))
2072 return false;
2073 break;
2074 case BO_LOr:
2075 // a || b is equivalent to a!=0 | b!=0
2076 if (!this->emitBitOr(ResultElemT, E))
2077 return false;
2078 break;
2079 default:
2080 return this->emitInvalid(E);
2081 }
2082
2083 // The result of the comparison is a vector of the same width and number
2084 // of elements as the comparison operands with a signed integral element
2085 // type.
2086 //
2087 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
2088 if (E->isComparisonOp()) {
2089 if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), E))
2090 return false;
2091 if (!this->emitNeg(ResultElemT, E))
2092 return false;
2093 }
2094
2095 // If we performed an integer promotion, we need to cast the compute result
2096 // into result vector element type.
2097 if (NeedIntPromot &&
2098 !this->emitPrimCast(PromotT, ResultElemT, VecTy->getElementType(), E))
2099 return false;
2100
2101 // Initialize array element with the value we just computed.
2102 if (!this->emitInitElem(ResultElemT, I, E))
2103 return false;
2104 }
2105
2106 if (DiscardResult && E->isCompoundAssignmentOp() && !this->emitPopPtr(E))
2107 return false;
2108 return true;
2109}
2110
2111template <class Emitter>
2113 const Expr *LHS = E->getLHS();
2114 const Expr *RHS = E->getRHS();
2115 const ASTContext &ASTCtx = Ctx.getASTContext();
2116
2117 assert(LHS->getType()->isFixedPointType() ||
2118 RHS->getType()->isFixedPointType());
2119
2120 auto LHSSema = ASTCtx.getFixedPointSemantics(LHS->getType());
2121 auto LHSSemaInt = LHSSema.toOpaqueInt();
2122 auto RHSSema = ASTCtx.getFixedPointSemantics(RHS->getType());
2123 auto RHSSemaInt = RHSSema.toOpaqueInt();
2124
2125 if (!this->visit(LHS))
2126 return false;
2127 if (!LHS->getType()->isFixedPointType()) {
2128 if (!this->emitCastIntegralFixedPoint(classifyPrim(LHS->getType()),
2129 LHSSemaInt, E))
2130 return false;
2131 }
2132
2133 if (!this->visit(RHS))
2134 return false;
2135 if (!RHS->getType()->isFixedPointType()) {
2136 if (!this->emitCastIntegralFixedPoint(classifyPrim(RHS->getType()),
2137 RHSSemaInt, E))
2138 return false;
2139 }
2140
2141 // Convert the result to the target semantics.
2142 auto ConvertResult = [&](bool R) -> bool {
2143 if (!R)
2144 return false;
2145 auto ResultSema = ASTCtx.getFixedPointSemantics(E->getType()).toOpaqueInt();
2146 auto CommonSema = LHSSema.getCommonSemantics(RHSSema).toOpaqueInt();
2147 if (ResultSema != CommonSema)
2148 return this->emitCastFixedPoint(ResultSema, E);
2149 return true;
2150 };
2151
2152 auto MaybeCastToBool = [&](bool Result) {
2153 if (!Result)
2154 return false;
2155 PrimType T = classifyPrim(E);
2156 if (DiscardResult)
2157 return this->emitPop(T, E);
2158 if (T != PT_Bool)
2159 return this->emitCast(PT_Bool, T, E);
2160 return true;
2161 };
2162
2163 switch (E->getOpcode()) {
2164 case BO_EQ:
2165 return MaybeCastToBool(this->emitEQFixedPoint(E));
2166 case BO_NE:
2167 return MaybeCastToBool(this->emitNEFixedPoint(E));
2168 case BO_LT:
2169 return MaybeCastToBool(this->emitLTFixedPoint(E));
2170 case BO_LE:
2171 return MaybeCastToBool(this->emitLEFixedPoint(E));
2172 case BO_GT:
2173 return MaybeCastToBool(this->emitGTFixedPoint(E));
2174 case BO_GE:
2175 return MaybeCastToBool(this->emitGEFixedPoint(E));
2176 case BO_Add:
2177 return ConvertResult(this->emitAddFixedPoint(E));
2178 case BO_Sub:
2179 return ConvertResult(this->emitSubFixedPoint(E));
2180 case BO_Mul:
2181 return ConvertResult(this->emitMulFixedPoint(E));
2182 case BO_Div:
2183 return ConvertResult(this->emitDivFixedPoint(E));
2184 case BO_Shl:
2185 return ConvertResult(this->emitShiftFixedPoint(/*Left=*/true, E));
2186 case BO_Shr:
2187 return ConvertResult(this->emitShiftFixedPoint(/*Left=*/false, E));
2188
2189 default:
2190 return this->emitInvalid(E);
2191 }
2192
2193 llvm_unreachable("unhandled binop opcode");
2194}
2195
2196template <class Emitter>
2198 const Expr *SubExpr = E->getSubExpr();
2199 assert(SubExpr->getType()->isFixedPointType());
2200
2201 switch (E->getOpcode()) {
2202 case UO_Plus:
2203 return this->delegate(SubExpr);
2204 case UO_Minus:
2205 if (!this->visit(SubExpr))
2206 return false;
2207 if (!this->emitNegFixedPoint(E))
2208 return false;
2209 if (DiscardResult)
2210 return this->emitPopFixedPoint(E);
2211 return true;
2212 default:
2213 return false;
2214 }
2215
2216 llvm_unreachable("Unhandled unary opcode");
2217}
2218
2219template <class Emitter>
2221 const ImplicitValueInitExpr *E) {
2222 if (DiscardResult)
2223 return true;
2224
2225 QualType QT = E->getType();
2226
2227 if (OptPrimType T = classify(QT))
2228 return this->visitZeroInitializer(*T, QT, E);
2229
2230 if (QT->isRecordType()) {
2231 const RecordDecl *RD = QT->getAsRecordDecl();
2232 assert(RD);
2233 if (RD->isInvalidDecl())
2234 return false;
2235
2236 const Record *R = getRecord(QT);
2237 if (!R)
2238 return false;
2239
2240 assert(Initializing);
2241 return this->visitZeroRecordInitializer(R, E);
2242 }
2243
2244 if (QT->isIncompleteArrayType())
2245 return true;
2246
2247 if (QT->isArrayType())
2248 return this->visitZeroArrayInitializer(QT, E);
2249
2250 if (const auto *ComplexTy = E->getType()->getAs<ComplexType>()) {
2251 assert(Initializing);
2252 QualType ElemQT = ComplexTy->getElementType();
2253 PrimType ElemT = classifyPrim(ElemQT);
2254 for (unsigned I = 0; I < 2; ++I) {
2255 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2256 return false;
2257 if (!this->emitInitElem(ElemT, I, E))
2258 return false;
2259 }
2260 return true;
2261 }
2262
2263 if (const auto *VecT = E->getType()->getAs<VectorType>()) {
2264 unsigned NumVecElements = VecT->getNumElements();
2265 QualType ElemQT = VecT->getElementType();
2266 PrimType ElemT = classifyPrim(ElemQT);
2267
2268 for (unsigned I = 0; I < NumVecElements; ++I) {
2269 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2270 return false;
2271 if (!this->emitInitElem(ElemT, I, E))
2272 return false;
2273 }
2274 return true;
2275 }
2276
2277 if (const auto *MT = E->getType()->getAs<ConstantMatrixType>()) {
2278 unsigned NumElems = MT->getNumElementsFlattened();
2279 QualType ElemQT = MT->getElementType();
2280 PrimType ElemT = classifyPrim(ElemQT);
2281
2282 for (unsigned I = 0; I != NumElems; ++I) {
2283 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2284 return false;
2285 if (!this->emitInitElem(ElemT, I, E))
2286 return false;
2287 }
2288 return true;
2289 }
2290
2291 return false;
2292}
2293
2294template <class Emitter>
2296 if (E->getType()->isVoidType() || E->containsErrors())
2297 return false;
2298
2299 const Expr *LHS = E->getLHS();
2300 const Expr *RHS = E->getRHS();
2301 const Expr *Index = E->getIdx();
2302 const Expr *Base = E->getBase();
2303
2304 // C++17's rules require us to evaluate the LHS first, regardless of which
2305 // side is the base.
2306 bool Success = true;
2307 for (const Expr *SubExpr : {LHS, RHS}) {
2308 if (!this->visit(SubExpr)) {
2309 Success = false;
2310 continue;
2311 }
2312
2313 // Expand the base if this is a subscript on a
2314 // pointer expression.
2315 if (SubExpr == Base && Base->getType()->isPointerType()) {
2316 if (!this->emitExpandPtr(E))
2317 Success = false;
2318 }
2319 }
2320
2321 if (!Success)
2322 return false;
2323
2324 OptPrimType IndexT = classify(Index->getType());
2325 // In error-recovery cases, the index expression has a dependent type.
2326 if (!IndexT)
2327 return this->emitError(E);
2328 // If the index is first, we need to change that.
2329 if (LHS == Index) {
2330 if (!this->emitFlip(PT_Ptr, *IndexT, E))
2331 return false;
2332 }
2333
2334 if (!this->emitArrayElemPtrPop(*IndexT, E))
2335 return false;
2336 if (DiscardResult)
2337 return this->emitPopPtr(E);
2338
2339 if (E->isGLValue())
2340 return true;
2341
2343 return this->emitLoadPop(*T, E);
2344}
2345
2346template <class Emitter>
2348 const Expr *ArrayFiller, const Expr *E) {
2350
2351 QualType QT = E->getType();
2352 if (const auto *AT = QT->getAs<AtomicType>())
2353 QT = AT->getValueType();
2354
2355 if (QT->isVoidType()) {
2356 if (Inits.size() == 0)
2357 return true;
2358 return this->emitInvalid(E);
2359 }
2360
2361 // Primitive values. A discarded one can simply discard each initializer;
2362 // there is no object to establish.
2363 if (OptPrimType T = classify(QT)) {
2364 if (DiscardResult) {
2365 for (const Expr *Init : Inits) {
2366 if (!this->discard(Init))
2367 return false;
2368 }
2369 return true;
2370 }
2371 if (Inits.size() == 0)
2372 return this->visitZeroInitializer(*T, QT, E);
2373 assert(Inits.size() == 1);
2374 return this->delegate(Inits[0]);
2375 }
2376
2377 assert(!canClassify(E->getType()));
2378
2379 // A composite prvalue needs somewhere to live even when it is discarded: a
2380 // default member initializer may read subobjects initialized earlier in this
2381 // same list, so those have to actually be written and `this` has to denote
2382 // the object. Materialize one and initialize into it.
2383 if (DiscardResult && !Initializing) {
2384 UnsignedOrNone LocalIndex = allocateLocal(E);
2385 if (!LocalIndex)
2386 return false;
2387 if (!this->emitGetPtrLocal(*LocalIndex, E))
2388 return false;
2389 InitLinkScope<Emitter> ILS2(this, InitLink::Temp(*LocalIndex));
2390 return this->visitInitializerPop(E);
2391 }
2392
2393 if (QT->isRecordType()) {
2394 const Record *R = getRecord(QT);
2395
2396 if (Inits.size() == 1 && E->getType() == Inits[0]->getType())
2397 return this->delegate(Inits[0]);
2398
2399 if (!R)
2400 return false;
2401
2402 auto initPrimitiveField = [=](const Record::Field *FieldToInit,
2403 const Expr *Init, PrimType T,
2404 bool Activate = false) -> bool {
2407
2408 if (DefaultInit && !this->emitStartFieldInit(FieldToInit->Offset, Init))
2409 return false;
2410
2411 if (!this->visit(Init))
2412 return false;
2413
2414 if (DefaultInit && !this->emitEndInit(Init))
2415 return false;
2416
2417 bool BitField = FieldToInit->isBitField();
2418 if (BitField && Activate)
2419 return this->emitInitBitFieldActivate(T, FieldToInit->Offset,
2420 FieldToInit->bitWidth(), E);
2421 if (BitField)
2422 return this->emitInitBitField(T, FieldToInit->Offset,
2423 FieldToInit->bitWidth(), E);
2424 if (Activate)
2425 return this->emitInitFieldActivate(T, FieldToInit->Offset, E);
2426 return this->emitInitField(T, FieldToInit->Offset, E);
2427 };
2428
2429 auto initCompositeField = [=](const Record::Field *FieldToInit,
2430 const Expr *Init,
2431 bool Activate = false) -> bool {
2433 InitLinkScope<Emitter> ILS(this, InitLink::Field(FieldToInit->Offset));
2434
2435 // Non-primitive case. Get a pointer to the field-to-initialize
2436 // on the stack and recurse into visitInitializer().
2437 if (!this->emitGetPtrField(FieldToInit->Offset, Init))
2438 return false;
2439
2440 if (Activate && !this->emitActivate(E))
2441 return false;
2442
2443 if (!this->emitStartInit(Init))
2444 return false;
2445
2446 return this->visitInitializerPop(Init) && this->emitEndInit(Init);
2447 };
2448
2449 if (R->isUnion()) {
2450 if (Inits.size() == 0) {
2451 if (!this->visitZeroRecordInitializer(R, E))
2452 return false;
2453 } else {
2454 const Expr *Init = Inits[0];
2455 const FieldDecl *FToInit = nullptr;
2456 if (const auto *ILE = dyn_cast<InitListExpr>(E))
2457 FToInit = ILE->getInitializedFieldInUnion();
2458 else
2459 FToInit = cast<CXXParenListInitExpr>(E)->getInitializedFieldInUnion();
2460
2461 const Record::Field *FieldToInit = R->getField(FToInit);
2462 if (OptPrimType T = classify(Init)) {
2463 if (!initPrimitiveField(FieldToInit, Init, *T, /*Activate=*/true))
2464 return false;
2465 } else {
2466 if (!initCompositeField(FieldToInit, Init, /*Activate=*/true))
2467 return false;
2468 }
2469 }
2470 return this->emitFinishInit(E);
2471 }
2472
2473 assert(!R->isUnion());
2474 for (unsigned BI = 0; BI != R->getNumBases(); ++BI) {
2475 const Expr *Init = Inits[BI];
2476 const Record::Base *B = R->getBase(BI);
2478 InitLinkScope<Emitter> ILS(this, InitLink::Base(B->Offset));
2479 if (!this->emitGetPtrBase(B->Offset, Init))
2480 return false;
2481 if (!this->visitInitializerPop(Init))
2482 return false;
2483 }
2484
2485 unsigned FieldIndex = 0;
2486 for (unsigned FI = R->getNumBases(); FI != Inits.size();) {
2487 const Record::Field *FieldToInit = R->getField(FieldIndex);
2488 if (FieldToInit->isUnnamedBitField()) {
2489 ++FieldIndex;
2490 continue;
2491 }
2492
2493 const Expr *Init = Inits[FI];
2494 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
2495 // aren't supposed to be modified.
2496 if (isa<NoInitExpr>(Init)) {
2497 ++FieldIndex;
2498 ++FI;
2499 continue;
2500 }
2501
2502 if (OptPrimType T = classify(Init)) {
2503 if (!initPrimitiveField(FieldToInit, Init, *T))
2504 return false;
2505 } else if (!initCompositeField(FieldToInit, Init)) {
2506 return false;
2507 }
2508
2509 ++FI;
2510 ++FieldIndex;
2511 }
2512
2513 assert(R->getNumVirtualBases() == 0);
2514
2515 return this->emitFinishInit(E);
2516 }
2517
2518 if (QT->isArrayType()) {
2519 const ConstantArrayType *CAT =
2520 Ctx.getASTContext().getAsConstantArrayType(QT);
2521 uint64_t NumElems = CAT->getZExtSize();
2522
2523 if (Initializing &&
2524 (!InitializingDecl || InitializingDecl->hasLocalStorage()) &&
2525 !this->emitCheckArrayDestSize(NumElems, E))
2526 return false;
2527
2528 if (Inits.size() == 1 && QT == Inits[0]->getType())
2529 return this->delegate(Inits[0]);
2530
2531 OptPrimType InitT = classify(CAT->getElementType());
2532 unsigned ElementIndex = 0;
2533 for (const Expr *Init : Inits) {
2534 if (const auto *EmbedS =
2535 dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
2536 PrimType TargetT = classifyPrim(Init->getType());
2537
2538 auto Eval = [&](const IntegerLiteral *IL, unsigned ElemIndex) {
2539 if (TargetT == PT_Float) {
2540 if (!this->emitConst(IL->getValue(), classifyPrim(IL), Init))
2541 return false;
2542 const auto *Sem = &Ctx.getFloatSemantics(CAT->getElementType());
2543 if (!this->emitCastIntegralFloating(classifyPrim(IL), Sem,
2544 getFPOptions(E), E))
2545 return false;
2546 } else {
2547 if (!this->emitConst(IL->getValue(), TargetT, Init))
2548 return false;
2549 }
2550 return this->emitInitElem(TargetT, ElemIndex, IL);
2551 };
2552 if (!EmbedS->doForEachDataElement(Eval, ElementIndex))
2553 return false;
2554 } else if (isa<NoInitExpr>(Init)) {
2555 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
2556 // aren't supposed to be modified.
2557 ++ElementIndex;
2558 } else {
2559 if (!this->visitArrayElemInit(ElementIndex, Init, InitT))
2560 return false;
2561 ++ElementIndex;
2562 }
2563 }
2564
2565 // Expand the filler expression.
2566 // FIXME: This should go away.
2567 if (ArrayFiller && !isa<NoInitExpr>(ArrayFiller)) {
2568 for (; ElementIndex != NumElems; ++ElementIndex) {
2569 if (!this->visitArrayElemInit(ElementIndex, ArrayFiller, InitT))
2570 return false;
2571 }
2572 }
2573
2574 return this->emitFinishInit(E);
2575 }
2576
2577 if (const auto *ComplexTy = QT->getAs<ComplexType>()) {
2578 unsigned NumInits = Inits.size();
2579
2580 if (NumInits == 1)
2581 return this->delegate(Inits[0]);
2582
2583 QualType ElemQT = ComplexTy->getElementType();
2584 PrimType ElemT = classifyPrim(ElemQT);
2585 if (NumInits == 0) {
2586 // Zero-initialize both elements.
2587 for (unsigned I = 0; I < 2; ++I) {
2588 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2589 return false;
2590 if (!this->emitInitElem(ElemT, I, E))
2591 return false;
2592 }
2593 } else if (NumInits == 2) {
2594 unsigned InitIndex = 0;
2595 for (const Expr *Init : Inits) {
2596 if (!this->visit(Init))
2597 return false;
2598
2599 if (!this->emitInitElem(ElemT, InitIndex, E))
2600 return false;
2601 ++InitIndex;
2602 }
2603 }
2604 return true;
2605 }
2606
2607 if (const auto *VecT = QT->getAs<VectorType>()) {
2608 unsigned NumVecElements = VecT->getNumElements();
2609 assert(NumVecElements >= Inits.size());
2610
2611 QualType ElemQT = VecT->getElementType();
2612 PrimType ElemT = classifyPrim(ElemQT);
2613
2614 // All initializer elements.
2615 unsigned InitIndex = 0;
2616 for (const Expr *Init : Inits) {
2617 if (!this->visit(Init))
2618 return false;
2619
2620 // If the initializer is of vector type itself, we have to deconstruct
2621 // that and initialize all the target fields from the initializer fields.
2622 if (const auto *InitVecT = Init->getType()->getAs<VectorType>()) {
2623 if (!this->emitCopyArray(ElemT, 0, InitIndex,
2624 InitVecT->getNumElements(), E))
2625 return false;
2626 InitIndex += InitVecT->getNumElements();
2627 } else {
2628 if (!this->emitInitElem(ElemT, InitIndex, E))
2629 return false;
2630 ++InitIndex;
2631 }
2632 }
2633
2634 assert(InitIndex <= NumVecElements);
2635
2636 // Fill the rest with zeroes.
2637 for (; InitIndex != NumVecElements; ++InitIndex) {
2638 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2639 return false;
2640 if (!this->emitInitElem(ElemT, InitIndex, E))
2641 return false;
2642 }
2643 return true;
2644 }
2645
2646 if (const auto *MT = QT->getAs<ConstantMatrixType>()) {
2647 unsigned NumElems = MT->getNumElementsFlattened();
2648 assert(Inits.size() == NumElems);
2649
2650 QualType ElemQT = MT->getElementType();
2651 PrimType ElemT = classifyPrim(ElemQT);
2652
2653 // Matrix initializer list elements are in row-major order, which matches
2654 // the matrix APValue convention and therefore no index remapping is
2655 // required.
2656 for (unsigned I = 0; I != NumElems; ++I) {
2657 if (!this->visit(Inits[I]))
2658 return false;
2659 if (!this->emitInitElem(ElemT, I, E))
2660 return false;
2661 }
2662 return true;
2663 }
2664
2665 return false;
2666}
2667
2668/// Pointer to the array(not the element!) must be on the stack when calling
2669/// this.
2670template <class Emitter>
2671bool Compiler<Emitter>::visitArrayElemInit(unsigned ElemIndex, const Expr *Init,
2672 OptPrimType InitT) {
2673 if (InitT) {
2674 // Visit the primitive element like normal.
2675 if (!this->visit(Init))
2676 return false;
2677 return this->emitInitElem(*InitT, ElemIndex, Init);
2678 }
2679
2680 InitLinkScope<Emitter> ILS(this, InitLink::Elem(ElemIndex));
2681 // Advance the pointer currently on the stack to the given
2682 // dimension.
2683 if (!this->emitConstUint32(ElemIndex, Init))
2684 return false;
2685 if (!this->emitArrayElemPtrUint32(Init))
2686 return false;
2687 return this->visitInitializerPop(Init);
2688}
2689
2690template <class Emitter>
2692 const FunctionDecl *FuncDecl,
2693 bool Activate, bool IsOperatorCall) {
2694 assert(VarScope->getKind() == ScopeKind::Call);
2695 llvm::BitVector NonNullArgs;
2696 if (FuncDecl && FuncDecl->hasAttr<NonNullAttr>())
2697 NonNullArgs = collectNonNullArgs(FuncDecl, Args);
2698
2699 bool ExplicitMemberFn = false;
2700 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl))
2701 ExplicitMemberFn = MD->isExplicitObjectMemberFunction();
2702
2703 unsigned ArgIndex = 0;
2704 for (const Expr *Arg : Args) {
2705 if (canClassify(Arg)) {
2706 if (!this->visit(Arg))
2707 return false;
2708 } else {
2709
2710 DeclOrExpr Source = Arg;
2711 if (FuncDecl) {
2712 // Try to use the parameter declaration instead of the argument
2713 // expression as a source.
2714 unsigned DeclIndex = ArgIndex - IsOperatorCall + ExplicitMemberFn;
2715 if (DeclIndex < FuncDecl->getNumParams())
2716 Source = FuncDecl->getParamDecl(ArgIndex - IsOperatorCall +
2717 ExplicitMemberFn);
2718 }
2719
2720 UnsignedOrNone LocalIndex =
2721 allocateLocal(Source, Arg->getType(), ScopeKind::Call);
2722 if (!LocalIndex)
2723 return false;
2724
2725 if (!this->emitGetPtrLocal(*LocalIndex, Arg))
2726 return false;
2727 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
2728 if (!this->visitInitializer(Arg))
2729 return false;
2730 }
2731
2732 if (ArgIndex == 1 && Activate) {
2733 if (!this->emitActivate(Arg))
2734 return false;
2735 }
2736
2737 if (!NonNullArgs.empty() && NonNullArgs[ArgIndex]) {
2738 PrimType ArgT = classify(Arg).value_or(PT_Ptr);
2739 if (ArgT == PT_Ptr) {
2740 if (!this->emitCheckNonNullArg(ArgT, Arg))
2741 return false;
2742 }
2743 }
2744
2745 ++ArgIndex;
2746 }
2747
2748 return true;
2749}
2750
2751template <class Emitter>
2753 return this->visitInitList(E->inits(), E->getArrayFiller(), E);
2754}
2755
2756template <class Emitter>
2761
2762template <class Emitter>
2767
2768template <class Emitter>
2770 if (!E->hasAPValueResult())
2771 return this->delegate(E->getSubExpr());
2772
2773 // Emitting an APValue never has side effects.
2774 if (DiscardResult)
2775 return true;
2776
2777 if (OptPrimType T = classify(E)) {
2778 // Try to emit the APValue directly, without visiting the subexpr.
2779 // This will only fail if we can't emit the APValue, so won't emit any
2780 // diagnostics or any double values.
2781 return this->visitAPValue(E->getAPValueResult(), *T, E);
2782 }
2783
2784 if (!Initializing) {
2785 UnsignedOrNone LocalIndex = allocateLocal(E);
2786 if (!LocalIndex)
2787 return false;
2788 if (!this->emitGetPtrLocal(*LocalIndex, E))
2789 return false;
2790 }
2791 return this->visitAPValueInitializer(E->getAPValueResult(), E, E->getType());
2792}
2793
2794template <class Emitter>
2796 auto It = E->begin();
2797 return this->visit(*It);
2798}
2799
2801 UnaryExprOrTypeTrait Kind) {
2802 // C++ [expr.alignof]p3:
2803 // When alignof is applied to a reference type, the result is the
2804 // alignment of the referenced type.
2805 if (const auto *Ref = T->getAs<ReferenceType>())
2806 T = Ref->getPointeeType();
2807
2808 if (T.getQualifiers().hasUnaligned())
2809 return CharUnits::One();
2810
2811 bool AlignOfReturnsPreferred =
2812 ASTCtx.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver7);
2813 // __alignof is defined to return the preferred alignment.
2814 // Before 8, clang returned the preferred alignment for alignof and
2815 // _Alignof as well.
2816 if (Kind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
2817 return ASTCtx.toCharUnitsFromBits(ASTCtx.getPreferredTypeAlign(T));
2818
2819 return ASTCtx.getTypeAlignInChars(T);
2820}
2821
2822template <class Emitter>
2824 const UnaryExprOrTypeTraitExpr *E) {
2825
2826 UnaryExprOrTypeTrait Kind = E->getKind();
2827 const ASTContext &ASTCtx = Ctx.getASTContext();
2828
2829 if (Kind == UETT_SizeOf || Kind == UETT_DataSizeOf) {
2831
2832 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2833 // the result is the size of the referenced type."
2834 if (const auto *Ref = ArgType->getAs<ReferenceType>())
2835 ArgType = Ref->getPointeeType();
2836
2837 CharUnits Size;
2838 if (ArgType->isVoidType() || ArgType->isFunctionType())
2839 Size = CharUnits::One();
2840 else {
2841 if (ArgType->isDependentType() || !ArgType->isConstantSizeType())
2842 return this->emitInvalid(E);
2843
2844 if (Kind == UETT_SizeOf)
2845 Size = ASTCtx.getTypeSizeInChars(ArgType);
2846 else
2848 }
2849
2850 if (DiscardResult)
2851 return true;
2852
2853 return this->emitConst(Size.getQuantity(), E);
2854 }
2855
2856 if (Kind == UETT_CountOf) {
2857 QualType Ty = E->getTypeOfArgument();
2858 assert(Ty->isArrayType());
2859
2860 // We don't need to worry about array element qualifiers, so getting the
2861 // unsafe array type is fine.
2862 if (const auto *CAT =
2863 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
2864 if (DiscardResult)
2865 return true;
2866 return this->emitConst(CAT->getSize(), E);
2867 }
2868
2869 assert(!Ty->isConstantSizeType());
2870
2871 // If it's a variable-length array type, we need to check whether it is a
2872 // multidimensional array. If so, we need to check the size expression of
2873 // the VLA to see if it's a constant size. If so, we can return that value.
2874 const auto *VAT = ASTCtx.getAsVariableArrayType(Ty);
2875 assert(VAT);
2876 if (VAT->getElementType()->isArrayType()) {
2877 std::optional<APSInt> Res =
2878 VAT->getSizeExpr()
2879 ? VAT->getSizeExpr()->getIntegerConstantExpr(ASTCtx)
2880 : std::nullopt;
2881 if (Res) {
2882 if (DiscardResult)
2883 return true;
2884 return this->emitConst(*Res, E);
2885 }
2886 }
2887 }
2888
2889 if (Kind == UETT_AlignOf || Kind == UETT_PreferredAlignOf) {
2890 CharUnits Size;
2891
2892 if (E->isArgumentType()) {
2894
2895 Size = alignOfType(ArgType, ASTCtx, Kind);
2896 } else {
2897 // Argument is an expression, not a type.
2898 const Expr *Arg = E->getArgumentExpr()->IgnoreParens();
2899
2900 if (Arg->getType()->isDependentType())
2901 return false;
2902
2903 // The kinds of expressions that we have special-case logic here for
2904 // should be kept up to date with the special checks for those
2905 // expressions in Sema.
2906
2907 // alignof decl is always accepted, even if it doesn't make sense: we
2908 // default to 1 in those cases.
2909 if (const auto *DRE = dyn_cast<DeclRefExpr>(Arg))
2910 Size = ASTCtx.getDeclAlign(DRE->getDecl(),
2911 /*ForAlignOf=*/true);
2912 else if (const auto *ME = dyn_cast<MemberExpr>(Arg))
2913 Size = ASTCtx.getDeclAlign(ME->getMemberDecl(),
2914 /*ForAlignOf=*/true);
2915 else
2916 Size = alignOfType(Arg->getType(), ASTCtx, Kind);
2917 }
2918
2919 if (DiscardResult)
2920 return true;
2921
2922 return this->emitConst(Size.getQuantity(), E);
2923 }
2924
2925 if (Kind == UETT_VectorElements) {
2926 if (E->containsErrors())
2927 return false;
2928
2929 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>())
2930 return this->emitConst(VT->getNumElements(), E);
2932 return this->emitSizelessVectorElementSize(E);
2933 }
2934
2935 if (Kind == UETT_VecStep) {
2936 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>()) {
2937 unsigned N = VT->getNumElements();
2938
2939 // The vec_step built-in functions that take a 3-component
2940 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2941 if (N == 3)
2942 N = 4;
2943
2944 return this->emitConst(N, E);
2945 }
2946 return this->emitConst(1, E);
2947 }
2948
2949 if (Kind == UETT_OpenMPRequiredSimdAlign) {
2950 if (E->containsErrors())
2951 return false;
2952 assert(E->isArgumentType());
2953 unsigned Bits = ASTCtx.getOpenMPDefaultSimdAlign(E->getArgumentType());
2954
2955 return this->emitConst(ASTCtx.toCharUnitsFromBits(Bits).getQuantity(), E);
2956 }
2957
2958 if (Kind == UETT_PtrAuthTypeDiscriminator) {
2959 if (E->getArgumentType()->isDependentType())
2960 return this->emitInvalid(E);
2961
2962 return this->emitConst(
2963 const_cast<ASTContext &>(ASTCtx).getPointerAuthTypeDiscriminator(
2964 E->getArgumentType()),
2965 E);
2966 }
2967
2968 return false;
2969}
2970
2971template <class Emitter>
2973 // 'Base.Member'
2974 const Expr *Base = E->getBase();
2975 const ValueDecl *Member = E->getMemberDecl();
2976
2977 if (DiscardResult)
2978 return this->discard(Base);
2979
2980 if (const auto *VD = dyn_cast<VarDecl>(Member)) {
2981 // If the member is a VarDecl, this is a static variable.
2982 // We need to try to lazily evaluate its initializer here since the
2983 // variable might've been deserialized and not registered
2984 // as a global variable yet.
2985 if (VD->getInit() && !VD->getInit()->isValueDependent())
2986 VD->evaluateValue();
2987 if (auto GlobalIndex = P.getGlobal(VD)) {
2988 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2989 return false;
2990 if (Member->getType()->isReferenceType())
2991 return this->emitLoadPopPtr(E);
2992 return true;
2993 }
2994 return false;
2995 }
2996
2997 if (!isa<FieldDecl>(Member)) {
2998 // A non-static member function access only makes sense as part of the
2999 // enclosing call here. Don't try to evaluate it in isolation.
3000 if (const auto *MD = dyn_cast<CXXMethodDecl>(Member);
3001 MD && !MD->isStatic()) {
3002 return false;
3003 }
3004
3005 if (!this->discard(Base) && !this->emitSideEffect(E))
3006 return false;
3007
3008 return this->visitDeclRef(Member, E);
3009 }
3010
3011 if (!this->visit(Base))
3012 return false;
3013
3014 // Base above gives us a pointer on the stack.
3015 const auto *FD = cast<FieldDecl>(Member);
3016 const RecordDecl *RD = FD->getParent();
3017 const Record *R = getRecord(RD);
3018 if (!R)
3019 return false;
3020 const Record::Field *F = R->getField(FD);
3021
3022 // MemberExprs are almost always lvalues, in which case we don't need to
3023 // do the load. But sometimes they aren't.
3024 const auto maybeLoadValue = [&]() -> bool {
3025 if (E->isGLValue())
3026 return true;
3027 if (OptPrimType T = classify(E))
3028 return this->emitLoadPop(*T, E);
3029 return false;
3030 };
3031
3032 // Leave a pointer to the field on the stack.
3033 if (F->Decl->getType()->isReferenceType())
3034 return this->emitGetFieldPop(PT_Ptr, F->Offset, E) && maybeLoadValue();
3035 return this->emitGetPtrFieldPop(F->Offset, E) && maybeLoadValue();
3036}
3037
3038template <class Emitter>
3040 assert(!DiscardResult);
3041 // ArrayIndex might not be set if a ArrayInitIndexExpr is being evaluated
3042 // stand-alone, e.g. via EvaluateAsInt().
3043 if (!ArrayIndex)
3044 return false;
3045 return this->emitConst(*ArrayIndex, E);
3046}
3047
3048template <class Emitter>
3050 assert(Initializing);
3051 assert(!DiscardResult);
3052
3053 const Expr *Common = E->getCommonExpr();
3054 const Expr *SubExpr = E->getSubExpr();
3055 OptPrimType SubExprT = classify(SubExpr);
3056 size_t Size = E->getArraySize().getZExtValue();
3057 if (exceedsArraySizeLimit(Ctx.getLangOpts(), Size))
3058 return this->emitCheckArraySize(Size, E);
3059
3060 if (SubExprT) {
3061 // Unwrap the OpaqueValueExpr so we don't cache something we won't reuse.
3062 Common = cast<OpaqueValueExpr>(Common)->getSourceExpr();
3063
3064 if (!this->visit(Common))
3065 return false;
3066 return this->emitCopyArray(*SubExprT, 0, 0, Size, E);
3067 }
3068
3069 // We visit the common opaque expression here once so we have its value
3070 // cached.
3071 if (!this->discard(Common))
3072 return false;
3073
3074 // TODO: This compiles to quite a lot of bytecode if the array is larger.
3075 // Investigate compiling this to a loop.
3076
3077 // So, every iteration, we execute an assignment here
3078 // where the LHS is on the stack (the target array)
3079 // and the RHS is our SubExpr.
3080 for (size_t I = 0; I != Size; ++I) {
3081 ArrayIndexScope<Emitter> IndexScope(this, I);
3083
3084 if (!this->visitArrayElemInit(I, SubExpr, SubExprT))
3085 return false;
3086 if (!BS.destroyLocals())
3087 return false;
3088 }
3089 return true;
3090}
3091
3092template <class Emitter>
3094 const Expr *SourceExpr = E->getSourceExpr();
3095 if (!SourceExpr)
3096 return false;
3097
3098 if (Initializing) {
3099 assert(!DiscardResult);
3100 return this->visitInitializer(SourceExpr);
3101 }
3102
3103 PrimType SubExprT = classify(SourceExpr).value_or(PT_Ptr);
3104 if (auto It = OpaqueExprs.find(E); It != OpaqueExprs.end()) {
3105 if (DiscardResult)
3106 return true;
3107 return this->emitGetLocal(SubExprT, It->second, E);
3108 }
3109
3110 if (!this->visit(SourceExpr))
3111 return false;
3112
3113 // At this point we either have the evaluated source expression or a pointer
3114 // to an object on the stack. We want to create a local variable that stores
3115 // this value.
3116 unsigned LocalIndex = allocateLocalPrimitive(E, SubExprT, /*IsConst=*/true);
3117 if (!this->emitSetLocal(SubExprT, LocalIndex, E))
3118 return false;
3119
3120 // This is cleaned up when the local variable is destroyed.
3121 OpaqueExprs.insert({E, LocalIndex});
3122
3123 // Here the local variable is created but the value is removed from the stack,
3124 // so we put it back if the caller needs it.
3125 if (!DiscardResult)
3126 return this->emitGetLocal(SubExprT, LocalIndex, E);
3127 return true;
3128}
3129
3130template <class Emitter>
3132 const AbstractConditionalOperator *E) {
3133 const Expr *Condition = E->getCond();
3134 const Expr *TrueExpr = E->getTrueExpr();
3135 const Expr *FalseExpr = E->getFalseExpr();
3136
3137 if (std::optional<bool> BoolValue = getBoolValue(Condition)) {
3138 if (*BoolValue)
3139 return this->delegate(TrueExpr);
3140 return this->delegate(FalseExpr);
3141 }
3142
3143 bool IsBcpCall = false;
3144 if (const auto *CE = dyn_cast<CallExpr>(Condition->IgnoreParenCasts());
3145 CE && CE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) {
3146 IsBcpCall = true;
3147 }
3148
3149 LabelTy LabelEnd = this->getLabel(); // Label after the operator.
3150 LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
3151
3152 if (IsBcpCall) {
3153 if (!this->emitPushIgnoreDiags(E))
3154 return false;
3155 }
3156
3157 if (!this->visitBool(Condition)) {
3158 // If the condition failed and we're checking for undefined behavior
3159 // (which only happens with EvalEmitter) check the TrueExpr and FalseExpr
3160 // as well.
3161 if (this->checkingForUndefinedBehavior()) {
3162 if (!this->discard(TrueExpr))
3163 return false;
3164 if (!this->discard(FalseExpr))
3165 return false;
3166 }
3167 return false;
3168 }
3169
3170 // The TrueExpr and FalseExpr of a conditional operator do _not_ create a
3171 // scope, which means the local variables created within them unconditionally
3172 // always exist. However, we need to later differentiate which branch was
3173 // taken and only destroy the varibles of the active branch. This is what the
3174 // "enabled" flags on local variables are used for.
3175 llvm::SaveAndRestore LAAA(this->VarScope->LocalsAlwaysEnabled,
3176 /*NewValue=*/false);
3177
3178 if (!this->jumpFalse(LabelFalse, E))
3179 return false;
3180 if (!this->delegate(TrueExpr))
3181 return false;
3182
3183 if (!this->jump(LabelEnd, E))
3184 return false;
3185 this->emitLabel(LabelFalse);
3186 if (!this->delegate(FalseExpr))
3187 return false;
3188
3189 this->fallthrough(LabelEnd);
3190 this->emitLabel(LabelEnd);
3191
3192 if (IsBcpCall)
3193 return this->emitPopIgnoreDiags(E);
3194 return true;
3195}
3196
3197template <class Emitter>
3199 if (DiscardResult)
3200 return true;
3201
3202 if (!Initializing)
3203 return this->emitGetStringPtr(E, E);
3204
3205 // We are initializing an array on the stack.
3206 const ConstantArrayType *CAT =
3207 Ctx.getASTContext().getAsConstantArrayType(E->getType());
3208 assert(CAT && "a string literal that's not a constant array?");
3209
3210 // If the initializer string is too long, a diagnostic has already been
3211 // emitted. Read only the array length from the string literal.
3212 unsigned ArraySize = CAT->getZExtSize();
3213 unsigned N = std::min(ArraySize, E->getLength());
3214 unsigned CharWidth = E->getCharByteWidth();
3215
3216 for (unsigned I = 0; I != N; ++I) {
3217 uint32_t CodeUnit = E->getCodeUnit(I);
3218
3219 if (CharWidth == 1) {
3220 this->emitConstSint8(CodeUnit, E);
3221 this->emitInitElemSint8(I, E);
3222 } else if (CharWidth == 2) {
3223 this->emitConstUint16(CodeUnit, E);
3224 this->emitInitElemUint16(I, E);
3225 } else if (CharWidth == 4) {
3226 this->emitConstUint32(CodeUnit, E);
3227 this->emitInitElemUint32(I, E);
3228 } else {
3229 llvm_unreachable("unsupported character width");
3230 }
3231 }
3232
3233 // Fill up the rest of the char array with NUL bytes.
3234 for (unsigned I = N; I != ArraySize; ++I) {
3235 if (CharWidth == 1) {
3236 this->emitConstSint8(0, E);
3237 this->emitInitElemSint8(I, E);
3238 } else if (CharWidth == 2) {
3239 this->emitConstUint16(0, E);
3240 this->emitInitElemUint16(I, E);
3241 } else if (CharWidth == 4) {
3242 this->emitConstUint32(0, E);
3243 this->emitInitElemUint32(I, E);
3244 } else {
3245 llvm_unreachable("unsupported character width");
3246 }
3247 }
3248
3249 return true;
3250}
3251
3252template <class Emitter>
3254 if (DiscardResult)
3255 return true;
3256 return this->emitDummyPtr(E, E);
3257}
3258
3259template <class Emitter>
3261 auto &A = Ctx.getASTContext();
3262 std::string Str;
3263 A.getObjCEncodingForType(E->getEncodedType(), Str);
3264 StringLiteral *SL =
3266 /*Pascal=*/false, E->getType(), E->getAtLoc());
3267 return this->delegate(SL);
3268}
3269
3270template <class Emitter>
3272 const SYCLUniqueStableNameExpr *E) {
3273 if (DiscardResult)
3274 return true;
3275
3276 assert(!Initializing);
3277
3278 auto &A = Ctx.getASTContext();
3279 std::string ResultStr = E->ComputeName(A);
3280
3281 QualType CharTy = A.CharTy.withConst();
3282 APInt Size(A.getTypeSize(A.getSizeType()), ResultStr.size() + 1);
3283 QualType ArrayTy = A.getConstantArrayType(CharTy, Size, nullptr,
3285
3286 StringLiteral *SL =
3288 /*Pascal=*/false, ArrayTy, E->getLocation());
3289 return this->emitGetStringPtr(SL, E);
3290}
3291
3292template <class Emitter>
3294 if (DiscardResult)
3295 return true;
3296 return this->emitConst(E->getValue(), E);
3297}
3298
3299template <class Emitter>
3301 const CompoundAssignOperator *E) {
3302
3303 const Expr *LHS = E->getLHS();
3304 const Expr *RHS = E->getRHS();
3305 QualType LHSType = LHS->getType();
3306 QualType LHSComputationType = E->getComputationLHSType();
3307 QualType ResultType = E->getComputationResultType();
3308 OptPrimType LT = classify(LHSComputationType);
3309 OptPrimType RT = classify(ResultType);
3310
3311 assert(ResultType->isFloatingType());
3312
3313 if (!LT || !RT)
3314 return false;
3315
3316 PrimType LHST = classifyPrim(LHSType);
3317
3318 if (isSideEffectFree(RHS)) {
3319 if (!visit(LHS))
3320 return false;
3321 if (!this->emitLoad(LHST, E))
3322 return false;
3323 // If necessary, convert LHS to its computation type.
3324 if (!this->emitPrimCast(LHST, classifyPrim(LHSComputationType),
3325 LHSComputationType, E))
3326 return false;
3327 if (!visit(RHS))
3328 return false;
3329
3330 } else {
3331 // C++17 onwards require that we evaluate the RHS first.
3332 // Compute RHS and save it in a temporary variable so we can
3333 // load it again later.
3334 if (!visit(RHS))
3335 return false;
3336
3337 unsigned TempOffset =
3338 this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
3339 if (!this->emitSetLocal(*RT, TempOffset, E))
3340 return false;
3341
3342 // First, visit LHS.
3343 if (!visit(LHS))
3344 return false;
3345 if (!this->emitLoad(LHST, E))
3346 return false;
3347
3348 // If necessary, convert LHS to its computation type.
3349 if (!this->emitPrimCast(LHST, classifyPrim(LHSComputationType),
3350 LHSComputationType, E))
3351 return false;
3352
3353 // Now load RHS.
3354 if (!this->emitGetLocal(*RT, TempOffset, E))
3355 return false;
3356 }
3357
3358 switch (E->getOpcode()) {
3359 case BO_AddAssign:
3360 if (!this->emitAddf(getFPOptions(E), E))
3361 return false;
3362 break;
3363 case BO_SubAssign:
3364 if (!this->emitSubf(getFPOptions(E), E))
3365 return false;
3366 break;
3367 case BO_MulAssign:
3368 if (!this->emitMulf(getFPOptions(E), E))
3369 return false;
3370 break;
3371 case BO_DivAssign:
3372 if (!this->emitDivf(getFPOptions(E), E))
3373 return false;
3374 break;
3375 default:
3376 return false;
3377 }
3378
3379 if (!this->emitPrimCast(classifyPrim(ResultType), LHST, LHS->getType(), E))
3380 return false;
3381
3382 if (DiscardResult)
3383 return this->emitStorePop(LHST, E);
3384 return this->emitStore(LHST, E);
3385}
3386
3387template <class Emitter>
3389 const CompoundAssignOperator *E) {
3390 BinaryOperatorKind Op = E->getOpcode();
3391 const Expr *LHS = E->getLHS();
3392 const Expr *RHS = E->getRHS();
3393 OptPrimType LT = classify(LHS->getType());
3394 OptPrimType RT = classify(RHS->getType());
3395
3396 if (Op != BO_AddAssign && Op != BO_SubAssign)
3397 return false;
3398
3399 if (!LT || !RT)
3400 return false;
3401
3402 if (!visit(LHS))
3403 return false;
3404
3405 if (!this->emitLoad(*LT, LHS))
3406 return false;
3407
3408 if (!visit(RHS))
3409 return false;
3410
3411 if (Op == BO_AddAssign) {
3412 if (!this->emitAddOffset(*RT, E))
3413 return false;
3414 } else {
3415 if (!this->emitSubOffset(*RT, E))
3416 return false;
3417 }
3418
3419 if (DiscardResult)
3420 return this->emitStorePopPtr(E);
3421 return this->emitStorePtr(E);
3422}
3423
3424template <class Emitter>
3426 const CompoundAssignOperator *E) {
3427 if (E->getType()->isVectorType())
3428 return VisitVectorBinOp(E);
3429
3430 const Expr *LHS = E->getLHS();
3431 const Expr *RHS = E->getRHS();
3432 OptPrimType LHSComputationT = classify(E->getComputationLHSType());
3433 OptPrimType LT = classify(LHS->getType());
3434 OptPrimType RT = classify(RHS->getType());
3435 OptPrimType ResultT = classify(E->getType());
3436
3437 if (!Ctx.getLangOpts().CPlusPlus14)
3438 return this->visit(RHS) && this->visit(LHS) && this->emitError(E);
3439
3440 if (!LT || !RT || !ResultT || !LHSComputationT)
3441 return false;
3442
3443 // Handle floating point operations separately here, since they
3444 // require special care.
3445 if (ResultT == PT_Float || RT == PT_Float)
3447
3448 if (E->getType()->isPointerType())
3450
3451 assert(!E->getType()->isPointerType() && "Handled above");
3452 assert(!E->getType()->isFloatingType() && "Handled above");
3453
3454 if (isSideEffectFree(RHS)) {
3455 if (!visit(LHS))
3456 return false;
3457 if (!this->emitLoad(*LT, E))
3458 return false;
3459 if (LT != LHSComputationT &&
3460 !this->emitIntegralCast(*LT, *LHSComputationT,
3461 E->getComputationLHSType(), E))
3462 return false;
3463 if (!visit(RHS))
3464 return false;
3465 } else {
3466 // C++17 onwards require that we evaluate the RHS first.
3467 // Compute RHS and save it in a temporary variable so we can
3468 // load it again later.
3469 // FIXME: Compound assignments are unsequenced in C, so we might
3470 // have to figure out how to reject them.
3471 if (!visit(RHS))
3472 return false;
3473
3474 unsigned TempOffset =
3475 this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
3476
3477 if (!this->emitSetLocal(*RT, TempOffset, E))
3478 return false;
3479
3480 // Get LHS pointer, load its value and cast it to the
3481 // computation type if necessary.
3482 if (!visit(LHS))
3483 return false;
3484 if (!this->emitLoad(*LT, E))
3485 return false;
3486 if (LT != LHSComputationT &&
3487 !this->emitIntegralCast(*LT, *LHSComputationT,
3488 E->getComputationLHSType(), E))
3489 return false;
3490
3491 // Get the RHS value on the stack.
3492 if (!this->emitGetLocal(*RT, TempOffset, E))
3493 return false;
3494 }
3495
3496 // Perform operation.
3497 switch (E->getOpcode()) {
3498 case BO_AddAssign:
3499 if (!this->emitAdd(*LHSComputationT, E))
3500 return false;
3501 break;
3502 case BO_SubAssign:
3503 if (!this->emitSub(*LHSComputationT, E))
3504 return false;
3505 break;
3506 case BO_MulAssign:
3507 if (!this->emitMul(*LHSComputationT, E))
3508 return false;
3509 break;
3510 case BO_DivAssign:
3511 if (!this->emitDiv(*LHSComputationT, E))
3512 return false;
3513 break;
3514 case BO_RemAssign:
3515 if (!this->emitRem(*LHSComputationT, E))
3516 return false;
3517 break;
3518 case BO_ShlAssign:
3519 if (!this->emitShl(*LHSComputationT, *RT, E))
3520 return false;
3521 break;
3522 case BO_ShrAssign:
3523 if (!this->emitShr(*LHSComputationT, *RT, E))
3524 return false;
3525 break;
3526 case BO_AndAssign:
3527 if (!this->emitBitAnd(*LHSComputationT, E))
3528 return false;
3529 break;
3530 case BO_XorAssign:
3531 if (!this->emitBitXor(*LHSComputationT, E))
3532 return false;
3533 break;
3534 case BO_OrAssign:
3535 if (!this->emitBitOr(*LHSComputationT, E))
3536 return false;
3537 break;
3538 default:
3539 llvm_unreachable("Unimplemented compound assign operator");
3540 }
3541
3542 // And now cast from LHSComputationT to ResultT.
3543 if (ResultT != LHSComputationT &&
3544 !this->emitIntegralCast(*LHSComputationT, *ResultT, E->getType(), E))
3545 return false;
3546
3547 // And store the result in LHS.
3548 if (DiscardResult) {
3549 if (LHS->refersToBitField())
3550 return this->emitStoreBitFieldPop(*ResultT, E);
3551 return this->emitStorePop(*ResultT, E);
3552 }
3553 if (LHS->refersToBitField())
3554 return this->emitStoreBitField(*ResultT, E);
3555 return this->emitStore(*ResultT, E);
3556}
3557
3558template <class Emitter>
3561 const Expr *SubExpr = E->getSubExpr();
3562
3563 return this->delegate(SubExpr) && ES.destroyLocals(E);
3564}
3565
3566template <class Emitter>
3568 const MaterializeTemporaryExpr *E) {
3569 if (Initializing) {
3570 // We already have a value, just initialize that.
3571 return this->delegate(E->getSubExpr());
3572 }
3573 // If we don't end up using the materialized temporary anyway, don't
3574 // bother creating it.
3575 if (DiscardResult)
3576 return this->discard(E->getSubExpr());
3577
3580 const Expr *Inner;
3581 if (!Ctx.getLangOpts().CPlusPlus11)
3582 Inner =
3583 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
3584 else
3585 Inner = E->getSubExpr();
3586
3587 // If we passed any comma operators, evaluate their LHSs.
3588 for (const Expr *LHS : CommaLHSs) {
3589 if (!this->discard(LHS))
3590 return false;
3591 }
3592
3593 // FIXME: Find a test case where Adjustments matters.
3594
3595 // When we're extending a global variable *or* the storage duration of
3596 // the temporary is explicitly static, create a global variable.
3597 OptPrimType InnerT = classify(Inner);
3598 const ValueDecl *ExtendingDecl = E->getExtendingDecl();
3599 bool IsStatic = E->getStorageDuration() == SD_Static;
3600 if (IsStatic ||
3601 (ExtendingDecl && Context::shouldBeGloballyIndexed(ExtendingDecl))) {
3602
3603 if (this->constantFolding())
3604 return false;
3605
3606 UnsignedOrNone GlobalIndex = P.createGlobal(E, Inner->getType());
3607 if (!GlobalIndex)
3608 return false;
3609
3610 const LifetimeExtendedTemporaryDecl *TempDecl =
3612
3613 if (InnerT) {
3614 if (!this->visit(Inner))
3615 return false;
3616
3617 if (IsStatic) {
3618 assert(TempDecl);
3619 if (!this->emitInitGlobalTemp(*InnerT, *GlobalIndex, TempDecl, E))
3620 return false;
3621 } else {
3622 if (!this->emitInitGlobal(*InnerT, *GlobalIndex, E))
3623 return false;
3624 }
3625 return this->emitGetPtrGlobal(*GlobalIndex, E);
3626 }
3627
3628 if (!this->checkLiteralType(Inner))
3629 return false;
3630 // Non-primitive values.
3631 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3632 return false;
3633 if (!this->visitInitializer(Inner))
3634 return false;
3635 if (IsStatic) {
3636 assert(TempDecl);
3637 return this->emitInitGlobalTempComp(TempDecl, E);
3638 }
3639 return true;
3640 }
3641
3645
3646 // For everyhing else, use local variables.
3647 if (InnerT) {
3648 bool IsConst = Inner->getType().isConstQualified();
3649 bool IsVolatile = Inner->getType().isVolatileQualified();
3650 unsigned LocalIndex =
3651 allocateLocalPrimitive(E, *InnerT, IsConst, IsVolatile, VarScope);
3652 if (!this->VarScope->LocalsAlwaysEnabled &&
3653 !this->emitEnableLocal(LocalIndex, E))
3654 return false;
3655
3656 if (!this->visit(Inner))
3657 return false;
3658 if (!this->emitSetLocal(*InnerT, LocalIndex, E))
3659 return false;
3660
3661 return this->emitGetPtrLocal(LocalIndex, E);
3662 }
3663
3664 if (!this->checkLiteralType(Inner))
3665 return false;
3666
3667 if (UnsignedOrNone LocalIndex =
3668 allocateLocal(E, Inner->getType(), VarScope)) {
3669 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
3670
3671 if (!this->VarScope->LocalsAlwaysEnabled &&
3672 !this->emitEnableLocal(*LocalIndex, E))
3673 return false;
3674
3675 if (!this->emitGetPtrLocal(*LocalIndex, E))
3676 return false;
3677 return this->visitInitializer(Inner);
3678 }
3679 return false;
3680}
3681
3682template <class Emitter>
3684 const CXXBindTemporaryExpr *E) {
3685 const Expr *SubExpr = E->getSubExpr();
3686
3687 if (Initializing)
3688 return this->delegate(SubExpr);
3689
3690 // Make sure we create a temporary even if we're discarding, since that will
3691 // make sure we will also call the destructor.
3692
3693 if (!this->visit(SubExpr))
3694 return false;
3695
3696 if (DiscardResult)
3697 return this->emitPopPtr(E);
3698 return true;
3699}
3700
3701template <class Emitter>
3703 const Expr *Init = E->getInitializer();
3704 if (DiscardResult)
3705 return this->discard(Init);
3706
3707 if (Initializing) {
3708 // We already have a value, just initialize that.
3709 return this->visitInitializer(Init);
3710 }
3711
3712 OptPrimType T = classify(E->getType());
3713 if (E->isFileScope()) {
3714 // Avoid creating a variable if this is a primitive RValue anyway.
3715 if (T && !E->isLValue())
3716 return this->delegate(Init);
3717
3718 UnsignedOrNone GlobalIndex = P.createGlobal(E, E->getType());
3719 if (!GlobalIndex)
3720 return false;
3721
3722 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3723 return false;
3724
3725 // Since this is a global variable, we might've already seen,
3726 // don't do it again.
3727 if (P.isGlobalInitialized(*GlobalIndex))
3728 return true;
3729
3730 if (T) {
3731 if (!this->visit(Init))
3732 return false;
3733 return this->emitInitGlobal(*T, *GlobalIndex, E);
3734 }
3735
3736 return this->visitInitializer(Init);
3737 }
3738
3739 // Otherwise, use a local variable.
3740 if (T && !E->isLValue()) {
3741 // For primitive types, we just visit the initializer.
3742 return this->delegate(Init);
3743 }
3744
3745 unsigned LocalIndex;
3746 if (T)
3747 LocalIndex = this->allocateLocalPrimitive(Init, *T, /*IsConst=*/false);
3748 else if (UnsignedOrNone MaybeIndex = this->allocateLocal(Init))
3749 LocalIndex = *MaybeIndex;
3750 else
3751 return false;
3752
3753 if (!this->emitGetPtrLocal(LocalIndex, E))
3754 return false;
3755
3756 if (T)
3757 return this->visit(Init) && this->emitInit(*T, E);
3758 return this->visitInitializer(Init);
3759}
3760
3761template <class Emitter>
3763 if (DiscardResult)
3764 return true;
3765 if (E->isStoredAsBoolean()) {
3766 if (E->getType()->isBooleanType())
3767 return this->emitConstBool(E->getBoolValue(), E);
3768 return this->emitConst(E->getBoolValue(), E);
3769 }
3770 if (E->isStoredAsComparisonResult()) {
3771 const ComparisonCategoryInfo &CmpInfo =
3772 Ctx.getASTContext().CompCategories.getInfoForType(E->getType());
3773 const auto Result =
3774 ComparisonCategoryResult(E->getAPValue().getInt().getZExtValue());
3775 const Record *R = getRecord(E->getType());
3776 if (!R || R->getNumFields() == 0)
3777 return false;
3778 const Record::Field *Field = R->getField(0U);
3779 assert(Field->T);
3780 if (!this->emitConst(CmpInfo.getValueInfo(Result)->getIntValue(), *Field->T,
3781 E))
3782 return false;
3783 return this->emitInitField(*Field->T, Field->Offset, E);
3784 }
3785
3787 return this->visitAPValue(E->getAPValue(), T, E);
3788}
3789
3790template <class Emitter>
3792 if (DiscardResult)
3793 return true;
3794 return this->emitConst(E->getValue(), E);
3795}
3796
3797template <class Emitter>
3799 if (DiscardResult)
3800 return true;
3801
3802 assert(Initializing);
3803 const Record *R = P.getOrCreateRecord(E->getLambdaClass());
3804 if (!R)
3805 return false;
3806
3807 auto *CaptureInitIt = E->capture_init_begin();
3808 // Initialize all fields (which represent lambda captures) of the
3809 // record with their initializers.
3810 for (const Record::Field &F : R->fields()) {
3811 const Expr *Init = *CaptureInitIt;
3812 if (!Init || Init->containsErrors())
3813 continue;
3814 ++CaptureInitIt;
3815
3816 if (OptPrimType T = classify(Init)) {
3817 if (!this->visit(Init))
3818 return false;
3819
3820 if (!this->emitInitField(*T, F.Offset, E))
3821 return false;
3822 } else {
3823 if (!this->emitGetPtrField(F.Offset, E))
3824 return false;
3825
3826 if (!this->visitInitializerPop(Init))
3827 return false;
3828 }
3829 }
3830
3831 return true;
3832}
3833
3834template <class Emitter>
3836 if (DiscardResult)
3837 return true;
3838
3839 if (!Initializing)
3840 return this->emitGetStringPtr(E, E);
3841 return this->delegate(E->getFunctionName());
3842}
3843
3844template <class Emitter>
3846 if (E->getSubExpr() && !this->discard(E->getSubExpr()))
3847 return false;
3848
3849 return this->emitInvalid(E);
3850}
3851
3852template <class Emitter>
3854 const CXXReinterpretCastExpr *E) {
3855 const Expr *SubExpr = E->getSubExpr();
3856
3857 OptPrimType FromT = classify(SubExpr);
3858 OptPrimType ToT = classify(E);
3859
3860 if (!FromT || !ToT)
3861 return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, E);
3862
3863 if (FromT == PT_Ptr || ToT == PT_Ptr) {
3866 if (!this->emitInvalidCast(CastKind, /*Fatal=*/false, E))
3867 return false;
3868 if (E->getCastKind() == CK_LValueBitCast)
3869 return this->delegate(SubExpr);
3870 return this->VisitCastExpr(E);
3871 }
3872
3873 // Try to actually do the cast.
3874 bool Fatal = (ToT != FromT);
3875 if (!this->emitInvalidCast(CastKind::Reinterpret, Fatal, E))
3876 return false;
3877
3878 return this->VisitCastExpr(E);
3879}
3880
3881template <class Emitter>
3883 if (!Ctx.getLangOpts().CPlusPlus20) {
3884 if (!this->emitInvalidCast(CastKind::Dynamic, /*Fatal=*/false, E))
3885 return false;
3886 }
3887
3888 if (E->getCastKind() != CK_Dynamic)
3889 return this->VisitCastExpr(E);
3890
3891 QualType DestType = E->getType();
3892 // "target type must be a reference or pointer type to a defined class"
3893 if (DestType->isRecordType()) {
3894 assert(E->isGLValue());
3895 } else {
3896 assert(DestType->isPointerOrReferenceType());
3897 assert(DestType->isVoidPointerType() ||
3898 DestType->getPointeeType()->isRecordType());
3899 DestType = DestType->getPointeeType();
3900 }
3901
3902 if (!this->visit(E->getSubExpr()))
3903 return false;
3904 if (!this->emitDynamicCast(DestType.getTypePtr(),
3905 /*IsReferenceCast=*/E->isGLValue(), E))
3906 return false;
3907
3908 if (DiscardResult)
3909 return this->emitPopPtr(E);
3910 return true;
3911}
3912
3913template <class Emitter>
3915 assert(E->getType()->isBooleanType());
3916
3917 if (DiscardResult)
3918 return true;
3919 return this->emitConstBool(E->getValue(), E);
3920}
3921
3922template <class Emitter>
3924 QualType T = E->getType();
3925 assert(!canClassify(T));
3926
3927 if (T->isRecordType()) {
3928 const CXXConstructorDecl *Ctor = E->getConstructor();
3929
3930 // If we're discarding a construct expression, we still need
3931 // to allocate a variable and call the constructor and destructor.
3932 if (DiscardResult) {
3933 if (Ctor->isTrivial())
3934 return true;
3935 assert(!Initializing);
3936 UnsignedOrNone LocalIndex = allocateLocal(E);
3937
3938 if (!LocalIndex)
3939 return false;
3940
3941 if (!this->emitGetPtrLocal(*LocalIndex, E))
3942 return false;
3943 }
3944
3945 // Trivial copy/move constructor. Avoid copy.
3946 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
3947 Ctor->isTrivial() &&
3948 E->getArg(0)->isTemporaryObject(Ctx.getASTContext(),
3949 T->getAsCXXRecordDecl()))
3950 return this->visitInitializer(E->getArg(0));
3951
3952 // Zero initialization.
3953 bool ZeroInit = E->requiresZeroInitialization();
3954 if (ZeroInit) {
3955 const Record *R = getRecord(E->getType());
3956 if (!R)
3957 return false;
3958
3959 if (!this->visitZeroRecordInitializer(R, E))
3960 return false;
3961
3962 // If the constructor is trivial anyway, we're done.
3963 if (Ctor->isTrivial())
3964 return true;
3965 }
3966
3967 // Trivial default constructors might never be implicitly defined by the
3968 // AST, so we need to special-case them here.
3969 if (Ctor->isTrivial() && Ctor->isDefaultConstructor()) {
3970 if (!this->emitDefaultInit(Ctor, E))
3971 return false;
3972 if (DiscardResult)
3973 return this->emitPopPtr(E);
3974 return true;
3975 }
3976
3977 // Avoid materializing a temporary for an elidable copy/move constructor.
3978 if (!ZeroInit && E->isElidable()) {
3979 const Expr *SrcObj = E->getArg(0);
3980 assert(SrcObj->isTemporaryObject(Ctx.getASTContext(), Ctor->getParent()));
3981 assert(Ctx.getASTContext().hasSameUnqualifiedType(E->getType(),
3982 SrcObj->getType()));
3983 if (const auto *ME = dyn_cast<MaterializeTemporaryExpr>(SrcObj)) {
3984 if (!this->emitCheckFunctionDecl(Ctor, E))
3985 return false;
3986 return this->visitInitializer(ME->getSubExpr());
3987 }
3988 }
3989
3990 const Function *Func = getFunction(Ctor);
3991
3992 if (!Func)
3993 return false;
3994
3995 assert(Func->hasThisPointer());
3996 assert(!Func->hasRVO());
3997
3998 // The This pointer is already on the stack because this is an initializer,
3999 // but we need to dup() so the call() below has its own copy.
4000 if (!this->emitDupPtr(E))
4001 return false;
4002
4003 // Constructor arguments.
4004 for (const auto *Arg : E->arguments()) {
4005 if (!this->visit(Arg))
4006 return false;
4007 }
4008
4009 if (Func->isVariadic()) {
4010 uint32_t VarArgSize = 0;
4011 unsigned NumParams = Func->getNumWrittenParams();
4012 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) {
4013 VarArgSize +=
4014 align(primSize(classify(E->getArg(I)->getType()).value_or(PT_Ptr)));
4015 }
4016 if (!this->emitCallVar(Func, VarArgSize, E))
4017 return false;
4018 } else {
4019 if (!this->emitCall(Func, 0, E)) {
4020 // When discarding, we don't need the result anyway, so clean up
4021 // the instance dup we did earlier in case surrounding code wants
4022 // to keep evaluating.
4023 if (DiscardResult)
4024 (void)this->emitPopPtr(E);
4025 return false;
4026 }
4027 }
4028
4029 if (DiscardResult)
4030 return this->emitPopPtr(E);
4031 return true;
4032 }
4033
4034 if (T->isArrayType()) {
4035 const Function *Func = getFunction(E->getConstructor());
4036 if (!Func)
4037 return false;
4038
4039 if (!this->emitDupPtr(E))
4040 return false;
4041
4042 std::function<bool(QualType)> initArrayDimension;
4043 initArrayDimension = [&](QualType T) -> bool {
4044 if (!T->isArrayType()) {
4045 // Constructor arguments.
4046 for (const auto *Arg : E->arguments()) {
4047 if (!this->visit(Arg))
4048 return false;
4049 }
4050
4051 return this->emitCall(Func, 0, E);
4052 }
4053
4054 const ConstantArrayType *CAT =
4055 Ctx.getASTContext().getAsConstantArrayType(T);
4056 if (!CAT)
4057 return false;
4058 QualType ElemTy = CAT->getElementType();
4059 uint64_t NumElems = CAT->getZExtSize();
4060 if (exceedsArraySizeLimit(Ctx.getLangOpts(), NumElems))
4061 return this->emitCheckArraySize(NumElems, E);
4062 for (uint64_t I = 0; I != NumElems; ++I) {
4063 if (!this->emitConstUint64(I, E))
4064 return false;
4065 if (!this->emitArrayElemPtrUint64(E))
4066 return false;
4067 if (!initArrayDimension(ElemTy))
4068 return false;
4069 }
4070 return this->emitPopPtr(E);
4071 };
4072
4073 return initArrayDimension(E->getType());
4074 }
4075
4076 return false;
4077}
4078
4079template <class Emitter>
4081 if (DiscardResult)
4082 return true;
4083
4084 const APValue Val =
4085 E->EvaluateInContext(Ctx.getASTContext(), SourceLocDefaultExpr);
4086
4087 // Things like __builtin_LINE().
4088 if (E->getType()->isIntegerType()) {
4089 assert(Val.isInt());
4090 const APSInt &I = Val.getInt();
4091 return this->emitConst(I, E);
4092 }
4093 // Otherwise, the APValue is an LValue, with only one element.
4094 // Theoretically, we don't need the APValue at all of course.
4095 assert(E->getType()->isPointerType());
4096 assert(Val.isLValue());
4097 const APValue::LValueBase &Base = Val.getLValueBase();
4098 if (const Expr *LValueExpr = Base.dyn_cast<const Expr *>())
4099 return this->visit(LValueExpr);
4100
4101 // Otherwise, we have a decl (which is the case for
4102 // __builtin_source_location).
4103 assert(Base.is<const ValueDecl *>());
4104 assert(Val.getLValuePath().size() == 0);
4105 const auto *BaseDecl = Base.dyn_cast<const ValueDecl *>();
4106 assert(BaseDecl);
4107
4108 auto *UGCD = cast<UnnamedGlobalConstantDecl>(BaseDecl);
4109
4110 UnsignedOrNone GlobalIndex = P.getOrCreateGlobal(UGCD);
4111 if (!GlobalIndex)
4112 return false;
4113
4114 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
4115 return false;
4116
4117 const Record *R = getRecord(E->getType());
4118 const APValue &V = UGCD->getValue();
4119 for (unsigned I = 0, N = R->getNumFields(); I != N; ++I) {
4120 const Record::Field *F = R->getField(I);
4121 const APValue &FieldValue = V.getStructField(I);
4122
4123 if (!this->visitAPValue(FieldValue, *F->T, E))
4124 return false;
4125 if (!this->emitInitField(*F->T, F->Offset, E))
4126 return false;
4127 }
4128
4129 // Leave the pointer to the global on the stack.
4130 return true;
4131}
4132
4133template <class Emitter>
4135 unsigned N = E->getNumComponents();
4136 if (N == 0)
4137 return false;
4138
4139 for (unsigned I = 0; I != N; ++I) {
4140 const OffsetOfNode &Node = E->getComponent(I);
4141 if (Node.getKind() == OffsetOfNode::Array) {
4142 const Expr *ArrayIndexExpr = E->getIndexExpr(Node.getArrayExprIndex());
4143 PrimType IndexT = classifyPrim(ArrayIndexExpr->getType());
4144
4145 if (DiscardResult) {
4146 if (!this->discard(ArrayIndexExpr))
4147 return false;
4148 continue;
4149 }
4150
4151 if (IndexT == PT_IntAP || IndexT == PT_IntAPS) {
4152 if (!this->visit(ArrayIndexExpr))
4153 return false;
4154 if (!this->emitCastAPToOffsetIndex(IndexT, E))
4155 return false;
4156 continue;
4157 }
4158 if (!this->visit(ArrayIndexExpr))
4159 return false;
4160 // Cast to Sint64.
4161 if (IndexT != PT_Sint64) {
4162 if (!this->emitCast(IndexT, PT_Sint64, E))
4163 return false;
4164 }
4165 }
4166 }
4167
4168 if (DiscardResult)
4169 return true;
4170
4172 return this->emitOffsetOf(T, E, E);
4173}
4174
4175template <class Emitter>
4177 const CXXScalarValueInitExpr *E) {
4178 QualType Ty = E->getType();
4179
4180 if (DiscardResult || Ty->isVoidType())
4181 return true;
4182
4183 if (OptPrimType T = classify(Ty))
4184 return this->visitZeroInitializer(*T, Ty, E);
4185
4186 if (Ty->isAnyComplexType() || Ty->isVectorType()) {
4187 if (!Initializing) {
4188 UnsignedOrNone LocalIndex = allocateLocal(E);
4189 if (!LocalIndex)
4190 return false;
4191 if (!this->emitGetPtrLocal(*LocalIndex, E))
4192 return false;
4193 }
4194
4195 QualType ElemQT;
4196 unsigned NumElems;
4197 if (const auto *CT = Ty->getAs<ComplexType>()) {
4198 NumElems = 2;
4199 ElemQT = CT->getElementType();
4200 } else {
4201 const auto *VT = Ty->castAs<VectorType>();
4202 NumElems = VT->getNumElements();
4203 ElemQT = VT->getElementType();
4204 }
4205
4206 PrimType ElemT = classifyPrim(ElemQT);
4207
4208 // Initialize all fields to 0.
4209 for (unsigned I = 0; I != NumElems; ++I) {
4210 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
4211 return false;
4212 if (!this->emitInitElem(ElemT, I, E))
4213 return false;
4214 }
4215 return true;
4216 }
4217
4218 return false;
4219}
4220
4221template <class Emitter>
4223 return this->emitConst(E->getPackLength(), E);
4224}
4225
4226template <class Emitter>
4231
4232template <class Emitter>
4234 return this->delegate(E->getChosenSubExpr());
4235}
4236
4237template <class Emitter>
4239 if (DiscardResult)
4240 return true;
4241
4242 return this->emitConst(E->getValue(), E);
4243}
4244
4245template <class Emitter>
4247 const CXXInheritedCtorInitExpr *E) {
4248 const CXXConstructorDecl *Ctor = E->getConstructor();
4249
4250 if (Ctor->isTrivial())
4251 return true;
4252
4253 const Function *F = this->getFunction(Ctor);
4254 if (!F)
4255 return false;
4256 assert(!F->hasRVO());
4257 assert(F->hasThisPointer());
4258
4259 if (!this->emitDupPtr(SourceInfo{}))
4260 return false;
4261
4262 // Forward all arguments of the current function (which should be a
4263 // constructor itself) to the inherited ctor.
4264 // This is necessary because the calling code has pushed the pointer
4265 // of the correct base for us already, but the arguments need
4266 // to come after.
4267 unsigned ParamIndex = 0;
4268 for (const ParmVarDecl *PD : Ctor->parameters()) {
4269 PrimType PT = this->classify(PD->getType()).value_or(PT_Ptr);
4270
4271 if (!this->emitGetParam(PT, ParamIndex, E))
4272 return false;
4273 ++ParamIndex;
4274 }
4275
4276 return this->emitCall(F, 0, E);
4277}
4278
4279// FIXME: This function has become rather unwieldy, especially
4280// the part where we initialize an array allocation of dynamic size.
4281template <class Emitter>
4283 assert(classifyPrim(E->getType()) == PT_Ptr);
4284 const Expr *Init = E->getInitializer();
4285 QualType ElementType = E->getAllocatedType();
4286 OptPrimType ElemT = classify(ElementType);
4287 unsigned PlacementArgs = E->getNumPlacementArgs();
4288 const FunctionDecl *OperatorNew = E->getOperatorNew();
4289 const Expr *PlacementDest = nullptr;
4290 bool IsNoThrow = false;
4291
4292 if (E->containsErrors())
4293 return false;
4294
4295 if (PlacementArgs != 0) {
4296 // FIXME: There is no restriction on this, but it's not clear that any
4297 // other form makes any sense. We get here for cases such as:
4298 //
4299 // new (std::align_val_t{N}) X(int)
4300 //
4301 // (which should presumably be valid only if N is a multiple of
4302 // alignof(int), and in any case can't be deallocated unless N is
4303 // alignof(X) and X has new-extended alignment).
4304 if (PlacementArgs == 1) {
4305 const Expr *Arg1 = E->getPlacementArg(0);
4306 if (OperatorNew->isReservedGlobalPlacementOperator()) {
4307 if (!this->emitCheckPlacementNew(E, E))
4308 return false;
4309 PlacementDest = Arg1;
4310 } else if (
4311 Arg1->getType()->isNothrowT() &&
4312 OperatorNew
4313 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation()) {
4314 if (!this->discard(Arg1))
4315 return false;
4316 IsNoThrow = true;
4317 } else {
4318 // Any other placement list is invalid. This includes a user-declared
4319 // allocation function taking std::nothrow_t, e.g. by value.
4320 return this->emitInvalidNewDeleteExpr(E, E);
4321 }
4322 } else {
4323 // Always invalid.
4324 return this->emitInvalid(E);
4325 }
4326 } else if (!OperatorNew
4327 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
4328 return this->emitInvalidNewDeleteExpr(E, E);
4329
4330 const Descriptor *Desc;
4331 if (!PlacementDest) {
4332 if (ElemT) {
4333 if (E->isArray())
4334 Desc = nullptr; // We're not going to use it in this case.
4335 else
4336 Desc = P.createDescriptor(E, *ElemT);
4337 } else {
4338 Desc = P.createDescriptor(E, ElementType.getTypePtr(), /*IsConst=*/false,
4339 /*IsTemporary=*/false, /*IsMutable=*/false,
4340 /*IsVolatile=*/false, Init);
4341 }
4342 }
4343
4344 if (E->isArray()) {
4345 std::optional<const Expr *> ArraySizeExpr = E->getArraySize();
4346 if (!ArraySizeExpr)
4347 return false;
4348
4349 const Expr *Stripped = *ArraySizeExpr;
4350 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
4351 Stripped = ICE->getSubExpr())
4352 if (ICE->getCastKind() != CK_NoOp &&
4353 ICE->getCastKind() != CK_IntegralCast)
4354 break;
4355
4356 PrimType SizeT = classifyPrim(Stripped->getType());
4357
4358 // Save evaluated array size to a variable.
4359 unsigned ArrayLen =
4360 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
4361 if (!this->visit(Stripped))
4362 return false;
4363 if (!this->emitSetLocal(SizeT, ArrayLen, E))
4364 return false;
4365
4366 if (PlacementDest) {
4367 if (!this->visit(PlacementDest))
4368 return false;
4369 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4370 return false;
4371 if (!this->emitCheckNewTypeMismatchArray(SizeT, E, E))
4372 return false;
4373 } else {
4374 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4375 return false;
4376
4377 if (ElemT) {
4378 // N primitive elements.
4379 if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E))
4380 return false;
4381 } else {
4382 // N Composite elements.
4383 if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E))
4384 return false;
4385 }
4386 }
4387
4388 if (Init) {
4389 QualType InitType = Init->getType();
4390 size_t StaticInitElems = 0;
4391 const Expr *DynamicInit = nullptr;
4392 OptPrimType ElemT;
4393
4394 if (const ConstantArrayType *CAT =
4395 Ctx.getASTContext().getAsConstantArrayType(InitType)) {
4396 StaticInitElems = CAT->getZExtSize();
4397 // Initialize the first S element from the initializer.
4398 if (!this->visitInitializer(Init))
4399 return false;
4400
4401 if (const auto *ILE = dyn_cast<InitListExpr>(Init)) {
4402 if (ILE->hasArrayFiller())
4403 DynamicInit = ILE->getArrayFiller();
4404 else if (StaticInitElems > 0 && isa<StringLiteral>(ILE->getInit(0)))
4405 ElemT = classifyPrim(CAT->getElementType());
4406 }
4407 }
4408
4409 // The initializer initializes a certain number of elements, S.
4410 // However, the complete number of elements, N, might be larger than that.
4411 // In this case, we need to get an initializer for the remaining elements.
4412 // There are three cases:
4413 // 1) For the form 'new Struct[n];', the initializer is a
4414 // CXXConstructExpr and its type is an IncompleteArrayType.
4415 // 2) For the form 'new Struct[n]{1,2,3}', the initializer is an
4416 // InitListExpr and the initializer for the remaining elements
4417 // is the array filler.
4418 // 3) StringLiterals don't have an array filler, so we need to zero
4419 // the remaining elements.
4420
4421 if (DynamicInit || ElemT || InitType->isIncompleteArrayType()) {
4422 const Function *CtorFunc = nullptr;
4423 if (const auto *CE = dyn_cast<CXXConstructExpr>(Init)) {
4424 CtorFunc = getFunction(CE->getConstructor());
4425 if (!CtorFunc)
4426 return false;
4427 } else if (!DynamicInit && !ElemT)
4428 DynamicInit = Init;
4429
4430 LabelTy EndLabel = this->getLabel();
4431 LabelTy StartLabel = this->getLabel();
4432
4433 // In the nothrow case, the alloc above might have returned nullptr.
4434 // Don't call any constructors that case.
4435 if (IsNoThrow) {
4436 if (!this->emitDupPtr(E))
4437 return false;
4438 if (!this->emitIsNonNullPtr(E))
4439 return false;
4440 if (!this->jumpFalse(EndLabel, E))
4441 return false;
4442 }
4443
4444 // Create loop variables.
4445 unsigned Iter =
4446 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
4447 if (!this->emitConst(StaticInitElems, SizeT, E))
4448 return false;
4449 if (!this->emitSetLocal(SizeT, Iter, E))
4450 return false;
4451
4452 this->fallthrough(StartLabel);
4453 this->emitLabel(StartLabel);
4454 // Condition. Iter < ArrayLen?
4455 if (!this->emitGetLocal(SizeT, Iter, E))
4456 return false;
4457 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4458 return false;
4459 if (!this->emitLT(SizeT, E))
4460 return false;
4461 if (!this->jumpFalse(EndLabel, E))
4462 return false;
4463
4464 // Pointer to the allocated array is already on the stack.
4465 if (!this->emitGetLocal(SizeT, Iter, E))
4466 return false;
4467 if (!this->emitArrayElemPtr(SizeT, E))
4468 return false;
4469
4470 if (isa_and_nonnull<ImplicitValueInitExpr>(DynamicInit) &&
4471 DynamicInit->getType()->isArrayType()) {
4472 QualType ElemType =
4473 DynamicInit->getType()->getAsArrayTypeUnsafe()->getElementType();
4474 if (OptPrimType InitT = classify(ElemType)) {
4475 if (!this->visitZeroInitializer(*InitT, ElemType, E))
4476 return false;
4477 if (!this->emitStorePop(*InitT, E))
4478 return false;
4479 } else {
4480 assert(ElemType->isArrayType());
4481 if (!this->visitZeroArrayInitializer(ElemType, E))
4482 return false;
4483 }
4484 } else if (DynamicInit) {
4485 if (OptPrimType InitT = classify(DynamicInit)) {
4486 if (!this->visit(DynamicInit))
4487 return false;
4488 if (!this->emitStorePop(*InitT, E))
4489 return false;
4490 } else {
4491 if (!this->visitInitializerPop(DynamicInit))
4492 return false;
4493 }
4494 } else if (ElemT) {
4495 if (!this->visitZeroInitializer(
4496 *ElemT, InitType->getAsArrayTypeUnsafe()->getElementType(),
4497 Init))
4498 return false;
4499 if (!this->emitStorePop(*ElemT, E))
4500 return false;
4501 } else {
4502 assert(CtorFunc);
4503 if (!this->emitCall(CtorFunc, 0, E))
4504 return false;
4505 }
4506
4507 // ++Iter;
4508 if (!this->emitGetPtrLocal(Iter, E))
4509 return false;
4510 if (!this->emitIncPop(SizeT, false, E))
4511 return false;
4512
4513 if (!this->jump(StartLabel, E))
4514 return false;
4515
4516 this->fallthrough(EndLabel);
4517 this->emitLabel(EndLabel);
4518 }
4519 }
4520 } else { // Non-array.
4521 if (PlacementDest) {
4522 if (!this->visit(PlacementDest))
4523 return false;
4524 if (!this->emitCheckNewTypeMismatch(E, E))
4525 return false;
4526
4527 } else {
4528 // Allocate just one element.
4529 if (!this->emitAlloc(Desc, E))
4530 return false;
4531 }
4532
4533 if (Init) {
4534 if (ElemT) {
4535 if (!this->visit(Init))
4536 return false;
4537
4538 if (!this->emitInit(*ElemT, E))
4539 return false;
4540 } else {
4541 // Composite.
4542 if (!this->visitInitializer(Init))
4543 return false;
4544 }
4545 }
4546 }
4547
4548 if (DiscardResult)
4549 return this->emitPopPtr(E);
4550
4551 return true;
4552}
4553
4554template <class Emitter>
4556 if (E->containsErrors())
4557 return false;
4558 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
4559
4560 if (!OperatorDelete->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
4561 return this->emitInvalidNewDeleteExpr(E, E);
4562
4563 // Arg must be an lvalue.
4564 if (!this->visit(E->getArgument()))
4565 return false;
4566
4567 return this->emitFree(E->isArrayForm(), E->isGlobalDelete(), E);
4568}
4569
4570template <class Emitter>
4572 if (DiscardResult)
4573 return true;
4574
4575 const Function *Func = nullptr;
4576 if (const Function *F = Ctx.getOrCreateObjCBlock(E))
4577 Func = F;
4578
4579 if (!Func)
4580 return false;
4581 return this->emitGetFnPtr(Func, E);
4582}
4583
4584template <class Emitter>
4586 const Type *TypeInfoType = E->getType().getTypePtr();
4587
4588 auto canonType = [](const Type *T) {
4589 return T->getCanonicalTypeUnqualified().getTypePtr();
4590 };
4591
4592 if (!E->isPotentiallyEvaluated()) {
4593 if (DiscardResult)
4594 return true;
4595
4596 if (E->isTypeOperand())
4597 return this->emitGetTypeid(
4598 canonType(E->getTypeOperand(Ctx.getASTContext()).getTypePtr()),
4599 TypeInfoType, E);
4600
4601 return this->emitGetTypeid(
4602 canonType(E->getExprOperand()->getType().getTypePtr()), TypeInfoType,
4603 E);
4604 }
4605
4606 // Otherwise, we need to evaluate the expression operand.
4607 assert(E->getExprOperand());
4608 assert(E->getExprOperand()->isLValue());
4609
4610 if (!Ctx.getLangOpts().CPlusPlus20 && !this->emitDiagTypeid(E))
4611 return false;
4612
4613 if (!this->visit(E->getExprOperand()))
4614 return false;
4615
4616 if (!this->emitGetTypeidPtr(TypeInfoType, E))
4617 return false;
4618 if (DiscardResult)
4619 return this->emitPopPtr(E);
4620 return true;
4621}
4622
4623template <class Emitter>
4625 const ObjCDictionaryLiteral *E) {
4627 return this->emitDummyPtr(E, E);
4628 return this->emitError(E);
4629}
4630
4631template <class Emitter>
4634 return this->emitDummyPtr(E, E);
4635 return this->emitError(E);
4636}
4637
4638template <class Emitter>
4640 if (DiscardResult)
4641 return true;
4642
4643 switch (E->getKind()) {
4644 case ReflectionKind::Null: {
4645 assert(false && "null reflection can't be constructed from parsing a "
4646 "reflection operand");
4647 return false;
4648 }
4649 case ReflectionKind::Type: {
4650 return this->emitReflectValue(E->getKind(), E->getOpaqueValue(), E);
4651 }
4652 }
4653
4654 assert(false && "unknown or unimplemented reflection entities");
4655 return false;
4656}
4657
4658template <class Emitter>
4660 assert(Ctx.getLangOpts().CPlusPlus);
4661 return this->emitConstBool(E->getValue(), E);
4662}
4663
4664template <class Emitter>
4666 if (DiscardResult)
4667 return true;
4668 assert(!Initializing);
4669
4670 const MSGuidDecl *GuidDecl = E->getGuidDecl();
4671 const RecordDecl *RD = GuidDecl->getType()->getAsRecordDecl();
4672 assert(RD);
4673 // If the definiton of the result type is incomplete, just return a dummy.
4674 // If (and when) that is read from, we will fail, but not now.
4675 if (!RD->isCompleteDefinition())
4676 return this->emitDummyPtr(GuidDecl, E);
4677
4678 UnsignedOrNone GlobalIndex = P.getOrCreateGlobal(GuidDecl);
4679 if (!GlobalIndex)
4680 return false;
4681 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
4682 return false;
4683
4684 assert(this->getRecord(E->getType()));
4685
4686 const APValue &V = GuidDecl->getAsAPValue();
4687 if (V.getKind() == APValue::None)
4688 return true;
4689
4690 assert(V.isStruct());
4691 assert(V.getStructNumBases() == 0);
4692 if (!this->visitAPValueInitializer(V, E, E->getType()))
4693 return false;
4694
4695 return this->emitFinishInit(E);
4696}
4697
4698template <class Emitter>
4700 assert(classifyPrim(E->getType()) == PT_Bool);
4701 if (E->isValueDependent())
4702 return false;
4703 if (DiscardResult)
4704 return true;
4705 return this->emitConstBool(E->isSatisfied(), E);
4706}
4707
4708template <class Emitter>
4710 const ConceptSpecializationExpr *E) {
4711 assert(classifyPrim(E->getType()) == PT_Bool);
4712 if (DiscardResult)
4713 return true;
4714 return this->emitConstBool(E->isSatisfied(), E);
4715}
4716
4717template <class Emitter>
4722
4723template <class Emitter>
4725
4726 for (const Expr *SemE : E->semantics()) {
4727 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
4728 if (SemE == E->getResultExpr())
4729 return false;
4730
4731 if (OVE->isUnique())
4732 continue;
4733
4734 if (!this->discard(OVE))
4735 return false;
4736 } else if (SemE == E->getResultExpr()) {
4737 if (!this->delegate(SemE))
4738 return false;
4739 } else {
4740 if (!this->discard(SemE))
4741 return false;
4742 }
4743 }
4744 return true;
4745}
4746
4747template <class Emitter>
4751
4752template <class Emitter>
4754 return this->emitError(E);
4755}
4756
4757template <class Emitter>
4759 assert(E->getType()->isVoidPointerType());
4760 if (DiscardResult)
4761 return true;
4762
4763 return this->emitDummyPtr(E, E);
4764}
4765
4766template <class Emitter>
4767bool Compiler<Emitter>::emitVectorConversion(const Expr *Src, const Expr *E) {
4768 if (Src->containsErrors())
4769 return false;
4770
4771 const auto *VT = E->getType()->castAs<VectorType>();
4772 QualType ElemType = VT->getElementType();
4773 PrimType ElemT = classifyPrim(ElemType);
4774 QualType SrcType = Src->getType();
4775 PrimType SrcElemT = classifyVectorElementType(SrcType);
4776
4777 if (!Initializing) {
4778 UnsignedOrNone LocalIndex = allocateLocal(E);
4779 if (!LocalIndex)
4780 return false;
4781 if (!this->emitGetPtrLocal(*LocalIndex, E))
4782 return false;
4783 }
4784
4785 unsigned SrcOffset =
4786 this->allocateLocalPrimitive(Src, PT_Ptr, /*IsConst=*/true);
4787 if (!this->visit(Src))
4788 return false;
4789 if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
4790 return false;
4791
4792 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
4793 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
4794 return false;
4795 if (!this->emitArrayElemPop(SrcElemT, I, E))
4796 return false;
4797
4798 // Cast to the desired result element type.
4799 if (SrcElemT != ElemT) {
4800 if (!this->emitPrimCast(SrcElemT, ElemT, ElemType, E))
4801 return false;
4802 } else if (ElemType->isFloatingType() && SrcType != ElemType) {
4803 const auto *TargetSemantics = &Ctx.getFloatSemantics(ElemType);
4804 if (!this->emitCastFP(TargetSemantics, getRoundingMode(E), E))
4805 return false;
4806 }
4807 if (!this->emitInitElem(ElemT, I, E))
4808 return false;
4809 }
4810 return true;
4811}
4812
4813template <class Emitter>
4815 return emitVectorConversion(E->getSrcExpr(), E);
4816}
4817
4818template <class Emitter>
4820 // FIXME: Unary shuffle with mask not currently supported.
4821 if (E->getNumSubExprs() == 2)
4822 return this->emitInvalid(E);
4823
4824 assert(E->getNumSubExprs() > 2);
4825
4826 const Expr *Vecs[] = {E->getExpr(0), E->getExpr(1)};
4827 const VectorType *VT = Vecs[0]->getType()->castAs<VectorType>();
4828 PrimType ElemT = classifyPrim(VT->getElementType());
4829 unsigned NumInputElems = VT->getNumElements();
4830 unsigned NumOutputElems = E->getNumSubExprs() - 2;
4831 assert(NumOutputElems > 0);
4832
4833 if (!Initializing) {
4834 UnsignedOrNone LocalIndex = allocateLocal(E);
4835 if (!LocalIndex)
4836 return false;
4837 if (!this->emitGetPtrLocal(*LocalIndex, E))
4838 return false;
4839 }
4840
4841 // Save both input vectors to a local variable.
4842 unsigned VectorOffsets[2];
4843 for (unsigned I = 0; I != 2; ++I) {
4844 VectorOffsets[I] =
4845 this->allocateLocalPrimitive(Vecs[I], PT_Ptr, /*IsConst=*/true);
4846 if (!this->visit(Vecs[I]))
4847 return false;
4848 if (!this->emitSetLocal(PT_Ptr, VectorOffsets[I], E))
4849 return false;
4850 }
4851 for (unsigned I = 0; I != NumOutputElems; ++I) {
4852 APSInt ShuffleIndex = E->getShuffleMaskIdx(I);
4853 assert(ShuffleIndex >= -1);
4854 if (ShuffleIndex == -1)
4855 return this->emitInvalidShuffleVectorIndex(I, E);
4856
4857 assert(ShuffleIndex < (NumInputElems * 2));
4858 if (!this->emitGetLocal(PT_Ptr,
4859 VectorOffsets[ShuffleIndex >= NumInputElems], E))
4860 return false;
4861 unsigned InputVectorIndex = ShuffleIndex.getZExtValue() % NumInputElems;
4862 if (!this->emitArrayElemPop(ElemT, InputVectorIndex, E))
4863 return false;
4864
4865 if (!this->emitInitElem(ElemT, I, E))
4866 return false;
4867 }
4868
4869 if (DiscardResult)
4870 return this->emitPopPtr(E);
4871
4872 return true;
4873}
4874
4875template <class Emitter>
4877 const ExtVectorElementExpr *E) {
4878 const Expr *Base = E->getBase();
4879 assert(
4880 Base->getType()->isVectorType() ||
4881 Base->getType()->getAs<PointerType>()->getPointeeType()->isVectorType());
4882
4884 E->getEncodedElementAccess(Indices);
4885
4886 if (Indices.size() == 1) {
4887 if (!this->visit(Base))
4888 return false;
4889
4890 if (E->isGLValue()) {
4891 if (!this->emitConstUint32(Indices[0], E))
4892 return false;
4893 return this->emitArrayElemPtrPop(PT_Uint32, E);
4894 }
4895 // Else, also load the value.
4896 return this->emitArrayElemPop(classifyPrim(E->getType()), Indices[0], E);
4897 }
4898
4899 // Create a local variable for the base.
4900 unsigned BaseOffset = allocateLocalPrimitive(Base, PT_Ptr, /*IsConst=*/true);
4901 if (!this->visit(Base))
4902 return false;
4903 if (!this->emitSetLocal(PT_Ptr, BaseOffset, E))
4904 return false;
4905
4906 // Now the vector variable for the return value.
4907 if (!Initializing) {
4908 UnsignedOrNone ResultIndex = allocateLocal(E);
4909 if (!ResultIndex)
4910 return false;
4911 if (!this->emitGetPtrLocal(*ResultIndex, E))
4912 return false;
4913 }
4914
4915 assert(Indices.size() == E->getType()->getAs<VectorType>()->getNumElements());
4916
4917 PrimType ElemT =
4919 uint32_t DstIndex = 0;
4920 for (uint32_t I : Indices) {
4921 if (!this->emitGetLocal(PT_Ptr, BaseOffset, E))
4922 return false;
4923 if (!this->emitArrayElemPop(ElemT, I, E))
4924 return false;
4925 if (!this->emitInitElem(ElemT, DstIndex, E))
4926 return false;
4927 ++DstIndex;
4928 }
4929
4930 // Leave the result pointer on the stack.
4931 assert(!DiscardResult);
4932 return true;
4933}
4934
4935template <class Emitter>
4937 const Expr *SubExpr = E->getSubExpr();
4939 return this->discard(SubExpr) && this->emitInvalid(E);
4940
4941 if (DiscardResult)
4942 return true;
4943
4944 assert(classifyPrim(E) == PT_Ptr);
4945 return this->emitDummyPtr(E, E);
4946}
4947
4948template <class Emitter>
4950 const CXXStdInitializerListExpr *E) {
4951 const Expr *SubExpr = E->getSubExpr();
4953 Ctx.getASTContext().getAsConstantArrayType(SubExpr->getType());
4954 const Record *R = getRecord(E->getType());
4955 assert(SubExpr->isGLValue());
4956 assert(!canClassify(E->getType()));
4957
4958 if (!Initializing) {
4959 UnsignedOrNone LocalIndex = allocateLocal(E);
4960 if (!LocalIndex)
4961 return false;
4962 if (!this->emitGetPtrLocal(*LocalIndex, E))
4963 return false;
4964 }
4965
4966 if (!this->visit(SubExpr))
4967 return false;
4968 if (!this->emitConstUint8(0, E))
4969 return false;
4970 if (!this->emitArrayElemPtrPopUint8(E))
4971 return false;
4972 if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E))
4973 return false;
4974
4975 PrimType SecondFieldT = *R->getField(1u)->T;
4976 if (isIntegerOrBoolType(SecondFieldT)) {
4977 if (!this->emitConst(ArrayType->getSize(), SecondFieldT, E))
4978 return false;
4979 if (!this->emitInitField(SecondFieldT, R->getField(1u)->Offset, E))
4980 return false;
4981 if (DiscardResult)
4982 return this->emitPopPtr(E);
4983 return true;
4984 }
4985 assert(SecondFieldT == PT_Ptr);
4986
4987 if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E))
4988 return false;
4989 if (!this->emitExpandPtr(E))
4990 return false;
4991 if (!this->emitConst(ArrayType->getSize(), PT_Uint64, E))
4992 return false;
4993 if (!this->emitArrayElemPtrPop(PT_Uint64, E))
4994 return false;
4995
4996 if (!this->emitInitFieldPtr(R->getField(1u)->Offset, E))
4997 return false;
4998 if (DiscardResult)
4999 return this->emitPopPtr(E);
5000 return true;
5001}
5002
5003template <class Emitter>
5005 LocalScope<Emitter> BS(this);
5006 llvm::SaveAndRestore StmtExprSAR(this->InStmtExpr, true);
5007
5008 const CompoundStmt *CS = E->getSubStmt();
5009 const Stmt *Result = CS->body_back();
5010 for (const Stmt *S : CS->body()) {
5011 if (S != Result) {
5012 if (!this->visitStmt(S))
5013 return false;
5014 continue;
5015 }
5016
5017 assert(S == Result);
5018 if (const Expr *ResultExpr = dyn_cast<Expr>(S))
5019 return this->delegate(ResultExpr);
5020 if (!this->visitStmt(S))
5021 return false;
5022 return this->emitUnsupported(E);
5023 }
5024
5025 return BS.destroyLocals();
5026}
5027
5028template <class Emitter> bool Compiler<Emitter>::discard(const Expr *E) {
5029 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true,
5030 /*NewInitializing=*/false, /*ToLValue=*/false);
5031 return this->Visit(E);
5032}
5033
5034template <class Emitter> bool Compiler<Emitter>::delegate(const Expr *E) {
5035 // We're basically doing:
5036 // OptionScope<Emitter> Scope(this, DicardResult, Initializing, ToLValue);
5037 // but that's unnecessary of course.
5038 return this->Visit(E);
5039}
5040
5042 if (const auto *PE = dyn_cast<ParenExpr>(E))
5043 return stripCheckedDerivedToBaseCasts(PE->getSubExpr());
5044
5045 if (const auto *CE = dyn_cast<CastExpr>(E);
5046 CE &&
5047 (CE->getCastKind() == CK_DerivedToBase || CE->getCastKind() == CK_NoOp))
5048 return stripCheckedDerivedToBaseCasts(CE->getSubExpr());
5049
5050 return E;
5051}
5052
5053static const Expr *stripDerivedToBaseCasts(const Expr *E) {
5054 if (const auto *PE = dyn_cast<ParenExpr>(E))
5055 return stripDerivedToBaseCasts(PE->getSubExpr());
5056
5057 if (const auto *CE = dyn_cast<CastExpr>(E);
5058 CE && (CE->getCastKind() == CK_DerivedToBase ||
5059 CE->getCastKind() == CK_UncheckedDerivedToBase ||
5060 CE->getCastKind() == CK_NoOp))
5061 return stripDerivedToBaseCasts(CE->getSubExpr());
5062
5063 return E;
5064}
5065
5066template <class Emitter> bool Compiler<Emitter>::visit(const Expr *E) {
5067 if (E->getType().isNull())
5068 return false;
5069
5070 if (E->getType()->isVoidType())
5071 return this->discard(E);
5072
5073 // Create local variable to hold the return value.
5074 if (!E->isGLValue() && !canClassify(E->getType())) {
5075 UnsignedOrNone LocalIndex = allocateLocal(
5077 if (!LocalIndex)
5078 return false;
5079
5080 if (!this->emitGetPtrLocal(*LocalIndex, E))
5081 return false;
5082 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
5083 return this->visitInitializer(E);
5084 }
5085
5086 // Otherwise,we have a primitive return value, produce the value directly
5087 // and push it on the stack.
5088 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5089 /*NewInitializing=*/false, /*ToLValue=*/ToLValue);
5090 return this->Visit(E);
5091}
5092
5093template <class Emitter>
5095 assert(!canClassify(E->getType()));
5096
5097 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5098 /*NewInitializing=*/true, /*ToLValue=*/false);
5099 return this->Visit(E) && this->emitFinishInit(E);
5100}
5101
5102template <class Emitter>
5104 assert(!canClassify(E->getType()));
5105
5106 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5107 /*NewInitializing=*/true, /*ToLValue=*/false);
5108 return this->Visit(E) && this->emitFinishInitPop(E);
5109}
5110
5111template <class Emitter> bool Compiler<Emitter>::visitAsLValue(const Expr *E) {
5112 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5113 /*NewInitializing=*/false, /*ToLValue=*/true);
5114 return this->Visit(E);
5115}
5116
5117template <class Emitter> bool Compiler<Emitter>::visitBool(const Expr *E) {
5118 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5119 /*NewInitializing=*/false, /*ToLValue=*/ToLValue);
5120
5121 OptPrimType T = classify(E->getType());
5122 if (!T) {
5123 // Convert complex values to bool.
5124 if (E->getType()->isAnyComplexType()) {
5125 if (!this->visit(E))
5126 return false;
5127 return this->emitComplexBoolCast(E);
5128 }
5129 return false;
5130 }
5131
5132 if (!this->visit(E))
5133 return false;
5134
5135 if (T == PT_Bool)
5136 return true;
5137
5138 // Convert pointers to bool.
5139 if (T == PT_Ptr)
5140 return this->emitIsNonNullPtr(E);
5141
5142 // Or Floats.
5143 if (T == PT_Float)
5144 return this->emitCastFloatingIntegralBool(getFPOptions(E), E);
5145
5146 // Or anything else we can.
5147 return this->emitCast(*T, PT_Bool, E);
5148}
5149
5150template <class Emitter>
5151bool Compiler<Emitter>::visitZeroInitializer(PrimType T, QualType QT,
5152 const Expr *E) {
5153 if (const auto *AT = QT->getAs<AtomicType>())
5154 QT = AT->getValueType();
5155
5156 switch (T) {
5157 case PT_Bool:
5158 return this->emitZeroBool(E);
5159 case PT_Sint8:
5160 return this->emitZeroSint8(E);
5161 case PT_Uint8:
5162 return this->emitZeroUint8(E);
5163 case PT_Sint16:
5164 return this->emitZeroSint16(E);
5165 case PT_Uint16:
5166 return this->emitZeroUint16(E);
5167 case PT_Sint32:
5168 return this->emitZeroSint32(E);
5169 case PT_Uint32:
5170 return this->emitZeroUint32(E);
5171 case PT_Sint64:
5172 return this->emitZeroSint64(E);
5173 case PT_Uint64:
5174 return this->emitZeroUint64(E);
5175 case PT_IntAP:
5176 return this->emitZeroIntAP(Ctx.getBitWidth(QT), E);
5177 case PT_IntAPS:
5178 return this->emitZeroIntAPS(Ctx.getBitWidth(QT), E);
5179 case PT_Ptr:
5180 return this->emitNullPtr(Ctx.getASTContext().getTargetNullPointerValue(QT),
5181 nullptr, E);
5182 case PT_MemberPtr:
5183 return this->emitNullMemberPtr(0, nullptr, E);
5184 case PT_Float: {
5185 APFloat F = APFloat::getZero(Ctx.getFloatSemantics(QT));
5186 return this->emitFloat(F, E);
5187 }
5188 case PT_FixedPoint: {
5189 auto Sem = Ctx.getASTContext().getFixedPointSemantics(QT);
5190 return this->emitConstFixedPoint(FixedPoint::zero(Sem), E);
5191 }
5192 case PT_Reflect:
5193 return this->emitReflectValue(ReflectionKind::Null, nullptr, E);
5194 }
5195 llvm_unreachable("unknown primitive type");
5196}
5197
5198template <class Emitter>
5199bool Compiler<Emitter>::visitZeroRecordInitializer(const Record *R,
5200 const Expr *E,
5201 bool IsCompleteClass) {
5202 assert(E);
5203 assert(R);
5204 // Fields
5205 for (const Record::Field &Field : R->fields()) {
5206 if (Field.isUnnamedBitField())
5207 continue;
5208
5209 const Descriptor *D = Field.Desc;
5210 if (D->isPrimitive()) {
5211 QualType QT = D->getType();
5212 PrimType T = D->getPrimType();
5213 if (!this->visitZeroInitializer(T, QT, E))
5214 return false;
5215 if (R->isUnion()) {
5216 if (!this->emitInitFieldActivate(T, Field.Offset, E))
5217 return false;
5218 break;
5219 }
5220 if (!this->emitInitField(T, Field.Offset, E))
5221 return false;
5222 continue;
5223 }
5224
5225 if (!this->emitGetPtrField(Field.Offset, E))
5226 return false;
5227
5228 if (D->isPrimitiveArray()) {
5229 QualType ET = D->getElemQualType();
5230 PrimType T = D->getPrimType();
5231 for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
5232 if (!this->visitZeroInitializer(T, ET, E))
5233 return false;
5234 if (!this->emitInitElem(T, I, E))
5235 return false;
5236 }
5237 } else if (D->isCompositeArray()) {
5238 // Can't be a vector or complex field.
5239 if (!this->visitZeroArrayInitializer(D->getType(), E))
5240 return false;
5241 } else if (D->isRecord()) {
5242 if (!this->visitZeroRecordInitializer(D->ElemRecord, E))
5243 return false;
5244 } else
5245 return false;
5246
5247 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5248 // object's first non-static named data member is zero-initialized
5249 if (R->isUnion()) {
5250 if (!this->emitFinishInitActivatePop(E))
5251 return false;
5252 break;
5253 }
5254 if (!this->emitFinishInitPop(E))
5255 return false;
5256 }
5257
5258 for (const Record::Base &B : R->bases()) {
5259 if (!this->emitGetPtrBase(B.Offset, E))
5260 return false;
5261 if (!this->visitZeroRecordInitializer(B.R, E, /*IsCompleteClass=*/false))
5262 return false;
5263 if (!this->emitFinishInitPop(E))
5264 return false;
5265 }
5266
5267 if (IsCompleteClass) {
5268 for (const Record::Base &B : R->virtual_bases()) {
5269 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(B.R->getDecl()), E))
5270 return false;
5271 if (!this->visitZeroRecordInitializer(B.R, E, /*IsCompleteClass=*/false))
5272 return false;
5273 if (!this->emitFinishInitPop(E))
5274 return false;
5275 }
5276 }
5277
5278 return true;
5279}
5280
5281template <class Emitter>
5282bool Compiler<Emitter>::visitZeroArrayInitializer(QualType T, const Expr *E) {
5283 assert(T->isArrayType() || T->isAnyComplexType() || T->isVectorType());
5284 const ArrayType *AT = T->getAsArrayTypeUnsafe();
5285 QualType ElemType = AT->getElementType();
5286 size_t NumElems = cast<ConstantArrayType>(AT)->getZExtSize();
5287
5288 if (OptPrimType ElemT = classify(ElemType)) {
5289 for (size_t I = 0; I != NumElems; ++I) {
5290 if (!this->visitZeroInitializer(*ElemT, ElemType, E))
5291 return false;
5292 if (!this->emitInitElem(*ElemT, I, E))
5293 return false;
5294 }
5295 return true;
5296 }
5297 if (ElemType->isRecordType()) {
5298 const Record *R = getRecord(ElemType);
5299 if (!R)
5300 return false;
5301
5302 for (size_t I = 0; I != NumElems; ++I) {
5303 if (!this->emitConstUint32(I, E))
5304 return false;
5305 if (!this->emitArrayElemPtr(PT_Uint32, E))
5306 return false;
5307 if (!this->visitZeroRecordInitializer(R, E))
5308 return false;
5309 if (!this->emitPopPtr(E))
5310 return false;
5311 }
5312 return true;
5313 }
5314 if (ElemType->isArrayType()) {
5315 for (size_t I = 0; I != NumElems; ++I) {
5316 if (!this->emitConstUint32(I, E))
5317 return false;
5318 if (!this->emitArrayElemPtr(PT_Uint32, E))
5319 return false;
5320 if (!this->visitZeroArrayInitializer(ElemType, E))
5321 return false;
5322 if (!this->emitPopPtr(E))
5323 return false;
5324 }
5325 return true;
5326 }
5327
5328 return false;
5329}
5330
5331template <class Emitter>
5332bool Compiler<Emitter>::visitAssignment(const Expr *LHS, const Expr *RHS,
5333 const Expr *E) {
5334 if (!canClassify(E->getType()))
5335 return false;
5336
5337 bool NeedsFlip = !isSideEffectFree(RHS);
5338 if (!NeedsFlip) {
5339 if (!this->visit(LHS))
5340 return false;
5341 if (!this->visit(RHS))
5342 return false;
5343 } else {
5344 if (!this->visit(RHS))
5345 return false;
5346 if (!this->visit(LHS))
5347 return false;
5348 }
5349
5350 if (LHS->getType().isVolatileQualified())
5351 return this->emitInvalidStore(LHS->getType().getTypePtr(), E);
5352
5353 // We don't support assignments in C.
5354 if (!Ctx.getLangOpts().CPlusPlus && !this->emitInvalid(E))
5355 return false;
5356
5357 PrimType RHT = classifyPrim(RHS);
5358 bool Activates = refersToUnion(LHS);
5359 bool BitField = LHS->refersToBitField();
5360
5361 if (NeedsFlip && !this->emitFlip(PT_Ptr, RHT, E))
5362 return false;
5363
5364 if (DiscardResult) {
5365 if (BitField && Activates)
5366 return this->emitStoreBitFieldActivatePop(RHT, E);
5367 if (BitField)
5368 return this->emitStoreBitFieldPop(RHT, E);
5369 if (Activates)
5370 return this->emitStoreActivatePop(RHT, E);
5371 // Otherwise, regular non-activating store.
5372 return this->emitStorePop(RHT, E);
5373 }
5374
5375 auto maybeLoad = [&](bool Result) -> bool {
5376 if (!Result)
5377 return false;
5378 // Assignments aren't necessarily lvalues in C.
5379 // Load from them in that case.
5380 if (!E->isLValue())
5381 return this->emitLoadPop(RHT, E);
5382 return true;
5383 };
5384
5385 if (BitField && Activates)
5386 return maybeLoad(this->emitStoreBitFieldActivate(RHT, E));
5387 if (BitField)
5388 return maybeLoad(this->emitStoreBitField(RHT, E));
5389 if (Activates)
5390 return maybeLoad(this->emitStoreActivate(RHT, E));
5391 // Otherwise, regular non-activating store.
5392 return maybeLoad(this->emitStore(RHT, E));
5393}
5394
5395template <class Emitter>
5396template <typename T>
5397bool Compiler<Emitter>::emitConst(T Value, PrimType Ty, SourceInfo Info) {
5398 switch (Ty) {
5399 case PT_Sint8:
5400 return this->emitConstSint8(Value, Info);
5401 case PT_Uint8:
5402 return this->emitConstUint8(Value, Info);
5403 case PT_Sint16:
5404 return this->emitConstSint16(Value, Info);
5405 case PT_Uint16:
5406 return this->emitConstUint16(Value, Info);
5407 case PT_Sint32:
5408 return this->emitConstSint32(Value, Info);
5409 case PT_Uint32:
5410 return this->emitConstUint32(Value, Info);
5411 case PT_Sint64:
5412 return this->emitConstSint64(Value, Info);
5413 case PT_Uint64:
5414 return this->emitConstUint64(Value, Info);
5415 case PT_Bool:
5416 return this->emitConstBool(Value, Info);
5417 case PT_Ptr:
5418 case PT_MemberPtr:
5419 case PT_Float:
5420 case PT_IntAP:
5421 case PT_IntAPS:
5422 case PT_FixedPoint:
5423 case PT_Reflect:
5424 llvm_unreachable("Invalid integral type");
5425 break;
5426 }
5427 llvm_unreachable("unknown primitive type");
5428}
5429
5430template <class Emitter>
5431template <typename T>
5432bool Compiler<Emitter>::emitConst(T Value, const Expr *E) {
5433 return this->emitConst(Value, classifyPrim(E->getType()), E);
5434}
5435
5436template <class Emitter>
5437bool Compiler<Emitter>::emitConst(const APSInt &Value, PrimType Ty,
5438 SourceInfo Info) {
5439 if (Ty == PT_IntAPS)
5440 return this->emitConstIntAPS(Value, Info);
5441 if (Ty == PT_IntAP)
5442 return this->emitConstIntAP(Value, Info);
5443
5444 if (Value.isSigned())
5445 return this->emitConst(Value.getSExtValue(), Ty, Info);
5446 return this->emitConst(Value.getZExtValue(), Ty, Info);
5447}
5448
5449template <class Emitter>
5450bool Compiler<Emitter>::emitConst(const APInt &Value, PrimType Ty,
5451 SourceInfo Info) {
5452 if (Ty == PT_IntAPS)
5453 return this->emitConstIntAPS(Value, Info);
5454 if (Ty == PT_IntAP)
5455 return this->emitConstIntAP(Value, Info);
5456
5457 if (isSignedType(Ty))
5458 return this->emitConst(Value.getSExtValue(), Ty, Info);
5459 return this->emitConst(Value.getZExtValue(), Ty, Info);
5460}
5461
5462template <class Emitter>
5463bool Compiler<Emitter>::emitConst(const APSInt &Value, const Expr *E) {
5464 return this->emitConst(Value, classifyPrim(E->getType()), E);
5465}
5466
5467template <class Emitter>
5469 bool IsConst,
5470 bool IsVolatile,
5471 ScopeKind SC) {
5472 // FIXME: There are cases where Src.isExpr() is wrong, e.g.
5473 // (int){12} in C. Consider using Expr::isTemporaryObject() instead
5474 // or isa<MaterializeTemporaryExpr>().
5475 Descriptor *D = P.createDescriptor(Src, Ty, nullptr, IsConst, Src.isExpr(),
5476 /*IsMutable=*/false, IsVolatile);
5478 Scope::Local Local = this->createLocal(D);
5479 if (auto *VD = Src.asValueDecl())
5480 Locals.insert({VD, Local});
5481 VarScope->addForScopeKind(Local, SC);
5482 return Local.Offset;
5483}
5484
5485template <class Emitter>
5487 ScopeKind SC) {
5488 const ValueDecl *Key = nullptr;
5489 const Expr *Init = nullptr;
5490 bool IsTemporary = false;
5491 if (auto *VD = Src.asValueDecl()) {
5492 Key = VD;
5493
5494 if (const auto *VarD = dyn_cast<VarDecl>(VD))
5495 Init = VarD->getInit();
5496 }
5497 if (const auto *E = Src.asExpr()) {
5498 IsTemporary = true;
5499 if (Ty.isNull())
5500 Ty = E->getType();
5501 }
5502
5503 Descriptor *D = P.createDescriptor(
5504 Src, Ty.getTypePtr(), Ty.isConstQualified(), IsTemporary,
5505 /*IsMutable=*/false, /*IsVolatile=*/Ty.isVolatileQualified(), Init);
5506 if (!D)
5507 return std::nullopt;
5509
5510 Scope::Local Local = this->createLocal(D);
5511 if (Key)
5512 Locals.insert({Key, Local});
5513 VarScope->addForScopeKind(Local, SC);
5514 return Local.Offset;
5515}
5516
5517template <class Emitter>
5519 QualType Ty = E->getType();
5520 assert(!Ty->isRecordType());
5521
5522 Descriptor *D = P.createDescriptor(E, Ty.getTypePtr(), Ty.isConstQualified(),
5523 /*IsTemporary=*/true);
5524
5525 if (!D)
5526 return std::nullopt;
5527
5528 Scope::Local Local = this->createLocal(D);
5530 assert(S);
5531 // Attach to topmost scope.
5532 while (S->getParent())
5533 S = S->getParent();
5534 assert(S && !S->getParent());
5535 S->addLocal(Local);
5536 return Local.Offset;
5537}
5538
5539template <class Emitter>
5541 if (const PointerType *PT = dyn_cast<PointerType>(Ty))
5542 return PT->getPointeeType()->getAsCanonical<RecordType>();
5543 return Ty->getAsCanonical<RecordType>();
5544}
5545
5546template <class Emitter> Record *Compiler<Emitter>::getRecord(QualType Ty) {
5547 if (const auto *RecordTy = getRecordTy(Ty))
5548 return getRecord(RecordTy->getDecl()->getDefinitionOrSelf());
5549 return nullptr;
5550}
5551
5552template <class Emitter>
5554 return P.getOrCreateRecord(RD);
5555}
5556
5557template <class Emitter>
5559 return Ctx.getOrCreateFunction(FD);
5560}
5561
5562template <class Emitter>
5563bool Compiler<Emitter>::visitExpr(const Expr *E, bool DestroyToplevelScope) {
5564 assert(E);
5565 assert(!E->getType().isNull());
5567
5568 auto maybeDestroyLocals = [&]() -> bool {
5569 if (DestroyToplevelScope)
5570 return RootScope.destroyLocals() && this->emitCheckAllocations(E);
5571 return this->emitCheckAllocations(E);
5572 };
5573
5574 // Void expressions.
5575 if (E->getType()->isVoidType()) {
5576 if (!visit(E))
5577 return false;
5578 return this->emitRetVoid(E) && maybeDestroyLocals();
5579 }
5580
5581 // Expressions with a primitive return type.
5582 if (OptPrimType T = classify(E)) {
5583 if (!visit(E))
5584 return false;
5585
5586 return this->emitRet(*T, E) && maybeDestroyLocals();
5587 }
5588
5589 // Expressions with a composite return type.
5590 // For us, that means everything we don't
5591 // have a PrimType for.
5592 if (UnsignedOrNone LocalOffset = this->allocateLocal(E)) {
5593 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalOffset));
5594 if (!this->emitGetPtrLocal(*LocalOffset, E))
5595 return false;
5596
5597 if (!visitInitializer(E))
5598 return false;
5599 // We are destroying the locals AFTER the Ret op.
5600 // The Ret op needs to copy the (alive) values, but the
5601 // destructors may still turn the entire expression invalid.
5602 return this->emitRetValue(E) && maybeDestroyLocals();
5603 }
5604
5605 return maybeDestroyLocals() && false;
5606}
5607
5608template <class Emitter>
5610 bool DestroyToplevelScope) {
5611 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5612 /*NewInitializing=*/false, /*ToLValue=*/true);
5613
5614 return this->visitExpr(E, DestroyToplevelScope);
5615}
5616
5617template <class Emitter>
5619
5620 auto R = this->visitVarDecl(VD, VD->getInit(), /*Toplevel=*/true);
5621
5622 if (R.notCreated())
5623 return R;
5624
5625 if (R)
5626 return true;
5627
5628 if (!R && Context::shouldBeGloballyIndexed(VD)) {
5629 if (auto GlobalIndex = P.getGlobal(VD)) {
5630 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
5631 auto &GD = GlobalBlock->getBlockDesc<GlobalInlineDescriptor>();
5632
5634 GlobalBlock->invokeDtor();
5635 }
5636 }
5637
5638 return R;
5639}
5640
5641/// Toplevel visitDeclAndReturn().
5642/// We get here from evaluateAsInitializer().
5643/// We need to evaluate the initializer and return its value.
5644template <class Emitter>
5646 bool ConstantContext) {
5647 // We only create variables if we're evaluating in a constant context.
5648 // Otherwise, just evaluate the initializer and return it.
5649 if (!ConstantContext) {
5650 DeclScope<Emitter> LS(this, VD);
5651 if (!this->visit(Init))
5652 return false;
5653 return this->emitRet(classify(Init).value_or(PT_Ptr), VD) &&
5654 LS.destroyLocals() && this->emitCheckAllocations(VD);
5655 }
5656
5657 LocalScope<Emitter> VDScope(this);
5658 if (!this->visitVarDecl(VD, Init, /*Toplevel=*/true))
5659 return false;
5660
5661 OptPrimType VarT = classify(VD->getType());
5662 bool IsReference = VD->getType()->isReferenceType();
5664 auto GlobalIndex = P.getGlobal(VD);
5665 assert(GlobalIndex); // visitVarDecl() didn't return false.
5666 if (VarT) {
5667 if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
5668 return false;
5669 } else {
5670 if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
5671 return false;
5672 }
5673 } else {
5674 auto Local = Locals.find(VD);
5675 assert(Local != Locals.end()); // Same here.
5676 if (VarT) {
5677 if (IsReference) {
5678 if (!this->emitGetRefLocal(Local->second.Offset, VD))
5679 return false;
5680 } else if (!this->emitGetLocal(*VarT, Local->second.Offset, VD))
5681 return false;
5682 } else {
5683 if (!this->emitGetPtrLocal(Local->second.Offset, VD))
5684 return false;
5685 }
5686 }
5687
5688 // Return the value.
5689 if (!this->emitRet(VarT.value_or(PT_Ptr), VD)) {
5690 // If the Ret above failed and this is a global variable. Mark it as
5691 // uninitialized, even if everything else succeeded.
5693 auto GlobalIndex = P.getGlobal(VD);
5694 assert(GlobalIndex);
5695 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
5696 auto &GD = GlobalBlock->getBlockDesc<GlobalInlineDescriptor>();
5697
5699 GlobalBlock->invokeDtor();
5700 }
5701 return false;
5702 }
5703
5704 return VDScope.destroyLocals() && this->emitCheckAllocations(VD);
5705}
5706
5707template <class Emitter>
5709 const Expr *Init,
5710 bool Toplevel) {
5711 QualType VarTy = VD->getType();
5712 // We don't know what to do with these, so just return false.
5713 if (VarTy.isNull())
5714 return false;
5715
5716 // This case is EvalEmitter-only. If we won't create any instructions for the
5717 // initializer anyway, don't bother creating the variable in the first place.
5718 if (!this->isActive())
5720
5721 OptPrimType VarT = classify(VD->getType());
5722
5723 if (Init && Init->isValueDependent())
5724 return false;
5725
5727 auto checkDecl = [&]() -> bool {
5728 bool NeedsOp = !Toplevel && VD->isLocalVarDecl() && VD->isStaticLocal();
5729 return !NeedsOp || this->emitCheckDecl(VD, VD);
5730 };
5731
5733 UnsignedOrNone GlobalIndex = P.getGlobal(VD);
5734 if (GlobalIndex) {
5735 // The global was previously created but the initializer failed.
5736 if (!P.getGlobal(*GlobalIndex)->isInitialized())
5737 return false;
5738 // We've already seen and initialized this global.
5739 if (P.isGlobalInitialized(*GlobalIndex))
5740 return checkDecl();
5741 // The previous attempt at initialization might've been unsuccessful,
5742 // so let's try this one.
5743 } else if ((GlobalIndex =
5744 P.createGlobal(VD, Init, VariablesAreConstexprUnknown))) {
5745 } else {
5746 return false;
5747 }
5748 if (!Init)
5749 return true;
5750
5751 if (!checkDecl())
5752 return false;
5753
5754 if (VarT) {
5755 if (!this->visit(Init))
5756 return false;
5757
5758 return this->emitInitGlobal(*VarT, *GlobalIndex, VD);
5759 }
5760
5761 if (!this->emitGetPtrGlobal(*GlobalIndex, Init))
5762 return false;
5763
5764 if (!this->emitStartInit(Init))
5765 return false;
5766
5767 if (!visitInitializer(Init))
5768 return false;
5769
5770 if (!this->emitEndInit(Init))
5771 return false;
5772
5773 return this->emitFinishInitGlobal(Init);
5774 }
5775 // Local variables.
5777
5778 if (VarT) {
5779 unsigned Offset = this->allocateLocalPrimitive(
5780 VD, *VarT, VarTy.isConstQualified(), VarTy.isVolatileQualified(),
5782
5783 if (!Init || Init->getType()->isVoidType())
5784 return true;
5785
5786 // If this is a toplevel declaration, create a scope for the
5787 // initializer.
5788 if (Toplevel) {
5790 if (!this->visit(Init))
5791 return false;
5792 return this->emitSetLocal(*VarT, Offset, VD) && Scope.destroyLocals();
5793 }
5794 if (!this->visit(Init))
5795 return false;
5796
5797 if (VarTy->isReferenceType()) {
5798 // [C++26][decl.ref]
5799 // The object designated by such a glvalue can be outside its lifetime
5800 // Because a null pointer value or a pointer past the end of an object
5801 // does not point to an object, a reference in a well-defined program
5802 // cannot refer to such things;
5803 assert(classifyPrim(VarTy) == PT_Ptr);
5804 if (!this->emitCheckRefInit(Init))
5805 return false;
5806 }
5807
5808 return this->emitSetLocal(*VarT, Offset, VD);
5809 }
5810 // Local composite variables.
5811 if (UnsignedOrNone Offset =
5812 this->allocateLocal(VD, VarTy, ScopeKind::Block)) {
5813 if (!Init)
5814 return true;
5815
5816 if (!this->emitGetPtrLocal(*Offset, Init))
5817 return false;
5818
5819 return visitInitializerPop(Init);
5820 }
5821 return false;
5822}
5823
5824template <class Emitter>
5826 assert(!canClassify(VD->getType()));
5827
5829 // Create a local variable to use as the instance.
5830 QualType Ty = VD->getType();
5831 Descriptor *D =
5832 P.createDescriptor(VD, Ty.getTypePtr(), /*IsConst=*/Ty.isConstQualified(),
5833 /*IsTemporary=*/false, /*IsMutable=*/false,
5834 /*IsVolatile=*/Ty.isVolatileQualified(), nullptr);
5835 if (!D)
5836 return false;
5837
5838 // FIXME: Would be nice if we didn't allocate the descriptor at all in this
5839 // case.
5840 if (D->hasTrivialDtor())
5841 return true;
5842
5843 Scope::Local Local = this->createLocal(D);
5844 Locals.insert({VD, Local});
5845 VarScope->addForScopeKind(Local, ScopeKind::Block);
5846
5847 if (!this->emitGetPtrLocal(Local.Offset, VD))
5848 return false;
5849
5850 if (!this->visitAPValueInitializer(Value, VD, Ty))
5851 return false;
5852
5853 return this->emitDestructionPop(D, VD);
5854}
5855
5857public:
5859 explicit ParamFinder() {}
5860
5861 bool VisitDeclRefExpr(const DeclRefExpr *E) override {
5862 if (const auto *P = dyn_cast<ParmVarDecl>(E->getDecl()))
5863 FoundParams.insert(P);
5864 return true;
5865 }
5866};
5867
5868/// Evaluate the \p Condition as if it was in the body of \p Callee.
5869/// Specifically, all the parameters of the callee are available to use
5870/// for the condition, and their values are given by \p Args (and \p This).
5871///
5872// Since this is a somewhat niche feature, we're abusing a few other mechanisms
5873// to implement this.
5874//
5875// We don't create an actual function frame but instead register the parameters
5876// as local variables.
5877//
5878// So we evaluate something like:
5879//
5880// bool thisfunc() {
5881// auto Arg0 = Args[0];
5882// ...
5883// return Condition;
5884// }
5885//
5886template <class Emitter>
5889 const Expr *This,
5890 const Expr *Condition) {
5891 // Instead of evaluating all parameters and trying to ignore failure,
5892 // we collect all the parameters used in the condition and only evaluate
5893 // those. Note that we still ignore failure in the loop below because the
5894 // failure might be inconsequential in the end,
5895 // e.g. in the case of `true || x`.
5896 ParamFinder PF;
5898
5899 LocalScope<Emitter> ArgScope(this);
5900 for (const ParmVarDecl *PVD : PF.FoundParams) {
5901 unsigned ParamIndex = 0;
5902 for (const ParmVarDecl *P : Callee->parameters()) {
5903 if (P == PVD)
5904 break;
5905 ++ParamIndex;
5906 }
5907
5908 const Expr *Arg = Args[ParamIndex];
5909 const ParmVarDecl *Param = Callee->getParamDecl(ParamIndex);
5910 if (OptPrimType ParamT = classify(Param->getType())) {
5911 unsigned ArgOffset =
5912 allocateLocalPrimitive(Param, *ParamT, /*IsConst=*/true);
5913 if (!this->visit(Arg))
5914 continue;
5915 if (!this->emitSetLocal(*ParamT, ArgOffset, Arg))
5916 return false;
5917 } else {
5918 UnsignedOrNone ArgOffset = this->allocateLocal(Param, Param->getType());
5919 if (!ArgOffset)
5920 return false;
5921 if (!this->emitGetPtrLocal(*ArgOffset, Arg))
5922 return false;
5923 if (!this->visitInitializerPop(Arg))
5924 continue;
5925 }
5926 }
5927
5928 if (This) {
5929 // We abuse the init stack for this and tell it to use
5930 // either a local variable or another decl for the This pointer.
5931 this->InitStackActive = true;
5932
5933 if (This->getType()->isPointerType()) {
5934 // Nothing to do here, the evaluation will fail if the instance
5935 // pointer is used.
5936 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(This)) {
5937 InitStack.push_back(InitLink::Decl(DRE->getDecl()));
5938 } else {
5939 assert(!canClassify(This->getType()));
5940 UnsignedOrNone ArgOffset = this->allocateLocal(This, This->getType());
5941 if (!ArgOffset)
5942 return false;
5943 if (!this->emitGetPtrLocal(*ArgOffset, This))
5944 return false;
5945 if (!this->visitInitializerPop(This))
5946 return false;
5947 this->InitStack.push_back(InitLink::Temp(*ArgOffset));
5948 }
5949 }
5950
5951 // Destruction of the argument values is part of the callee frame,
5952 // so we simply ignore them here.
5953 this->VarScope = nullptr;
5954
5955 LocalScope<Emitter> RetScope(this);
5956 if (!this->visit(Condition))
5957 return false;
5958 if (!RetScope.destroyLocals())
5959 return false;
5960
5961 // Result of the condition should be on the stack.
5962 return this->emitRet(PT_Bool, Condition);
5963}
5964
5965template <class Emitter>
5967 SourceInfo Info) {
5968 assert(!Val.isIndeterminate() && "Needs to be checked before");
5969 assert(!DiscardResult);
5970 if (Val.isInt())
5971 return this->emitConst(Val.getInt(), ValType, Info);
5972 if (Val.isFloat())
5973 return this->emitFloat(Val.getFloat(), Info);
5974
5975 if (Val.isMemberPointer()) {
5976 if (const ValueDecl *MemberDecl = Val.getMemberPointerDecl()) {
5977 if (!this->emitGetMemberPtr(MemberDecl, Info))
5978 return false;
5979
5980 bool IsDerived = Val.isMemberPointerToDerivedMember();
5981 // Apply the member pointer path.
5982 for (const CXXRecordDecl *PathEntry : Val.getMemberPointerPath()) {
5983 if (!this->emitCopyMemberPtrPath(PathEntry, IsDerived, Info))
5984 return false;
5985 }
5986
5987 return true;
5988 }
5989 return this->emitNullMemberPtr(0, nullptr, Info);
5990 }
5991
5992 if (Val.isLValue()) {
5993 if (Val.isNullPointer())
5994 return this->emitNull(ValType, 0, nullptr, Info);
5995
5997 QualType EntryType;
5998 if (const Expr *BaseExpr = Base.dyn_cast<const Expr *>()) {
5999 // Try to avoid evaluating the BaseExpr multiple times.
6000 if (UnsignedOrNone GlobalIndex = P.getGlobal(BaseExpr);
6001 GlobalIndex && P.isGlobalInitialized(*GlobalIndex)) {
6002 if (!this->emitGetPtrGlobal(*GlobalIndex, Info))
6003 return false;
6004 } else {
6005 if (!this->visit(BaseExpr))
6006 return false;
6007 }
6008 EntryType = BaseExpr->getType();
6009 } else if (const auto *VD = Base.dyn_cast<const ValueDecl *>()) {
6010 if (!this->visitDeclRef(VD, Info.asExpr()))
6011 return false;
6012 EntryType = VD->getType();
6013 } else if (Base.is<TypeInfoLValue>()) {
6014 // The type_info object for the type the lvalue describes.
6015 const Type *OperandType = Base.get<TypeInfoLValue>()
6016 .getType()
6017 ->getCanonicalTypeUnqualified()
6018 .getTypePtr();
6019 EntryType = Base.getTypeInfoType();
6020 if (!this->emitGetTypeid(OperandType, EntryType.getTypePtr(), Info))
6021 return false;
6022 } else if (!Base) {
6023 // An integer cast to a pointer.
6024 const Expr *E = Info.asExpr();
6025 if (!E)
6026 return false;
6027 QualType PtrType = E->isGLValue()
6028 ? Ctx.getASTContext().getPointerType(E->getType())
6029 : E->getType();
6030 uint64_t Offset = Val.getLValueOffset().getQuantity();
6031 if (!this->emitConstUint64(Offset, Info))
6032 return false;
6033 if (!this->emitGetIntPtrUint64(PtrType.getTypePtr(), Info))
6034 return false;
6035 EntryType = PtrType->getPointeeType();
6036 } else {
6037 return false;
6038 }
6039
6040 if (Val.hasLValuePath()) {
6041 for (auto &Entry : Val.getLValuePath()) {
6042 if (EntryType->isArrayType()) {
6043 uint64_t Index = Entry.getAsArrayIndex();
6044 QualType ElemType =
6045 EntryType->getAsArrayTypeUnsafe()->getElementType();
6046 if (!this->emitConst(Index, PT_Uint64, Info))
6047 return false;
6048 if (!this->emitArrayElemPtrPop(PT_Uint64, Info))
6049 return false;
6050 EntryType = ElemType;
6051 } else {
6052 assert(EntryType->isRecordType());
6053 const Record *EntryRecord = getRecord(EntryType);
6054 if (!EntryRecord)
6055 return false;
6056
6057 const Decl *BaseOrMember = Entry.getAsBaseOrMember().getPointer();
6058 if (const auto *FD = dyn_cast<FieldDecl>(BaseOrMember)) {
6059 unsigned EntryOffset = EntryRecord->getField(FD)->Offset;
6060 if (!this->emitGetPtrFieldPop(EntryOffset, Info))
6061 return false;
6062 EntryType = FD->getType();
6063 } else {
6064 const auto *Base = cast<CXXRecordDecl>(BaseOrMember);
6065 if (const Record::Base *B = EntryRecord->getBaseOrNull(Base)) {
6066 if (!this->emitGetPtrBasePop(B->Offset, /*NullOK=*/false, Info))
6067 return false;
6068 } else {
6069 // Must be a virtual base.
6070 assert(EntryRecord->findVirtualBase(Base));
6071 if (!this->emitGetPtrVirtBasePop(Base, Info))
6072 return false;
6073 }
6074 EntryType = Ctx.getASTContext().getCanonicalTagType(Base);
6075 }
6076 }
6077 }
6078 }
6079
6080 if (isPtrType(ValType))
6081 return true;
6082
6083 // A pointer cast to an integer is stored as an lvalue; cast it the same
6084 // way the source expression does.
6085 if (ValType == PT_IntAP || ValType == PT_IntAPS) {
6086 const Expr *E = Info.asExpr();
6087 if (!E)
6088 return false;
6089 uint32_t BitWidth = Ctx.getBitWidth(E->getType());
6090 return ValType == PT_IntAP
6091 ? this->emitCastPointerIntegralAP(BitWidth, Info)
6092 : this->emitCastPointerIntegralAPS(BitWidth, Info);
6093 }
6094 return this->emitCastPointerIntegral(ValType, Info);
6095 }
6096
6097 return false;
6098}
6099
6100template <class Emitter>
6102 SourceInfo Info, QualType T,
6103 bool IsCompleteClass) {
6104 if (Val.isStruct()) {
6105 const Record *R = this->getRecord(T);
6106 assert(R);
6107
6108 assert(R->getNumBases() == Val.getStructNumBases());
6109 if (IsCompleteClass)
6110 assert(R->getNumVirtualBases() == Val.getStructNumVirtualBases());
6111
6112 for (unsigned I = 0, N = Val.getStructNumBases(); I != N; ++I) {
6113 const APValue &B = Val.getStructBase(I);
6114 if (B.isIndeterminate())
6115 continue;
6116 const Record::Base *RB = R->getBase(I);
6117 QualType BaseType = Ctx.getASTContext().getCanonicalTagType(RB->Decl);
6118
6119 if (!this->emitGetPtrBase(RB->Offset, Info))
6120 return false;
6121 if (!this->visitAPValueInitializer(B, Info, BaseType,
6122 /*IsCompleteClass=*/false))
6123 return false;
6124 if (!this->emitFinishInitPop(Info))
6125 return false;
6126 }
6127
6128 for (unsigned I = 0, N = Val.getStructNumFields(); I != N; ++I) {
6129 const APValue &F = Val.getStructField(I);
6130 if (F.isIndeterminate())
6131 continue;
6132 const Record::Field *RF = R->getField(I);
6133 QualType FieldType = RF->Decl->getType();
6134 // Fields.
6135 if (OptPrimType PT = RF->T) {
6136 if (!this->visitAPValue(F, *PT, Info))
6137 return false;
6138 if (!this->emitInitField(*PT, RF->Offset, Info))
6139 return false;
6140 } else {
6141 if (!this->emitGetPtrField(RF->Offset, Info))
6142 return false;
6143 if (!this->visitAPValueInitializer(F, Info, FieldType))
6144 return false;
6145 if (!this->emitFinishInitPop(Info))
6146 return false;
6147 }
6148 }
6149
6150 // Virtual Bases.
6151 if (IsCompleteClass) {
6152 for (unsigned I = 0, N = Val.getStructNumVirtualBases(); I != N; ++I) {
6153 const APValue &B = Val.getStructVirtualBase(I);
6154 if (B.isIndeterminate())
6155 continue;
6156 const Record::Base *RB = R->getVirtualBase(I);
6157 QualType BaseType = Ctx.getASTContext().getCanonicalTagType(RB->Decl);
6158
6159 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(RB->R->getDecl()),
6160 Info))
6161 return false;
6162 if (!this->visitAPValueInitializer(B, Info, BaseType,
6163 /*IsCompleteClass=*/false))
6164 return false;
6165 if (!this->emitFinishInitPop(Info))
6166 return false;
6167 }
6168 }
6169
6170 return true;
6171 }
6172 if (Val.isUnion()) {
6173 const FieldDecl *UnionField = Val.getUnionField();
6174 if (!UnionField)
6175 return true;
6176 const Record *R = this->getRecord(T);
6177 assert(R);
6178 const APValue &F = Val.getUnionValue();
6179 if (F.isIndeterminate())
6180 return true;
6181 const Record::Field *RF = R->getField(UnionField);
6182 QualType FieldType = RF->Decl->getType();
6183
6184 if (OptPrimType PT = RF->T) {
6185 if (!this->visitAPValue(F, *PT, Info))
6186 return false;
6187 if (RF->isBitField())
6188 return this->emitInitBitFieldActivate(*PT, RF->Offset, RF->bitWidth(),
6189 Info);
6190 return this->emitInitFieldActivate(*PT, RF->Offset, Info);
6191 }
6192
6193 if (!this->emitGetPtrField(RF->Offset, Info))
6194 return false;
6195 if (!this->emitActivate(Info))
6196 return false;
6197 if (!this->visitAPValueInitializer(F, Info, FieldType))
6198 return false;
6199 return this->emitPopPtr(Info);
6200 }
6201 if (Val.isArray()) {
6202 unsigned InitializedElems = Val.getArrayInitializedElts();
6203 const auto *ArrType = T->getAsArrayTypeUnsafe();
6204 QualType ElemType = ArrType->getElementType();
6205 OptPrimType ElemT = classify(ElemType);
6206
6207 for (unsigned A = 0, AN = Val.getArraySize(); A != AN; ++A) {
6208 const APValue &Elem = A >= InitializedElems
6209 ? Val.getArrayFiller()
6210 : Val.getArrayInitializedElt(A);
6211 if (Elem.isIndeterminate())
6212 continue;
6213
6214 if (ElemT) {
6215 if (!this->visitAPValue(Elem, *ElemT, Info))
6216 return false;
6217 if (!this->emitInitElem(*ElemT, A, Info))
6218 return false;
6219 } else {
6220 if (!this->emitConstUint32(A, Info))
6221 return false;
6222 if (!this->emitArrayElemPtrUint32(Info))
6223 return false;
6224 if (!this->visitAPValueInitializer(Elem, Info, ElemType))
6225 return false;
6226 if (!this->emitPopPtr(Info))
6227 return false;
6228 }
6229 }
6230 return true;
6231 }
6232 if (Val.isComplexFloat()) {
6233 assert(T->isComplexType());
6234 if (!this->emitFloat(Val.getComplexFloatReal(), Info))
6235 return false;
6236 if (!this->emitInitElemFloat(0, Info))
6237 return false;
6238 if (!this->emitFloat(Val.getComplexFloatImag(), Info))
6239 return false;
6240 if (!this->emitInitElemFloat(1, Info))
6241 return false;
6242 return true;
6243 }
6244 if (Val.isComplexInt()) {
6245 assert(T->isComplexIntegerType());
6246 PrimType IntT = classifyPrim(T->castAs<ComplexType>()->getElementType());
6247 if (!this->emitConst(Val.getComplexIntReal(), IntT, Info))
6248 return false;
6249 if (!this->emitInitElem(IntT, 0, Info))
6250 return false;
6251 if (!this->emitConst(Val.getComplexIntImag(), IntT, Info))
6252 return false;
6253 if (!this->emitInitElem(IntT, 1, Info))
6254 return false;
6255 return true;
6256 }
6257 if (Val.isVector()) {
6258 assert(T->isVectorType());
6259 PrimType ElemT = classifyPrim(T->castAs<VectorType>()->getElementType());
6260 for (unsigned I = 0, N = Val.getVectorLength(); I != N; ++I) {
6261 const APValue &Elem = Val.getVectorElt(I);
6262 if (Elem.isIndeterminate())
6263 continue;
6264 if (!this->visitAPValue(Elem, ElemT, Info))
6265 return false;
6266 if (!this->emitInitElem(ElemT, I, Info))
6267 return false;
6268 }
6269 return true;
6270 }
6271
6272 // TODO: Other types.
6273 return false;
6274}
6275
6276template <class Emitter>
6278 if (P.getGlobal(VD))
6279 return true;
6280
6281 UnsignedOrNone GlobalIndex = P.createGlobal(VD, /*Init=*/nullptr);
6282 if (!GlobalIndex) {
6283 llvm_unreachable("Why didn't that work?");
6284 }
6285
6286 assert(canClassify(VD->getType()) &&
6287 "registerRedecl should only be called with primitive values");
6288
6289 PrimType T = classifyPrim(VD->getType());
6290 if (!visitAPValue(Val, T, VD))
6291 return false;
6292 return this->emitInitGlobal(T, *GlobalIndex, {});
6293}
6294
6295template <class Emitter>
6297 unsigned BuiltinID) {
6298 const ASTContext &ASTCtx = Ctx.getASTContext();
6299
6300 // BuiltinID is the raw ID baked into the bytecode. The "is constant
6301 // evaluated" gate needs the raw ID so that auxiliary-target IDs resolve into
6302 // the correct (aux-target) builtin records.
6303 if (!Ctx.getASTContext().BuiltinInfo.isConstantEvaluated(BuiltinID))
6304 return this->emitInvalid(E);
6305
6306 // Convert an auxiliary x86 target builtin ID to its canonical X86::BI* value
6307 // so the target-specific cases below (and the handlers they call) match. This
6308 // is a cheap integer operation (a single comparison for the common,
6309 // target-independent case); we deliberately avoid re-deriving the ID from the
6310 // call expression, which is comparatively slow.
6311 BuiltinID = ConvertBuiltinIDToX86BuiltinID(ASTCtx, BuiltinID);
6312
6313 if (BuiltinID == Builtin::BI__builtin_constant_p) {
6314 // Void argument is always invalid and harder to handle later.
6315 if (E->getArg(0)->getType()->isVoidType()) {
6316 if (DiscardResult)
6317 return true;
6318 return this->emitConst(0, E);
6319 }
6320
6321 if (!this->emitStartSpeculation(E))
6322 return false;
6323 LabelTy EndLabel = this->getLabel();
6324 if (!this->speculate(E, EndLabel))
6325 return false;
6326 if (!this->emitEndSpeculation(E))
6327 return false;
6328 this->fallthrough(EndLabel);
6329 if (DiscardResult)
6330 return this->emitPop(classifyPrim(E), E);
6331 return true;
6332 }
6333
6334 // For these, we're expected to ultimately return an APValue pointing
6335 // to the CallExpr. This is needed to get the correct codegen.
6336 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6337 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString ||
6338 BuiltinID == Builtin::BI__builtin_ptrauth_sign_constant ||
6339 BuiltinID == Builtin::BI__builtin_function_start) {
6340 if (DiscardResult)
6341 return true;
6342 return this->emitDummyPtr(E, E);
6343 }
6344
6346 OptPrimType ReturnT = classify(E);
6347
6348 // Non-primitive return type. Prepare storage.
6349 if (!Initializing && !ReturnT && !ReturnType->isVoidType()) {
6350 UnsignedOrNone LocalIndex = allocateLocal(E);
6351 if (!LocalIndex)
6352 return false;
6353 if (!this->emitGetPtrLocal(*LocalIndex, E))
6354 return false;
6355 }
6356
6357 // Prepare function arguments including special cases.
6358 switch (BuiltinID) {
6359 case Builtin::BI__builtin_object_size:
6360 case Builtin::BI__builtin_dynamic_object_size: {
6361 assert(E->getNumArgs() == 2);
6362 const Expr *Arg0 = E->getArg(0);
6363 if (Arg0->isGLValue()) {
6364 if (!this->visit(Arg0))
6365 return false;
6366
6367 } else {
6369 return false;
6370 }
6371 if (!this->visit(E->getArg(1)))
6372 return false;
6373
6374 } break;
6375 case Builtin::BI__assume:
6376 case Builtin::BI__builtin_assume:
6377 // Argument is not evaluated.
6378 break;
6379 case Builtin::BI__atomic_is_lock_free:
6380 case Builtin::BI__atomic_always_lock_free: {
6381 assert(E->getNumArgs() == 2);
6382 if (!this->visit(E->getArg(0)))
6383 return false;
6384 if (!this->visitAsLValue(E->getArg(1)))
6385 return false;
6386 } break;
6387
6388 default:
6389 if (!Context::isUnevaluatedBuiltin(BuiltinID)) {
6390 // Put arguments on the stack.
6391 for (const auto *Arg : E->arguments()) {
6392 if (!this->visit(Arg))
6393 return false;
6394 }
6395 }
6396 }
6397
6398 if (!this->emitCallBI(E, BuiltinID, E))
6399 return false;
6400
6401 if (DiscardResult && !ReturnType->isVoidType())
6402 return this->emitPop(ReturnT.value_or(PT_Ptr), E);
6403
6404 return true;
6405}
6406
6408 if (!MD || !MD->isDefaulted())
6409 return false;
6411 return false;
6412 assert(!MD->getParent()->isInvalidDecl());
6413 return MD->getParent()->isUnion() ||
6415}
6416
6417template <class Emitter>
6419 if (E->containsErrors())
6420 return false;
6421 const FunctionDecl *FuncDecl = E->getDirectCallee();
6422
6423 if (FuncDecl) {
6424 if (unsigned BuiltinID = FuncDecl->getBuiltinID())
6425 return VisitBuiltinCallExpr(E, BuiltinID);
6426
6427 // Calls to replaceable operator new/operator delete.
6429 if (FuncDecl->getDeclName().isAnyOperatorNew())
6430 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_new);
6431 assert(FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
6432 FuncDecl->getDeclName().getCXXOverloadedOperator() ==
6433 OO_Array_Delete);
6434 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_delete);
6435 }
6436
6437 // Explicit calls to trivial destructors
6438 if (const auto *DD = dyn_cast<CXXDestructorDecl>(FuncDecl);
6439 DD && DD->isTrivial()) {
6440 const auto *MemberCall = cast<CXXMemberCallExpr>(E);
6441 if (!this->visit(MemberCall->getImplicitObjectArgument()))
6442 return false;
6443 return this->emitCheckDestruction(E) && this->emitEndLifetime(E) &&
6444 this->emitPopPtr(E);
6445 }
6446 }
6447
6448 // Don't generate code for method with invalid parent decls.
6449 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl);
6450 MD && MD->getParent()->isInvalidDecl())
6451 return false;
6452
6453 LocalScope<Emitter> CallScope(this, ScopeKind::Call);
6454 ArrayRef<const Expr *> Args(E->getArgs(), E->getNumArgs());
6455 bool ActivateLHS = false;
6456
6457 // Emit a special op for trivial copy/move operators.
6458 if (isTrivialMemoryOperation(dyn_cast_if_present<CXXMethodDecl>(FuncDecl))) {
6459 const Function *Func = getFunction(FuncDecl);
6460 if (!Func)
6461 return false;
6462
6463 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
6464 OCE && OCE->isAssignmentOp()) {
6465 const CXXRecordDecl *LHSRecord = Args[0]->getType()->getAsCXXRecordDecl();
6466 ActivateLHS = LHSRecord && LHSRecord->hasTrivialDefaultConstructor();
6467 }
6468 if (const auto *MCE = dyn_cast<CXXMemberCallExpr>(E))
6469 if (!this->visit(MCE->getImplicitObjectArgument()))
6470 return false;
6471
6472 if (!this->visitCallArgs(Args, FuncDecl, /*ActivateLHS=*/ActivateLHS,
6474 return false;
6475
6476 if (!this->emitTrivialCopy(ActivateLHS, Func, E))
6477 return false;
6478
6479 if (!DiscardResult)
6480 return CallScope.destroyLocals();
6481 return this->emitPopPtr(E) && CallScope.destroyLocals();
6482 }
6483
6484 QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
6486 bool HasRVO = !ReturnType->isVoidType() && !T;
6487
6488 if (HasRVO) {
6489 if (DiscardResult) {
6490 // If we need to discard the return value but the function returns its
6491 // value via an RVO pointer, we need to create one such pointer just
6492 // for this call.
6493 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
6494 if (!this->emitGetPtrLocal(*LocalIndex, E))
6495 return false;
6496 }
6497 } else {
6498 // We need the result. Prepare a pointer to return or
6499 // dup the current one.
6500 if (!Initializing) {
6501 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
6502 if (!this->emitGetPtrLocal(*LocalIndex, E))
6503 return false;
6504 }
6505 }
6506 if (!this->emitDupPtr(E))
6507 return false;
6508 }
6509 }
6510
6511 const Expr *ReversedArgs[2];
6512 bool IsAssignmentOperatorCall = false;
6513 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
6514 OCE && OCE->isAssignmentOp()) {
6515 // Just like with regular assignments, we need to special-case assignment
6516 // operators here and evaluate the RHS (the second arg) before the LHS (the
6517 // first arg). We fix this by using a Flip op later.
6518 assert(Args.size() == 2);
6519 const CXXRecordDecl *LHSRecord = Args[0]->getType()->getAsCXXRecordDecl();
6520 ActivateLHS = LHSRecord && LHSRecord->hasTrivialDefaultConstructor();
6521 IsAssignmentOperatorCall = true;
6522 ReversedArgs[0] = Args[1];
6523 ReversedArgs[1] = Args[0];
6524 Args = ReversedArgs;
6525 }
6526
6527 // Calling a static operator will still
6528 // pass the instance, but we don't need it.
6529 // Discard it here.
6530 if (isa<CXXOperatorCallExpr>(E)) {
6531 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl);
6532 MD && MD->isStatic()) {
6533 if (!this->discard(E->getArg(0)))
6534 return false;
6535 // Drop first arg.
6536 Args = Args.drop_front();
6537 }
6538 }
6539
6540 bool Devirtualized = false;
6541 UnsignedOrNone CalleeOffset = std::nullopt;
6542 // Add the (optional, implicit) This pointer.
6543 if (const auto *MC = dyn_cast<CXXMemberCallExpr>(E)) {
6544 if (!FuncDecl && classifyPrim(E->getCallee()) == PT_MemberPtr) {
6545 // If we end up creating a CallPtr op for this, we need the base of the
6546 // member pointer as the instance pointer, and later extract the function
6547 // decl as the function pointer.
6548 const Expr *Callee = E->getCallee();
6549 CalleeOffset =
6550 this->allocateLocalPrimitive(Callee, PT_MemberPtr, /*IsConst=*/true);
6551 if (!this->visit(Callee))
6552 return false;
6553 if (!this->emitSetLocal(PT_MemberPtr, *CalleeOffset, E))
6554 return false;
6555 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
6556 return false;
6557 if (!this->emitGetMemberPtrBase(E))
6558 return false;
6559 } else {
6560 const auto *InstancePtr = MC->getImplicitObjectArgument();
6561 if (isa_and_nonnull<CXXDestructorDecl>(CompilingFunction) ||
6562 isa_and_nonnull<CXXConstructorDecl>(CompilingFunction)) {
6563 const auto *Stripped = stripCheckedDerivedToBaseCasts(InstancePtr);
6564 if (isa<CXXThisExpr>(Stripped)) {
6565 FuncDecl =
6566 cast<CXXMethodDecl>(FuncDecl)->getCorrespondingMethodInClass(
6567 Stripped->getType()->getPointeeType()->getAsCXXRecordDecl());
6568 Devirtualized = true;
6569 if (!this->visit(Stripped))
6570 return false;
6571 } else {
6572 if (!this->visit(InstancePtr))
6573 return false;
6574 }
6575 } else {
6576 if (!this->visit(InstancePtr))
6577 return false;
6578 }
6579 }
6580 } else if (const auto *PD =
6581 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee())) {
6582 if (!this->emitCheckPseudoDtor(E))
6583 return false;
6584 const Expr *Base = PD->getBase();
6585 // E.g. `using T = int; 0.~T();`.
6586 if (OptPrimType BaseT = classify(Base); !BaseT || BaseT != PT_Ptr)
6587 return this->discard(Base);
6588 if (!this->visit(Base))
6589 return false;
6590 return this->emitPseudoDtor(E);
6591 } else if (!FuncDecl) {
6592 const Expr *Callee = E->getCallee();
6593 CalleeOffset =
6594 this->allocateLocalPrimitive(Callee, PT_Ptr, /*IsConst=*/true);
6595 if (!this->visit(Callee))
6596 return false;
6597 if (!this->emitSetLocal(PT_Ptr, *CalleeOffset, E))
6598 return false;
6599 }
6600
6601 if (!this->visitCallArgs(Args, FuncDecl, ActivateLHS,
6603 return false;
6604
6605 // Undo the argument reversal we did earlier.
6606 if (IsAssignmentOperatorCall) {
6607 assert(Args.size() == 2);
6608 PrimType Arg1T = classify(Args[0]).value_or(PT_Ptr);
6609 PrimType Arg2T = classify(Args[1]).value_or(PT_Ptr);
6610 if (!this->emitFlip(Arg2T, Arg1T, E))
6611 return false;
6612 }
6613
6614 if (FuncDecl) {
6615 const Function *Func = getFunction(FuncDecl);
6616 if (!Func)
6617 return false;
6618
6619 // In error cases, the function may be called with fewer arguments than
6620 // parameters.
6621 if (E->getNumArgs() < Func->getNumWrittenParams())
6622 return false;
6623
6624 assert(HasRVO == Func->hasRVO());
6625
6626 bool HasQualifier = false;
6627 if (const auto *ME = dyn_cast<MemberExpr>(E->getCallee()))
6628 HasQualifier = ME->hasQualifier();
6629
6630 bool IsVirtual = false;
6631 if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl))
6632 IsVirtual = !Devirtualized && MD->isVirtual();
6633
6634 // In any case call the function. The return value will end up on the stack
6635 // and if the function has RVO, we already have the pointer on the stack to
6636 // write the result into.
6637 if (IsVirtual && !HasQualifier) {
6638 uint32_t VarArgSize = 0;
6639 unsigned NumParams =
6640 Func->getNumWrittenParams() +
6641 (isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisPointer());
6642 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
6643 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6644
6645 if (!this->emitCallVirt(Func, VarArgSize, E))
6646 return false;
6647 } else if (Func->isVariadic()) {
6648 uint32_t VarArgSize = 0;
6649 unsigned NumParams =
6650 Func->getNumWrittenParams() +
6651 (isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisPointer());
6652 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
6653 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6654 if (!this->emitCallVar(Func, VarArgSize, E))
6655 return false;
6656 } else {
6657 if (!this->emitCall(Func, 0, E))
6658 return false;
6659 }
6660 } else {
6661 // Indirect call. Visit the callee, which will leave a FunctionPointer on
6662 // the stack. Cleanup of the returned value if necessary will be done after
6663 // the function call completed.
6664
6665 // Sum the size of all args from the call expr.
6666 uint32_t ArgSize = 0;
6667 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
6668 ArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6669
6670 // Get the callee, either from a member pointer or function pointer saved in
6671 // CalleeOffset.
6672 if (isa<CXXMemberCallExpr>(E) && CalleeOffset) {
6673 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
6674 return false;
6675 if (!this->emitGetMemberPtrDecl(E))
6676 return false;
6677 } else {
6678 if (!this->emitGetLocal(PT_Ptr, *CalleeOffset, E))
6679 return false;
6680 }
6681 if (!this->emitCallPtr(ArgSize, E, E))
6682 return false;
6683 }
6684
6685 // Cleanup for discarded return values.
6686 if (DiscardResult && !ReturnType->isVoidType() && T)
6687 return this->emitPop(*T, E) && CallScope.destroyLocals();
6688
6689 return CallScope.destroyLocals();
6690}
6691
6692template <class Emitter>
6694 SourceLocScope<Emitter> SLS(this, E);
6695
6696 return this->delegate(E->getExpr());
6697}
6698
6699template <class Emitter>
6701 SourceLocScope<Emitter> SLS(this, E);
6702
6703 return this->delegate(E->getExpr());
6704}
6705
6706template <class Emitter>
6708 if (DiscardResult)
6709 return true;
6710
6711 return this->emitConstBool(E->getValue(), E);
6712}
6713
6714template <class Emitter>
6716 const CXXNullPtrLiteralExpr *E) {
6717 if (DiscardResult)
6718 return true;
6719
6720 uint64_t Val = Ctx.getASTContext().getTargetNullPointerValue(E->getType());
6721 return this->emitNullPtr(Val, nullptr, E);
6722}
6723
6724template <class Emitter>
6726 if (DiscardResult)
6727 return true;
6728
6729 assert(E->getType()->isIntegerType());
6730
6732 return this->emitZero(T, E);
6733}
6734
6735template <class Emitter>
6737 if (DiscardResult)
6738 return true;
6739
6740 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
6741 if (this->LambdaThisCapture.Offset > 0) {
6742 if (this->LambdaThisCapture.IsPtr)
6743 return this->emitGetThisFieldPtr(this->LambdaThisCapture.Offset, E);
6744 return this->emitGetPtrThisField(this->LambdaThisCapture.Offset, E);
6745 }
6746 }
6747
6748 // In some circumstances, the 'this' pointer does not actually refer to the
6749 // instance pointer of the current function frame, but e.g. to the declaration
6750 // currently being initialized. Here we emit the necessary instruction(s) for
6751 // this scenario.
6752 if (!InitStackActive || InitStack.empty())
6753 return this->emitThis(E);
6754
6755 // If our init stack is, for example:
6756 // 0 Stack: 3 (decl)
6757 // 1 Stack: 6 (init list)
6758 // 2 Stack: 1 (field)
6759 // 3 Stack: 6 (init list)
6760 // 4 Stack: 1 (field)
6761 //
6762 // We want to find the LAST element in it that's an init list,
6763 // which is marked with the K_InitList marker. The index right
6764 // before that points to an init list. We need to find the
6765 // elements before the K_InitList element that point to a base
6766 // (e.g. a decl or This), optionally followed by field, elem, etc.
6767 // In the example above, we want to emit elements [0..2].
6768 unsigned StartIndex = 0;
6769 unsigned EndIndex = 0;
6770 // Find the init list.
6771 for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) {
6772 if (InitStack[StartIndex].Kind == InitLink::K_DIE) {
6773 EndIndex = StartIndex;
6774 --StartIndex;
6775 break;
6776 }
6777 }
6778
6779 // Walk backwards to find the base.
6780 for (; StartIndex > 0; --StartIndex) {
6781 if (InitStack[StartIndex].Kind == InitLink::K_InitList)
6782 continue;
6783
6784 if (InitStack[StartIndex].Kind != InitLink::K_Field &&
6785 InitStack[StartIndex].Kind != InitLink::K_Elem &&
6786 InitStack[StartIndex].Kind != InitLink::K_Base &&
6787 InitStack[StartIndex].Kind != InitLink::K_DIE)
6788 break;
6789 }
6790
6791 if (StartIndex == 0 && EndIndex == 0)
6792 EndIndex = InitStack.size() - 1;
6793
6794 assert(InitStack[StartIndex].Kind == InitLink::K_Decl ||
6795 InitStack[StartIndex].Kind == InitLink::K_This ||
6796 InitStack[StartIndex].Kind == InitLink::K_Temp ||
6797 InitStack[StartIndex].Kind == InitLink::K_RVO);
6798
6799 // NOTE: This could be StartIndex < EndIndex, but we're also abusing the
6800 // InitStack mechanism in visitWithSubstitutions to have the This pointer
6801 // _just_ be a local variable.
6802 assert(StartIndex <= EndIndex);
6803
6804 // Emit the instructions.
6805 for (unsigned I = StartIndex; I != (EndIndex + 1); ++I) {
6806 if (InitStack[I].Kind == InitLink::K_InitList ||
6807 InitStack[I].Kind == InitLink::K_DIE)
6808 continue;
6809 if (!InitStack[I].template emit<Emitter>(this, E))
6810 return false;
6811 }
6812 return true;
6813}
6814
6815template <class Emitter> bool Compiler<Emitter>::visitStmt(const Stmt *S) {
6816 switch (S->getStmtClass()) {
6817 case Stmt::CompoundStmtClass:
6819 case Stmt::DeclStmtClass:
6820 return visitDeclStmt(cast<DeclStmt>(S), /*EvaluateConditionDecl=*/true);
6821 case Stmt::ReturnStmtClass:
6823 case Stmt::IfStmtClass:
6824 return visitIfStmt(cast<IfStmt>(S));
6825 case Stmt::WhileStmtClass:
6827 case Stmt::DoStmtClass:
6828 return visitDoStmt(cast<DoStmt>(S));
6829 case Stmt::ForStmtClass:
6830 return visitForStmt(cast<ForStmt>(S));
6831 case Stmt::CXXForRangeStmtClass:
6833 case Stmt::BreakStmtClass:
6835 case Stmt::ContinueStmtClass:
6837 case Stmt::SwitchStmtClass:
6839 case Stmt::CaseStmtClass:
6840 return visitCaseStmt(cast<CaseStmt>(S));
6841 case Stmt::DefaultStmtClass:
6843 case Stmt::AttributedStmtClass:
6845 case Stmt::CXXTryStmtClass:
6847 case Stmt::NullStmtClass:
6848 return true;
6849 // Always invalid statements.
6850 case Stmt::GCCAsmStmtClass:
6851 case Stmt::MSAsmStmtClass:
6852 case Stmt::GotoStmtClass:
6853 return this->emitInvalid(S);
6854 case Stmt::LabelStmtClass:
6855 return this->visitStmt(cast<LabelStmt>(S)->getSubStmt());
6856 case Stmt::CXXExpansionStmtInstantiationClass:
6859 default: {
6860 if (const auto *E = dyn_cast<Expr>(S))
6861 return this->discard(E);
6862 return false;
6863 }
6864 }
6865}
6866
6867template <class Emitter>
6870 for (const auto *InnerStmt : S->body())
6871 if (!visitStmt(InnerStmt))
6872 return false;
6873 return Scope.destroyLocals();
6874}
6875
6876template <class Emitter>
6877bool Compiler<Emitter>::maybeEmitDeferredVarInit(const VarDecl *VD) {
6878 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
6879 for (auto *BD : DD->flat_bindings())
6880 if (auto *KD = BD->getHoldingVar();
6881 KD && !this->visitVarDecl(KD, KD->getInit()))
6882 return false;
6883 }
6884 return true;
6885}
6886
6888 assert(FD);
6889 assert(FD->getParent()->isUnion());
6890 const CXXRecordDecl *CXXRD =
6892 return !CXXRD || CXXRD->hasTrivialDefaultConstructor();
6893}
6894
6895template <class Emitter> bool Compiler<Emitter>::refersToUnion(const Expr *E) {
6896 for (;;) {
6897 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
6898 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6899 FD && FD->getParent()->isUnion() && hasTrivialDefaultCtorParent(FD))
6900 return true;
6901 E = ME->getBase();
6902 continue;
6903 }
6904
6905 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6906 E = ASE->getBase()->IgnoreImplicit();
6907 continue;
6908 }
6909
6910 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
6911 ICE && (ICE->getCastKind() == CK_NoOp ||
6912 ICE->getCastKind() == CK_DerivedToBase ||
6913 ICE->getCastKind() == CK_UncheckedDerivedToBase)) {
6914 E = ICE->getSubExpr();
6915 continue;
6916 }
6917
6918 if (const auto *This = dyn_cast<CXXThisExpr>(E)) {
6919 const auto *ThisRecord =
6920 This->getType()->getPointeeType()->getAsRecordDecl();
6921 if (!ThisRecord->isUnion())
6922 return false;
6923 // Otherwise, always activate if we're in the ctor.
6924 if (const auto *Ctor =
6925 dyn_cast_if_present<CXXConstructorDecl>(CompilingFunction))
6926 return Ctor->getParent() == ThisRecord;
6927 return false;
6928 }
6929
6930 break;
6931 }
6932 return false;
6933}
6934
6935template <class Emitter>
6937 bool EvaluateConditionDecl) {
6938 for (const auto *D : DS->decls()) {
6941 continue;
6942
6943 if (const auto *ESD = dyn_cast<CXXExpansionStmtDecl>(D)) {
6944 assert(ESD->getInstantiations() && "not expanded?");
6945 if (!this->visitStmt(ESD->getInstantiations()))
6946 return false;
6947 continue;
6948 }
6949
6950 const auto *VD = dyn_cast<VarDecl>(D);
6951 if (!VD)
6952 return false;
6953 if (!this->visitVarDecl(VD, VD->getInit()))
6954 return false;
6955
6956 // Register decomposition decl holding vars.
6957 if (EvaluateConditionDecl && !this->maybeEmitDeferredVarInit(VD))
6958 return false;
6959 }
6960
6961 return true;
6962}
6963
6964template <class Emitter>
6966 if (this->InStmtExpr)
6967 return this->emitUnsupported(RS);
6968
6969 if (const Expr *RE = RS->getRetValue()) {
6970 LocalScope<Emitter> RetScope(this);
6971 if (ReturnType) {
6972 // Primitive types are simply returned.
6973 if (!this->visit(RE))
6974 return false;
6975 this->emitCleanup();
6976 return this->emitRet(*ReturnType, RS);
6977 }
6978
6979 if (RE->getType()->isVoidType()) {
6980 if (!this->visit(RE))
6981 return false;
6982 } else {
6983 if (RE->containsErrors())
6984 return false;
6985
6987 // RVO - construct the value in the return location.
6988 if (!this->emitRVOPtr(RE))
6989 return false;
6990 if (!this->visitInitializerPop(RE))
6991 return false;
6992
6993 this->emitCleanup();
6994 return this->emitRetVoid(RS);
6995 }
6996 }
6997
6998 // Void return.
6999 this->emitCleanup();
7000 return this->emitRetVoid(RS);
7001}
7002
7003template <class Emitter> bool Compiler<Emitter>::visitIfStmt(const IfStmt *IS) {
7004 LocalScope<Emitter> IfScope(this);
7005
7006 auto visitChildStmt = [&](const Stmt *S) -> bool {
7007 LocalScope<Emitter> SScope(this);
7008 if (!visitStmt(S))
7009 return false;
7010 return SScope.destroyLocals();
7011 };
7012
7013 if (auto *CondInit = IS->getInit()) {
7014 if (!visitStmt(CondInit))
7015 return false;
7016 }
7017
7018 if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt()) {
7019 if (!visitDeclStmt(CondDecl))
7020 return false;
7021 }
7022
7023 // Save ourselves compiling some code and the jumps, etc. if the condition is
7024 // stataically known to be either true or false. We could look at more cases
7025 // here, but I think all the ones that actually happen are using a
7026 // ConstantExpr.
7027 if (std::optional<bool> BoolValue = getBoolValue(IS->getCond())) {
7028 if (*BoolValue)
7029 return visitChildStmt(IS->getThen());
7030 if (const Stmt *Else = IS->getElse())
7031 return visitChildStmt(Else);
7032 return true;
7033 }
7034
7035 // Otherwise, compile the condition.
7036 if (IS->isNonNegatedConsteval()) {
7037 if (!this->emitIsConstantContext(IS))
7038 return false;
7039 } else if (IS->isNegatedConsteval()) {
7040 if (!this->emitIsConstantContext(IS))
7041 return false;
7042 if (!this->emitInv(IS))
7043 return false;
7044 } else {
7046 if (!this->visitBool(IS->getCond()))
7047 return false;
7048 if (!CondScope.destroyLocals())
7049 return false;
7050 }
7051
7052 if (!this->maybeEmitDeferredVarInit(IS->getConditionVariable()))
7053 return false;
7054
7055 if (const Stmt *Else = IS->getElse()) {
7056 LabelTy LabelElse = this->getLabel();
7057 LabelTy LabelEnd = this->getLabel();
7058 if (!this->jumpFalse(LabelElse, IS))
7059 return false;
7060 if (!visitChildStmt(IS->getThen()))
7061 return false;
7062 if (!this->jump(LabelEnd, IS))
7063 return false;
7064 this->emitLabel(LabelElse);
7065 if (!visitChildStmt(Else))
7066 return false;
7067 this->emitLabel(LabelEnd);
7068 } else {
7069 LabelTy LabelEnd = this->getLabel();
7070 if (!this->jumpFalse(LabelEnd, IS))
7071 return false;
7072 if (!visitChildStmt(IS->getThen()))
7073 return false;
7074 this->emitLabel(LabelEnd);
7075 }
7076
7077 if (!IfScope.destroyLocals())
7078 return false;
7079
7080 return true;
7081}
7082
7083template <class Emitter>
7085 const Expr *Cond = S->getCond();
7086 const Stmt *Body = S->getBody();
7087
7088 LabelTy CondLabel = this->getLabel(); // Label before the condition.
7089 LabelTy EndLabel = this->getLabel(); // Label after the loop.
7090 LocalScope<Emitter> WholeLoopScope(this);
7091 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
7092
7093 this->fallthrough(CondLabel);
7094 this->emitLabel(CondLabel);
7095
7096 // Start of the loop body {
7097 LocalScope<Emitter> CondScope(this);
7098
7099 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
7100 if (!visitDeclStmt(CondDecl))
7101 return false;
7102 }
7103
7104 if (!this->visitBool(Cond))
7105 return false;
7106
7107 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
7108 return false;
7109
7110 if (!this->jumpFalse(EndLabel, S))
7111 return false;
7112
7113 if (!this->visitStmt(Body))
7114 return false;
7115
7116 if (!CondScope.destroyLocals())
7117 return false;
7118 // } End of loop body.
7119
7120 if (!this->jump(CondLabel, S))
7121 return false;
7122 this->fallthrough(EndLabel);
7123 this->emitLabel(EndLabel);
7124
7125 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
7126}
7127
7128template <class Emitter> bool Compiler<Emitter>::visitDoStmt(const DoStmt *S) {
7129 const Expr *Cond = S->getCond();
7130 const Stmt *Body = S->getBody();
7131
7132 LabelTy StartLabel = this->getLabel();
7133 LabelTy EndLabel = this->getLabel();
7134 LabelTy CondLabel = this->getLabel();
7135 LocalScope<Emitter> WholeLoopScope(this);
7136 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
7137
7138 this->fallthrough(StartLabel);
7139 this->emitLabel(StartLabel);
7140
7141 {
7142 LocalScope<Emitter> CondScope(this);
7143 if (!this->visitStmt(Body))
7144 return false;
7145 this->fallthrough(CondLabel);
7146 this->emitLabel(CondLabel);
7147 if (!this->visitBool(Cond))
7148 return false;
7149
7150 if (!CondScope.destroyLocals())
7151 return false;
7152 }
7153 if (!this->jumpTrue(StartLabel, S))
7154 return false;
7155
7156 this->fallthrough(EndLabel);
7157 this->emitLabel(EndLabel);
7158 return WholeLoopScope.destroyLocals();
7159}
7160
7161template <class Emitter>
7163 // for (Init; Cond; Inc) { Body }
7164 const Stmt *Init = S->getInit();
7165 const Expr *Cond = S->getCond();
7166 const Expr *Inc = S->getInc();
7167 const Stmt *Body = S->getBody();
7168
7169 LabelTy EndLabel = this->getLabel();
7170 LabelTy CondLabel = this->getLabel();
7171 LabelTy IncLabel = this->getLabel();
7172
7173 LocalScope<Emitter> WholeLoopScope(this);
7174 if (Init && !this->visitStmt(Init))
7175 return false;
7176
7177 // Start of the loop body {
7178 this->fallthrough(CondLabel);
7179 this->emitLabel(CondLabel);
7180
7181 LocalScope<Emitter> CondScope(this);
7182 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
7183 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
7184 if (!visitDeclStmt(CondDecl))
7185 return false;
7186 }
7187
7188 if (Cond) {
7189 if (!this->visitBool(Cond))
7190 return false;
7191 if (!this->jumpFalse(EndLabel, S))
7192 return false;
7193 }
7194 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
7195 return false;
7196
7197 if (Body && !this->visitStmt(Body))
7198 return false;
7199
7200 this->fallthrough(IncLabel);
7201 this->emitLabel(IncLabel);
7202 if (Inc && !this->discard(Inc))
7203 return false;
7204
7205 if (!CondScope.destroyLocals())
7206 return false;
7207 if (!this->jump(CondLabel, S))
7208 return false;
7209 // } End of loop body.
7210
7211 this->emitLabel(EndLabel);
7212 // If we jumped out of the loop above, we still need to clean up the condition
7213 // scope.
7214 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
7215}
7216
7217template <class Emitter>
7219 const Stmt *Init = S->getInit();
7220 const Expr *Cond = S->getCond();
7221 const Expr *Inc = S->getInc();
7222 const Stmt *Body = S->getBody();
7223 const Stmt *BeginStmt = S->getBeginStmt();
7224 const Stmt *RangeStmt = S->getRangeStmt();
7225 const Stmt *EndStmt = S->getEndStmt();
7226
7227 LabelTy EndLabel = this->getLabel();
7228 LabelTy CondLabel = this->getLabel();
7229 LabelTy IncLabel = this->getLabel();
7230 LocalScope<Emitter> WholeLoopScope(this);
7231 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
7232
7233 // Emit declarations needed in the loop.
7234 if (Init && !this->visitStmt(Init))
7235 return false;
7236 if (!this->visitStmt(RangeStmt))
7237 return false;
7238 if (!this->visitStmt(BeginStmt))
7239 return false;
7240 if (!this->visitStmt(EndStmt))
7241 return false;
7242
7243 LocalScope<Emitter> CondScope(this);
7244 // Now the condition as well as the loop variable assignment.
7245 this->fallthrough(CondLabel);
7246 this->emitLabel(CondLabel);
7247 if (!this->visitBool(Cond))
7248 return false;
7249 if (!this->jumpFalse(EndLabel, S))
7250 return false;
7251
7252 if (!this->visitDeclStmt(S->getLoopVarStmt(), /*EvaluateConditionDecl=*/true))
7253 return false;
7254
7255 // Body.
7256 {
7257 if (!this->visitStmt(Body))
7258 return false;
7259
7260 this->fallthrough(IncLabel);
7261 this->emitLabel(IncLabel);
7262 if (!this->discard(Inc))
7263 return false;
7264 }
7265
7266 if (!CondScope.destroyLocals())
7267 return false;
7268 if (!this->jump(CondLabel, S))
7269 return false;
7270
7271 this->fallthrough(EndLabel);
7272 this->emitLabel(EndLabel);
7273 return WholeLoopScope.destroyLocals();
7274}
7275
7276template <class Emitter>
7278 if (LabelInfoStack.empty())
7279 return this->emitInvalidTargetLabel(/*IsContinue=*/false, S);
7280
7281 OptLabelTy TargetLabel = std::nullopt;
7282 const VariableScope<Emitter> *BreakScope = nullptr;
7283
7284 if (!S->isNamed()) {
7285
7286 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
7287 if (LI.BreakLabel) {
7288 TargetLabel = *LI.BreakLabel;
7289 BreakScope = LI.BreakOrContinueScope;
7290 break;
7291 }
7292 }
7293 } else {
7294 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
7295 // May be null if the named loop is outside of the
7296 // current evaluation context, i.e. not a valid target.
7297 if (!TargetLoop)
7298 return this->emitInvalidTargetLabel(/*IsContinue=*/false, S);
7299
7300 for (const auto &LI : LabelInfoStack) {
7301 if (LI.Name == TargetLoop) {
7302 TargetLabel = *LI.BreakLabel;
7303 BreakScope = LI.BreakOrContinueScope;
7304 break;
7305 }
7306 }
7307 }
7308
7309 // Faulty break statement (e.g. label redefined or named loops disabled).
7310 if (!TargetLabel)
7311 return false;
7312
7313 for (VariableScope<Emitter> *C = this->VarScope; C != BreakScope;
7314 C = C->getParent()) {
7315 if (!C->destroyLocals())
7316 return false;
7317 }
7318
7319 return this->jump(*TargetLabel, S);
7320}
7321
7322template <class Emitter>
7324 if (LabelInfoStack.empty())
7325 return this->emitInvalidTargetLabel(/*IsContinue=*/true, S);
7326
7327 OptLabelTy TargetLabel = std::nullopt;
7328 const VariableScope<Emitter> *ContinueScope = nullptr;
7329
7330 if (!S->isNamed()) {
7331 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
7332 if (LI.ContinueLabel) {
7333 TargetLabel = *LI.ContinueLabel;
7334 ContinueScope = LI.BreakOrContinueScope;
7335 break;
7336 }
7337 }
7338 } else {
7339 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
7340 // May be null if the named loop is outside of the
7341 // current evaluation context, i.e. not a valid target.
7342 if (!TargetLoop)
7343 return this->emitInvalidTargetLabel(/*IsContinue=*/true, S);
7344
7345 for (auto LI : LabelInfoStack) {
7346 if (LI.Name == TargetLoop) {
7347 TargetLabel = *LI.ContinueLabel;
7348 ContinueScope = LI.BreakOrContinueScope;
7349 break;
7350 }
7351 }
7352 }
7353
7354 if (!TargetLabel)
7355 return false;
7356
7357 for (VariableScope<Emitter> *C = VarScope; C != ContinueScope;
7358 C = C->getParent()) {
7359 if (!C->destroyLocals())
7360 return false;
7361 }
7362
7363 return this->jump(*TargetLabel, S);
7364}
7365
7366template <class Emitter>
7368 const Expr *Cond = S->getCond();
7369 if (Cond->containsErrors())
7370 return false;
7371
7372 PrimType CondT = this->classifyPrim(Cond->getType());
7373 LocalScope<Emitter> LS(this);
7374 llvm::SaveAndRestore StmtExprSAR(this->SwitchInStmtExpr, this->InStmtExpr);
7375
7376 LabelTy EndLabel = this->getLabel();
7377 UnsignedOrNone DefaultLabel = std::nullopt;
7378 unsigned CondVar =
7379 this->allocateLocalPrimitive(Cond, CondT, /*IsConst=*/true);
7380
7381 if (const auto *CondInit = S->getInit())
7382 if (!visitStmt(CondInit))
7383 return false;
7384
7385 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
7386 if (!visitDeclStmt(CondDecl))
7387 return false;
7388
7389 // Initialize condition variable.
7390 if (!this->visit(Cond))
7391 return false;
7392 if (!this->emitSetLocal(CondT, CondVar, S))
7393 return false;
7394
7395 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
7396 return false;
7397
7399 // Create labels and comparison ops for all case statements.
7400 for (const SwitchCase *SC = S->getSwitchCaseList(); SC;
7401 SC = SC->getNextSwitchCase()) {
7402 if (const auto *CS = dyn_cast<CaseStmt>(SC)) {
7403 CaseLabels[SC] = this->getLabel();
7404
7405 if (CS->caseStmtIsGNURange()) {
7406 LabelTy EndOfRangeCheck = this->getLabel();
7407 const Expr *Low = CS->getLHS();
7408 const Expr *High = CS->getRHS();
7409 if (Low->isValueDependent() || High->isValueDependent())
7410 return false;
7411
7412 if (!this->emitGetLocal(CondT, CondVar, CS))
7413 return false;
7414 if (!this->visit(Low))
7415 return false;
7416 PrimType LT = this->classifyPrim(Low->getType());
7417 if (!this->emitGE(LT, S))
7418 return false;
7419 if (!this->jumpFalse(EndOfRangeCheck, S))
7420 return false;
7421
7422 if (!this->emitGetLocal(CondT, CondVar, CS))
7423 return false;
7424 if (!this->visit(High))
7425 return false;
7426 PrimType HT = this->classifyPrim(High->getType());
7427 if (!this->emitLE(HT, S))
7428 return false;
7429 if (!this->jumpTrue(CaseLabels[CS], S))
7430 return false;
7431 this->emitLabel(EndOfRangeCheck);
7432 continue;
7433 }
7434
7435 const Expr *Value = CS->getLHS();
7436 if (Value->isValueDependent())
7437 return false;
7438 PrimType ValueT = this->classifyPrim(Value->getType());
7439
7440 // Compare the case statement's value to the switch condition.
7441 if (!this->emitGetLocal(CondT, CondVar, CS))
7442 return false;
7443 if (!this->visit(Value))
7444 return false;
7445
7446 // Compare and jump to the case label.
7447 if (!this->emitEQ(ValueT, S))
7448 return false;
7449 if (!this->jumpTrue(CaseLabels[CS], S))
7450 return false;
7451 } else {
7452 assert(!DefaultLabel);
7453 DefaultLabel = this->getLabel();
7454 }
7455 }
7456
7457 // If none of the conditions above were true, fall through to the default
7458 // statement or jump after the switch statement.
7459 if (DefaultLabel) {
7460 if (!this->jump(*DefaultLabel, S))
7461 return false;
7462 } else {
7463 if (!this->jump(EndLabel, S))
7464 return false;
7465 }
7466
7467 SwitchScope<Emitter> SS(this, S, std::move(CaseLabels), EndLabel,
7468 DefaultLabel);
7469 if (!this->visitStmt(S->getBody()))
7470 return false;
7471 this->fallthrough(EndLabel);
7472 this->emitLabel(EndLabel);
7473
7474 return LS.destroyLocals();
7475}
7476
7477template <class Emitter>
7479 this->fallthrough(CaseLabels[S]);
7480 this->emitLabel(CaseLabels[S]);
7481
7482 // We can't jump from an outer switch statement to a case label
7483 // that's inside a StmtExpr.
7484 if (this->InStmtExpr && !this->SwitchInStmtExpr)
7485 return this->emitUnsupported(S);
7486
7487 return this->visitStmt(S->getSubStmt());
7488}
7489
7490template <class Emitter>
7492 if (LabelInfoStack.empty())
7493 return false;
7494
7495 LabelTy DefaultLabel;
7496 for (const LabelInfo &LI : llvm::reverse(LabelInfoStack)) {
7497 if (LI.DefaultLabel) {
7498 DefaultLabel = *LI.DefaultLabel;
7499 break;
7500 }
7501 }
7502
7503 this->emitLabel(DefaultLabel);
7504 return this->visitStmt(S->getSubStmt());
7505}
7506
7507template <class Emitter>
7509 const Stmt *SubStmt = S->getSubStmt();
7510
7511 bool IsMSVCConstexprAttr = isa<ReturnStmt>(SubStmt) &&
7513
7514 if (IsMSVCConstexprAttr && !this->emitPushMSVCCE(S))
7515 return false;
7516
7517 if (this->Ctx.getLangOpts().CXXAssumptions &&
7518 !this->Ctx.getLangOpts().MSVCCompat) {
7519 for (const Attr *A : S->getAttrs()) {
7520 auto *AA = dyn_cast<CXXAssumeAttr>(A);
7521 if (!AA)
7522 continue;
7523
7524 assert(isa<NullStmt>(SubStmt));
7525
7526 const Expr *Assumption = AA->getAssumption();
7527 if (Assumption->isValueDependent())
7528 return false;
7529
7530 if (Assumption->HasSideEffects(this->Ctx.getASTContext()))
7531 continue;
7532
7533 // Evaluate assumption.
7534 if (!this->visitBool(Assumption))
7535 return false;
7536
7537 if (!this->emitAssume(Assumption))
7538 return false;
7539 }
7540 }
7541
7542 // Ignore other attributes.
7543 if (!this->visitStmt(SubStmt))
7544 return false;
7545
7546 if (IsMSVCConstexprAttr)
7547 return this->emitPopMSVCCE(S);
7548 return true;
7549}
7550
7551template <class Emitter>
7553 // Ignore all handlers.
7554 return this->visitStmt(S->getTryBlock());
7555}
7556
7557/// template for (auto x : {1, 2}) {}
7558///
7559/// This is not a loop from an AST perspective at all since it has already
7560/// been instantiated to a list of compound statements.
7561///
7562/// Since we can have control flow in those compound statements, we need to
7563/// handle it mostly like a loop though.
7564template <class Emitter>
7567 LocalScope<Emitter> WholeLoopScope(this, ScopeKind::Block);
7568
7569 for (const Stmt *PreambleStmt : S->getPreambleStmts()) {
7570 if (!this->visitDeclStmt(cast<DeclStmt>(PreambleStmt), true))
7571 return false;
7572 }
7573
7574 LabelTy EndLabel = this->getLabel();
7575 for (const Stmt *Instantiation : S->getInstantiations()) {
7576 LabelTy ContinueLabel = this->getLabel();
7577 LoopScope<Emitter> LS(this, S, EndLabel, ContinueLabel);
7578
7579 if (!this->visitStmt(Instantiation))
7580 return false;
7581 this->emitLabel(ContinueLabel);
7582 }
7583
7584 this->emitLabel(EndLabel);
7585
7586 return WholeLoopScope.destroyLocals();
7587}
7588
7589template <class Emitter>
7590bool Compiler<Emitter>::emitLambdaStaticInvokerBody(const CXXMethodDecl *MD) {
7591 assert(MD->isLambdaStaticInvoker());
7592 assert(MD->hasBody());
7593 assert(cast<CompoundStmt>(MD->getBody())->body_empty());
7594
7595 const CXXRecordDecl *ClosureClass = MD->getParent();
7596 const FunctionDecl *LambdaCallOp;
7597 assert(ClosureClass->captures().empty());
7598 if (ClosureClass->isGenericLambda()) {
7599 LambdaCallOp = ClosureClass->getLambdaCallOperator();
7600 assert(MD->isFunctionTemplateSpecialization() &&
7601 "A generic lambda's static-invoker function must be a "
7602 "template specialization");
7604 FunctionTemplateDecl *CallOpTemplate =
7605 LambdaCallOp->getDescribedFunctionTemplate();
7606 llvm::FoldingSetInsertToken InsertToken;
7607 const FunctionDecl *CorrespondingCallOpSpecialization =
7608 CallOpTemplate->findSpecialization(TAL->asArray(), InsertToken);
7609 assert(CorrespondingCallOpSpecialization);
7610 LambdaCallOp = CorrespondingCallOpSpecialization;
7611 } else {
7612 LambdaCallOp = ClosureClass->getLambdaCallOperator();
7613 }
7614 assert(ClosureClass->captures().empty());
7615 const Function *Func = this->getFunction(LambdaCallOp);
7616 if (!Func)
7617 return false;
7618 assert(Func->hasThisPointer());
7619 assert(Func->getNumParams() == (MD->getNumParams() + 1 + Func->hasRVO()));
7620
7621 if (Func->hasRVO()) {
7622 if (!this->emitRVOPtr(MD))
7623 return false;
7624 }
7625
7626 // The lambda call operator needs an instance pointer, but we don't have
7627 // one here, and we don't need one either because the lambda cannot have
7628 // any captures, as verified above. Emit a null pointer. This is then
7629 // special-cased when interpreting to not emit any misleading diagnostics.
7630 if (!this->emitNullPtr(0, nullptr, MD))
7631 return false;
7632
7633 // Forward all arguments from the static invoker to the lambda call operator.
7634 for (const ParmVarDecl *PVD : MD->parameters()) {
7635 auto It = this->Params.find(PVD);
7636 assert(It != this->Params.end());
7637
7638 // We do the lvalue-to-rvalue conversion manually here, so no need
7639 // to care about references.
7640 PrimType ParamType = this->classify(PVD->getType()).value_or(PT_Ptr);
7641 if (!this->emitGetParam(ParamType, It->second.Index, MD))
7642 return false;
7643 }
7644
7645 if (!this->emitCall(Func, 0, LambdaCallOp))
7646 return false;
7647
7648 this->emitCleanup();
7649 if (ReturnType)
7650 return this->emitRet(*ReturnType, MD);
7651
7652 // Nothing to do, since we emitted the RVO pointer above.
7653 return this->emitRetVoid(MD);
7654}
7655
7656template <class Emitter>
7657bool Compiler<Emitter>::checkLiteralType(const Expr *E) {
7658 if (Ctx.getLangOpts().CPlusPlus23)
7659 return true;
7660
7661 if (!E->isPRValue() || E->getType()->isLiteralType(Ctx.getASTContext()))
7662 return true;
7663
7664 return this->emitCheckLiteralType(E->getType().getTypePtr(), E);
7665}
7666
7668 const Expr *InitExpr = Init->getInit();
7669
7670 if (!Init->isWritten() && !Init->isInClassMemberInitializer() &&
7671 !isa<CXXConstructExpr>(InitExpr))
7672 return true;
7673
7674 if (const auto *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
7675 const CXXConstructorDecl *Ctor = CE->getConstructor();
7676 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
7677 Ctor->isTrivial())
7678 return true;
7679 }
7680
7681 return false;
7682}
7683
7684template <class Emitter>
7685bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
7686 assert(!ReturnType);
7687
7688 // Only start the lifetime of the instance pointer.
7689 if (!this->emitStartThisLifetime1(Ctor))
7690 return false;
7691
7692 auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset,
7693 const Expr *InitExpr,
7694 bool Activate = false) -> bool {
7695 // We don't know what to do with these, so just return false.
7696 if (InitExpr->getType().isNull())
7697 return false;
7698
7699 if (OptPrimType T = this->classify(InitExpr)) {
7700 if (Activate && !this->emitActivateThisField(FieldOffset, InitExpr))
7701 return false;
7702
7703 if (!this->visit(InitExpr))
7704 return false;
7705
7706 if (F->isBitField())
7707 return this->emitInitThisBitField(*T, FieldOffset, F->bitWidth(),
7708 InitExpr);
7709 return this->emitInitThisField(*T, FieldOffset, InitExpr);
7710 }
7711 // Non-primitive case. Get a pointer to the field-to-initialize
7712 // on the stack and call visitInitialzer() for it.
7713 InitLinkScope<Emitter> FieldScope(this, InitLink::Field(F->Offset));
7714 if (!this->emitGetPtrThisField(FieldOffset, InitExpr))
7715 return false;
7716
7717 if (Activate && !this->emitActivate(InitExpr))
7718 return false;
7719
7720 return this->visitInitializerPop(InitExpr);
7721 };
7722
7723 const RecordDecl *RD = Ctor->getParent();
7724 const Record *R = this->getRecord(RD);
7725 if (!R)
7726 return false;
7727 bool IsUnion = R->isUnion();
7728
7729 // Default union copy and move ctors are special.
7730 if (IsUnion && Ctor->isCopyOrMoveConstructor() && Ctor->isDefaulted()) {
7732
7733 // No special case for NumFields == 0 here, so the Memcpy op
7734 // below also does its checks in those cases.
7735
7736 assert(cast<CompoundStmt>(Ctor->getBody())->body_empty());
7737 if (!this->emitThis(Ctor))
7738 return false;
7739
7740 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, Ctor))
7741 return false;
7742
7743 return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) &&
7744 this->emitRetVoid(Ctor);
7745 }
7746
7747 unsigned FieldInits = 0;
7748 InitLinkScope<Emitter> InitScope(this, InitLink::This());
7749 // First, initialize virtual bases if the records has them.
7750 if (R->getNumVirtualBases() > 0) {
7751 if (!this->emitThis(Ctor))
7752 return false;
7753 LabelTy AfterVirtBasesLabel = this->getLabel();
7754
7755 // If the instance pointer is a base class, skip the virtual bases.
7756 if (!this->emitIsBaseClass({}))
7757 return false;
7758 if (!this->jumpTrue(AfterVirtBasesLabel, {}))
7759 return false;
7760
7761 for (const auto *Init : Ctor->inits()) {
7762 if (const Type *Base = Init->getBaseClass();
7763 Base && Init->isBaseVirtual()) {
7764 const auto *BaseDecl = Base->getAsCXXRecordDecl();
7765 assert(BaseDecl);
7766 assert(R->findVirtualBase(BaseDecl));
7767 if (!this->emitGetPtrThisVirtBase(BaseDecl, Ctor))
7768 return false;
7769 if (!this->visitInitializerPop(Init->getInit()))
7770 return false;
7771 }
7772 }
7773
7774 this->fallthrough(AfterVirtBasesLabel);
7775 this->emitLabel(AfterVirtBasesLabel);
7776
7777 if (!this->emitPopPtr(Ctor))
7778 return false;
7779 }
7780
7781 for (const auto *Init : Ctor->inits()) {
7782 // Scope needed for the initializers.
7783 LocalScope<Emitter> Scope(this, ScopeKind::FullExpression);
7784
7785 const Expr *InitExpr = Init->getInit();
7786 if (const FieldDecl *Member = Init->getMember()) {
7787 const Record::Field *F = R->getField(Member);
7788
7791 if (!emitFieldInitializer(F, F->Offset, InitExpr, IsUnion))
7792 return false;
7793 ++FieldInits;
7794 } else if (const Type *Base = Init->getBaseClass()) {
7795 const auto *BaseDecl = Base->getAsCXXRecordDecl();
7796 assert(BaseDecl);
7797
7798 if (Init->isBaseVirtual()) {
7799 // See above.
7800 continue;
7801 } else {
7802 // Base class initializer.
7803 // Get This Base and call initializer on it.
7804 const Record::Base *B = R->getBase(BaseDecl);
7805 assert(B);
7806 if (!this->emitGetPtrThisBase(B->Offset, InitExpr))
7807 return false;
7808 }
7809
7810 if (!this->visitInitializerPop(InitExpr))
7811 return false;
7812 } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) {
7815 unsigned ChainSize = IFD->getChainingSize();
7816 assert(ChainSize >= 2);
7817
7818 unsigned NestedFieldOffset = 0;
7819 const Record::Field *NestedField = nullptr;
7820 for (unsigned I = 0; I != ChainSize; ++I) {
7821 const auto *FD = cast<FieldDecl>(IFD->chain()[I]);
7822 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7823 assert(FieldRecord);
7824
7825 NestedField = FieldRecord->getField(FD);
7826 assert(NestedField);
7827 IsUnion = IsUnion || FieldRecord->isUnion();
7828
7829 NestedFieldOffset += NestedField->Offset;
7830
7831 // Add a new InitChainLink for the record, but not for the final field.
7832 if (I != ChainSize - 1)
7833 InitStack.push_back(InitLink::Field(NestedField->Offset));
7834 }
7835 assert(NestedField);
7836
7838 if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr,
7839 IsUnion))
7840 return false;
7841
7842 // Mark all chain links as initialized.
7843 unsigned InitFieldOffset = 0;
7844 for (const NamedDecl *ND : IFD->chain().drop_back()) {
7845 const auto *FD = cast<FieldDecl>(ND);
7846 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7847 assert(FieldRecord);
7848 NestedField = FieldRecord->getField(FD);
7849 InitFieldOffset += NestedField->Offset;
7850 assert(NestedField);
7851 if (!this->emitGetPtrThisField(InitFieldOffset, InitExpr))
7852 return false;
7853 if (!this->emitFinishInitPop(InitExpr))
7854 return false;
7855 }
7856
7857 InitStack.pop_back_n(ChainSize - 1);
7858
7859 } else {
7860 assert(Init->isDelegatingInitializer());
7861 if (!this->emitThis(InitExpr))
7862 return false;
7863 if (!this->visitInitializerPop(Init->getInit()))
7864 return false;
7865 }
7866
7867 if (!Scope.destroyLocals())
7868 return false;
7869 }
7870
7871 if (FieldInits != R->getNumFields()) {
7872 assert(FieldInits < R->getNumFields());
7873 // Start the lifetime of all members.
7874 if (!this->emitStartThisLifetime(Ctor))
7875 return false;
7876 }
7877
7878 if (const Stmt *Body = Ctor->getBody()) {
7879 // Only emit the CtorCheck op for non-empty CompoundStmt bodies.
7880 // For non-CompoundStmts, always assume they are non-empty and emit it.
7881 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
7882 if (!CS->body_empty() && !this->emitCtorCheck(SourceInfo{}))
7883 return false;
7884 } else {
7885 if (!this->emitCtorCheck(SourceInfo{}))
7886 return false;
7887 }
7888
7889 if (!visitStmt(Body))
7890 return false;
7891 }
7892
7893 return this->emitRetVoid(SourceInfo{});
7894}
7895
7896template <class Emitter>
7897bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) {
7898 const RecordDecl *RD = Dtor->getParent();
7899 const Record *R = this->getRecord(RD);
7900 if (!R)
7901 return false;
7902
7903 if (!Dtor->isTrivial() && Dtor->getBody()) {
7904 if (!this->visitStmt(Dtor->getBody()))
7905 return false;
7906 }
7907
7908 if (!this->emitThis(Dtor))
7909 return false;
7910
7911 if (!this->emitCheckDestruction(Dtor))
7912 return false;
7913
7914 assert(R);
7915 if (!R->isUnion()) {
7916
7918 // First, destroy all fields.
7919 for (const Record::Field &Field : llvm::reverse(R->fields())) {
7920 const Descriptor *D = Field.Desc;
7921 if (D->hasTrivialDtor())
7922 continue;
7923 if (!this->emitGetPtrField(Field.Offset, SourceInfo{}))
7924 return false;
7925 if (!this->emitDestructionPop(D, SourceInfo{}))
7926 return false;
7927 }
7928 }
7929
7930 for (const Record::Base &Base : llvm::reverse(R->bases())) {
7931 if (Base.R->hasTrivialDtor())
7932 continue;
7933 if (!this->emitGetPtrBase(Base.Offset, SourceInfo{}))
7934 return false;
7935 if (!this->emitRecordDestructionPop(Base.R, {}))
7936 return false;
7937 }
7938
7939 if (R->getNumVirtualBases() > 0) {
7940 LabelTy EndLabel = this->getLabel();
7941 // If this is a base class, skip the virtual bases.
7942 if (!this->emitIsBaseClass({}))
7943 return false;
7944 if (!this->jumpTrue(EndLabel, {}))
7945 return false;
7946
7947 for (const Record::Base &Base : llvm::reverse(R->virtual_bases())) {
7948 if (Base.R->hasTrivialDtor())
7949 continue;
7950 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(Base.R->getDecl()),
7951 SourceInfo{}))
7952 return false;
7953 if (!this->emitRecordDestructionPop(Base.R, {}))
7954 return false;
7955 }
7956
7957 this->fallthrough(EndLabel);
7958 this->emitLabel(EndLabel);
7959 }
7960
7961 if (!this->emitMarkDestroyed(Dtor))
7962 return false;
7963
7964 return this->emitPopPtr(Dtor) && this->emitRetVoid(Dtor);
7965}
7966
7967template <class Emitter>
7968bool Compiler<Emitter>::compileUnionAssignmentOperator(
7969 const CXXMethodDecl *MD) {
7970 if (!this->emitThis(MD))
7971 return false;
7972
7973 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, MD))
7974 return false;
7975
7976 return this->emitMemcpy(MD) && this->emitRet(PT_Ptr, MD);
7977}
7978
7979template <class Emitter>
7981 if (F->getReturnType()->isDependentType())
7982 return false;
7983
7984 // Classify the return type.
7985 ReturnType = this->classify(F->getReturnType());
7986
7987 this->CompilingFunction = F;
7988
7989 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F))
7990 return this->compileConstructor(Ctor);
7991 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F))
7992 return this->compileDestructor(Dtor);
7993
7994 // Emit custom code if this is a lambda static invoker.
7995 if (const auto *MD = dyn_cast<CXXMethodDecl>(F)) {
7996 const RecordDecl *RD = MD->getParent();
7997
7998 if (RD->isUnion() &&
8000 return this->compileUnionAssignmentOperator(MD);
8001
8002 if (MD->isLambdaStaticInvoker())
8003 return this->emitLambdaStaticInvokerBody(MD);
8004 }
8005
8006 // Regular functions.
8007 if (const auto *Body = F->getBody())
8008 if (!visitStmt(Body))
8009 return false;
8010
8011 // Emit a guard return to protect against a code path missing one.
8012 if (F->getReturnType()->isVoidType())
8013 return this->emitRetVoid(SourceInfo{});
8014 return this->emitNoRet(SourceInfo{});
8015}
8016
8017static uint32_t getBitWidth(const Expr *E) {
8018 assert(E->refersToBitField());
8019 const auto *ME = cast<MemberExpr>(E);
8020 const auto *FD = cast<FieldDecl>(ME->getMemberDecl());
8021 return FD->getBitWidthValue();
8022}
8023
8024template <class Emitter>
8026 if (E->containsErrors())
8027 return false;
8028
8029 const Expr *SubExpr = E->getSubExpr();
8030 if (SubExpr->getType()->isAnyComplexType())
8031 return this->VisitComplexUnaryOperator(E);
8032 if (SubExpr->getType()->isVectorType())
8033 return this->VisitVectorUnaryOperator(E);
8034 if (SubExpr->getType()->isFixedPointType())
8035 return this->VisitFixedPointUnaryOperator(E);
8036 OptPrimType T = classify(SubExpr->getType());
8037
8038 switch (E->getOpcode()) {
8039 case UO_PostInc: { // x++
8040 if (!Ctx.getLangOpts().CPlusPlus14)
8041 return this->emitInvalid(E);
8042 if (!T)
8043 return this->emitError(E);
8044
8045 if (!this->visit(SubExpr))
8046 return false;
8047
8048 if (T == PT_Ptr) {
8049 if (!this->emitIncPtr(E))
8050 return false;
8051
8052 return DiscardResult ? this->emitPopPtr(E) : true;
8053 }
8054
8055 if (T == PT_Float)
8056 return DiscardResult ? this->emitIncfPop(getFPOptions(E), E)
8057 : this->emitIncf(getFPOptions(E), E);
8058
8059 if (SubExpr->refersToBitField())
8060 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
8061 getBitWidth(SubExpr), E)
8062 : this->emitIncBitfield(*T, E->canOverflow(),
8063 getBitWidth(SubExpr), E);
8064
8065 return DiscardResult ? this->emitIncPop(*T, E->canOverflow(), E)
8066 : this->emitInc(*T, E->canOverflow(), E);
8067 }
8068 case UO_PostDec: { // x--
8069 if (!Ctx.getLangOpts().CPlusPlus14)
8070 return this->emitInvalid(E);
8071 if (!T)
8072 return this->emitError(E);
8073
8074 if (!this->visit(SubExpr))
8075 return false;
8076
8077 if (T == PT_Ptr) {
8078 if (!this->emitDecPtr(E))
8079 return false;
8080
8081 return DiscardResult ? this->emitPopPtr(E) : true;
8082 }
8083
8084 if (T == PT_Float)
8085 return DiscardResult ? this->emitDecfPop(getFPOptions(E), E)
8086 : this->emitDecf(getFPOptions(E), E);
8087
8088 if (SubExpr->refersToBitField()) {
8089 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
8090 getBitWidth(SubExpr), E)
8091 : this->emitDecBitfield(*T, E->canOverflow(),
8092 getBitWidth(SubExpr), E);
8093 }
8094
8095 return DiscardResult ? this->emitDecPop(*T, E->canOverflow(), E)
8096 : this->emitDec(*T, E->canOverflow(), E);
8097 }
8098 case UO_PreInc: { // ++x
8099 if (!Ctx.getLangOpts().CPlusPlus14)
8100 return this->emitInvalid(E);
8101 if (!T)
8102 return this->emitError(E);
8103
8104 if (!this->visit(SubExpr))
8105 return false;
8106
8107 if (T == PT_Ptr) {
8108 if (!this->emitLoadPtr(E))
8109 return false;
8110 if (!this->emitConstUint8(1, E))
8111 return false;
8112 if (!this->emitAddOffsetUint8(E))
8113 return false;
8114 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
8115 }
8116
8117 // Post-inc and pre-inc are the same if the value is to be discarded.
8118 if (DiscardResult) {
8119 if (T == PT_Float)
8120 return this->emitIncfPop(getFPOptions(E), E);
8121 if (SubExpr->refersToBitField())
8122 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
8123 getBitWidth(SubExpr), E)
8124 : this->emitIncBitfield(*T, E->canOverflow(),
8125 getBitWidth(SubExpr), E);
8126 return this->emitIncPop(*T, E->canOverflow(), E);
8127 }
8128
8129 if (T == PT_Float) {
8130 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
8131 if (!this->emitLoadFloat(E))
8132 return false;
8133 APFloat F(TargetSemantics, 1);
8134 if (!this->emitFloat(F, E))
8135 return false;
8136
8137 if (!this->emitAddf(getFPOptions(E), E))
8138 return false;
8139 if (!this->emitStoreFloat(E))
8140 return false;
8141 } else if (SubExpr->refersToBitField()) {
8142 assert(isIntegerOrBoolType(*T));
8143 if (!this->emitPreIncBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
8144 E))
8145 return false;
8146 } else {
8147 assert(isIntegerOrBoolType(*T));
8148 if (!this->emitPreInc(*T, E->canOverflow(), E))
8149 return false;
8150 }
8151 return E->isGLValue() || this->emitLoadPop(*T, E);
8152 }
8153 case UO_PreDec: { // --x
8154 if (!Ctx.getLangOpts().CPlusPlus14)
8155 return this->emitInvalid(E);
8156 if (!T)
8157 return this->emitError(E);
8158
8159 if (!this->visit(SubExpr))
8160 return false;
8161
8162 if (T == PT_Ptr) {
8163 if (!this->emitLoadPtr(E))
8164 return false;
8165 if (!this->emitConstUint8(1, E))
8166 return false;
8167 if (!this->emitSubOffsetUint8(E))
8168 return false;
8169 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
8170 }
8171
8172 // Post-dec and pre-dec are the same if the value is to be discarded.
8173 if (DiscardResult) {
8174 if (T == PT_Float)
8175 return this->emitDecfPop(getFPOptions(E), E);
8176 if (SubExpr->refersToBitField())
8177 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
8178 getBitWidth(SubExpr), E)
8179 : this->emitDecBitfield(*T, E->canOverflow(),
8180 getBitWidth(SubExpr), E);
8181 return this->emitDecPop(*T, E->canOverflow(), E);
8182 }
8183
8184 if (T == PT_Float) {
8185 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
8186 if (!this->emitLoadFloat(E))
8187 return false;
8188 APFloat F(TargetSemantics, 1);
8189 if (!this->emitFloat(F, E))
8190 return false;
8191
8192 if (!this->emitSubf(getFPOptions(E), E))
8193 return false;
8194 if (!this->emitStoreFloat(E))
8195 return false;
8196 } else if (SubExpr->refersToBitField()) {
8197 assert(isIntegerOrBoolType(*T));
8198 if (!this->emitPreDecBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
8199 E))
8200 return false;
8201 } else {
8202 assert(isIntegerOrBoolType(*T));
8203 if (!this->emitPreDec(*T, E->canOverflow(), E))
8204 return false;
8205 }
8206 return E->isGLValue() || this->emitLoadPop(*T, E);
8207 }
8208 case UO_LNot: // !x
8209 if (!T)
8210 return this->emitError(E);
8211
8212 if (DiscardResult)
8213 return this->discard(SubExpr);
8214
8215 if (!this->visitBool(SubExpr))
8216 return false;
8217
8218 if (!this->emitInv(E))
8219 return false;
8220
8221 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
8222 return this->emitCast(PT_Bool, ET, E);
8223 return true;
8224 case UO_Minus: // -x
8225 if (!T)
8226 return this->emitError(E);
8227
8228 if (!this->visit(SubExpr))
8229 return false;
8230 return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E);
8231 case UO_Plus: // +x
8232 if (!T)
8233 return this->emitError(E);
8234
8235 if (!this->visit(SubExpr)) // noop
8236 return false;
8237 return DiscardResult ? this->emitPop(*T, E) : true;
8238 case UO_AddrOf: // &x
8239 if (E->getType()->isMemberPointerType()) {
8240 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
8241 // member can be formed.
8242 if (DiscardResult)
8243 return true;
8244 return this->emitGetMemberPtr(cast<DeclRefExpr>(SubExpr)->getDecl(), E);
8245 }
8246 // [C11 6.5.3.2p3]: if the operand of '&' is the result of a unary '*'
8247 // operator, neither operator is evaluated and the result is as if both
8248 // were omitted. So '&*q' is just 'q' with no dereference; delegate to the
8249 // pointer operand directly instead of to the '*' (which would emit a null
8250 // check), so that e.g. '&*(int *)0' is not rejected.
8251 if (!Ctx.getLangOpts().CPlusPlus) {
8252 const Expr *Sub = SubExpr->IgnoreParens();
8253
8254 if (const auto *Deref = dyn_cast<UnaryOperator>(Sub);
8255 Deref && Deref->getOpcode() == UO_Deref) {
8256 if (DiscardResult)
8257 return this->discard(Deref->getSubExpr());
8258 return this->visit(Deref->getSubExpr()) && this->emitAddrOf(E);
8259 }
8260 }
8261 // We should already have a pointer when we get here.
8262 if (DiscardResult)
8263 return this->discard(SubExpr);
8264 return this->delegate(SubExpr) && this->emitAddrOf(E);
8265 case UO_Deref: // *x
8266 if (DiscardResult)
8267 return this->discard(SubExpr);
8268
8269 if (!this->visit(SubExpr))
8270 return false;
8271
8272 if (!SubExpr->getType()->isFunctionPointerType() && !this->emitCheckNull(E))
8273 return false;
8274
8275 if (classifyPrim(SubExpr) == PT_Ptr)
8276 return this->emitNarrowPtr(E);
8277 return true;
8278
8279 case UO_Not: // ~x
8280 if (!T)
8281 return this->emitError(E);
8282
8283 if (!this->visit(SubExpr))
8284 return false;
8285 return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
8286 case UO_Real: // __real x
8287 if (!T)
8288 return false;
8289 return this->delegate(SubExpr);
8290 case UO_Imag: { // __imag x
8291 if (!T)
8292 return false;
8293 if (!this->discard(SubExpr))
8294 return false;
8295 return DiscardResult
8296 ? true
8297 : this->visitZeroInitializer(*T, SubExpr->getType(), SubExpr);
8298 }
8299 case UO_Extension:
8300 return this->delegate(SubExpr);
8301 case UO_Coawait:
8302 assert(false && "Unhandled opcode");
8303 }
8304
8305 return false;
8306}
8307
8308template <class Emitter>
8310 const Expr *SubExpr = E->getSubExpr();
8311 assert(SubExpr->getType()->isAnyComplexType());
8312
8313 if (DiscardResult)
8314 return this->discard(SubExpr);
8315
8316 OptPrimType ResT = classify(E);
8317 auto prepareResult = [=]() -> bool {
8318 if (!ResT && !Initializing) {
8319 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
8320 if (!LocalIndex)
8321 return false;
8322 return this->emitGetPtrLocal(*LocalIndex, E);
8323 }
8324
8325 return true;
8326 };
8327
8328 // The offset of the temporary, if we created one.
8329 unsigned SubExprOffset = ~0u;
8330 auto createTemp = [=, &SubExprOffset]() -> bool {
8331 SubExprOffset =
8332 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
8333 if (!this->visit(SubExpr))
8334 return false;
8335 return this->emitSetLocal(PT_Ptr, SubExprOffset, E);
8336 };
8337
8338 PrimType ElemT = classifyComplexElementType(SubExpr->getType());
8339 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
8340 if (!this->emitGetLocal(PT_Ptr, Offset, E))
8341 return false;
8342 return this->emitArrayElemPop(ElemT, Index, E);
8343 };
8344
8345 switch (E->getOpcode()) {
8346 case UO_Minus: // -x
8347 if (!prepareResult())
8348 return false;
8349 if (!createTemp())
8350 return false;
8351 for (unsigned I = 0; I != 2; ++I) {
8352 if (!getElem(SubExprOffset, I))
8353 return false;
8354 if (!this->emitNeg(ElemT, E))
8355 return false;
8356 if (!this->emitInitElem(ElemT, I, E))
8357 return false;
8358 }
8359 break;
8360
8361 case UO_Plus: // +x
8362 case UO_AddrOf: // &x
8363 case UO_Deref: // *x
8364 return this->delegate(SubExpr);
8365
8366 case UO_LNot:
8367 if (!this->visit(SubExpr))
8368 return false;
8369 if (!this->emitComplexBoolCast(SubExpr))
8370 return false;
8371 if (!this->emitInv(E))
8372 return false;
8373 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
8374 return this->emitCast(PT_Bool, ET, E);
8375 return true;
8376
8377 case UO_Real:
8378 return this->emitComplexReal(SubExpr);
8379
8380 case UO_Imag:
8381 if (!this->visit(SubExpr))
8382 return false;
8383
8384 if (SubExpr->isLValue()) {
8385 if (!this->emitConstUint8(1, E))
8386 return false;
8387 return this->emitArrayElemPtrPopUint8(E);
8388 }
8389
8390 // Since our _Complex implementation does not map to a primitive type,
8391 // we sometimes have to do the lvalue-to-rvalue conversion here manually.
8392 return this->emitArrayElemPop(classifyPrim(E->getType()), 1, E);
8393
8394 case UO_Not: // ~x
8395 if (!this->delegate(SubExpr))
8396 return false;
8397 // Negate the imaginary component.
8398 if (!this->emitArrayElem(ElemT, 1, E))
8399 return false;
8400 if (!this->emitNeg(ElemT, E))
8401 return false;
8402 if (!this->emitInitElem(ElemT, 1, E))
8403 return false;
8404 return DiscardResult ? this->emitPopPtr(E) : true;
8405
8406 case UO_Extension:
8407 return this->delegate(SubExpr);
8408
8409 default:
8410 return this->emitInvalid(E);
8411 }
8412
8413 return true;
8414}
8415
8416template <class Emitter>
8418 const Expr *SubExpr = E->getSubExpr();
8419 assert(SubExpr->getType()->isVectorType());
8420
8421 if (DiscardResult)
8422 return this->discard(SubExpr);
8423
8424 auto UnaryOp = E->getOpcode();
8425 if (UnaryOp == UO_Extension)
8426 return this->delegate(SubExpr);
8427
8428 if (UnaryOp != UO_Plus && UnaryOp != UO_Minus && UnaryOp != UO_LNot &&
8429 UnaryOp != UO_Not && UnaryOp != UO_AddrOf)
8430 return this->emitInvalid(E);
8431
8432 // Nothing to do here.
8433 if (UnaryOp == UO_Plus || UnaryOp == UO_AddrOf)
8434 return this->delegate(SubExpr);
8435
8436 if (!Initializing) {
8437 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
8438 if (!LocalIndex)
8439 return false;
8440 if (!this->emitGetPtrLocal(*LocalIndex, E))
8441 return false;
8442 }
8443
8444 // The offset of the temporary, if we created one.
8445 unsigned SubExprOffset =
8446 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
8447 if (!this->visit(SubExpr))
8448 return false;
8449 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E))
8450 return false;
8451
8452 const auto *VecTy = SubExpr->getType()->getAs<VectorType>();
8453 PrimType ElemT = classifyVectorElementType(SubExpr->getType());
8454 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
8455 if (!this->emitGetLocal(PT_Ptr, Offset, E))
8456 return false;
8457 return this->emitArrayElemPop(ElemT, Index, E);
8458 };
8459
8460 switch (UnaryOp) {
8461 case UO_Minus:
8462 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8463 if (!getElem(SubExprOffset, I))
8464 return false;
8465 if (!this->emitNeg(ElemT, E))
8466 return false;
8467 if (!this->emitInitElem(ElemT, I, E))
8468 return false;
8469 }
8470 break;
8471 case UO_LNot: { // !x
8472 // In C++, the logic operators !, &&, || are available for vectors. !v is
8473 // equivalent to v == 0.
8474 //
8475 // The result of the comparison is a vector of the same width and number of
8476 // elements as the comparison operands with a signed integral element type.
8477 //
8478 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
8479 QualType ResultVecTy = E->getType();
8480 PrimType ResultVecElemT =
8481 classifyPrim(ResultVecTy->getAs<VectorType>()->getElementType());
8482 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8483 if (!getElem(SubExprOffset, I))
8484 return false;
8485 // operator ! on vectors returns -1 for 'truth', so negate it.
8486 if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
8487 return false;
8488 if (!this->emitInv(E))
8489 return false;
8490 if (!this->emitPrimCast(PT_Bool, ElemT, VecTy->getElementType(), E))
8491 return false;
8492 if (!this->emitNeg(ElemT, E))
8493 return false;
8494 if (ElemT != ResultVecElemT &&
8495 !this->emitPrimCast(ElemT, ResultVecElemT, ResultVecTy, E))
8496 return false;
8497 if (!this->emitInitElem(ResultVecElemT, I, E))
8498 return false;
8499 }
8500 break;
8501 }
8502 case UO_Not: // ~x
8503 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8504 if (!getElem(SubExprOffset, I))
8505 return false;
8506 if (ElemT == PT_Bool) {
8507 if (!this->emitInv(E))
8508 return false;
8509 } else {
8510 if (!this->emitComp(ElemT, E))
8511 return false;
8512 }
8513 if (!this->emitInitElem(ElemT, I, E))
8514 return false;
8515 }
8516 break;
8517 default:
8518 llvm_unreachable("Unsupported unary operators should be handled up front");
8519 }
8520 return true;
8521}
8522
8523template <class Emitter>
8525 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
8526 if (DiscardResult)
8527 return true;
8528 return this->emitConst(ECD->getInitVal(), E);
8529 }
8530 if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) {
8531 if (DiscardResult)
8532 return true;
8533 const Function *F = getFunction(FuncDecl);
8534 return F && this->emitGetFnPtr(F, E);
8535 }
8536 if (const auto *TPOD = dyn_cast<TemplateParamObjectDecl>(D)) {
8537 TPOD = TPOD->getFirstDecl();
8538 if (DiscardResult)
8539 return true;
8540 if (UnsignedOrNone GlobalIndex = P.getGlobal(TPOD))
8541 return this->emitGetPtrGlobal(*GlobalIndex, E);
8542
8543 if (UnsignedOrNone Index = P.getOrCreateGlobal(TPOD)) {
8544 if (OptPrimType T = classify(TPOD->getType())) {
8545 if (!this->visitAPValue(TPOD->getValue(), *T, E))
8546 return false;
8547 return this->emitInitGlobal(*T, *Index, E);
8548 }
8549
8550 if (!this->emitGetPtrGlobal(*Index, E))
8551 return false;
8552 if (!this->visitAPValueInitializer(TPOD->getValue(), E, TPOD->getType()))
8553 return false;
8554 return this->emitFinishInit(E);
8555 }
8556 return false;
8557 }
8558
8559 // References are implemented via pointers, so when we see a DeclRefExpr
8560 // pointing to a reference, we need to get its value directly (i.e. the
8561 // pointer to the actual value) instead of a pointer to the pointer to the
8562 // value.
8563 QualType DeclType = D->getType();
8564 bool IsReference = DeclType->isReferenceType();
8565
8566 auto maybePopPtr = [&]() -> bool {
8567 if (DiscardResult)
8568 return this->emitPopPtr(E);
8569 return true;
8570 };
8571
8572 // Function parameters.
8573 // Note that it's important to check them first since we might have a local
8574 // variable created for a ParmVarDecl as well.
8575 if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
8576 if (DiscardResult)
8577 return true;
8578
8579 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
8580 !DeclType->isIntegralOrEnumerationType()) {
8581 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8582 /*InitializerFailed=*/false, E);
8583 }
8584 if (auto It = this->Params.find(PVD); It != this->Params.end()) {
8585 if (IsReference || !It->second.IsPtr)
8586 return this->emitGetParam(classifyPrim(E), It->second.Index, E);
8587
8588 return this->emitGetPtrParam(It->second.Index, E);
8589 }
8590
8591 if (!Ctx.getLangOpts().CPlusPlus23 && IsReference && !Locals.contains(D))
8592 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8593 /*InitializerFailed=*/false, E);
8594 }
8595
8596 // Local variables.
8597 if (auto It = Locals.find(D); It != Locals.end()) {
8598 const unsigned Offset = It->second.Offset;
8599 if (IsReference) {
8600 assert(classifyPrim(E) == PT_Ptr);
8601 return this->emitGetRefLocal(Offset, E) && maybePopPtr();
8602 }
8603 return this->emitGetPtrLocal(Offset, E) && maybePopPtr();
8604 }
8605 // Global variables.
8606 if (auto GlobalIndex = P.getGlobal(D)) {
8607 if (IsReference) {
8608 if (!Ctx.getLangOpts().CPlusPlus11)
8609 return this->emitGetGlobal(classifyPrim(E), *GlobalIndex, E);
8610 if (!Ctx.getLangOpts().CPlusPlus23)
8611 return this->emitGetGlobalUnchecked(classifyPrim(E), *GlobalIndex, E);
8612
8613 return this->emitGetRefGlobal(*GlobalIndex, E) && maybePopPtr();
8614 }
8615
8616 return this->emitGetPtrGlobal(*GlobalIndex, E) && maybePopPtr();
8617 }
8618
8619 // In case we need to re-visit a declaration.
8620 auto revisit = [&](const VarDecl *VD,
8621 bool IsConstexprUnknown = true) -> bool {
8623 IsConstexprUnknown);
8624 if constexpr (std::is_same_v<Emitter, EvalEmitter>) {
8625 if (!this->emitPushCC(VD->hasConstantInitialization(), E))
8626 return false;
8627 }
8628 auto VarState = this->visitDecl(VD);
8629
8630 if constexpr (std::is_same_v<Emitter, EvalEmitter>) {
8631 if (!this->emitPopCC(E))
8632 return false;
8633 }
8634
8635 if (VarState.notCreated())
8636 return true;
8637 if (!VarState)
8638 return false;
8639 // Retry.
8640 return this->visitDeclRef(D, E);
8641 };
8642
8643 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
8644 // Lambda captures.
8645 if (auto It = this->LambdaCaptures.find(D);
8646 It != this->LambdaCaptures.end()) {
8647 auto [Offset, IsPtr] = It->second;
8648
8649 if (IsPtr)
8650 return this->emitGetThisFieldPtr(Offset, E) && maybePopPtr();
8651 return this->emitGetPtrThisField(Offset, E) && maybePopPtr();
8652 }
8653 }
8654
8655 if (const auto *DRE = dyn_cast<DeclRefExpr>(E);
8656 DRE && DRE->refersToEnclosingVariableOrCapture()) {
8657 if (const auto *VD = dyn_cast<VarDecl>(D); VD && VD->isInitCapture())
8658 return revisit(VD);
8659 }
8660
8661 if (const auto *BD = dyn_cast<BindingDecl>(D))
8662 return this->delegate(BD->getBinding());
8663
8664 // Avoid infinite recursion.
8665 if (D == InitializingDecl) {
8666 if (DiscardResult)
8667 return true;
8668 return this->emitDummyPtr(D, E);
8669 }
8670
8671 // Try to lazily visit (or emit dummy pointers for) declarations
8672 // we haven't seen yet.
8673 const auto *VD = dyn_cast<VarDecl>(D);
8674 if (!VD)
8675 return this->emitError(E);
8676
8677 // For C.
8678 if (!Ctx.getLangOpts().CPlusPlus) {
8679 if (VD->getInit() && !VD->getInit()->isValueDependent() &&
8680 DeclType.isConstant(Ctx.getASTContext()) && !VD->isWeak() &&
8681 VD->evaluateValue())
8682 return revisit(VD, /*IsConstexprUnknown=*/false);
8683
8684 if (DiscardResult)
8685 return true;
8686 return this->emitDummyPtr(D, E);
8687 }
8688
8689 // ... and C++.
8690 const auto typeShouldBeVisited = [&](QualType T) -> bool {
8691 if (T.isConstant(Ctx.getASTContext()))
8692 return true;
8693 return T->isReferenceType();
8694 };
8695
8696 if ((VD->hasGlobalStorage() || VD->isStaticDataMember()) &&
8697 typeShouldBeVisited(DeclType)) {
8698 if (const Expr *Init = VD->getAnyInitializer();
8699 Init && !Init->isValueDependent()) {
8700 // Whether or not the evaluation is successul doesn't really matter
8701 // here -- we will create a global variable in any case, and that
8702 // will have the state of initializer evaluation attached.
8704 (void)Init->EvaluateAsInitializer(Ctx.getASTContext(), VD, Result, true);
8705 return this->visitDeclRef(D, E);
8706 }
8707 return revisit(VD, !VD->isConstexpr() && DeclType->isReferenceType());
8708 }
8709
8710 // FIXME: The evaluateValue() check here is a little ridiculous, since
8711 // it will ultimately call into Context::evaluateAsInitializer(). In
8712 // other words, we're evaluating the initializer, just to know if we can
8713 // evaluate the initializer.
8714 if (VD->isLocalVarDecl() && typeShouldBeVisited(DeclType) && VD->getInit() &&
8715 !VD->getInit()->isValueDependent()) {
8716 if (VD->evaluateValue()) {
8717 bool IsConstexprUnknown = !DeclType.isConstant(Ctx.getASTContext()) &&
8718 !DeclType->isReferenceType();
8719 // Revisit the variable declaration, but make sure it's associated with a
8720 // different evaluation, so e.g. mutable reads don't work on it.
8721 EvalIDScope _(Ctx);
8722 return revisit(VD, IsConstexprUnknown);
8723 } else if (Ctx.getLangOpts().CPlusPlus23 && IsReference)
8724 return revisit(VD, /*IsConstexprUnknown=*/true);
8725
8726 if (IsReference)
8727 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8728 /*InitializerFailed=*/true, E);
8729 }
8730
8731 if (DiscardResult)
8732 return true;
8733 return this->emitDummyPtr(
8734 D, E, Ctx.getLangOpts().CPlusPlus23 && DeclType->isReferenceType());
8735}
8736
8737template <class Emitter>
8739 const auto *D = E->getDecl();
8740 return this->visitDeclRef(D, E);
8741}
8742
8743template <class Emitter>
8745 const DesignatedInitUpdateExpr *E) {
8746 if (!this->visitInitializer(E->getBase()))
8747 return false;
8748 return this->visitInitializer(E->getUpdater());
8749}
8750
8751template <class Emitter> bool Compiler<Emitter>::emitCleanup() {
8752 for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent()) {
8753 if (!C->destroyLocals())
8754 return false;
8755 }
8756 return true;
8757}
8758
8759template <class Emitter>
8760unsigned Compiler<Emitter>::collectBaseOffset(const QualType BaseType,
8761 const QualType DerivedType) {
8762 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
8763 if (const auto *R = Ty->getPointeeCXXRecordDecl())
8764 return R;
8765 return Ty->getAsCXXRecordDecl();
8766 };
8767 const CXXRecordDecl *BaseDecl = extractRecordDecl(BaseType);
8768 const CXXRecordDecl *DerivedDecl = extractRecordDecl(DerivedType);
8769
8770 return Ctx.collectBaseOffset(BaseDecl, DerivedDecl);
8771}
8772
8773/// Emit casts from a PrimType to another PrimType.
8774template <class Emitter>
8775bool Compiler<Emitter>::emitPrimCast(PrimType FromT, PrimType ToT,
8776 QualType ToQT, const Expr *E) {
8777
8778 if (FromT == PT_Float) {
8779 // Floating to floating.
8780 if (ToT == PT_Float) {
8781 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8782 return this->emitCastFP(ToSem, getRoundingMode(E), E);
8783 }
8784
8785 if (ToT == PT_IntAP)
8786 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(ToQT),
8787 getFPOptions(E), E);
8788 if (ToT == PT_IntAPS)
8789 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(ToQT),
8790 getFPOptions(E), E);
8791
8792 // Float to integral.
8793 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8794 return this->emitCastFloatingIntegral(ToT, getFPOptions(E), E);
8795 }
8796
8797 if (isIntegerOrBoolType(FromT) || FromT == PT_Bool) {
8798 if (ToT == PT_IntAP)
8799 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8800 if (ToT == PT_IntAPS)
8801 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8802
8803 // Integral to integral.
8804 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8805 return FromT != ToT ? this->emitCast(FromT, ToT, E) : true;
8806
8807 if (ToT == PT_Float) {
8808 // Integral to floating.
8809 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8810 return this->emitCastIntegralFloating(FromT, ToSem, getFPOptions(E), E);
8811 }
8812 }
8813
8814 return false;
8815}
8816
8817template <class Emitter>
8818bool Compiler<Emitter>::emitIntegralCast(PrimType FromT, PrimType ToT,
8819 QualType ToQT, const Expr *E) {
8820 assert(FromT != ToT);
8821
8822 if (ToT == PT_IntAP)
8823 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8824 if (ToT == PT_IntAPS)
8825 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8826
8827 return this->emitCast(FromT, ToT, E);
8828}
8829
8830/// Emits __real(SubExpr)
8831template <class Emitter>
8832bool Compiler<Emitter>::emitComplexReal(const Expr *SubExpr) {
8833 assert(SubExpr->getType()->isAnyComplexType());
8834
8835 if (DiscardResult)
8836 return this->discard(SubExpr);
8837
8838 if (!this->visit(SubExpr))
8839 return false;
8840 if (SubExpr->isLValue()) {
8841 if (!this->emitConstUint8(0, SubExpr))
8842 return false;
8843 return this->emitArrayElemPtrPopUint8(SubExpr);
8844 }
8845
8846 // Rvalue, load the actual element.
8847 return this->emitArrayElemPop(classifyComplexElementType(SubExpr->getType()),
8848 0, SubExpr);
8849}
8850
8851template <class Emitter>
8852bool Compiler<Emitter>::emitComplexBoolCast(const Expr *E) {
8853 assert(!DiscardResult);
8854 PrimType ElemT = classifyComplexElementType(E->getType());
8855 // We emit the expression (__real(E) != 0 || __imag(E) != 0)
8856 // for us, that means (bool)E[0] || (bool)E[1]
8857 if (!this->emitArrayElem(ElemT, 0, E))
8858 return false;
8859 if (ElemT == PT_Float) {
8860 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8861 return false;
8862 } else {
8863 if (!this->emitCast(ElemT, PT_Bool, E))
8864 return false;
8865 }
8866
8867 // We now have the bool value of E[0] on the stack.
8868 LabelTy LabelTrue = this->getLabel();
8869 if (!this->jumpTrue(LabelTrue, E))
8870 return false;
8871
8872 if (!this->emitArrayElemPop(ElemT, 1, E))
8873 return false;
8874 if (ElemT == PT_Float) {
8875 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8876 return false;
8877 } else {
8878 if (!this->emitCast(ElemT, PT_Bool, E))
8879 return false;
8880 }
8881 // Leave the boolean value of E[1] on the stack.
8882 LabelTy EndLabel = this->getLabel();
8883 this->jump(EndLabel, E);
8884
8885 this->emitLabel(LabelTrue);
8886 if (!this->emitPopPtr(E))
8887 return false;
8888 if (!this->emitConstBool(true, E))
8889 return false;
8890
8891 this->fallthrough(EndLabel);
8892 this->emitLabel(EndLabel);
8893
8894 return true;
8895}
8896
8897template <class Emitter>
8898bool Compiler<Emitter>::emitComplexComparison(const Expr *LHS, const Expr *RHS,
8899 const BinaryOperator *E) {
8900 assert(E->isComparisonOp());
8901 assert(!Initializing);
8902 if (DiscardResult)
8903 return this->discard(LHS) && this->discard(RHS);
8904
8905 PrimType ElemT;
8906 bool LHSIsComplex;
8907 unsigned LHSOffset;
8908 if (LHS->getType()->isAnyComplexType()) {
8909 LHSIsComplex = true;
8910 ElemT = classifyComplexElementType(LHS->getType());
8911 LHSOffset = allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
8912 if (!this->visit(LHS))
8913 return false;
8914 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
8915 return false;
8916 } else {
8917 LHSIsComplex = false;
8918 PrimType LHST = classifyPrim(LHS->getType());
8919 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, /*IsConst=*/true);
8920 if (!this->visit(LHS))
8921 return false;
8922 if (!this->emitSetLocal(LHST, LHSOffset, E))
8923 return false;
8924 }
8925
8926 bool RHSIsComplex;
8927 unsigned RHSOffset;
8928 if (RHS->getType()->isAnyComplexType()) {
8929 RHSIsComplex = true;
8930 ElemT = classifyComplexElementType(RHS->getType());
8931 RHSOffset = allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
8932 if (!this->visit(RHS))
8933 return false;
8934 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
8935 return false;
8936 } else {
8937 RHSIsComplex = false;
8938 PrimType RHST = classifyPrim(RHS->getType());
8939 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, /*IsConst=*/true);
8940 if (!this->visit(RHS))
8941 return false;
8942 if (!this->emitSetLocal(RHST, RHSOffset, E))
8943 return false;
8944 }
8945
8946 auto getElem = [&](unsigned LocalOffset, unsigned Index,
8947 bool IsComplex) -> bool {
8948 if (IsComplex) {
8949 if (!this->emitGetLocal(PT_Ptr, LocalOffset, E))
8950 return false;
8951 return this->emitArrayElemPop(ElemT, Index, E);
8952 }
8953 return this->emitGetLocal(ElemT, LocalOffset, E);
8954 };
8955
8956 for (unsigned I = 0; I != 2; ++I) {
8957 // Get both values.
8958 if (!getElem(LHSOffset, I, LHSIsComplex))
8959 return false;
8960 if (!getElem(RHSOffset, I, RHSIsComplex))
8961 return false;
8962 // And compare them.
8963 if (!this->emitEQ(ElemT, E))
8964 return false;
8965
8966 if (!this->emitCastBoolUint8(E))
8967 return false;
8968 }
8969
8970 // We now have two bool values on the stack. Compare those.
8971 if (!this->emitAddUint8(E))
8972 return false;
8973 if (!this->emitConstUint8(2, E))
8974 return false;
8975
8976 if (E->getOpcode() == BO_EQ) {
8977 if (!this->emitEQUint8(E))
8978 return false;
8979 } else if (E->getOpcode() == BO_NE) {
8980 if (!this->emitNEUint8(E))
8981 return false;
8982 } else
8983 return false;
8984
8985 // In C, this returns an int.
8986 if (PrimType ResT = classifyPrim(E->getType()); ResT != PT_Bool)
8987 return this->emitCast(PT_Bool, ResT, E);
8988 return true;
8989}
8990
8991/// When calling this, we have a pointer of the local-to-destroy
8992/// on the stack.
8993/// Emit destruction of record types (or arrays of record types).
8994template <class Emitter>
8995bool Compiler<Emitter>::emitRecordDestructionPop(const Record *R,
8996 SourceInfo Loc) {
8997 assert(R);
8998 assert(!R->hasTrivialDtor());
8999 const CXXDestructorDecl *Dtor = R->getDestructor();
9000 assert(Dtor);
9001 const Function *DtorFunc = getFunction(Dtor);
9002 if (!DtorFunc)
9003 return false;
9004 assert(DtorFunc->hasThisPointer());
9005 assert(DtorFunc->getNumParams() == 1);
9006 return this->emitCall(DtorFunc, 0, Loc);
9007}
9008/// When calling this, we have a pointer of the local-to-destroy
9009/// on the stack.
9010/// Emit destruction of record types (or arrays of record types).
9011template <class Emitter>
9012bool Compiler<Emitter>::emitDestructionPop(const Descriptor *Desc,
9013 SourceInfo Loc) {
9014 assert(Desc);
9015 assert(!Desc->hasTrivialDtor());
9016
9017 // Arrays.
9018 if (Desc->isArray()) {
9019 const Descriptor *ElemDesc = Desc->ElemDesc;
9020 assert(ElemDesc);
9021
9022 unsigned N = Desc->getNumElems();
9023 if (N == 0)
9024 return this->emitPopPtr(Loc);
9025
9026 for (ssize_t I = N - 1; I >= 1; --I) {
9027 if (!this->emitConstUint64(I, Loc))
9028 return false;
9029 if (!this->emitArrayElemPtrUint64(Loc))
9030 return false;
9031 if (!this->emitDestructionPop(ElemDesc, Loc))
9032 return false;
9033 }
9034 // Last iteration, removes the instance pointer from the stack.
9035 if (!this->emitConstUint64(0, Loc))
9036 return false;
9037 if (!this->emitArrayElemPtrPopUint64(Loc))
9038 return false;
9039 return this->emitDestructionPop(ElemDesc, Loc);
9040 }
9041
9042 assert(Desc->ElemRecord);
9043 assert(!Desc->ElemRecord->hasTrivialDtor());
9044 return this->emitRecordDestructionPop(Desc->ElemRecord, Loc);
9045}
9046
9047/// Create a dummy pointer for the given decl (or expr) and
9048/// push a pointer to it on the stack.
9049template <class Emitter>
9050bool Compiler<Emitter>::emitDummyPtr(DeclOrExpr D, const Expr *E, bool CU) {
9051 assert(!DiscardResult && "Should've been checked before");
9052 return this->emitGetOpaquePtr(D, CU, E);
9053}
9054
9055template <class Emitter>
9056bool Compiler<Emitter>::emitFloat(const APFloat &F, SourceInfo Info) {
9057 if (Floating::singleWord(F.getSemantics()))
9058 return this->emitConstFloat(Floating(F), Info);
9059
9060 APInt I = F.bitcastToAPInt();
9061 return this->emitConstFloat(
9062 Floating(const_cast<uint64_t *>(I.getRawData()),
9063 llvm::APFloatBase::SemanticsToEnum(F.getSemantics())),
9064 Info);
9065}
9066
9067// This function is constexpr if and only if To, From, and the types of
9068// all subobjects of To and From are types T such that...
9069// (3.1) - is_union_v<T> is false;
9070// (3.2) - is_pointer_v<T> is false;
9071// (3.3) - is_member_pointer_v<T> is false;
9072// (3.4) - is_volatile_v<T> is false; and
9073// (3.5) - T has no non-static data members of reference type
9074template <class Emitter>
9075bool Compiler<Emitter>::emitBuiltinBitCast(const CastExpr *E) {
9076 const Expr *SubExpr = E->getSubExpr();
9077 QualType FromType = SubExpr->getType();
9078 QualType ToType = E->getType();
9079 OptPrimType ToT = classify(ToType);
9080
9081 assert(!ToType->isReferenceType());
9082
9083 // Prepare storage for the result in case we discard.
9084 if (DiscardResult && !Initializing && !ToT) {
9085 UnsignedOrNone LocalIndex = allocateLocal(E);
9086 if (!LocalIndex)
9087 return false;
9088 if (!this->emitGetPtrLocal(*LocalIndex, E))
9089 return false;
9090 }
9091
9092 // Get a pointer to the value-to-cast on the stack.
9093 // For CK_LValueToRValueBitCast, this is always an lvalue and
9094 // we later assume it to be one (i.e. a PT_Ptr). However,
9095 // we call this function for other utility methods where
9096 // a bitcast might be useful, so convert it to a PT_Ptr in that case.
9097 if (SubExpr->isGLValue() || FromType->isVectorType()) {
9098 if (!this->visit(SubExpr))
9099 return false;
9100 } else if (OptPrimType FromT = classify(SubExpr)) {
9101 unsigned TempOffset =
9102 allocateLocalPrimitive(SubExpr, *FromT, /*IsConst=*/true);
9103 if (!this->visit(SubExpr))
9104 return false;
9105 if (!this->emitSetLocal(*FromT, TempOffset, E))
9106 return false;
9107 if (!this->emitGetPtrLocal(TempOffset, E))
9108 return false;
9109 } else {
9110 return false;
9111 }
9112
9113 if (!ToT) {
9114 if (!this->emitBitCast(E))
9115 return false;
9116 return DiscardResult ? this->emitPopPtr(E) : true;
9117 }
9118 assert(ToT);
9119
9120 const llvm::fltSemantics *TargetSemantics = nullptr;
9121 if (ToT == PT_Float)
9122 TargetSemantics = &Ctx.getFloatSemantics(ToType);
9123
9124 // Conversion to a primitive type. FromType can be another
9125 // primitive type, or a record/array.
9126 bool ToTypeIsUChar = (ToType->isSpecificBuiltinType(BuiltinType::UChar) ||
9127 ToType->isSpecificBuiltinType(BuiltinType::Char_U));
9128 uint32_t ResultBitWidth = std::max(Ctx.getBitWidth(ToType), 8u);
9129
9130 if (!this->emitBitCastPrim(*ToT, ToTypeIsUChar || ToType->isStdByteType(),
9131 ResultBitWidth, TargetSemantics,
9132 ToType.getTypePtr(), E))
9133 return false;
9134
9135 if (DiscardResult)
9136 return this->emitPop(*ToT, E);
9137
9138 return true;
9139}
9140
9141/// Replicate a scalar value into every scalar element of an aggregate.
9142/// The scalar is stored in a local at \p SrcOffset and a pointer to the
9143/// destination must be on top of the interpreter stack. Each element receives
9144/// the scalar, cast to its own type.
9145template <class Emitter>
9146bool Compiler<Emitter>::emitHLSLAggregateSplat(PrimType SrcT,
9147 unsigned SrcOffset,
9148 QualType DestType,
9149 const Expr *E) {
9150 // Vectors and matrices are treated as flat sequences of elements.
9151 unsigned NumElems = 0;
9152 QualType ElemType;
9153 if (const auto *VT = DestType->getAs<VectorType>()) {
9154 NumElems = VT->getNumElements();
9155 ElemType = VT->getElementType();
9156 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
9157 NumElems = MT->getNumElementsFlattened();
9158 ElemType = MT->getElementType();
9159 }
9160 if (NumElems > 0) {
9161 PrimType ElemT = classifyPrim(ElemType);
9162 for (unsigned I = 0; I != NumElems; ++I) {
9163 if (!this->emitGetLocal(SrcT, SrcOffset, E))
9164 return false;
9165 if (!this->emitPrimCast(SrcT, ElemT, ElemType, E))
9166 return false;
9167 if (!this->emitInitElem(ElemT, I, E))
9168 return false;
9169 }
9170 return true;
9171 }
9172
9173 // Arrays: primitive elements are filled directly; composite elements
9174 // require recursion into each sub-aggregate.
9175 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
9176 const auto *CAT = cast<ConstantArrayType>(AT);
9177 QualType ArrElemType = CAT->getElementType();
9178 unsigned ArrSize = CAT->getZExtSize();
9179
9180 if (OptPrimType ElemT = classify(ArrElemType)) {
9181 for (unsigned I = 0; I != ArrSize; ++I) {
9182 if (!this->emitGetLocal(SrcT, SrcOffset, E))
9183 return false;
9184 if (!this->emitPrimCast(SrcT, *ElemT, ArrElemType, E))
9185 return false;
9186 if (!this->emitInitElem(*ElemT, I, E))
9187 return false;
9188 }
9189 } else {
9190 for (unsigned I = 0; I != ArrSize; ++I) {
9191 if (!this->emitConstUint32(I, E))
9192 return false;
9193 if (!this->emitArrayElemPtrUint32(E))
9194 return false;
9195 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, ArrElemType, E))
9196 return false;
9197 if (!this->emitFinishInitPop(E))
9198 return false;
9199 }
9200 }
9201 return true;
9202 }
9203
9204 // Records: fill base classes first, then named fields in declaration
9205 // order.
9206 if (DestType->isRecordType()) {
9207 const Record *R = getRecord(DestType);
9208 if (!R)
9209 return false;
9210
9211 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9212 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9213 const Record::Base *B = R->getBase(BS.getType());
9214 assert(B);
9215 if (!this->emitGetPtrBase(B->Offset, E))
9216 return false;
9217 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, BS.getType(), E))
9218 return false;
9219 if (!this->emitFinishInitPop(E))
9220 return false;
9221 }
9222 }
9223
9224 for (const Record::Field &F : R->fields()) {
9225 if (F.isUnnamedBitField())
9226 continue;
9227
9228 QualType FieldType = F.Decl->getType();
9229 if (OptPrimType FieldT = F.T) {
9230 if (!this->emitGetLocal(SrcT, SrcOffset, E))
9231 return false;
9232 if (!this->emitPrimCast(SrcT, *FieldT, FieldType, E))
9233 return false;
9234 if (F.isBitField()) {
9235 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
9236 return false;
9237 } else {
9238 if (!this->emitInitField(*FieldT, F.Offset, E))
9239 return false;
9240 }
9241 } else {
9242 if (!this->emitGetPtrField(F.Offset, E))
9243 return false;
9244 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, FieldType, E))
9245 return false;
9246 if (!this->emitPopPtr(E))
9247 return false;
9248 }
9249 }
9250 return true;
9251 }
9252
9253 return false;
9254}
9255
9256/// Return the total number of scalar elements in a type. This is used
9257/// to cap how many source elements are extracted during an elementwise cast,
9258/// so we never flatten more than the destination can hold.
9259template <class Emitter>
9260unsigned Compiler<Emitter>::countHLSLFlatElements(QualType Ty) {
9261 // Vector and matrix types are treated as flat sequences of elements.
9262 if (const auto *VT = Ty->getAs<VectorType>())
9263 return VT->getNumElements();
9264 if (const auto *MT = Ty->getAs<ConstantMatrixType>())
9265 return MT->getNumElementsFlattened();
9266 // Arrays: total count is array size * scalar elements per element.
9267 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
9268 const auto *CAT = cast<ConstantArrayType>(AT);
9269 return CAT->getZExtSize() * countHLSLFlatElements(CAT->getElementType());
9270 }
9271 // Records: sum scalar element counts of base classes and named fields.
9272 if (Ty->isRecordType()) {
9273 const Record *R = getRecord(Ty);
9274 if (!R)
9275 return 0;
9276 unsigned Count = 0;
9277 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9278 for (const CXXBaseSpecifier &BS : CXXRD->bases())
9279 Count += countHLSLFlatElements(BS.getType());
9280 }
9281 for (const Record::Field &F : R->fields()) {
9282 if (F.isUnnamedBitField())
9283 continue;
9284 Count += countHLSLFlatElements(F.Decl->getType());
9285 }
9286 return Count;
9287 }
9288 // Scalar primitive types contribute one element.
9289 if (canClassify(Ty))
9290 return 1;
9291 return 0;
9292}
9293
9294/// Walk a source aggregate and extract every scalar element into its own local
9295/// variable. The results are appended to \p Elements in declaration order,
9296/// stopping once \p MaxElements have been collected. A pointer to the
9297/// source aggregate must be stored in the local at \p SrcOffset.
9298template <class Emitter>
9299bool Compiler<Emitter>::emitHLSLFlattenAggregate(
9300 QualType SrcType, unsigned SrcOffset,
9301 SmallVectorImpl<HLSLFlatElement> &Elements, unsigned MaxElements,
9302 const Expr *E) {
9303
9304 // Save a scalar value from the stack into a new local and record it.
9305 auto saveToLocal = [&](PrimType T) -> bool {
9306 unsigned Offset = allocateLocalPrimitive(E, T, /*IsConst=*/true);
9307 if (!this->emitSetLocal(T, Offset, E))
9308 return false;
9309 Elements.push_back({Offset, T});
9310 return true;
9311 };
9312
9313 // Save a pointer from the stack into a new local for later use.
9314 auto savePtrToLocal = [&]() -> UnsignedOrNone {
9315 unsigned Offset = allocateLocalPrimitive(E, PT_Ptr, /*IsConst=*/true);
9316 if (!this->emitSetLocal(PT_Ptr, Offset, E))
9317 return std::nullopt;
9318 return Offset;
9319 };
9320
9321 // Vectors and matrices are flat sequences of elements.
9322 unsigned NumElems = 0;
9323 QualType ElemType;
9324 if (const auto *VT = SrcType->getAs<VectorType>()) {
9325 NumElems = VT->getNumElements();
9326 ElemType = VT->getElementType();
9327 } else if (const auto *MT = SrcType->getAs<ConstantMatrixType>()) {
9328 NumElems = MT->getNumElementsFlattened();
9329 ElemType = MT->getElementType();
9330 }
9331 if (NumElems > 0) {
9332 PrimType ElemT = classifyPrim(ElemType);
9333 for (unsigned I = 0; I != NumElems && Elements.size() < MaxElements; ++I) {
9334 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9335 return false;
9336 if (!this->emitArrayElemPop(ElemT, I, E))
9337 return false;
9338 if (!saveToLocal(ElemT))
9339 return false;
9340 }
9341 return true;
9342 }
9343
9344 // Arrays: primitive elements are extracted directly; composite elements
9345 // require recursion into each sub-aggregate.
9346 if (const auto *AT = SrcType->getAsArrayTypeUnsafe()) {
9347 const auto *CAT = cast<ConstantArrayType>(AT);
9348 QualType ArrElemType = CAT->getElementType();
9349 unsigned ArrSize = CAT->getZExtSize();
9350
9351 if (OptPrimType ElemT = classify(ArrElemType)) {
9352 for (unsigned I = 0; I != ArrSize && Elements.size() < MaxElements; ++I) {
9353 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9354 return false;
9355 if (!this->emitArrayElemPop(*ElemT, I, E))
9356 return false;
9357 if (!saveToLocal(*ElemT))
9358 return false;
9359 }
9360 } else {
9361 for (unsigned I = 0; I != ArrSize && Elements.size() < MaxElements; ++I) {
9362 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9363 return false;
9364 if (!this->emitConstUint32(I, E))
9365 return false;
9366 if (!this->emitArrayElemPtrPopUint32(E))
9367 return false;
9368 UnsignedOrNone ElemPtrOffset = savePtrToLocal();
9369 if (!ElemPtrOffset)
9370 return false;
9371 if (!emitHLSLFlattenAggregate(ArrElemType, *ElemPtrOffset, Elements,
9372 MaxElements, E))
9373 return false;
9374 }
9375 }
9376 return true;
9377 }
9378
9379 // Records: base classes come first, then named fields in declaration
9380 // order.
9381 if (SrcType->isRecordType()) {
9382 const Record *R = getRecord(SrcType);
9383 if (!R)
9384 return false;
9385
9386 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9387 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9388 if (Elements.size() >= MaxElements)
9389 break;
9390 const Record::Base *B = R->getBase(BS.getType());
9391 assert(B);
9392 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9393 return false;
9394 if (!this->emitGetPtrBasePop(B->Offset, /*NullOK=*/false, E))
9395 return false;
9396 UnsignedOrNone BasePtrOffset = savePtrToLocal();
9397 if (!BasePtrOffset)
9398 return false;
9399 if (!emitHLSLFlattenAggregate(BS.getType(), *BasePtrOffset, Elements,
9400 MaxElements, E))
9401 return false;
9402 }
9403 }
9404
9405 for (const Record::Field &F : R->fields()) {
9406 if (Elements.size() >= MaxElements)
9407 break;
9408 if (F.isUnnamedBitField())
9409 continue;
9410
9411 QualType FieldType = F.Decl->getType();
9412 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9413 return false;
9414 if (!this->emitGetPtrFieldPop(F.Offset, E))
9415 return false;
9416
9417 if (OptPrimType FieldT = F.T) {
9418 if (!this->emitLoadPop(*FieldT, E))
9419 return false;
9420 if (!saveToLocal(*FieldT))
9421 return false;
9422 } else {
9423 UnsignedOrNone FieldPtrOffset = savePtrToLocal();
9424 if (!FieldPtrOffset)
9425 return false;
9426 if (!emitHLSLFlattenAggregate(FieldType, *FieldPtrOffset, Elements,
9427 MaxElements, E))
9428 return false;
9429 }
9430 }
9431 return true;
9432 }
9433
9434 return false;
9435}
9436
9437/// Populate an HLSL aggregate from a flat list of previously extracted source
9438/// elements, casting each to the corresponding destination element type.
9439/// \p ElemIdx tracks the current position in \p Elements and is advanced as
9440/// elements are consumed. A pointer to the destination must be on top of the
9441/// interpreter stack.
9442template <class Emitter>
9443bool Compiler<Emitter>::emitHLSLConstructAggregate(
9444 QualType DestType, ArrayRef<HLSLFlatElement> Elements, unsigned &ElemIdx,
9445 const Expr *E) {
9446
9447 // Consume the next source element, cast it, and leave it on the stack.
9448 auto loadAndCast = [&](PrimType DestT, QualType DestQT) -> bool {
9449 const auto &Src = Elements[ElemIdx++];
9450 if (!this->emitGetLocal(Src.Type, Src.LocalOffset, E))
9451 return false;
9452 return this->emitPrimCast(Src.Type, DestT, DestQT, E);
9453 };
9454
9455 // Vectors and matrices are flat sequences of elements.
9456 unsigned NumElems = 0;
9457 QualType ElemType;
9458 if (const auto *VT = DestType->getAs<VectorType>()) {
9459 NumElems = VT->getNumElements();
9460 ElemType = VT->getElementType();
9461 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
9462 NumElems = MT->getNumElementsFlattened();
9463 ElemType = MT->getElementType();
9464 }
9465 if (NumElems > 0) {
9466 PrimType DestElemT = classifyPrim(ElemType);
9467 for (unsigned I = 0; I != NumElems; ++I) {
9468 if (!loadAndCast(DestElemT, ElemType))
9469 return false;
9470 if (!this->emitInitElem(DestElemT, I, E))
9471 return false;
9472 }
9473 return true;
9474 }
9475
9476 // Arrays: primitive elements are filled directly; composite elements
9477 // require recursion into each sub-aggregate.
9478 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
9479 const auto *CAT = cast<ConstantArrayType>(AT);
9480 QualType ArrElemType = CAT->getElementType();
9481 unsigned ArrSize = CAT->getZExtSize();
9482
9483 if (OptPrimType ElemT = classify(ArrElemType)) {
9484 for (unsigned I = 0; I != ArrSize; ++I) {
9485 if (!loadAndCast(*ElemT, ArrElemType))
9486 return false;
9487 if (!this->emitInitElem(*ElemT, I, E))
9488 return false;
9489 }
9490 } else {
9491 for (unsigned I = 0; I != ArrSize; ++I) {
9492 if (!this->emitConstUint32(I, E))
9493 return false;
9494 if (!this->emitArrayElemPtrUint32(E))
9495 return false;
9496 if (!emitHLSLConstructAggregate(ArrElemType, Elements, ElemIdx, E))
9497 return false;
9498 if (!this->emitFinishInitPop(E))
9499 return false;
9500 }
9501 }
9502 return true;
9503 }
9504
9505 // Records: base classes come first, then named fields in declaration
9506 // order.
9507 if (DestType->isRecordType()) {
9508 const Record *R = getRecord(DestType);
9509 if (!R)
9510 return false;
9511
9512 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9513 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9514 const Record::Base *B = R->getBase(BS.getType());
9515 assert(B);
9516 if (!this->emitGetPtrBase(B->Offset, E))
9517 return false;
9518 if (!emitHLSLConstructAggregate(BS.getType(), Elements, ElemIdx, E))
9519 return false;
9520 if (!this->emitFinishInitPop(E))
9521 return false;
9522 }
9523 }
9524
9525 for (const Record::Field &F : R->fields()) {
9526 if (F.isUnnamedBitField())
9527 continue;
9528
9529 QualType FieldType = F.Decl->getType();
9530 if (OptPrimType FieldT = F.T) {
9531 if (!loadAndCast(*FieldT, FieldType))
9532 return false;
9533 if (F.isBitField()) {
9534 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
9535 return false;
9536 } else {
9537 if (!this->emitInitField(*FieldT, F.Offset, E))
9538 return false;
9539 }
9540 } else {
9541 if (!this->emitGetPtrField(F.Offset, E))
9542 return false;
9543 if (!emitHLSLConstructAggregate(FieldType, Elements, ElemIdx, E))
9544 return false;
9545 if (!this->emitPopPtr(E))
9546 return false;
9547 }
9548 }
9549 return true;
9550 }
9551
9552 return false;
9553}
9554
9555namespace clang {
9556namespace interp {
9557
9558template class Compiler<ByteCodeEmitter>;
9559template class Compiler<EvalEmitter>;
9560
9561} // namespace interp
9562} // namespace clang
static bool visitAPValue(const APValue &Value, llvm::function_ref< bool(const APValue &)> Visitor)
Definition APValue.cpp:24
#define V(N, I)
static bool emit(llvm::SmallVectorImpl< std::byte > &Code, const T &Val)
Helper to write bytecode and bail out if 32-bit offsets become invalid.
static void emitCleanup(CIRGenFunction &cgf, cir::CleanupScopeOp cleanupScope, EHScopeStack::Cleanup *cleanup, EHScopeStack::Cleanup::Flags flags, Address activeFlag)
static uint32_t getBitWidth(const Expr *E)
static CharUnits alignOfType(QualType T, const ASTContext &ASTCtx, UnaryExprOrTypeTrait Kind)
#define EMIT_ARITH_OP(OP)
static const Expr * stripDerivedToBaseCasts(const Expr *E)
static bool isTrivialMemoryOperation(const CXXMethodDecl *MD)
static const Expr * stripCheckedDerivedToBaseCasts(const Expr *E)
static bool hasTrivialDefaultCtorParent(const FieldDecl *FD)
static bool initNeedsOverridenLoc(const CXXCtorInitializer *Init)
llvm::APSInt APSInt
Definition Compiler.cpp:26
const Expr * ignorePointerCastsAndParens(const Expr *E)
A more selective version of E->IgnoreParenCasts for tryEvaluateBuiltinObjectSize. This ignores some c...
bool isReadByLvalueToRvalueConversion(const CXXRecordDecl *RD)
Determine whether a type would actually be read by an lvalue-to-rvalue conversion.
unsigned ConvertBuiltinIDToX86BuiltinID(const ASTContext &Ctx, unsigned BuiltinOp)
Convert a builtin ID to the canonical x86 builtin ID the constant evaluators dispatch on in their x86...
TokenType getType() const
Returns the token's type, e.g.
Result
Implement __builtin_bit_cast and related operations.
llvm::SmallPtrSet< const ParmVarDecl *, 1 > FoundParams
bool VisitDeclRefExpr(const DeclRefExpr *E) override
a trap message and trap category.
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
const LValueBase getLValueBase() const
Definition APValue.cpp:1126
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:691
ArrayRef< LValuePathEntry > getLValuePath() const
Definition APValue.cpp:1146
APSInt & getInt()
Definition APValue.h:573
APValue & getStructField(unsigned i)
Definition APValue.h:736
const FieldDecl * getUnionField() const
Definition APValue.h:757
bool isVector() const
Definition APValue.h:555
APSInt & getComplexIntImag()
Definition APValue.h:611
unsigned getStructNumFields() const
Definition APValue.h:723
bool isComplexInt() const
Definition APValue.h:552
APValue & getStructVirtualBase(unsigned i)
Definition APValue.h:741
bool isArray() const
Definition APValue.h:557
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1216
unsigned getArrayInitializedElts() const
Definition APValue.h:710
bool isFloat() const
Definition APValue.h:550
unsigned getStructNumBases() const
Definition APValue.h:719
unsigned getStructNumVirtualBases() const
Definition APValue.h:727
bool hasLValuePath() const
Definition APValue.cpp:1141
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1209
APValue & getUnionValue()
Definition APValue.h:761
CharUnits & getLValueOffset()
Definition APValue.cpp:1136
bool isComplexFloat() const
Definition APValue.h:553
APValue & getVectorElt(unsigned I)
Definition APValue.h:647
APValue & getArrayFiller()
Definition APValue.h:702
unsigned getVectorLength() const
Definition APValue.h:655
bool isLValue() const
Definition APValue.h:554
bool isIndeterminate() const
Definition APValue.h:546
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1223
bool isMemberPointer() const
Definition APValue.h:560
bool isInt() const
Definition APValue.h:549
unsigned getArraySize() const
Definition APValue.h:714
bool isUnion() const
Definition APValue.h:559
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:165
bool isStruct() const
Definition APValue.h:558
bool isNullPointer() const
Definition APValue.cpp:1162
APSInt & getComplexIntReal()
Definition APValue.h:603
APFloat & getComplexFloatImag()
Definition APValue.h:627
APFloat & getComplexFloatReal()
Definition APValue.h:619
APFloat & getFloat()
Definition APValue.h:587
APValue & getStructBase(unsigned i)
Definition APValue.h:731
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
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.
const LangOptions & getLangOpts() const
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
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.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
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:4422
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4600
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4606
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4612
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition Expr.h:4619
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition Expr.h:6107
Represents a loop initializing the elements of an array.
Definition Expr.h:6054
llvm::APInt getArraySize() const
Definition Expr.h:6076
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:6069
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6074
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2790
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2819
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition ExprCXX.h:3011
uint64_t getValue() const
Definition ExprCXX.h:3059
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
Attr - This represents one attribute.
Definition Attr.h:47
Represents an attribute applied to a statement.
Definition Stmt.h:2214
Stmt * getSubStmt()
Definition Stmt.h:2250
ArrayRef< const Attr * > getAttrs() const
Definition Stmt.h:2246
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3526
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4240
Expr * getLHS() const
Definition Expr.h:4157
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4207
static bool isShiftOp(Opcode Opc)
Definition Expr.h:4195
static bool isCommaOp(Opcode Opc)
Definition Expr.h:4210
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4254
Expr * getRHS() const
Definition Expr.h:4159
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4184
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4243
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4248
Opcode getOpcode() const
Definition Expr.h:4152
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4198
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6758
BreakStmt - This represents a break.
Definition Stmt.h:3148
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition ExprCXX.h:5530
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents binding an expression to a temporary.
Definition ExprCXX.h:1498
const Expr * getSubExpr() const
Definition ExprCXX.h:1520
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:728
bool getValue() const
Definition ExprCXX.h:745
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1622
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1696
arg_range arguments()
Definition ExprCXX.h:1677
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1655
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1616
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1693
Represents a C++ constructor within a class.
Definition DeclCXX.h:2642
bool isDefaultConstructor() const
Whether this constructor is a default constructor (C++ [class.ctor]p5), which can be used to default-...
Definition DeclCXX.cpp:3049
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3069
Represents a C++ base or member initializer.
Definition DeclCXX.h:2407
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1275
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1382
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1137
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2631
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2670
bool isArrayForm() const
Definition ExprCXX.h:2657
bool isGlobalDelete() const
Definition ExprCXX.h:2656
Represents a C++ destructor within a class.
Definition DeclCXX.h:2907
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition ExprCXX.h:486
Represents the code generated for an expanded expansion statement.
Definition StmtCXX.h:1028
ArrayRef< Stmt * > getInstantiations() const
Definition StmtCXX.h:1069
ArrayRef< Stmt * > getPreambleStmts() const
Definition StmtCXX.h:1073
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:136
DeclStmt * getBeginStmt()
Definition StmtCXX.h:164
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:170
DeclStmt * getEndStmt()
Definition StmtCXX.h:167
DeclStmt * getRangeStmt()
Definition StmtCXX.h:163
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1756
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1793
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2293
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2730
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2895
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2360
bool isArray() const
Definition ExprCXX.h:2469
QualType getAllocatedType() const
Definition ExprCXX.h:2439
std::optional< Expr * > getArraySize()
This might return std::nullopt even if isArray() returns true, since there might not be an array size...
Definition ExprCXX.h:2474
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2508
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2499
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2464
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2538
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition ExprCXX.h:4363
bool getValue() const
Definition ExprCXX.h:4386
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:773
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5195
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5235
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1256
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1681
capture_const_range captures() const
Definition DeclCXX.h:1107
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1744
Represents a C++26 reflect expression [expr.reflect].
Definition ExprCXX.h:5562
ReflectionKind getKind() const
Definition ExprCXX.h:5599
const void * getOpaqueValue() const
Definition ExprCXX.h:5600
A C++ reinterpret_cast expression (C++ [expr.reinterpret.cast]).
Definition ExprCXX.h:531
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:291
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:309
An expression "T()" which creates an rvalue of a non-class type T.
Definition ExprCXX.h:2201
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition ExprCXX.h:805
Represents the this expression in C++.
Definition ExprCXX.h:1159
A C++ throw-expression (C++ [except.throw]).
Definition ExprCXX.h:1213
const Expr * getSubExpr() const
Definition ExprCXX.h:1233
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:70
CompoundStmt * getTryBlock()
Definition StmtCXX.h:101
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:853
bool isTypeOperand() const
Definition ExprCXX.h:889
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:168
Expr * getExprOperand() const
Definition ExprCXX.h:900
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:136
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1073
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1119
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
Expr * getCallee()
Definition Expr.h:3159
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3203
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3206
arg_range arguments()
Definition Expr.h:3264
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1635
CaseStmt - Represent a case statement.
Definition Stmt.h:1931
Stmt * getSubStmt()
Definition Stmt.h:2044
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3745
path_iterator path_begin()
Definition Expr.h:3815
CastKind getCastKind() const
Definition Expr.h:3789
llvm::iterator_range< path_iterator > path()
Path through the class hierarchy taken by casts between base and derived classes (see implementation ...
Definition Expr.h:3832
const FieldDecl * getTargetUnionField() const
Definition Expr.h:3839
path_iterator path_end()
Definition Expr.h:3816
Expr * getSubExpr()
Definition Expr.h:3795
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
unsigned getValue() const
Definition Expr.h:1674
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4917
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4953
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3362
QualType getElementType() const
Definition TypeBase.h:3372
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4369
QualType getComputationLHSType() const
Definition Expr.h:4403
QualType getComputationResultType() const
Definition Expr.h:4406
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3674
bool isFileScope() const
Definition Expr.h:3706
const Expr * getInitializer() const
Definition Expr.h:3702
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1751
body_range body()
Definition Stmt.h:1814
Stmt * body_back()
Definition Stmt.h:1819
Represents the specialization of a concept - evaluates to a prvalue of type bool.
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3934
An expression that occurs in a constant context and the result of evaluating the expression.
Definition Expr.h:1127
APValue getAPValueResult() const
Definition Expr.cpp:419
bool hasAPValueResult() const
Definition Expr.h:1202
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4490
ContinueStmt - This represents a continue.
Definition Stmt.h:3132
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition Expr.h:4788
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4878
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2121
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
ValueDecl * getDecl()
Definition Expr.h:1383
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1642
decl_range decls()
Definition Stmt.h:1690
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInvalidDecl() const
Definition DeclBase.h:597
bool hasAttr() const
Definition DeclBase.h:586
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
Stmt * getSubStmt()
Definition Stmt.h:2092
InitListExpr * getUpdater() const
Definition Expr.h:6022
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2843
Stmt * getBody()
Definition Stmt.h:2868
Expr * getCond()
Definition Stmt.h:2861
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
Recursively visit a statement or expression, by dispatching to Traverse*() based on the argument's dy...
const Expr * getBase() const
Definition Expr.h:6667
Represents a reference to emded data.
Definition Expr.h:5204
ChildElementIter< false > begin()
Definition Expr.h:5310
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3715
This represents one expression.
Definition Expr.h:114
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:85
bool isGLValue() const
Definition Expr.h:289
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:179
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3117
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:248
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool isPRValue() const
Definition Expr.h:287
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:286
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:3728
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:3292
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:481
QualType getType() const
Definition Expr.h:146
An expression trait intrinsic.
Definition ExprCXX.h:3084
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6696
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4598
Represents a member of a struct/union/class.
Definition Decl.h:3311
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3547
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1620
llvm::APFloat getValue() const
Definition Expr.h:1711
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2899
Stmt * getInit()
Definition Stmt.h:2914
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2943
Expr * getInc()
Definition Stmt.h:2942
Expr * getCond()
Definition Stmt.h:2941
DeclStmt * getConditionVariableDeclStmt()
If this ForStmt has a condition variable, return the faux DeclStmt associated with the creation of th...
Definition Stmt.h:2929
const Expr * getSubExpr() const
Definition Expr.h:1107
Represents a function declaration or definition.
Definition Decl.h:2071
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2944
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3279
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4262
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4250
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3817
QualType getReturnType() const
Definition Decl.h:2992
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2917
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2516
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4386
bool isUsableAsGlobalAllocationFunctionInConstantEvaluation(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions described in i...
Definition Decl.cpp:3481
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2524
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3881
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3199
Declaration of a template function.
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, llvm::FoldingSetInsertToken &InsertToken)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4992
Represents a C11 generic selection.
Definition Expr.h:6268
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6554
IfStmt - This represents an if/then/else.
Definition Stmt.h:2270
Stmt * getThen()
Definition Stmt.h:2359
Stmt * getInit()
Definition Stmt.h:2420
bool isNonNegatedConsteval() const
Definition Stmt.h:2455
Expr * getCond()
Definition Stmt.h:2347
bool isNegatedConsteval() const
Definition Stmt.h:2459
Stmt * getElse()
Definition Stmt.h:2368
DeclStmt * getConditionVariableDeclStmt()
If this IfStmt has a condition variable, return the faux DeclStmt associated with the creation of tha...
Definition Stmt.h:2403
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1776
const Expr * getSubExpr() const
Definition Expr.h:1788
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6143
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3618
Describes an C or C++ initializer list.
Definition Expr.h:5377
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5491
ArrayRef< Expr * > inits() const
Definition Expr.h:5441
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1973
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2099
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1432
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool isCompatibleWith(ClangABI Version) const
Implicit declaration of a temporary that was materialized by a MaterializeTemporaryExpr and lifetime-...
Definition DeclCXX.h:3338
bool isNamed() const
Definition Stmt.h:3101
const Stmt * getNamedLoopOrSwitch() const
If this is a named break/continue, get the loop or switch statement that this targets.
Definition Stmt.cpp:1535
A global _GUID constant.
Definition DeclCXX.h:4451
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
Definition DeclCXX.cpp:3931
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4974
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4999
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4991
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:5024
LifetimeExtendedTemporaryDecl * getLifetimeExtendedTemporaryDecl()
Definition ExprCXX.h:5014
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3516
Expr * getBase() const
Definition Expr.h:3510
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
This represents a decl that may have a name.
Definition Decl.h:276
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:342
Represents a C++ namespace alias.
Definition DeclCXX.h:3231
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition ExprObjC.h:219
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition ExprObjC.h:118
ObjCBoxedExpr - used for generalized expression boxing.
Definition ExprObjC.h:158
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition ExprObjC.h:341
ObjCEncodeExpr, used for @encode in Objective-C.
Definition ExprObjC.h:440
QualType getEncodedType() const
Definition ExprObjC.h:459
SourceLocation getAtLoc() const
Definition ExprObjC.h:454
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:67
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:83
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2596
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2655
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2643
unsigned getNumComponents() const
Definition Expr.h:2651
Helper class for OffsetOfExpr.
Definition Expr.h:2490
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2548
@ Array
An index into an array.
Definition Expr.h:2495
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2544
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1223
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1273
Expr * getSelectedExpr() const
Definition ExprCXX.h:4693
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2251
const Expr * getSubExpr() const
Definition Expr.h:2268
Represents a parameter to a function.
Definition Decl.h:1832
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
QualType getPointeeType() const
Definition TypeBase.h:3413
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2074
StringLiteral * getFunctionName()
Definition Expr.h:2118
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6890
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6938
ArrayRef< Expr * > semantics()
Definition Expr.h:6962
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8530
QualType withConst() const
Definition TypeBase.h:1175
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8446
bool isConstant(const ASTContext &Ctx) const
Definition TypeBase.h:1098
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8519
Represents a struct/union/class.
Definition Decl.h:4476
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7589
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3678
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
bool isSatisfied() const
Whether or not the requires clause is satisfied.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3173
Expr * getRetValue()
Definition Stmt.h:3200
SourceLocation getLocation() const
Definition Expr.h:2224
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:597
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4712
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4764
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4745
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4751
Represents an expression that computes the length of a parameter pack.
Definition ExprCXX.h:4495
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4569
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition Expr.h:5095
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2319
Represents a C++11 static_assert declaration.
Definition DeclCXX.h:4166
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4664
CompoundStmt * getSubStmt()
Definition Expr.h:4681
Stmt - This represents one statement.
Definition Stmt.h:85
StmtClass getStmtClass() const
Definition Stmt.h:1504
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
unsigned getLength() const
Definition Expr.h:1969
uint32_t getCodeUnit(size_t I) const
Return the code unit at the given position.
Definition Expr.h:1931
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1198
unsigned getCharByteWidth() const
Definition Expr.h:1971
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4718
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1904
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2520
Expr * getCond()
Definition Stmt.h:2583
Stmt * getBody()
Definition Stmt.h:2595
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2600
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2651
DeclStmt * getConditionVariableDeclStmt()
If this SwitchStmt has a condition variable, return the faux DeclStmt associated with the creation of...
Definition Stmt.h:2634
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3868
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3969
bool isUnion() const
Definition Decl.h:4079
A template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
Symbolic representation of typeid(T) for some type T.
Definition APValue.h:48
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition ExprCXX.h:2901
bool getBoolValue() const
Definition ExprCXX.h:2962
bool isStoredAsComparisonResult() const
Definition ExprCXX.h:2958
const APValue & getAPValue() const
Definition ExprCXX.h:2967
bool isStoredAsBoolean() const
Definition ExprCXX.h:2954
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9068
bool isBooleanType() const
Definition TypeBase.h:9209
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3239
bool isIncompleteArrayType() const
Definition TypeBase.h:8790
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isNothrowT() const
Definition Type.cpp:3430
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:845
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2645
bool isArrayType() const
Definition TypeBase.h:8782
bool isFunctionPointerType() const
Definition TypeBase.h:8750
bool isConstantMatrixType() const
Definition TypeBase.h:8850
bool isPointerType() const
Definition TypeBase.h:8683
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9116
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9366
bool isReferenceType() const
Definition TypeBase.h:8707
bool isEnumeralType() const
Definition TypeBase.h:8814
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9194
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9037
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2863
bool isAnyComplexType() const
Definition TypeBase.h:8818
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9132
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9252
bool isMemberPointerType() const
Definition TypeBase.h:8764
bool isAtomicType() const
Definition TypeBase.h:8875
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isStdByteType() const
Definition Type.cpp:3449
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9352
bool isPointerOrReferenceType() const
Definition TypeBase.h:8687
bool isFunctionType() const
Definition TypeBase.h:8679
bool isVectorType() const
Definition TypeBase.h:8822
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2533
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:3002
bool isFloatingType() const
Definition Type.cpp:2517
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9299
bool isRecordType() const
Definition TypeBase.h:8810
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2791
bool hasBooleanRepresentation() const
Determine whether this type has a boolean representation – i.e., it is a boolean type,...
Definition Type.cpp:2572
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3713
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2694
QualType getArgumentType() const
Definition Expr.h:2737
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2763
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2726
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2367
Represents C++ using-directive.
Definition DeclCXX.h:3126
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5671
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:934
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1606
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1615
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1308
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1249
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2654
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1216
const Expr * getInit() const
Definition Decl.h:1393
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2561
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1276
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1383
Represents a GCC generic vector type.
Definition TypeBase.h:4273
unsigned getNumElements() const
Definition TypeBase.h:4288
QualType getElementType() const
Definition TypeBase.h:4287
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2708
Expr * getCond()
Definition Stmt.h:2760
DeclStmt * getConditionVariableDeclStmt()
If this WhileStmt has a condition variable, return the faux DeclStmt associated with the creation of ...
Definition Stmt.h:2796
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2772
ArrayIndexScope(Compiler< Emitter > *Ctx, uint64_t Index)
Definition Compiler.cpp:216
A memory block, either on the stack or in the heap.
Definition Block.h:43
void invokeDtor()
Invokes the Destructor.
Definition Block.h:150
Compilation context for expressions.
Definition Compiler.h:116
llvm::SmallVector< InitLink > InitStack
Definition Compiler.h:503
bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E)
bool VisitCXXDeleteExpr(const CXXDeleteExpr *E)
bool VisitOffsetOfExpr(const OffsetOfExpr *E)
bool visitContinueStmt(const ContinueStmt *S)
bool VisitCharacterLiteral(const CharacterLiteral *E)
bool visitArrayElemInit(unsigned ElemIndex, const Expr *Init, OptPrimType InitT)
Pointer to the array(not the element!) must be on the stack when calling this.
bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E)
bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E)
bool visitInitializerPop(const Expr *E)
Similar, but will also pop the pointer.
bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
bool visitBool(const Expr *E)
Visits an expression and converts it to a boolean.
bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
PrimType classifyPrim(QualType Ty) const
Classifies a known primitive type.
Definition Compiler.h:297
bool VisitTypeTraitExpr(const TypeTraitExpr *E)
bool VisitLambdaExpr(const LambdaExpr *E)
bool VisitMemberExpr(const MemberExpr *E)
llvm::DenseMap< const OpaqueValueExpr *, unsigned > OpaqueExprs
OpaqueValueExpr to location mapping.
Definition Compiler.h:478
bool VisitBinaryOperator(const BinaryOperator *E)
bool visitCXXExpansionStmtInstantiation(const CXXExpansionStmtInstantiation *S)
template for (auto x : {1, 2}) {}
bool visitAttributedStmt(const AttributedStmt *S)
bool VisitPackIndexingExpr(const PackIndexingExpr *E)
bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
bool VisitCallExpr(const CallExpr *E)
std::optional< uint64_t > ArrayIndex
Current argument index. Needed to emit ArrayInitIndexExpr.
Definition Compiler.h:484
bool VisitPseudoObjectExpr(const PseudoObjectExpr *E)
bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E)
bool visitAPValueInitializer(const APValue &Val, SourceInfo Info, QualType T, bool IsCompleteClass=true)
const Function * getFunction(const FunctionDecl *FD)
Returns a function for the given FunctionDecl.
bool VisitFixedPointBinOp(const BinaryOperator *E)
bool VisitCastExpr(const CastExpr *E)
Definition Compiler.cpp:447
bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E)
bool VisitFixedPointUnaryOperator(const UnaryOperator *E)
bool VisitComplexUnaryOperator(const UnaryOperator *E)
llvm::DenseMap< const SwitchCase *, LabelTy > CaseMap
Definition Compiler.h:122
bool VisitBlockExpr(const BlockExpr *E)
bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E)
bool VisitLogicalBinOp(const BinaryOperator *E)
bool visitCompoundStmt(const CompoundStmt *S)
Context & Ctx
Current compilation context.
Definition Compiler.h:139
const VarDecl * InitializingDecl
Definition Compiler.h:501
bool visitDeclRef(const ValueDecl *D, const Expr *E)
Visit the given decl as if we have a reference to it.
bool visitBreakStmt(const BreakStmt *S)
bool visitExpr(const Expr *E, bool DestroyToplevelScope) override
bool visitForStmt(const ForStmt *S)
bool VisitDeclRefExpr(const DeclRefExpr *E)
bool VisitOpaqueValueExpr(const OpaqueValueExpr *E)
bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E)
bool visitAPValue(const APValue &Val, PrimType ValType, SourceInfo Info)
Visit an APValue.
bool VisitStmtExpr(const StmtExpr *E)
bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E)
bool VisitFixedPointLiteral(const FixedPointLiteral *E)
const FunctionDecl * CompilingFunction
Definition Compiler.h:514
bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E)
VarCreationState visitVarDecl(const VarDecl *VD, const Expr *Init, bool Toplevel=false)
Creates and initializes a variable from the given decl.
VariableScope< Emitter > * VarScope
Current scope.
Definition Compiler.h:481
bool visitDeclAndReturn(const VarDecl *VD, const Expr *Init, bool ConstantContext) override
Toplevel visitDeclAndReturn().
bool VisitCXXNewExpr(const CXXNewExpr *E)
bool VisitCompoundAssignOperator(const CompoundAssignOperator *E)
bool visit(const Expr *E) override
Evaluates an expression and places the result on the stack.
bool delegate(const Expr *E)
Just pass evaluation on to E.
bool visitLValueExpr(const Expr *E, bool DestroyToplevelScope) override
bool discard(const Expr *E)
Evaluates an expression for side effects and discards the result.
bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
CaseMap CaseLabels
Switch case mapping.
Definition Compiler.h:510
Record * getRecord(QualType Ty)
Returns a record from a record or pointer type.
bool VisitCXXReflectExpr(const CXXReflectExpr *E)
const RecordType * getRecordTy(QualType Ty)
Returns a record type from a record or pointer type.
bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E)
bool visitInitList(ArrayRef< const Expr * > Inits, const Expr *ArrayFiller, const Expr *E)
bool VisitSizeOfPackExpr(const SizeOfPackExpr *E)
bool VisitPredefinedExpr(const PredefinedExpr *E)
bool VisitSourceLocExpr(const SourceLocExpr *E)
bool visitDeclStmt(const DeclStmt *DS, bool EvaluateConditionDecl=false)
bool registerRedecl(const VarDecl *VD, const APValue &V)
bool emitCleanup()
Emits scope cleanup instructions.
bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E)
bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E)
bool visitInitializer(const Expr *E)
Compiles an initializer.
bool visitDtorCall(const VarDecl *VD, const APValue &Value) override
const Expr * SourceLocDefaultExpr
DefaultInit- or DefaultArgExpr, needed for SourceLocExpr.
Definition Compiler.h:487
bool VisitObjCArrayLiteral(const ObjCArrayLiteral *E)
UnsignedOrNone OptLabelTy
Definition Compiler.h:121
bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E)
bool VisitPointerArithBinOp(const BinaryOperator *E)
Perform addition/subtraction of a pointer and an integer or subtraction of two pointers.
bool visitCallArgs(ArrayRef< const Expr * > Args, const FunctionDecl *FuncDecl, bool Activate, bool IsOperatorCall)
bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E)
bool visitDefaultStmt(const DefaultStmt *S)
bool VisitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E)
bool visitWithSubstitutions(const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This, const Expr *Condition) override
Evaluate the Condition as if it was in the body of Callee.
typename Emitter::LabelTy LabelTy
Definition Compiler.h:119
VarCreationState visitDecl(const VarDecl *VD)
bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E)
bool visitStmt(const Stmt *S)
bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E)
bool VisitVectorUnaryOperator(const UnaryOperator *E)
bool VisitCXXConstructExpr(const CXXConstructExpr *E)
bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E)
bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E)
bool VisitRecoveryExpr(const RecoveryExpr *E)
bool VisitRequiresExpr(const RequiresExpr *E)
bool Initializing
Flag inidicating if we're initializing an already created variable.
Definition Compiler.h:500
bool visitReturnStmt(const ReturnStmt *RS)
bool VisitCXXThrowExpr(const CXXThrowExpr *E)
bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
bool VisitChooseExpr(const ChooseExpr *E)
bool visitFunc(const FunctionDecl *F) override
bool visitCXXForRangeStmt(const CXXForRangeStmt *S)
bool visitCaseStmt(const CaseStmt *S)
bool VisitComplexBinOp(const BinaryOperator *E)
llvm::DenseMap< const ValueDecl *, Scope::Local > Locals
Variable to storage mapping.
Definition Compiler.h:475
bool VisitAbstractConditionalOperator(const AbstractConditionalOperator *E)
bool VisitCXXTypeidExpr(const CXXTypeidExpr *E)
UnsignedOrNone allocateTemporary(const Expr *E)
bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinID)
bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E)
OptPrimType ReturnType
Type of the expression returned by the function.
Definition Compiler.h:507
bool VisitUnaryOperator(const UnaryOperator *E)
bool VisitFloatCompoundAssignOperator(const CompoundAssignOperator *E)
OptPrimType classify(const Expr *E) const
Definition Compiler.h:291
llvm::SmallVector< LabelInfo > LabelInfoStack
Stack of label information for loops and switch statements.
Definition Compiler.h:512
bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
bool visitDoStmt(const DoStmt *S)
bool VisitIntegerLiteral(const IntegerLiteral *E)
bool VisitInitListExpr(const InitListExpr *E)
bool VisitVectorBinOp(const BinaryOperator *E)
bool VisitStringLiteral(const StringLiteral *E)
bool VisitParenExpr(const ParenExpr *E)
bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E)
bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E)
bool VisitPointerCompoundAssignOperator(const CompoundAssignOperator *E)
bool DiscardResult
Flag indicating if return value is to be discarded.
Definition Compiler.h:490
bool VisitEmbedExpr(const EmbedExpr *E)
UnsignedOrNone allocateLocal(DeclOrExpr Decl, QualType Ty=QualType(), ScopeKind=ScopeKind::Block)
Allocates a space storing a local given its type.
bool VisitConvertVectorExpr(const ConvertVectorExpr *E)
bool VisitCXXThisExpr(const CXXThisExpr *E)
bool VisitConstantExpr(const ConstantExpr *E)
bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
bool visitSwitchStmt(const SwitchStmt *S)
bool VisitCXXUuidofExpr(const CXXUuidofExpr *E)
bool VisitExprWithCleanups(const ExprWithCleanups *E)
bool visitAsLValue(const Expr *E)
unsigned allocateLocalPrimitive(DeclOrExpr Decl, PrimType Ty, bool IsConst, bool IsVolatile=false, ScopeKind SC=ScopeKind::Block)
Creates a local primitive value.
bool visitWhileStmt(const WhileStmt *S)
bool visitIfStmt(const IfStmt *IS)
bool VisitAddrLabelExpr(const AddrLabelExpr *E)
bool canClassify(const Expr *E) const
Definition Compiler.h:293
bool VisitFloatingLiteral(const FloatingLiteral *E)
Program & P
Program to link to.
Definition Compiler.h:141
bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E)
bool VisitGNUNullExpr(const GNUNullExpr *E)
bool VisitImaginaryLiteral(const ImaginaryLiteral *E)
bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E)
bool visitCXXTryStmt(const CXXTryStmt *S)
static bool isUnevaluatedBuiltin(unsigned ID)
Unevaluated builtins don't get their arguments put on the stack automatically.
Definition Context.cpp:837
static bool shouldBeGloballyIndexed(const ValueDecl *VD)
Returns whether we should create a global variable for the given ValueDecl.
Definition Context.h:175
Scope used to handle temporaries in toplevel variable declarations.
Definition Compiler.cpp:285
DeclScope(Compiler< Emitter > *Ctx, const VarDecl *VD)
Definition Compiler.cpp:287
Wrapper around fixed point types.
Definition FixedPoint.h:23
static FixedPoint zero(llvm::FixedPointSemantics Sem)
Definition FixedPoint.h:36
If a Floating is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition Floating.h:35
bool singleWord() const
Definition Floating.h:107
Bytecode function.
Definition Function.h:98
bool hasThisPointer() const
Definition Function.h:230
bool hasRVO() const
Checks if the first argument is a RVO pointer.
Definition Function.h:160
InitLinkScope(Compiler< Emitter > *Ctx, InitLink &&Link)
Definition Compiler.cpp:251
Compiler< Emitter > * Ctx
Definition Compiler.cpp:258
InitStackScope(Compiler< Emitter > *Ctx, bool Active)
Definition Compiler.cpp:263
When generating code for e.g.
Definition Compiler.cpp:422
LocOverrideScope(Compiler< Emitter > *Ctx, SourceInfo NewValue, bool Enabled=true)
Definition Compiler.cpp:424
Generic scope for local variables.
Definition Compiler.cpp:121
UnsignedOrNone Idx
Index of the scope in the chain.
Definition Compiler.cpp:210
~LocalScope() override
Emit a Destroy op for this scope.
Definition Compiler.cpp:127
bool destroyLocals(const Expr *E=nullptr) override
Explicit destruction of local variables.
Definition Compiler.cpp:134
bool emitDestructors(const Expr *E=nullptr) override
Definition Compiler.cpp:156
void removeIfStoredOpaqueValue(const Scope::Local &Local)
Definition Compiler.cpp:202
void addLocal(Scope::Local Local) override
Definition Compiler.cpp:146
LocalScope(Compiler< Emitter > *Ctx, ScopeKind Kind=ScopeKind::Block)
Definition Compiler.cpp:123
Sets the context for break/continue statements.
Definition Compiler.cpp:361
typename Compiler< Emitter >::LabelTy LabelTy
Definition Compiler.cpp:363
typename Compiler< Emitter >::OptLabelTy OptLabelTy
Definition Compiler.cpp:364
typename Compiler< Emitter >::LabelInfo LabelInfo
Definition Compiler.cpp:365
LoopScope(Compiler< Emitter > *Ctx, const Stmt *Name, LabelTy BreakLabel, LabelTy ContinueLabel)
Definition Compiler.cpp:367
PrimType value_or(PrimType PT) const
Definition PrimType.h:90
Scope used to handle initialization methods.
Definition Compiler.cpp:305
OptionScope(Compiler< Emitter > *Ctx, bool NewDiscardResult, bool NewInitializing, bool NewToLValue)
Root constructor, compiling or discarding primitives.
Definition Compiler.cpp:308
Context to manage declaration lifetimes.
Definition Program.h:139
Structure/Class descriptor.
Definition Record.h:27
bool isUnion() const
Checks if the record is a union.
Definition Record.h:71
const Field * getField(unsigned I) const
Definition Record.h:97
const Base * getBaseOrNull(const RecordDecl *RD) const
Definition Record.cpp:56
bool hasTrivialDtor() const
Returns true for anonymous unions and records with no destructor or for those with a trivial destruct...
Definition Record.cpp:34
const Base * findVirtualBase(const RecordDecl *RD) const
Returns a virtual base descriptor.
Definition Record.cpp:75
Describes a scope block.
Definition Function.h:35
Describes the statement/declaration an opcode was generated from.
Definition Source.h:77
const Expr * asExpr() const
Definition Source.h:92
SourceLocScope(Compiler< Emitter > *Ctx, const Expr *DefaultExpr)
Definition Compiler.cpp:230
typename Compiler< Emitter >::LabelTy LabelTy
Definition Compiler.cpp:389
typename Compiler< Emitter >::OptLabelTy OptLabelTy
Definition Compiler.cpp:390
typename Compiler< Emitter >::LabelInfo LabelInfo
Definition Compiler.cpp:392
typename Compiler< Emitter >::CaseMap CaseMap
Definition Compiler.cpp:391
SwitchScope(Compiler< Emitter > *Ctx, const Stmt *Name, CaseMap &&CaseLabels, LabelTy BreakLabel, OptLabelTy DefaultLabel)
Definition Compiler.cpp:394
Scope chain managing the variable lifetimes.
Definition Compiler.cpp:64
void addForScopeKind(const Scope::Local &Local, ScopeKind Kind)
Like addExtended, but adds to the nearest scope of the given kind.
Definition Compiler.cpp:79
bool LocalsAlwaysEnabled
Whether locals added to this scope are enabled by default.
Definition Compiler.cpp:110
Compiler< Emitter > * Ctx
Compiler instance.
Definition Compiler.cpp:114
virtual bool emitDestructors(const Expr *E=nullptr)
Definition Compiler.cpp:102
VariableScope(Compiler< Emitter > *Ctx, ScopeKind Kind=ScopeKind::Block)
Definition Compiler.cpp:66
virtual bool destroyLocals(const Expr *E=nullptr)
Definition Compiler.cpp:103
virtual void addLocal(Scope::Local Local)
Definition Compiler.cpp:75
VariableScope * Parent
Link to the parent scope.
Definition Compiler.cpp:116
ScopeKind getKind() const
Definition Compiler.cpp:105
VariableScope * getParent() const
Definition Compiler.cpp:104
uint16_t getPointerAuthTypeDiscriminator(CodeGenModule &CGM, QualType FunctionType)
Return a type discriminator for the given function type.
bool Sub(InterpState &S, CodePtr OpPC)
Definition Interp.h:428
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1520
static llvm::RoundingMode getRoundingMode(FPOptions FPO)
constexpr bool isSignedType(PrimType T)
Definition PrimType.h:61
bool Div(InterpState &S, CodePtr OpPC)
1) Pops the RHS from the stack.
Definition Interp.h:773
constexpr bool isPtrType(PrimType T)
Definition PrimType.h:57
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:218
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3218
constexpr bool isIntegerOrBoolType(PrimType T)
Definition PrimType.h:54
llvm::APFloat APFloat
Definition Floating.h:27
static void discard(InterpStack &Stk, PrimType T)
static bool isSideEffectFree(const Expr *E)
Check if E has side-effects.
Definition Compiler.cpp:44
llvm::APInt APInt
Definition FixedPoint.h:19
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1527
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:35
static std::optional< bool > getBoolValue(const Expr *E)
Definition Compiler.cpp:31
static bool Activate(InterpState &S)
Definition Interp.h:2303
static bool exceedsArraySizeLimit(const LangOptions &LangOpts, uint64_t NumElems)
Whether the CheckArraySize op rejects an array with NumElems elements.
Definition Compiler.cpp:55
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2420
bool DefaultInit(InterpState &S, CodePtr OpPC, const CXXConstructorDecl *Ctor)
Definition Interp.cpp:2790
bool Mul(InterpState &S, CodePtr OpPC)
Definition Interp.h:482
size_t primSize(PrimType Type)
Returns the size of a primitive type in bytes.
Definition PrimType.cpp:25
bool Inc(InterpState &S, CodePtr OpPC, bool CanOverflow)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition Interp.h:967
bool Add(InterpState &S, CodePtr OpPC)
Definition Interp.h:399
llvm::BitVector collectNonNullArgs(const FunctionDecl *F, ArrayRef< const Expr * > Args)
constexpr bool isIntegerType(PrimType T)
Definition PrimType.h:55
llvm::APSInt APSInt
Definition FixedPoint.h:20
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool hasSpecificAttr(const Container &container)
@ Success
Annotation was successful.
Definition Parser.h:65
@ Link
'link' clause, allowed on 'declare' construct.
DynamicRecursiveASTVisitorBase< true > ConstDynamicRecursiveASTVisitor
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
@ SD_Static
Static storage duration.
Definition Specifiers.h:345
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:342
@ Result
The result type of a method or function.
Definition TypeBase.h:906
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327
int const char * function
Definition c++config.h:31
#define true
Definition stdbool.h:25
llvm::APSInt getIntValue() const
Get the constant integer value used by this variable to represent the comparison category result type...
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
A quantity in bits.
const ValueDecl * asValueDecl() const
Definition DeclOrExpr.h:35
const Expr * asExpr() const
Definition DeclOrExpr.h:33
Describes a memory block created by an allocation site.
Definition Descriptor.h:121
unsigned getNumElems() const
Returns the number of elements stored in the block.
Definition Descriptor.h:245
bool isPrimitive() const
Checks if the descriptor is of a primitive.
Definition Descriptor.h:259
QualType getElemQualType() const
bool hasTrivialDtor() const
Whether variables of this descriptor need their destructor called or not.
bool isCompositeArray() const
Checks if the descriptor is of an array of composites.
Definition Descriptor.h:252
QualType getType() const
const Descriptor *const ElemDesc
Descriptor of the array element.
Definition Descriptor.h:147
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition Descriptor.h:250
PrimType getPrimType() const
Definition Descriptor.h:230
bool isRecord() const
Checks if the descriptor is of a record.
Definition Descriptor.h:264
const Record *const ElemRecord
Pointer to the record, if block contains records.
Definition Descriptor.h:145
bool isArray() const
Checks if the descriptor is of an array.
Definition Descriptor.h:262
Descriptor used for global variables.
Definition Descriptor.h:48
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:101
static VarCreationState NotCreated()
Definition Compiler.h:105