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