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