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