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