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