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