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