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