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 }
3684 if (E->isStoredAsComparisonResult()) {
3685 const ComparisonCategoryInfo &CmpInfo =
3686 Ctx.getASTContext().CompCategories.getInfoForType(E->getType());
3687 const auto Result =
3688 ComparisonCategoryResult(E->getAPValue().getInt().getZExtValue());
3689 const Record *R = getRecord(E->getType());
3690 if (!R || R->getNumFields() == 0)
3691 return false;
3692 const Record::Field *Field = R->getField(0U);
3693 PrimType FieldT = classifyPrim(Field->Decl->getType());
3694 if (!this->emitConst(CmpInfo.getValueInfo(Result)->getIntValue(), FieldT,
3695 E))
3696 return false;
3697 return this->emitInitField(FieldT, Field->Offset, E);
3698 }
3699
3701 return this->visitAPValue(E->getAPValue(), T, E);
3702}
3703
3704template <class Emitter>
3706 if (DiscardResult)
3707 return true;
3708 return this->emitConst(E->getValue(), E);
3709}
3710
3711template <class Emitter>
3713 if (DiscardResult)
3714 return true;
3715
3716 assert(Initializing);
3717 const Record *R = P.getOrCreateRecord(E->getLambdaClass());
3718 if (!R)
3719 return false;
3720
3721 auto *CaptureInitIt = E->capture_init_begin();
3722 // Initialize all fields (which represent lambda captures) of the
3723 // record with their initializers.
3724 for (const Record::Field &F : R->fields()) {
3725 const Expr *Init = *CaptureInitIt;
3726 if (!Init || Init->containsErrors())
3727 continue;
3728 ++CaptureInitIt;
3729
3730 if (OptPrimType T = classify(Init)) {
3731 if (!this->visit(Init))
3732 return false;
3733
3734 if (!this->emitInitField(*T, F.Offset, E))
3735 return false;
3736 } else {
3737 if (!this->emitGetPtrField(F.Offset, E))
3738 return false;
3739
3740 if (!this->visitInitializerPop(Init))
3741 return false;
3742 }
3743 }
3744
3745 return true;
3746}
3747
3748template <class Emitter>
3750 if (DiscardResult)
3751 return true;
3752
3753 if (!Initializing) {
3754 unsigned StringIndex = P.createGlobalString(E->getFunctionName(), E);
3755 return this->emitGetPtrGlobal(StringIndex, E);
3756 }
3757
3758 return this->delegate(E->getFunctionName());
3759}
3760
3761template <class Emitter>
3763 if (E->getSubExpr() && !this->discard(E->getSubExpr()))
3764 return false;
3765
3766 return this->emitInvalid(E);
3767}
3768
3769template <class Emitter>
3771 const CXXReinterpretCastExpr *E) {
3772 const Expr *SubExpr = E->getSubExpr();
3773
3774 OptPrimType FromT = classify(SubExpr);
3775 OptPrimType ToT = classify(E);
3776
3777 if (!FromT || !ToT)
3778 return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, E);
3779
3780 if (FromT == PT_Ptr || ToT == PT_Ptr) {
3783 if (!this->emitInvalidCast(CastKind, /*Fatal=*/false, E))
3784 return false;
3785 if (E->getCastKind() == CK_LValueBitCast)
3786 return this->delegate(SubExpr);
3787 return this->VisitCastExpr(E);
3788 }
3789
3790 // Try to actually do the cast.
3791 bool Fatal = (ToT != FromT);
3792 if (!this->emitInvalidCast(CastKind::Reinterpret, Fatal, E))
3793 return false;
3794
3795 return this->VisitCastExpr(E);
3796}
3797
3798template <class Emitter>
3800 if (!Ctx.getLangOpts().CPlusPlus20) {
3801 if (!this->emitInvalidCast(CastKind::Dynamic, /*Fatal=*/false, E))
3802 return false;
3803 }
3804
3805 if (E->getCastKind() != CK_Dynamic)
3806 return this->VisitCastExpr(E);
3807
3808 QualType DestType = E->getType();
3809 // "target type must be a reference or pointer type to a defined class"
3810 if (DestType->isRecordType()) {
3811 assert(E->isGLValue());
3812 } else {
3813 assert(DestType->isPointerOrReferenceType());
3814 assert(DestType->isVoidPointerType() ||
3815 DestType->getPointeeType()->isRecordType());
3816 DestType = DestType->getPointeeType();
3817 }
3818
3819 if (!this->visit(E->getSubExpr()))
3820 return false;
3821 if (!this->emitDynamicCast(DestType.getTypePtr(),
3822 /*IsReferenceCast=*/E->isGLValue(), E))
3823 return false;
3824
3825 if (DiscardResult)
3826 return this->emitPopPtr(E);
3827 return true;
3828}
3829
3830template <class Emitter>
3832 assert(E->getType()->isBooleanType());
3833
3834 if (DiscardResult)
3835 return true;
3836 return this->emitConstBool(E->getValue(), E);
3837}
3838
3839template <class Emitter>
3841 QualType T = E->getType();
3842 assert(!canClassify(T));
3843
3844 if (T->isRecordType()) {
3845 const CXXConstructorDecl *Ctor = E->getConstructor();
3846
3847 // If we're discarding a construct expression, we still need
3848 // to allocate a variable and call the constructor and destructor.
3849 if (DiscardResult) {
3850 if (Ctor->isTrivial())
3851 return true;
3852 assert(!Initializing);
3853 UnsignedOrNone LocalIndex = allocateLocal(E);
3854
3855 if (!LocalIndex)
3856 return false;
3857
3858 if (!this->emitGetPtrLocal(*LocalIndex, E))
3859 return false;
3860 }
3861
3862 // Trivial copy/move constructor. Avoid copy.
3863 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
3864 Ctor->isTrivial() &&
3865 E->getArg(0)->isTemporaryObject(Ctx.getASTContext(),
3866 T->getAsCXXRecordDecl()))
3867 return this->visitInitializer(E->getArg(0));
3868
3869 // Zero initialization.
3870 bool ZeroInit = E->requiresZeroInitialization();
3871 if (ZeroInit) {
3872 const Record *R = getRecord(E->getType());
3873 if (!R)
3874 return false;
3875
3876 if (!this->visitZeroRecordInitializer(R, E))
3877 return false;
3878
3879 // If the constructor is trivial anyway, we're done.
3880 if (Ctor->isTrivial())
3881 return true;
3882 }
3883
3884 // Avoid materializing a temporary for an elidable copy/move constructor.
3885 if (!ZeroInit && E->isElidable()) {
3886 const Expr *SrcObj = E->getArg(0);
3887 assert(SrcObj->isTemporaryObject(Ctx.getASTContext(), Ctor->getParent()));
3888 assert(Ctx.getASTContext().hasSameUnqualifiedType(E->getType(),
3889 SrcObj->getType()));
3890 if (const auto *ME = dyn_cast<MaterializeTemporaryExpr>(SrcObj)) {
3891 if (!this->emitCheckFunctionDecl(Ctor, E))
3892 return false;
3893 return this->visitInitializer(ME->getSubExpr());
3894 }
3895 }
3896
3897 const Function *Func = getFunction(Ctor);
3898
3899 if (!Func)
3900 return false;
3901
3902 assert(Func->hasThisPointer());
3903 assert(!Func->hasRVO());
3904
3905 // The This pointer is already on the stack because this is an initializer,
3906 // but we need to dup() so the call() below has its own copy.
3907 if (!this->emitDupPtr(E))
3908 return false;
3909
3910 // Constructor arguments.
3911 for (const auto *Arg : E->arguments()) {
3912 if (!this->visit(Arg))
3913 return false;
3914 }
3915
3916 if (Func->isVariadic()) {
3917 uint32_t VarArgSize = 0;
3918 unsigned NumParams = Func->getNumWrittenParams();
3919 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) {
3920 VarArgSize +=
3921 align(primSize(classify(E->getArg(I)->getType()).value_or(PT_Ptr)));
3922 }
3923 if (!this->emitCallVar(Func, VarArgSize, E))
3924 return false;
3925 } else {
3926 if (!this->emitCall(Func, 0, E)) {
3927 // When discarding, we don't need the result anyway, so clean up
3928 // the instance dup we did earlier in case surrounding code wants
3929 // to keep evaluating.
3930 if (DiscardResult)
3931 (void)this->emitPopPtr(E);
3932 return false;
3933 }
3934 }
3935
3936 if (DiscardResult)
3937 return this->emitPopPtr(E);
3938 return true;
3939 }
3940
3941 if (T->isArrayType()) {
3942 const Function *Func = getFunction(E->getConstructor());
3943 if (!Func)
3944 return false;
3945
3946 if (!this->emitDupPtr(E))
3947 return false;
3948
3949 std::function<bool(QualType)> initArrayDimension;
3950 initArrayDimension = [&](QualType T) -> bool {
3951 if (!T->isArrayType()) {
3952 // Constructor arguments.
3953 for (const auto *Arg : E->arguments()) {
3954 if (!this->visit(Arg))
3955 return false;
3956 }
3957
3958 return this->emitCall(Func, 0, E);
3959 }
3960
3961 const ConstantArrayType *CAT =
3962 Ctx.getASTContext().getAsConstantArrayType(T);
3963 if (!CAT)
3964 return false;
3965 QualType ElemTy = CAT->getElementType();
3966 unsigned NumElems = CAT->getZExtSize();
3967 for (size_t I = 0; I != NumElems; ++I) {
3968 if (!this->emitConstUint64(I, E))
3969 return false;
3970 if (!this->emitArrayElemPtrUint64(E))
3971 return false;
3972 if (!initArrayDimension(ElemTy))
3973 return false;
3974 }
3975 return this->emitPopPtr(E);
3976 };
3977
3978 return initArrayDimension(E->getType());
3979 }
3980
3981 return false;
3982}
3983
3984template <class Emitter>
3986 if (DiscardResult)
3987 return true;
3988
3989 const APValue Val =
3990 E->EvaluateInContext(Ctx.getASTContext(), SourceLocDefaultExpr);
3991
3992 // Things like __builtin_LINE().
3993 if (E->getType()->isIntegerType()) {
3994 assert(Val.isInt());
3995 const APSInt &I = Val.getInt();
3996 return this->emitConst(I, E);
3997 }
3998 // Otherwise, the APValue is an LValue, with only one element.
3999 // Theoretically, we don't need the APValue at all of course.
4000 assert(E->getType()->isPointerType());
4001 assert(Val.isLValue());
4002 const APValue::LValueBase &Base = Val.getLValueBase();
4003 if (const Expr *LValueExpr = Base.dyn_cast<const Expr *>())
4004 return this->visit(LValueExpr);
4005
4006 // Otherwise, we have a decl (which is the case for
4007 // __builtin_source_location).
4008 assert(Base.is<const ValueDecl *>());
4009 assert(Val.getLValuePath().size() == 0);
4010 const auto *BaseDecl = Base.dyn_cast<const ValueDecl *>();
4011 assert(BaseDecl);
4012
4013 auto *UGCD = cast<UnnamedGlobalConstantDecl>(BaseDecl);
4014
4015 UnsignedOrNone GlobalIndex = P.getOrCreateGlobal(UGCD);
4016 if (!GlobalIndex)
4017 return false;
4018
4019 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
4020 return false;
4021
4022 const Record *R = getRecord(E->getType());
4023 const APValue &V = UGCD->getValue();
4024 for (unsigned I = 0, N = R->getNumFields(); I != N; ++I) {
4025 const Record::Field *F = R->getField(I);
4026 const APValue &FieldValue = V.getStructField(I);
4027
4028 PrimType FieldT = classifyPrim(F->Decl->getType());
4029
4030 if (!this->visitAPValue(FieldValue, FieldT, E))
4031 return false;
4032 if (!this->emitInitField(FieldT, F->Offset, E))
4033 return false;
4034 }
4035
4036 // Leave the pointer to the global on the stack.
4037 return true;
4038}
4039
4040template <class Emitter>
4042 unsigned N = E->getNumComponents();
4043 if (N == 0)
4044 return false;
4045
4046 for (unsigned I = 0; I != N; ++I) {
4047 const OffsetOfNode &Node = E->getComponent(I);
4048 if (Node.getKind() == OffsetOfNode::Array) {
4049 const Expr *ArrayIndexExpr = E->getIndexExpr(Node.getArrayExprIndex());
4050 PrimType IndexT = classifyPrim(ArrayIndexExpr->getType());
4051
4052 if (DiscardResult) {
4053 if (!this->discard(ArrayIndexExpr))
4054 return false;
4055 continue;
4056 }
4057
4058 if (IndexT == PT_IntAP || IndexT == PT_IntAPS) {
4059 if (!this->visit(ArrayIndexExpr))
4060 return false;
4061 if (!this->emitCastAPToOffsetIndex(IndexT, E))
4062 return false;
4063 continue;
4064 }
4065 if (!this->visit(ArrayIndexExpr))
4066 return false;
4067 // Cast to Sint64.
4068 if (IndexT != PT_Sint64) {
4069 if (!this->emitCast(IndexT, PT_Sint64, E))
4070 return false;
4071 }
4072 }
4073 }
4074
4075 if (DiscardResult)
4076 return true;
4077
4079 return this->emitOffsetOf(T, E, E);
4080}
4081
4082template <class Emitter>
4084 const CXXScalarValueInitExpr *E) {
4085 QualType Ty = E->getType();
4086
4087 if (DiscardResult || Ty->isVoidType())
4088 return true;
4089
4090 if (OptPrimType T = classify(Ty))
4091 return this->visitZeroInitializer(*T, Ty, E);
4092
4093 if (Ty->isAnyComplexType() || Ty->isVectorType()) {
4094 if (!Initializing) {
4095 UnsignedOrNone LocalIndex = allocateLocal(E);
4096 if (!LocalIndex)
4097 return false;
4098 if (!this->emitGetPtrLocal(*LocalIndex, E))
4099 return false;
4100 }
4101
4102 QualType ElemQT;
4103 unsigned NumElems;
4104 if (const auto *CT = Ty->getAs<ComplexType>()) {
4105 NumElems = 2;
4106 ElemQT = CT->getElementType();
4107 } else {
4108 const auto *VT = Ty->castAs<VectorType>();
4109 NumElems = VT->getNumElements();
4110 ElemQT = VT->getElementType();
4111 }
4112
4113 PrimType ElemT = classifyPrim(ElemQT);
4114
4115 // Initialize all fields to 0.
4116 for (unsigned I = 0; I != NumElems; ++I) {
4117 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
4118 return false;
4119 if (!this->emitInitElem(ElemT, I, E))
4120 return false;
4121 }
4122 return true;
4123 }
4124
4125 return false;
4126}
4127
4128template <class Emitter>
4130 return this->emitConst(E->getPackLength(), E);
4131}
4132
4133template <class Emitter>
4138
4139template <class Emitter>
4141 return this->delegate(E->getChosenSubExpr());
4142}
4143
4144template <class Emitter>
4146 if (DiscardResult)
4147 return true;
4148
4149 return this->emitConst(E->getValue(), E);
4150}
4151
4152template <class Emitter>
4154 const CXXInheritedCtorInitExpr *E) {
4155 const CXXConstructorDecl *Ctor = E->getConstructor();
4156 assert(!Ctor->isTrivial() &&
4157 "Trivial CXXInheritedCtorInitExpr, implement. (possible?)");
4158 const Function *F = this->getFunction(Ctor);
4159 if (!F)
4160 return false;
4161 assert(!F->hasRVO());
4162 assert(F->hasThisPointer());
4163
4164 if (!this->emitDupPtr(SourceInfo{}))
4165 return false;
4166
4167 // Forward all arguments of the current function (which should be a
4168 // constructor itself) to the inherited ctor.
4169 // This is necessary because the calling code has pushed the pointer
4170 // of the correct base for us already, but the arguments need
4171 // to come after.
4172 unsigned ParamIndex = 0;
4173 for (const ParmVarDecl *PD : Ctor->parameters()) {
4174 PrimType PT = this->classify(PD->getType()).value_or(PT_Ptr);
4175
4176 if (!this->emitGetParam(PT, ParamIndex, E))
4177 return false;
4178 ++ParamIndex;
4179 }
4180
4181 return this->emitCall(F, 0, E);
4182}
4183
4184// FIXME: This function has become rather unwieldy, especially
4185// the part where we initialize an array allocation of dynamic size.
4186template <class Emitter>
4188 assert(classifyPrim(E->getType()) == PT_Ptr);
4189 const Expr *Init = E->getInitializer();
4190 QualType ElementType = E->getAllocatedType();
4191 OptPrimType ElemT = classify(ElementType);
4192 unsigned PlacementArgs = E->getNumPlacementArgs();
4193 const FunctionDecl *OperatorNew = E->getOperatorNew();
4194 const Expr *PlacementDest = nullptr;
4195 bool IsNoThrow = false;
4196
4197 if (E->containsErrors())
4198 return false;
4199
4200 if (PlacementArgs != 0) {
4201 // FIXME: There is no restriction on this, but it's not clear that any
4202 // other form makes any sense. We get here for cases such as:
4203 //
4204 // new (std::align_val_t{N}) X(int)
4205 //
4206 // (which should presumably be valid only if N is a multiple of
4207 // alignof(int), and in any case can't be deallocated unless N is
4208 // alignof(X) and X has new-extended alignment).
4209 if (PlacementArgs == 1) {
4210 const Expr *Arg1 = E->getPlacementArg(0);
4211 if (Arg1->getType()->isNothrowT()) {
4212 if (!this->discard(Arg1))
4213 return false;
4214 IsNoThrow = true;
4215 } else {
4216 // Invalid unless we have C++26 or are in a std:: function.
4217 if (!this->emitInvalidNewDeleteExpr(E, E))
4218 return false;
4219
4220 // If we have a placement-new destination, we'll later use that instead
4221 // of allocating.
4222 if (OperatorNew->isReservedGlobalPlacementOperator())
4223 PlacementDest = Arg1;
4224 }
4225 } else {
4226 // Always invalid.
4227 return this->emitInvalid(E);
4228 }
4229 } else if (!OperatorNew
4230 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
4231 return this->emitInvalidNewDeleteExpr(E, E);
4232
4233 const Descriptor *Desc;
4234 if (!PlacementDest) {
4235 if (ElemT) {
4236 if (E->isArray())
4237 Desc = nullptr; // We're not going to use it in this case.
4238 else
4239 Desc = P.createDescriptor(E, *ElemT);
4240 } else {
4241 Desc = P.createDescriptor(E, ElementType.getTypePtr(), /*IsConst=*/false,
4242 /*IsTemporary=*/false, /*IsMutable=*/false,
4243 /*IsVolatile=*/false, Init);
4244 }
4245 }
4246
4247 if (E->isArray()) {
4248 std::optional<const Expr *> ArraySizeExpr = E->getArraySize();
4249 if (!ArraySizeExpr)
4250 return false;
4251
4252 const Expr *Stripped = *ArraySizeExpr;
4253 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
4254 Stripped = ICE->getSubExpr())
4255 if (ICE->getCastKind() != CK_NoOp &&
4256 ICE->getCastKind() != CK_IntegralCast)
4257 break;
4258
4259 PrimType SizeT = classifyPrim(Stripped->getType());
4260
4261 // Save evaluated array size to a variable.
4262 unsigned ArrayLen =
4263 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
4264 if (!this->visit(Stripped))
4265 return false;
4266 if (!this->emitSetLocal(SizeT, ArrayLen, E))
4267 return false;
4268
4269 if (PlacementDest) {
4270 if (!this->visit(PlacementDest))
4271 return false;
4272 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4273 return false;
4274 if (!this->emitCheckNewTypeMismatchArray(SizeT, E, E))
4275 return false;
4276 } else {
4277 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4278 return false;
4279
4280 if (ElemT) {
4281 // N primitive elements.
4282 if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E))
4283 return false;
4284 } else {
4285 // N Composite elements.
4286 if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E))
4287 return false;
4288 }
4289 }
4290
4291 if (Init) {
4292 QualType InitType = Init->getType();
4293 size_t StaticInitElems = 0;
4294 const Expr *DynamicInit = nullptr;
4295 OptPrimType ElemT;
4296
4297 if (const ConstantArrayType *CAT =
4298 Ctx.getASTContext().getAsConstantArrayType(InitType)) {
4299 StaticInitElems = CAT->getZExtSize();
4300 // Initialize the first S element from the initializer.
4301 if (!this->visitInitializer(Init))
4302 return false;
4303
4304 if (const auto *ILE = dyn_cast<InitListExpr>(Init)) {
4305 if (ILE->hasArrayFiller())
4306 DynamicInit = ILE->getArrayFiller();
4307 else if (StaticInitElems > 0 && isa<StringLiteral>(ILE->getInit(0)))
4308 ElemT = classifyPrim(CAT->getElementType());
4309 }
4310 }
4311
4312 // The initializer initializes a certain number of elements, S.
4313 // However, the complete number of elements, N, might be larger than that.
4314 // In this case, we need to get an initializer for the remaining elements.
4315 // There are three cases:
4316 // 1) For the form 'new Struct[n];', the initializer is a
4317 // CXXConstructExpr and its type is an IncompleteArrayType.
4318 // 2) For the form 'new Struct[n]{1,2,3}', the initializer is an
4319 // InitListExpr and the initializer for the remaining elements
4320 // is the array filler.
4321 // 3) StringLiterals don't have an array filler, so we need to zero
4322 // the remaining elements.
4323
4324 if (DynamicInit || ElemT || InitType->isIncompleteArrayType()) {
4325 const Function *CtorFunc = nullptr;
4326 if (const auto *CE = dyn_cast<CXXConstructExpr>(Init)) {
4327 CtorFunc = getFunction(CE->getConstructor());
4328 if (!CtorFunc)
4329 return false;
4330 } else if (!DynamicInit && !ElemT)
4331 DynamicInit = Init;
4332
4333 LabelTy EndLabel = this->getLabel();
4334 LabelTy StartLabel = this->getLabel();
4335
4336 // In the nothrow case, the alloc above might have returned nullptr.
4337 // Don't call any constructors that case.
4338 if (IsNoThrow) {
4339 if (!this->emitDupPtr(E))
4340 return false;
4341 if (!this->emitNullPtr(0, nullptr, E))
4342 return false;
4343 if (!this->emitEQPtr(E))
4344 return false;
4345 if (!this->jumpTrue(EndLabel, E))
4346 return false;
4347 }
4348
4349 // Create loop variables.
4350 unsigned Iter =
4351 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
4352 if (!this->emitConst(StaticInitElems, SizeT, E))
4353 return false;
4354 if (!this->emitSetLocal(SizeT, Iter, E))
4355 return false;
4356
4357 this->fallthrough(StartLabel);
4358 this->emitLabel(StartLabel);
4359 // Condition. Iter < ArrayLen?
4360 if (!this->emitGetLocal(SizeT, Iter, E))
4361 return false;
4362 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4363 return false;
4364 if (!this->emitLT(SizeT, E))
4365 return false;
4366 if (!this->jumpFalse(EndLabel, E))
4367 return false;
4368
4369 // Pointer to the allocated array is already on the stack.
4370 if (!this->emitGetLocal(SizeT, Iter, E))
4371 return false;
4372 if (!this->emitArrayElemPtr(SizeT, E))
4373 return false;
4374
4375 if (isa_and_nonnull<ImplicitValueInitExpr>(DynamicInit) &&
4376 DynamicInit->getType()->isArrayType()) {
4377 QualType ElemType =
4378 DynamicInit->getType()->getAsArrayTypeUnsafe()->getElementType();
4379 if (OptPrimType InitT = classify(ElemType)) {
4380 if (!this->visitZeroInitializer(*InitT, ElemType, E))
4381 return false;
4382 if (!this->emitStorePop(*InitT, E))
4383 return false;
4384 } else {
4385 assert(ElemType->isArrayType());
4386 if (!this->visitZeroArrayInitializer(ElemType, E))
4387 return false;
4388 }
4389 } else if (DynamicInit) {
4390 if (OptPrimType InitT = classify(DynamicInit)) {
4391 if (!this->visit(DynamicInit))
4392 return false;
4393 if (!this->emitStorePop(*InitT, E))
4394 return false;
4395 } else {
4396 if (!this->visitInitializerPop(DynamicInit))
4397 return false;
4398 }
4399 } else if (ElemT) {
4400 if (!this->visitZeroInitializer(
4401 *ElemT, InitType->getAsArrayTypeUnsafe()->getElementType(),
4402 Init))
4403 return false;
4404 if (!this->emitStorePop(*ElemT, E))
4405 return false;
4406 } else {
4407 assert(CtorFunc);
4408 if (!this->emitCall(CtorFunc, 0, E))
4409 return false;
4410 }
4411
4412 // ++Iter;
4413 if (!this->emitGetPtrLocal(Iter, E))
4414 return false;
4415 if (!this->emitIncPop(SizeT, false, E))
4416 return false;
4417
4418 if (!this->jump(StartLabel, E))
4419 return false;
4420
4421 this->fallthrough(EndLabel);
4422 this->emitLabel(EndLabel);
4423 }
4424 }
4425 } else { // Non-array.
4426 if (PlacementDest) {
4427 if (!this->visit(PlacementDest))
4428 return false;
4429 if (!this->emitCheckNewTypeMismatch(E, E))
4430 return false;
4431
4432 } else {
4433 // Allocate just one element.
4434 if (!this->emitAlloc(Desc, E))
4435 return false;
4436 }
4437
4438 if (Init) {
4439 if (ElemT) {
4440 if (!this->visit(Init))
4441 return false;
4442
4443 if (!this->emitInit(*ElemT, E))
4444 return false;
4445 } else {
4446 // Composite.
4447 if (!this->visitInitializer(Init))
4448 return false;
4449 }
4450 }
4451 }
4452
4453 if (DiscardResult)
4454 return this->emitPopPtr(E);
4455
4456 return true;
4457}
4458
4459template <class Emitter>
4461 if (E->containsErrors())
4462 return false;
4463 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
4464
4465 if (!OperatorDelete->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
4466 return this->emitInvalidNewDeleteExpr(E, E);
4467
4468 // Arg must be an lvalue.
4469 if (!this->visit(E->getArgument()))
4470 return false;
4471
4472 return this->emitFree(E->isArrayForm(), E->isGlobalDelete(), E);
4473}
4474
4475template <class Emitter>
4477 if (DiscardResult)
4478 return true;
4479
4480 const Function *Func = nullptr;
4481 if (const Function *F = Ctx.getOrCreateObjCBlock(E))
4482 Func = F;
4483
4484 if (!Func)
4485 return false;
4486 return this->emitGetFnPtr(Func, E);
4487}
4488
4489template <class Emitter>
4491 const Type *TypeInfoType = E->getType().getTypePtr();
4492
4493 auto canonType = [](const Type *T) {
4494 return T->getCanonicalTypeUnqualified().getTypePtr();
4495 };
4496
4497 if (!E->isPotentiallyEvaluated()) {
4498 if (DiscardResult)
4499 return true;
4500
4501 if (E->isTypeOperand())
4502 return this->emitGetTypeid(
4503 canonType(E->getTypeOperand(Ctx.getASTContext()).getTypePtr()),
4504 TypeInfoType, E);
4505
4506 return this->emitGetTypeid(
4507 canonType(E->getExprOperand()->getType().getTypePtr()), TypeInfoType,
4508 E);
4509 }
4510
4511 // Otherwise, we need to evaluate the expression operand.
4512 assert(E->getExprOperand());
4513 assert(E->getExprOperand()->isLValue());
4514
4515 if (!Ctx.getLangOpts().CPlusPlus20 && !this->emitDiagTypeid(E))
4516 return false;
4517
4518 if (!this->visit(E->getExprOperand()))
4519 return false;
4520
4521 if (!this->emitGetTypeidPtr(TypeInfoType, E))
4522 return false;
4523 if (DiscardResult)
4524 return this->emitPopPtr(E);
4525 return true;
4526}
4527
4528template <class Emitter>
4530 const ObjCDictionaryLiteral *E) {
4532 return this->emitDummyPtr(E, E);
4533 return this->emitError(E);
4534}
4535
4536template <class Emitter>
4539 return this->emitDummyPtr(E, E);
4540 return this->emitError(E);
4541}
4542
4543template <class Emitter>
4545 assert(Ctx.getLangOpts().CPlusPlus);
4546 return this->emitConstBool(E->getValue(), E);
4547}
4548
4549template <class Emitter>
4551 if (DiscardResult)
4552 return true;
4553 assert(!Initializing);
4554
4555 const MSGuidDecl *GuidDecl = E->getGuidDecl();
4556 const RecordDecl *RD = GuidDecl->getType()->getAsRecordDecl();
4557 assert(RD);
4558 // If the definiton of the result type is incomplete, just return a dummy.
4559 // If (and when) that is read from, we will fail, but not now.
4560 if (!RD->isCompleteDefinition())
4561 return this->emitDummyPtr(GuidDecl, E);
4562
4563 UnsignedOrNone GlobalIndex = P.getOrCreateGlobal(GuidDecl);
4564 if (!GlobalIndex)
4565 return false;
4566 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
4567 return false;
4568
4569 assert(this->getRecord(E->getType()));
4570
4571 const APValue &V = GuidDecl->getAsAPValue();
4572 if (V.getKind() == APValue::None)
4573 return true;
4574
4575 assert(V.isStruct());
4576 assert(V.getStructNumBases() == 0);
4577 if (!this->visitAPValueInitializer(V, E, E->getType()))
4578 return false;
4579
4580 return this->emitFinishInit(E);
4581}
4582
4583template <class Emitter>
4585 assert(classifyPrim(E->getType()) == PT_Bool);
4586 if (E->isValueDependent())
4587 return false;
4588 if (DiscardResult)
4589 return true;
4590 return this->emitConstBool(E->isSatisfied(), E);
4591}
4592
4593template <class Emitter>
4595 const ConceptSpecializationExpr *E) {
4596 assert(classifyPrim(E->getType()) == PT_Bool);
4597 if (DiscardResult)
4598 return true;
4599 return this->emitConstBool(E->isSatisfied(), E);
4600}
4601
4602template <class Emitter>
4607
4608template <class Emitter>
4610
4611 for (const Expr *SemE : E->semantics()) {
4612 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
4613 if (SemE == E->getResultExpr())
4614 return false;
4615
4616 if (OVE->isUnique())
4617 continue;
4618
4619 if (!this->discard(OVE))
4620 return false;
4621 } else if (SemE == E->getResultExpr()) {
4622 if (!this->delegate(SemE))
4623 return false;
4624 } else {
4625 if (!this->discard(SemE))
4626 return false;
4627 }
4628 }
4629 return true;
4630}
4631
4632template <class Emitter>
4636
4637template <class Emitter>
4639 return this->emitError(E);
4640}
4641
4642template <class Emitter>
4644 assert(E->getType()->isVoidPointerType());
4645 if (DiscardResult)
4646 return true;
4647
4648 return this->emitDummyPtr(E, E);
4649}
4650
4651template <class Emitter>
4652bool Compiler<Emitter>::emitVectorConversion(const Expr *Src, const Expr *E) {
4653 if (Src->containsErrors())
4654 return false;
4655
4656 const auto *VT = E->getType()->castAs<VectorType>();
4657 QualType ElemType = VT->getElementType();
4658 PrimType ElemT = classifyPrim(ElemType);
4659 QualType SrcType = Src->getType();
4660 PrimType SrcElemT = classifyVectorElementType(SrcType);
4661
4662 if (!Initializing) {
4663 UnsignedOrNone LocalIndex = allocateLocal(E);
4664 if (!LocalIndex)
4665 return false;
4666 if (!this->emitGetPtrLocal(*LocalIndex, E))
4667 return false;
4668 }
4669
4670 unsigned SrcOffset =
4671 this->allocateLocalPrimitive(Src, PT_Ptr, /*IsConst=*/true);
4672 if (!this->visit(Src))
4673 return false;
4674 if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
4675 return false;
4676
4677 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
4678 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
4679 return false;
4680 if (!this->emitArrayElemPop(SrcElemT, I, E))
4681 return false;
4682
4683 // Cast to the desired result element type.
4684 if (SrcElemT != ElemT) {
4685 if (!this->emitPrimCast(SrcElemT, ElemT, ElemType, E))
4686 return false;
4687 } else if (ElemType->isFloatingType() && SrcType != ElemType) {
4688 const auto *TargetSemantics = &Ctx.getFloatSemantics(ElemType);
4689 if (!this->emitCastFP(TargetSemantics, getRoundingMode(E), E))
4690 return false;
4691 }
4692 if (!this->emitInitElem(ElemT, I, E))
4693 return false;
4694 }
4695 return true;
4696}
4697
4698template <class Emitter>
4700 return emitVectorConversion(E->getSrcExpr(), E);
4701}
4702
4703template <class Emitter>
4705 // FIXME: Unary shuffle with mask not currently supported.
4706 if (E->getNumSubExprs() == 2)
4707 return this->emitInvalid(E);
4708
4709 assert(E->getNumSubExprs() > 2);
4710
4711 const Expr *Vecs[] = {E->getExpr(0), E->getExpr(1)};
4712 const VectorType *VT = Vecs[0]->getType()->castAs<VectorType>();
4713 PrimType ElemT = classifyPrim(VT->getElementType());
4714 unsigned NumInputElems = VT->getNumElements();
4715 unsigned NumOutputElems = E->getNumSubExprs() - 2;
4716 assert(NumOutputElems > 0);
4717
4718 if (!Initializing) {
4719 UnsignedOrNone LocalIndex = allocateLocal(E);
4720 if (!LocalIndex)
4721 return false;
4722 if (!this->emitGetPtrLocal(*LocalIndex, E))
4723 return false;
4724 }
4725
4726 // Save both input vectors to a local variable.
4727 unsigned VectorOffsets[2];
4728 for (unsigned I = 0; I != 2; ++I) {
4729 VectorOffsets[I] =
4730 this->allocateLocalPrimitive(Vecs[I], PT_Ptr, /*IsConst=*/true);
4731 if (!this->visit(Vecs[I]))
4732 return false;
4733 if (!this->emitSetLocal(PT_Ptr, VectorOffsets[I], E))
4734 return false;
4735 }
4736 for (unsigned I = 0; I != NumOutputElems; ++I) {
4737 APSInt ShuffleIndex = E->getShuffleMaskIdx(I);
4738 assert(ShuffleIndex >= -1);
4739 if (ShuffleIndex == -1)
4740 return this->emitInvalidShuffleVectorIndex(I, E);
4741
4742 assert(ShuffleIndex < (NumInputElems * 2));
4743 if (!this->emitGetLocal(PT_Ptr,
4744 VectorOffsets[ShuffleIndex >= NumInputElems], E))
4745 return false;
4746 unsigned InputVectorIndex = ShuffleIndex.getZExtValue() % NumInputElems;
4747 if (!this->emitArrayElemPop(ElemT, InputVectorIndex, E))
4748 return false;
4749
4750 if (!this->emitInitElem(ElemT, I, E))
4751 return false;
4752 }
4753
4754 if (DiscardResult)
4755 return this->emitPopPtr(E);
4756
4757 return true;
4758}
4759
4760template <class Emitter>
4762 const ExtVectorElementExpr *E) {
4763 const Expr *Base = E->getBase();
4764 assert(
4765 Base->getType()->isVectorType() ||
4766 Base->getType()->getAs<PointerType>()->getPointeeType()->isVectorType());
4767
4769 E->getEncodedElementAccess(Indices);
4770
4771 if (Indices.size() == 1) {
4772 if (!this->visit(Base))
4773 return false;
4774
4775 if (E->isGLValue()) {
4776 if (!this->emitConstUint32(Indices[0], E))
4777 return false;
4778 return this->emitArrayElemPtrPop(PT_Uint32, E);
4779 }
4780 // Else, also load the value.
4781 return this->emitArrayElemPop(classifyPrim(E->getType()), Indices[0], E);
4782 }
4783
4784 // Create a local variable for the base.
4785 unsigned BaseOffset = allocateLocalPrimitive(Base, PT_Ptr, /*IsConst=*/true);
4786 if (!this->visit(Base))
4787 return false;
4788 if (!this->emitSetLocal(PT_Ptr, BaseOffset, E))
4789 return false;
4790
4791 // Now the vector variable for the return value.
4792 if (!Initializing) {
4793 UnsignedOrNone ResultIndex = allocateLocal(E);
4794 if (!ResultIndex)
4795 return false;
4796 if (!this->emitGetPtrLocal(*ResultIndex, E))
4797 return false;
4798 }
4799
4800 assert(Indices.size() == E->getType()->getAs<VectorType>()->getNumElements());
4801
4802 PrimType ElemT =
4804 uint32_t DstIndex = 0;
4805 for (uint32_t I : Indices) {
4806 if (!this->emitGetLocal(PT_Ptr, BaseOffset, E))
4807 return false;
4808 if (!this->emitArrayElemPop(ElemT, I, E))
4809 return false;
4810 if (!this->emitInitElem(ElemT, DstIndex, E))
4811 return false;
4812 ++DstIndex;
4813 }
4814
4815 // Leave the result pointer on the stack.
4816 assert(!DiscardResult);
4817 return true;
4818}
4819
4820template <class Emitter>
4822 const Expr *SubExpr = E->getSubExpr();
4824 return this->discard(SubExpr) && this->emitInvalid(E);
4825
4826 if (DiscardResult)
4827 return true;
4828
4829 assert(classifyPrim(E) == PT_Ptr);
4830 return this->emitDummyPtr(E, E);
4831}
4832
4833template <class Emitter>
4835 const CXXStdInitializerListExpr *E) {
4836 const Expr *SubExpr = E->getSubExpr();
4838 Ctx.getASTContext().getAsConstantArrayType(SubExpr->getType());
4839 const Record *R = getRecord(E->getType());
4840 assert(Initializing);
4841 assert(SubExpr->isGLValue());
4842
4843 if (!this->visit(SubExpr))
4844 return false;
4845 if (!this->emitConstUint8(0, E))
4846 return false;
4847 if (!this->emitArrayElemPtrPopUint8(E))
4848 return false;
4849 if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E))
4850 return false;
4851
4852 PrimType SecondFieldT = classifyPrim(R->getField(1u)->Decl->getType());
4853 if (isIntegerOrBoolType(SecondFieldT)) {
4854 if (!this->emitConst(ArrayType->getSize(), SecondFieldT, E))
4855 return false;
4856 return this->emitInitField(SecondFieldT, R->getField(1u)->Offset, E);
4857 }
4858 assert(SecondFieldT == PT_Ptr);
4859
4860 if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E))
4861 return false;
4862 if (!this->emitExpandPtr(E))
4863 return false;
4864 if (!this->emitConst(ArrayType->getSize(), PT_Uint64, E))
4865 return false;
4866 if (!this->emitArrayElemPtrPop(PT_Uint64, E))
4867 return false;
4868 return this->emitInitFieldPtr(R->getField(1u)->Offset, E);
4869}
4870
4871template <class Emitter>
4873 LocalScope<Emitter> BS(this);
4874 llvm::SaveAndRestore StmtExprSAR(this->InStmtExpr, true);
4875
4876 const CompoundStmt *CS = E->getSubStmt();
4877 const Stmt *Result = CS->body_back();
4878 for (const Stmt *S : CS->body()) {
4879 if (S != Result) {
4880 if (!this->visitStmt(S))
4881 return false;
4882 continue;
4883 }
4884
4885 assert(S == Result);
4886 if (const Expr *ResultExpr = dyn_cast<Expr>(S))
4887 return this->delegate(ResultExpr);
4888 if (!this->visitStmt(S))
4889 return false;
4890 return this->emitUnsupported(E);
4891 }
4892
4893 return BS.destroyLocals();
4894}
4895
4896template <class Emitter> bool Compiler<Emitter>::discard(const Expr *E) {
4897 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true,
4898 /*NewInitializing=*/false, /*ToLValue=*/false);
4899 return this->Visit(E);
4900}
4901
4902template <class Emitter> bool Compiler<Emitter>::delegate(const Expr *E) {
4903 // We're basically doing:
4904 // OptionScope<Emitter> Scope(this, DicardResult, Initializing, ToLValue);
4905 // but that's unnecessary of course.
4906 return this->Visit(E);
4907}
4908
4910 if (const auto *PE = dyn_cast<ParenExpr>(E))
4911 return stripCheckedDerivedToBaseCasts(PE->getSubExpr());
4912
4913 if (const auto *CE = dyn_cast<CastExpr>(E);
4914 CE &&
4915 (CE->getCastKind() == CK_DerivedToBase || CE->getCastKind() == CK_NoOp))
4916 return stripCheckedDerivedToBaseCasts(CE->getSubExpr());
4917
4918 return E;
4919}
4920
4921static const Expr *stripDerivedToBaseCasts(const Expr *E) {
4922 if (const auto *PE = dyn_cast<ParenExpr>(E))
4923 return stripDerivedToBaseCasts(PE->getSubExpr());
4924
4925 if (const auto *CE = dyn_cast<CastExpr>(E);
4926 CE && (CE->getCastKind() == CK_DerivedToBase ||
4927 CE->getCastKind() == CK_UncheckedDerivedToBase ||
4928 CE->getCastKind() == CK_NoOp))
4929 return stripDerivedToBaseCasts(CE->getSubExpr());
4930
4931 return E;
4932}
4933
4934template <class Emitter> bool Compiler<Emitter>::visit(const Expr *E) {
4935 if (E->getType().isNull())
4936 return false;
4937
4938 if (E->getType()->isVoidType())
4939 return this->discard(E);
4940
4941 // Create local variable to hold the return value.
4942 if (!E->isGLValue() && !canClassify(E->getType())) {
4943 UnsignedOrNone LocalIndex = allocateLocal(
4945 if (!LocalIndex)
4946 return false;
4947
4948 if (!this->emitGetPtrLocal(*LocalIndex, E))
4949 return false;
4950 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
4951 return this->visitInitializer(E);
4952 }
4953
4954 // Otherwise,we have a primitive return value, produce the value directly
4955 // and push it on the stack.
4956 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4957 /*NewInitializing=*/false, /*ToLValue=*/ToLValue);
4958 return this->Visit(E);
4959}
4960
4961template <class Emitter>
4963 assert(!canClassify(E->getType()));
4964
4965 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4966 /*NewInitializing=*/true, /*ToLValue=*/false);
4967 return this->Visit(E) && this->emitFinishInit(E);
4968}
4969
4970template <class Emitter>
4972 assert(!canClassify(E->getType()));
4973
4974 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4975 /*NewInitializing=*/true, /*ToLValue=*/false);
4976 return this->Visit(E) && this->emitFinishInitPop(E);
4977}
4978
4979template <class Emitter> bool Compiler<Emitter>::visitAsLValue(const Expr *E) {
4980 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4981 /*NewInitializing=*/false, /*ToLValue=*/true);
4982 return this->Visit(E);
4983}
4984
4985template <class Emitter> bool Compiler<Emitter>::visitBool(const Expr *E) {
4986 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4987 /*NewInitializing=*/false, /*ToLValue=*/ToLValue);
4988
4989 OptPrimType T = classify(E->getType());
4990 if (!T) {
4991 // Convert complex values to bool.
4992 if (E->getType()->isAnyComplexType()) {
4993 if (!this->visit(E))
4994 return false;
4995 return this->emitComplexBoolCast(E);
4996 }
4997 return false;
4998 }
4999
5000 if (!this->visit(E))
5001 return false;
5002
5003 if (T == PT_Bool)
5004 return true;
5005
5006 // Convert pointers to bool.
5007 if (T == PT_Ptr)
5008 return this->emitIsNonNullPtr(E);
5009
5010 // Or Floats.
5011 if (T == PT_Float)
5012 return this->emitCastFloatingIntegralBool(getFPOptions(E), E);
5013
5014 // Or anything else we can.
5015 return this->emitCast(*T, PT_Bool, E);
5016}
5017
5018template <class Emitter>
5019bool Compiler<Emitter>::visitZeroInitializer(PrimType T, QualType QT,
5020 const Expr *E) {
5021 if (const auto *AT = QT->getAs<AtomicType>())
5022 QT = AT->getValueType();
5023
5024 switch (T) {
5025 case PT_Bool:
5026 return this->emitZeroBool(E);
5027 case PT_Sint8:
5028 return this->emitZeroSint8(E);
5029 case PT_Uint8:
5030 return this->emitZeroUint8(E);
5031 case PT_Sint16:
5032 return this->emitZeroSint16(E);
5033 case PT_Uint16:
5034 return this->emitZeroUint16(E);
5035 case PT_Sint32:
5036 return this->emitZeroSint32(E);
5037 case PT_Uint32:
5038 return this->emitZeroUint32(E);
5039 case PT_Sint64:
5040 return this->emitZeroSint64(E);
5041 case PT_Uint64:
5042 return this->emitZeroUint64(E);
5043 case PT_IntAP:
5044 return this->emitZeroIntAP(Ctx.getBitWidth(QT), E);
5045 case PT_IntAPS:
5046 return this->emitZeroIntAPS(Ctx.getBitWidth(QT), E);
5047 case PT_Ptr:
5048 return this->emitNullPtr(Ctx.getASTContext().getTargetNullPointerValue(QT),
5049 nullptr, E);
5050 case PT_MemberPtr:
5051 return this->emitNullMemberPtr(0, nullptr, E);
5052 case PT_Float: {
5053 APFloat F = APFloat::getZero(Ctx.getFloatSemantics(QT));
5054 return this->emitFloat(F, E);
5055 }
5056 case PT_FixedPoint: {
5057 auto Sem = Ctx.getASTContext().getFixedPointSemantics(QT);
5058 return this->emitConstFixedPoint(FixedPoint::zero(Sem), E);
5059 }
5060 }
5061 llvm_unreachable("unknown primitive type");
5062}
5063
5064template <class Emitter>
5065bool Compiler<Emitter>::visitZeroRecordInitializer(const Record *R,
5066 const Expr *E,
5067 bool IsCompleteClass) {
5068 assert(E);
5069 assert(R);
5070 // Fields
5071 for (const Record::Field &Field : R->fields()) {
5072 if (Field.isUnnamedBitField())
5073 continue;
5074
5075 const Descriptor *D = Field.Desc;
5076 if (D->isPrimitive()) {
5077 QualType QT = D->getType();
5078 PrimType T = D->getPrimType();
5079 if (!this->visitZeroInitializer(T, QT, E))
5080 return false;
5081 if (R->isUnion()) {
5082 if (!this->emitInitFieldActivate(T, Field.Offset, E))
5083 return false;
5084 break;
5085 }
5086 if (!this->emitInitField(T, Field.Offset, E))
5087 return false;
5088 continue;
5089 }
5090
5091 if (!this->emitGetPtrField(Field.Offset, E))
5092 return false;
5093
5094 if (D->isPrimitiveArray()) {
5095 QualType ET = D->getElemQualType();
5096 PrimType T = D->getPrimType();
5097 for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
5098 if (!this->visitZeroInitializer(T, ET, E))
5099 return false;
5100 if (!this->emitInitElem(T, I, E))
5101 return false;
5102 }
5103 } else if (D->isCompositeArray()) {
5104 // Can't be a vector or complex field.
5105 if (!this->visitZeroArrayInitializer(D->getType(), E))
5106 return false;
5107 } else if (D->isRecord()) {
5108 if (!this->visitZeroRecordInitializer(D->ElemRecord, E))
5109 return false;
5110 } else
5111 return false;
5112
5113 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5114 // object's first non-static named data member is zero-initialized
5115 if (R->isUnion()) {
5116 if (!this->emitFinishInitActivatePop(E))
5117 return false;
5118 break;
5119 }
5120 if (!this->emitFinishInitPop(E))
5121 return false;
5122 }
5123
5124 for (const Record::Base &B : R->bases()) {
5125 if (!this->emitGetPtrBase(B.Offset, E))
5126 return false;
5127 if (!this->visitZeroRecordInitializer(B.R, E, /*IsCompleteClass=*/false))
5128 return false;
5129 if (!this->emitFinishInitPop(E))
5130 return false;
5131 }
5132
5133 if (IsCompleteClass) {
5134 for (const Record::Base &B : R->virtual_bases()) {
5135 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(B.R->getDecl()), E))
5136 return false;
5137 if (!this->visitZeroRecordInitializer(B.R, E, /*IsCompleteClass=*/false))
5138 return false;
5139 if (!this->emitFinishInitPop(E))
5140 return false;
5141 }
5142 }
5143
5144 return true;
5145}
5146
5147template <class Emitter>
5148bool Compiler<Emitter>::visitZeroArrayInitializer(QualType T, const Expr *E) {
5149 assert(T->isArrayType() || T->isAnyComplexType() || T->isVectorType());
5150 const ArrayType *AT = T->getAsArrayTypeUnsafe();
5151 QualType ElemType = AT->getElementType();
5152 size_t NumElems = cast<ConstantArrayType>(AT)->getZExtSize();
5153
5154 if (OptPrimType ElemT = classify(ElemType)) {
5155 for (size_t I = 0; I != NumElems; ++I) {
5156 if (!this->visitZeroInitializer(*ElemT, ElemType, E))
5157 return false;
5158 if (!this->emitInitElem(*ElemT, I, E))
5159 return false;
5160 }
5161 return true;
5162 }
5163 if (ElemType->isRecordType()) {
5164 const Record *R = getRecord(ElemType);
5165 if (!R)
5166 return false;
5167
5168 for (size_t I = 0; I != NumElems; ++I) {
5169 if (!this->emitConstUint32(I, E))
5170 return false;
5171 if (!this->emitArrayElemPtr(PT_Uint32, E))
5172 return false;
5173 if (!this->visitZeroRecordInitializer(R, E))
5174 return false;
5175 if (!this->emitPopPtr(E))
5176 return false;
5177 }
5178 return true;
5179 }
5180 if (ElemType->isArrayType()) {
5181 for (size_t I = 0; I != NumElems; ++I) {
5182 if (!this->emitConstUint32(I, E))
5183 return false;
5184 if (!this->emitArrayElemPtr(PT_Uint32, E))
5185 return false;
5186 if (!this->visitZeroArrayInitializer(ElemType, E))
5187 return false;
5188 if (!this->emitPopPtr(E))
5189 return false;
5190 }
5191 return true;
5192 }
5193
5194 return false;
5195}
5196
5197template <class Emitter>
5198bool Compiler<Emitter>::visitAssignment(const Expr *LHS, const Expr *RHS,
5199 const Expr *E) {
5200 if (!canClassify(E->getType()))
5201 return false;
5202
5203 bool NeedsFlip = !isSideEffectFree(RHS);
5204 if (!NeedsFlip) {
5205 if (!this->visit(LHS))
5206 return false;
5207 if (!this->visit(RHS))
5208 return false;
5209 } else {
5210 if (!this->visit(RHS))
5211 return false;
5212 if (!this->visit(LHS))
5213 return false;
5214 }
5215
5216 if (LHS->getType().isVolatileQualified())
5217 return this->emitInvalidStore(LHS->getType().getTypePtr(), E);
5218
5219 // We don't support assignments in C.
5220 if (!Ctx.getLangOpts().CPlusPlus && !this->emitInvalid(E))
5221 return false;
5222
5223 PrimType RHT = classifyPrim(RHS);
5224 bool Activates = refersToUnion(LHS);
5225 bool BitField = LHS->refersToBitField();
5226
5227 if (NeedsFlip && !this->emitFlip(PT_Ptr, RHT, E))
5228 return false;
5229
5230 if (DiscardResult) {
5231 if (BitField && Activates)
5232 return this->emitStoreBitFieldActivatePop(RHT, E);
5233 if (BitField)
5234 return this->emitStoreBitFieldPop(RHT, E);
5235 if (Activates)
5236 return this->emitStoreActivatePop(RHT, E);
5237 // Otherwise, regular non-activating store.
5238 return this->emitStorePop(RHT, E);
5239 }
5240
5241 auto maybeLoad = [&](bool Result) -> bool {
5242 if (!Result)
5243 return false;
5244 // Assignments aren't necessarily lvalues in C.
5245 // Load from them in that case.
5246 if (!E->isLValue())
5247 return this->emitLoadPop(RHT, E);
5248 return true;
5249 };
5250
5251 if (BitField && Activates)
5252 return maybeLoad(this->emitStoreBitFieldActivate(RHT, E));
5253 if (BitField)
5254 return maybeLoad(this->emitStoreBitField(RHT, E));
5255 if (Activates)
5256 return maybeLoad(this->emitStoreActivate(RHT, E));
5257 // Otherwise, regular non-activating store.
5258 return maybeLoad(this->emitStore(RHT, E));
5259}
5260
5261template <class Emitter>
5262template <typename T>
5263bool Compiler<Emitter>::emitConst(T Value, PrimType Ty, SourceInfo Info) {
5264 switch (Ty) {
5265 case PT_Sint8:
5266 return this->emitConstSint8(Value, Info);
5267 case PT_Uint8:
5268 return this->emitConstUint8(Value, Info);
5269 case PT_Sint16:
5270 return this->emitConstSint16(Value, Info);
5271 case PT_Uint16:
5272 return this->emitConstUint16(Value, Info);
5273 case PT_Sint32:
5274 return this->emitConstSint32(Value, Info);
5275 case PT_Uint32:
5276 return this->emitConstUint32(Value, Info);
5277 case PT_Sint64:
5278 return this->emitConstSint64(Value, Info);
5279 case PT_Uint64:
5280 return this->emitConstUint64(Value, Info);
5281 case PT_Bool:
5282 return this->emitConstBool(Value, Info);
5283 case PT_Ptr:
5284 case PT_MemberPtr:
5285 case PT_Float:
5286 case PT_IntAP:
5287 case PT_IntAPS:
5288 case PT_FixedPoint:
5289 llvm_unreachable("Invalid integral type");
5290 break;
5291 }
5292 llvm_unreachable("unknown primitive type");
5293}
5294
5295template <class Emitter>
5296template <typename T>
5297bool Compiler<Emitter>::emitConst(T Value, const Expr *E) {
5298 return this->emitConst(Value, classifyPrim(E->getType()), E);
5299}
5300
5301template <class Emitter>
5302bool Compiler<Emitter>::emitConst(const APSInt &Value, PrimType Ty,
5303 SourceInfo Info) {
5304 if (Ty == PT_IntAPS)
5305 return this->emitConstIntAPS(Value, Info);
5306 if (Ty == PT_IntAP)
5307 return this->emitConstIntAP(Value, Info);
5308
5309 if (Value.isSigned())
5310 return this->emitConst(Value.getSExtValue(), Ty, Info);
5311 return this->emitConst(Value.getZExtValue(), Ty, Info);
5312}
5313
5314template <class Emitter>
5315bool Compiler<Emitter>::emitConst(const APInt &Value, PrimType Ty,
5316 SourceInfo Info) {
5317 if (Ty == PT_IntAPS)
5318 return this->emitConstIntAPS(Value, Info);
5319 if (Ty == PT_IntAP)
5320 return this->emitConstIntAP(Value, Info);
5321
5322 if (isSignedType(Ty))
5323 return this->emitConst(Value.getSExtValue(), Ty, Info);
5324 return this->emitConst(Value.getZExtValue(), Ty, Info);
5325}
5326
5327template <class Emitter>
5328bool Compiler<Emitter>::emitConst(const APSInt &Value, const Expr *E) {
5329 return this->emitConst(Value, classifyPrim(E->getType()), E);
5330}
5331
5332template <class Emitter>
5334 PrimType Ty, bool IsConst,
5335 bool IsVolatile,
5336 ScopeKind SC) {
5337 // FIXME: There are cases where Src.isExpr() is wrong, e.g.
5338 // (int){12} in C. Consider using Expr::isTemporaryObject() instead
5339 // or isa<MaterializeTemporaryExpr>().
5340 Descriptor *D = P.createDescriptor(Src, Ty, nullptr, IsConst, Src.isExpr(),
5341 /*IsMutable=*/false, IsVolatile);
5343 Scope::Local Local = this->createLocal(D);
5344 if (auto *VD = Src.asValueDecl())
5345 Locals.insert({VD, Local});
5346 VarScope->addForScopeKind(Local, SC);
5347 return Local.Offset;
5348}
5349
5350template <class Emitter>
5352 ScopeKind SC) {
5353 const ValueDecl *Key = nullptr;
5354 const Expr *Init = nullptr;
5355 bool IsTemporary = false;
5356 if (auto *VD = Src.asValueDecl()) {
5357 Key = VD;
5358
5359 if (const auto *VarD = dyn_cast<VarDecl>(VD))
5360 Init = VarD->getInit();
5361 }
5362 if (const auto *E = Src.asExpr()) {
5363 IsTemporary = true;
5364 if (Ty.isNull())
5365 Ty = E->getType();
5366 }
5367
5368 Descriptor *D = P.createDescriptor(
5369 Src, Ty.getTypePtr(), Ty.isConstQualified(), IsTemporary,
5370 /*IsMutable=*/false, /*IsVolatile=*/Ty.isVolatileQualified(), Init);
5371 if (!D)
5372 return std::nullopt;
5374
5375 Scope::Local Local = this->createLocal(D);
5376 if (Key)
5377 Locals.insert({Key, Local});
5378 VarScope->addForScopeKind(Local, SC);
5379 return Local.Offset;
5380}
5381
5382template <class Emitter>
5384 QualType Ty = E->getType();
5385 assert(!Ty->isRecordType());
5386
5387 Descriptor *D = P.createDescriptor(E, Ty.getTypePtr(), Ty.isConstQualified(),
5388 /*IsTemporary=*/true);
5389
5390 if (!D)
5391 return std::nullopt;
5392
5393 Scope::Local Local = this->createLocal(D);
5395 assert(S);
5396 // Attach to topmost scope.
5397 while (S->getParent())
5398 S = S->getParent();
5399 assert(S && !S->getParent());
5400 S->addLocal(Local);
5401 return Local.Offset;
5402}
5403
5404template <class Emitter>
5406 if (const PointerType *PT = dyn_cast<PointerType>(Ty))
5407 return PT->getPointeeType()->getAsCanonical<RecordType>();
5408 return Ty->getAsCanonical<RecordType>();
5409}
5410
5411template <class Emitter> Record *Compiler<Emitter>::getRecord(QualType Ty) {
5412 if (const auto *RecordTy = getRecordTy(Ty))
5413 return getRecord(RecordTy->getDecl()->getDefinitionOrSelf());
5414 return nullptr;
5415}
5416
5417template <class Emitter>
5419 return P.getOrCreateRecord(RD);
5420}
5421
5422template <class Emitter>
5424 return Ctx.getOrCreateFunction(FD);
5425}
5426
5427template <class Emitter>
5428bool Compiler<Emitter>::visitExpr(const Expr *E, bool DestroyToplevelScope) {
5430
5431 auto maybeDestroyLocals = [&]() -> bool {
5432 if (DestroyToplevelScope)
5433 return RootScope.destroyLocals() && this->emitCheckAllocations(E);
5434 return this->emitCheckAllocations(E);
5435 };
5436
5437 // Void expressions.
5438 if (E->getType()->isVoidType()) {
5439 if (!visit(E))
5440 return false;
5441 return this->emitRetVoid(E) && maybeDestroyLocals();
5442 }
5443
5444 // Expressions with a primitive return type.
5445 if (OptPrimType T = classify(E)) {
5446 if (!visit(E))
5447 return false;
5448
5449 return this->emitRet(*T, E) && maybeDestroyLocals();
5450 }
5451
5452 // Expressions with a composite return type.
5453 // For us, that means everything we don't
5454 // have a PrimType for.
5455 if (UnsignedOrNone LocalOffset = this->allocateLocal(E)) {
5456 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalOffset));
5457 if (!this->emitGetPtrLocal(*LocalOffset, E))
5458 return false;
5459
5460 if (!visitInitializer(E))
5461 return false;
5462 // We are destroying the locals AFTER the Ret op.
5463 // The Ret op needs to copy the (alive) values, but the
5464 // destructors may still turn the entire expression invalid.
5465 return this->emitRetValue(E) && maybeDestroyLocals();
5466 }
5467
5468 return maybeDestroyLocals() && false;
5469}
5470
5471template <class Emitter>
5473 bool DestroyToplevelScope) {
5474 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5475 /*NewInitializing=*/false, /*ToLValue=*/true);
5476
5477 return this->visitExpr(E, DestroyToplevelScope);
5478}
5479
5480template <class Emitter>
5482
5483 auto R = this->visitVarDecl(VD, VD->getInit(), /*Toplevel=*/true);
5484
5485 if (R.notCreated())
5486 return R;
5487
5488 if (R)
5489 return true;
5490
5491 if (!R && Context::shouldBeGloballyIndexed(VD)) {
5492 if (auto GlobalIndex = P.getGlobal(VD)) {
5493 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
5494 auto &GD = GlobalBlock->getBlockDesc<GlobalInlineDescriptor>();
5495
5497 GlobalBlock->invokeDtor();
5498 }
5499 }
5500
5501 return R;
5502}
5503
5504/// Toplevel visitDeclAndReturn().
5505/// We get here from evaluateAsInitializer().
5506/// We need to evaluate the initializer and return its value.
5507template <class Emitter>
5509 bool ConstantContext) {
5510 // We only create variables if we're evaluating in a constant context.
5511 // Otherwise, just evaluate the initializer and return it.
5512 if (!ConstantContext) {
5513 DeclScope<Emitter> LS(this, VD);
5514 if (!this->visit(Init))
5515 return false;
5516 return this->emitRet(classify(Init).value_or(PT_Ptr), VD) &&
5517 LS.destroyLocals() && this->emitCheckAllocations(VD);
5518 }
5519
5520 LocalScope<Emitter> VDScope(this);
5521 if (!this->visitVarDecl(VD, Init, /*Toplevel=*/true))
5522 return false;
5523
5524 OptPrimType VarT = classify(VD->getType());
5525 bool IsReference = VD->getType()->isReferenceType();
5527 auto GlobalIndex = P.getGlobal(VD);
5528 assert(GlobalIndex); // visitVarDecl() didn't return false.
5529 if (VarT) {
5530 if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
5531 return false;
5532 } else {
5533 if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
5534 return false;
5535 }
5536 } else {
5537 auto Local = Locals.find(VD);
5538 assert(Local != Locals.end()); // Same here.
5539 if (VarT) {
5540 if (IsReference) {
5541 if (!this->emitGetRefLocal(Local->second.Offset, VD))
5542 return false;
5543 } else if (!this->emitGetLocal(*VarT, Local->second.Offset, VD))
5544 return false;
5545 } else {
5546 if (!this->emitGetPtrLocal(Local->second.Offset, VD))
5547 return false;
5548 }
5549 }
5550
5551 // Return the value.
5552 if (!this->emitRet(VarT.value_or(PT_Ptr), VD)) {
5553 // If the Ret above failed and this is a global variable, mark it as
5554 // uninitialized, even everything else succeeded.
5556 auto GlobalIndex = P.getGlobal(VD);
5557 assert(GlobalIndex);
5558 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
5559 auto &GD = GlobalBlock->getBlockDesc<GlobalInlineDescriptor>();
5560
5562 GlobalBlock->invokeDtor();
5563 }
5564 return false;
5565 }
5566
5567 return VDScope.destroyLocals() && this->emitCheckAllocations(VD);
5568}
5569
5570template <class Emitter>
5572 const Expr *Init,
5573 bool Toplevel) {
5574 QualType VarTy = VD->getType();
5575 // We don't know what to do with these, so just return false.
5576 if (VarTy.isNull())
5577 return false;
5578
5579 // This case is EvalEmitter-only. If we won't create any instructions for the
5580 // initializer anyway, don't bother creating the variable in the first place.
5581 if (!this->isActive())
5583
5584 OptPrimType VarT = classify(VD->getType());
5585
5586 if (Init && Init->isValueDependent())
5587 return false;
5588
5590 auto checkDecl = [&]() -> bool {
5591 bool NeedsOp = !Toplevel && VD->isLocalVarDecl() && VD->isStaticLocal();
5592 return !NeedsOp || this->emitCheckDecl(VD, VD);
5593 };
5594
5596 UnsignedOrNone GlobalIndex = P.getGlobal(VD);
5597 if (GlobalIndex) {
5598 // The global was previously created but the initializer failed.
5599 if (!P.getGlobal(*GlobalIndex)->isInitialized())
5600 return false;
5601 // We've already seen and initialized this global.
5602 if (P.isGlobalInitialized(*GlobalIndex))
5603 return checkDecl();
5604 // The previous attempt at initialization might've been unsuccessful,
5605 // so let's try this one.
5606 } else if ((GlobalIndex =
5607 P.createGlobal(VD, Init, VariablesAreConstexprUnknown))) {
5608 } else {
5609 return false;
5610 }
5611 if (!Init)
5612 return true;
5613
5614 if (!checkDecl())
5615 return false;
5616
5617 if (VarT) {
5618 if (!this->visit(Init))
5619 return false;
5620
5621 return this->emitInitGlobal(*VarT, *GlobalIndex, VD);
5622 }
5623
5624 if (!this->emitGetPtrGlobal(*GlobalIndex, Init))
5625 return false;
5626
5627 if (!this->emitStartInit(Init))
5628 return false;
5629
5630 if (!visitInitializer(Init))
5631 return false;
5632
5633 if (!this->emitEndInit(Init))
5634 return false;
5635
5636 return this->emitFinishInitGlobal(Init);
5637 }
5638 // Local variables.
5640
5641 if (VarT) {
5642 unsigned Offset = this->allocateLocalPrimitive(
5643 VD, *VarT, VarTy.isConstQualified(), VarTy.isVolatileQualified(),
5645
5646 if (!Init || Init->getType()->isVoidType())
5647 return true;
5648
5649 // If this is a toplevel declaration, create a scope for the
5650 // initializer.
5651 if (Toplevel) {
5653 if (!this->visit(Init))
5654 return false;
5655 return this->emitSetLocal(*VarT, Offset, VD) && Scope.destroyLocals();
5656 }
5657 if (!this->visit(Init))
5658 return false;
5659
5660 if (VarTy->isReferenceType()) {
5661 // [C++26][decl.ref]
5662 // The object designated by such a glvalue can be outside its lifetime
5663 // Because a null pointer value or a pointer past the end of an object
5664 // does not point to an object, a reference in a well-defined program
5665 // cannot refer to such things;
5666 assert(classifyPrim(VarTy) == PT_Ptr);
5667 if (!this->emitCheckRefInit(Init))
5668 return false;
5669 }
5670
5671 return this->emitSetLocal(*VarT, Offset, VD);
5672 }
5673 // Local composite variables.
5674 if (UnsignedOrNone Offset =
5675 this->allocateLocal(VD, VarTy, ScopeKind::Block)) {
5676 if (!Init)
5677 return true;
5678
5679 if (!this->emitGetPtrLocal(*Offset, Init))
5680 return false;
5681
5682 return visitInitializerPop(Init);
5683 }
5684 return false;
5685}
5686
5687template <class Emitter>
5689 assert(!canClassify(VD->getType()));
5690
5692 // Create a local variable to use as the instance.
5693 QualType Ty = VD->getType();
5694 Descriptor *D =
5695 P.createDescriptor(VD, Ty.getTypePtr(), /*IsConst=*/Ty.isConstQualified(),
5696 /*IsTemporary=*/false, /*IsMutable=*/false,
5697 /*IsVolatile=*/Ty.isVolatileQualified(), nullptr);
5698 if (!D)
5699 return false;
5700
5701 // FIXME: Would be nice if we didn't allocate the descriptor at all in this
5702 // case.
5703 if (D->hasTrivialDtor())
5704 return true;
5705
5706 Scope::Local Local = this->createLocal(D);
5707 Locals.insert({VD, Local});
5708 VarScope->addForScopeKind(Local, ScopeKind::Block);
5709
5710 if (!this->emitGetPtrLocal(Local.Offset, VD))
5711 return false;
5712
5713 if (!this->visitAPValueInitializer(Value, VD, Ty))
5714 return false;
5715
5716 return this->emitDestructionPop(D, VD);
5717}
5718
5720public:
5722 explicit ParamFinder() {}
5723
5724 bool VisitDeclRefExpr(const DeclRefExpr *E) override {
5725 if (const auto *P = dyn_cast<ParmVarDecl>(E->getDecl()))
5726 FoundParams.insert(P);
5727 return true;
5728 }
5729};
5730
5731/// Evaluate the \p Condition as if it was in the body of \p Callee.
5732/// Specifically, all the parameters of the callee are available to use
5733/// for the condition, and their values are given by \p Args (and \p This).
5734///
5735// Since this is a somewhat niche feature, we're abusing a few other mechanisms
5736// to implement this.
5737//
5738// We don't create an actual function frame but instead register the parameters
5739// as local variables.
5740//
5741// So we evaluate something like:
5742//
5743// bool thisfunc() {
5744// auto Arg0 = Args[0];
5745// ...
5746// return Condition;
5747// }
5748//
5749template <class Emitter>
5752 const Expr *This,
5753 const Expr *Condition) {
5754 // Instead of evaluating all parameters and trying to ignore failure,
5755 // we collect all the parameters used in the condition and only evaluate
5756 // those. Note that we still ignore failure in the loop below because the
5757 // failure might be inconsequential in the end,
5758 // e.g. in the case of `true || x`.
5759 ParamFinder PF;
5761
5762 LocalScope<Emitter> ArgScope(this);
5763 for (const ParmVarDecl *PVD : PF.FoundParams) {
5764 unsigned ParamIndex = 0;
5765 for (const ParmVarDecl *P : Callee->parameters()) {
5766 if (P == PVD)
5767 break;
5768 ++ParamIndex;
5769 }
5770
5771 const Expr *Arg = Args[ParamIndex];
5772 const ParmVarDecl *Param = Callee->getParamDecl(ParamIndex);
5773 if (OptPrimType ParamT = classify(Param->getType())) {
5774 unsigned ArgOffset =
5775 allocateLocalPrimitive(Param, *ParamT, /*IsConst=*/true);
5776 if (!this->visit(Arg))
5777 continue;
5778 if (!this->emitSetLocal(*ParamT, ArgOffset, Arg))
5779 return false;
5780 } else {
5781 UnsignedOrNone ArgOffset = this->allocateLocal(Param, Param->getType());
5782 if (!ArgOffset)
5783 return false;
5784 if (!this->emitGetPtrLocal(*ArgOffset, Arg))
5785 return false;
5786 if (!this->visitInitializerPop(Arg))
5787 continue;
5788 }
5789 }
5790
5791 if (This) {
5792 // We abuse the init stack for this and tell it to use
5793 // either a local variable or another decl for the This pointer.
5794 this->InitStackActive = true;
5795
5796 if (This->getType()->isPointerType()) {
5797 // Nothing to do here, the evaluation will fail if the instance
5798 // pointer is used.
5799 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(This)) {
5800 InitStack.push_back(InitLink::Decl(DRE->getDecl()));
5801 } else {
5802 assert(!canClassify(This->getType()));
5803 UnsignedOrNone ArgOffset = this->allocateLocal(This, This->getType());
5804 if (!ArgOffset)
5805 return false;
5806 if (!this->emitGetPtrLocal(*ArgOffset, This))
5807 return false;
5808 if (!this->visitInitializerPop(This))
5809 return false;
5810 this->InitStack.push_back(InitLink::Temp(*ArgOffset));
5811 }
5812 }
5813
5814 // Destruction of the argument values is part of the callee frame,
5815 // so we simply ignore them here.
5816 this->VarScope = nullptr;
5817
5818 LocalScope<Emitter> RetScope(this);
5819 if (!this->visit(Condition))
5820 return false;
5821 if (!RetScope.destroyLocals())
5822 return false;
5823
5824 // Result of the condition should be on the stack.
5825 return this->emitRet(PT_Bool, Condition);
5826}
5827
5828template <class Emitter>
5830 SourceInfo Info) {
5831 assert(!Val.isIndeterminate() && "Needs to be checked before");
5832 assert(!DiscardResult);
5833 if (Val.isInt())
5834 return this->emitConst(Val.getInt(), ValType, Info);
5835 if (Val.isFloat()) {
5836 APFloat F = Val.getFloat();
5837 return this->emitFloat(F, Info);
5838 }
5839
5840 if (Val.isMemberPointer()) {
5841 if (const ValueDecl *MemberDecl = Val.getMemberPointerDecl()) {
5842 if (!this->emitGetMemberPtr(MemberDecl, Info))
5843 return false;
5844
5845 bool IsDerived = Val.isMemberPointerToDerivedMember();
5846 // Apply the member pointer path.
5847 for (const CXXRecordDecl *PathEntry : Val.getMemberPointerPath()) {
5848 if (!this->emitCopyMemberPtrPath(PathEntry, IsDerived, Info))
5849 return false;
5850 }
5851
5852 return true;
5853 }
5854 return this->emitNullMemberPtr(0, nullptr, Info);
5855 }
5856
5857 if (Val.isLValue()) {
5858 if (Val.isNullPointer())
5859 return this->emitNull(ValType, 0, nullptr, Info);
5860
5863
5864 if (const Expr *BaseExpr = Base.dyn_cast<const Expr *>())
5865 return this->visit(BaseExpr);
5866 if (const auto *VD = Base.dyn_cast<const ValueDecl *>()) {
5867 if (!this->visitDeclRef(VD, Info.asExpr()))
5868 return false;
5869
5870 QualType EntryType = VD->getType();
5871 for (auto &Entry : Path) {
5872 if (EntryType->isArrayType()) {
5873 uint64_t Index = Entry.getAsArrayIndex();
5874 QualType ElemType =
5875 EntryType->getAsArrayTypeUnsafe()->getElementType();
5876 if (!this->emitConst(Index, PT_Uint64, Info))
5877 return false;
5878 if (!this->emitArrayElemPtrPop(PT_Uint64, Info))
5879 return false;
5880 EntryType = ElemType;
5881 } else {
5882 assert(EntryType->isRecordType());
5883 const Record *EntryRecord = getRecord(EntryType);
5884 if (!EntryRecord)
5885 return false;
5886
5887 const Decl *BaseOrMember = Entry.getAsBaseOrMember().getPointer();
5888 if (const auto *FD = dyn_cast<FieldDecl>(BaseOrMember)) {
5889 unsigned EntryOffset = EntryRecord->getField(FD)->Offset;
5890 if (!this->emitGetPtrFieldPop(EntryOffset, Info))
5891 return false;
5892 EntryType = FD->getType();
5893 } else {
5894 const auto *Base = cast<CXXRecordDecl>(BaseOrMember);
5895 if (const Record::Base *B = EntryRecord->getBaseOrNull(Base)) {
5896 if (!this->emitGetPtrBasePop(B->Offset, /*NullOK=*/false, Info))
5897 return false;
5898 } else {
5899 // Must be a virtual base.
5900 assert(EntryRecord->getVirtualBase(Base));
5901 if (!this->emitGetPtrVirtBasePop(Base, Info))
5902 return false;
5903 }
5904 EntryType = Ctx.getASTContext().getCanonicalTagType(Base);
5905 }
5906 }
5907 }
5908
5909 return true;
5910 }
5911 }
5912
5913 return false;
5914}
5915
5916template <class Emitter>
5918 SourceInfo Info, QualType T,
5919 bool IsCompleteClass) {
5920 if (Val.isStruct()) {
5921 const Record *R = this->getRecord(T);
5922 assert(R);
5923
5924 assert(R->getNumBases() == Val.getStructNumBases());
5925 if (IsCompleteClass)
5926 assert(R->getNumVirtualBases() == Val.getStructNumVirtualBases());
5927
5928 for (unsigned I = 0, N = Val.getStructNumBases(); I != N; ++I) {
5929 const APValue &B = Val.getStructBase(I);
5930 if (B.isIndeterminate())
5931 continue;
5932 const Record::Base *RB = R->getBase(I);
5933 QualType BaseType = Ctx.getASTContext().getCanonicalTagType(RB->Decl);
5934
5935 if (!this->emitGetPtrBase(RB->Offset, Info))
5936 return false;
5937 if (!this->visitAPValueInitializer(B, Info, BaseType,
5938 /*IsCompleteClass=*/false))
5939 return false;
5940 if (!this->emitFinishInitPop(Info))
5941 return false;
5942 }
5943
5944 for (unsigned I = 0, N = Val.getStructNumFields(); I != N; ++I) {
5945 const APValue &F = Val.getStructField(I);
5946 if (F.isIndeterminate())
5947 continue;
5948 const Record::Field *RF = R->getField(I);
5949 QualType FieldType = RF->Decl->getType();
5950 // Fields.
5951 if (OptPrimType PT = classify(FieldType)) {
5952 if (!this->visitAPValue(F, *PT, Info))
5953 return false;
5954 if (!this->emitInitField(*PT, RF->Offset, Info))
5955 return false;
5956 } else {
5957 if (!this->emitGetPtrField(RF->Offset, Info))
5958 return false;
5959 if (!this->visitAPValueInitializer(F, Info, FieldType))
5960 return false;
5961 if (!this->emitFinishInitPop(Info))
5962 return false;
5963 }
5964 }
5965
5966 // Virtual Bases.
5967 if (IsCompleteClass) {
5968 for (unsigned I = 0, N = Val.getStructNumVirtualBases(); I != N; ++I) {
5969 const APValue &B = Val.getStructVirtualBase(I);
5970 if (B.isIndeterminate())
5971 continue;
5972 const Record::Base *RB = R->getVirtualBase(I);
5973 QualType BaseType = Ctx.getASTContext().getCanonicalTagType(RB->Decl);
5974
5975 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(RB->R->getDecl()),
5976 Info))
5977 return false;
5978 if (!this->visitAPValueInitializer(B, Info, BaseType,
5979 /*IsCompleteClass=*/false))
5980 return false;
5981 if (!this->emitFinishInitPop(Info))
5982 return false;
5983 }
5984 }
5985
5986 return true;
5987 }
5988 if (Val.isUnion()) {
5989 const FieldDecl *UnionField = Val.getUnionField();
5990 if (!UnionField)
5991 return true;
5992 const Record *R = this->getRecord(T);
5993 assert(R);
5994 const APValue &F = Val.getUnionValue();
5995 if (F.isIndeterminate())
5996 return true;
5997 const Record::Field *RF = R->getField(UnionField);
5998 QualType FieldType = RF->Decl->getType();
5999
6000 if (OptPrimType PT = classify(FieldType)) {
6001 if (!this->visitAPValue(F, *PT, Info))
6002 return false;
6003 if (RF->isBitField())
6004 return this->emitInitBitFieldActivate(*PT, RF->Offset, RF->bitWidth(),
6005 Info);
6006 return this->emitInitFieldActivate(*PT, RF->Offset, Info);
6007 }
6008
6009 if (!this->emitGetPtrField(RF->Offset, Info))
6010 return false;
6011 if (!this->emitActivate(Info))
6012 return false;
6013 if (!this->visitAPValueInitializer(F, Info, FieldType))
6014 return false;
6015 return this->emitPopPtr(Info);
6016 }
6017 if (Val.isArray()) {
6018 unsigned InitializedElems = Val.getArrayInitializedElts();
6019 const auto *ArrType = T->getAsArrayTypeUnsafe();
6020 QualType ElemType = ArrType->getElementType();
6021 OptPrimType ElemT = classify(ElemType);
6022
6023 for (unsigned A = 0, AN = Val.getArraySize(); A != AN; ++A) {
6024 const APValue &Elem = A >= InitializedElems
6025 ? Val.getArrayFiller()
6026 : Val.getArrayInitializedElt(A);
6027 if (Elem.isIndeterminate())
6028 continue;
6029
6030 if (ElemT) {
6031 if (!this->visitAPValue(Elem, *ElemT, Info))
6032 return false;
6033 if (!this->emitInitElem(*ElemT, A, Info))
6034 return false;
6035 } else {
6036 if (!this->emitConstUint32(A, Info))
6037 return false;
6038 if (!this->emitArrayElemPtrUint32(Info))
6039 return false;
6040 if (!this->visitAPValueInitializer(Elem, Info, ElemType))
6041 return false;
6042 if (!this->emitPopPtr(Info))
6043 return false;
6044 }
6045 }
6046 return true;
6047 }
6048 // TODO: Other types.
6049
6050 return false;
6051}
6052
6053template <class Emitter>
6055 unsigned BuiltinID) {
6056 if (BuiltinID == Builtin::BI__builtin_constant_p) {
6057 // Void argument is always invalid and harder to handle later.
6058 if (E->getArg(0)->getType()->isVoidType()) {
6059 if (DiscardResult)
6060 return true;
6061 return this->emitConst(0, E);
6062 }
6063
6064 if (!this->emitStartSpeculation(E))
6065 return false;
6066 LabelTy EndLabel = this->getLabel();
6067 if (!this->speculate(E, EndLabel))
6068 return false;
6069 if (!this->emitEndSpeculation(E))
6070 return false;
6071 this->fallthrough(EndLabel);
6072 if (DiscardResult)
6073 return this->emitPop(classifyPrim(E), E);
6074 return true;
6075 }
6076
6077 // For these, we're expected to ultimately return an APValue pointing
6078 // to the CallExpr. This is needed to get the correct codegen.
6079 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6080 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString ||
6081 BuiltinID == Builtin::BI__builtin_ptrauth_sign_constant ||
6082 BuiltinID == Builtin::BI__builtin_function_start) {
6083 if (DiscardResult)
6084 return true;
6085 return this->emitDummyPtr(E, E);
6086 }
6087
6089 OptPrimType ReturnT = classify(E);
6090
6091 // Non-primitive return type. Prepare storage.
6092 if (!Initializing && !ReturnT && !ReturnType->isVoidType()) {
6093 UnsignedOrNone LocalIndex = allocateLocal(E);
6094 if (!LocalIndex)
6095 return false;
6096 if (!this->emitGetPtrLocal(*LocalIndex, E))
6097 return false;
6098 }
6099
6100 // Prepare function arguments including special cases.
6101 switch (BuiltinID) {
6102 case Builtin::BI__builtin_object_size:
6103 case Builtin::BI__builtin_dynamic_object_size: {
6104 assert(E->getNumArgs() == 2);
6105 const Expr *Arg0 = E->getArg(0);
6106 if (Arg0->isGLValue()) {
6107 if (!this->visit(Arg0))
6108 return false;
6109
6110 } else {
6111 if (!this->visitAsLValue(Arg0))
6112 return false;
6113 }
6114 if (!this->visit(E->getArg(1)))
6115 return false;
6116
6117 } break;
6118 case Builtin::BI__assume:
6119 case Builtin::BI__builtin_assume:
6120 // Argument is not evaluated.
6121 break;
6122 case Builtin::BI__atomic_is_lock_free:
6123 case Builtin::BI__atomic_always_lock_free: {
6124 assert(E->getNumArgs() == 2);
6125 if (!this->visit(E->getArg(0)))
6126 return false;
6127 if (!this->visitAsLValue(E->getArg(1)))
6128 return false;
6129 } break;
6130
6131 default:
6132 if (!Context::isUnevaluatedBuiltin(BuiltinID)) {
6133 // Put arguments on the stack.
6134 for (const auto *Arg : E->arguments()) {
6135 if (!this->visit(Arg))
6136 return false;
6137 }
6138 }
6139 }
6140
6141 if (!this->emitCallBI(E, BuiltinID, E))
6142 return false;
6143
6144 if (DiscardResult && !ReturnType->isVoidType())
6145 return this->emitPop(ReturnT.value_or(PT_Ptr), E);
6146
6147 return true;
6148}
6149
6150template <class Emitter>
6152 if (E->containsErrors())
6153 return false;
6154 const FunctionDecl *FuncDecl = E->getDirectCallee();
6155
6156 if (FuncDecl) {
6157 if (unsigned BuiltinID = FuncDecl->getBuiltinID())
6158 return VisitBuiltinCallExpr(E, BuiltinID);
6159
6160 // Calls to replaceable operator new/operator delete.
6162 if (FuncDecl->getDeclName().isAnyOperatorNew())
6163 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_new);
6164 assert(FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
6165 FuncDecl->getDeclName().getCXXOverloadedOperator() ==
6166 OO_Array_Delete);
6167 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_delete);
6168 }
6169
6170 // Explicit calls to trivial destructors
6171 if (const auto *DD = dyn_cast<CXXDestructorDecl>(FuncDecl);
6172 DD && DD->isTrivial()) {
6173 const auto *MemberCall = cast<CXXMemberCallExpr>(E);
6174 if (!this->visit(MemberCall->getImplicitObjectArgument()))
6175 return false;
6176 return this->emitCheckDestruction(E) && this->emitEndLifetime(E) &&
6177 this->emitPopPtr(E);
6178 }
6179 }
6180
6181 LocalScope<Emitter> CallScope(this, ScopeKind::Call);
6182
6183 QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
6185 bool HasRVO = !ReturnType->isVoidType() && !T;
6186
6187 if (HasRVO) {
6188 if (DiscardResult) {
6189 // If we need to discard the return value but the function returns its
6190 // value via an RVO pointer, we need to create one such pointer just
6191 // for this call.
6192 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
6193 if (!this->emitGetPtrLocal(*LocalIndex, E))
6194 return false;
6195 }
6196 } else {
6197 // We need the result. Prepare a pointer to return or
6198 // dup the current one.
6199 if (!Initializing) {
6200 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
6201 if (!this->emitGetPtrLocal(*LocalIndex, E))
6202 return false;
6203 }
6204 }
6205 if (!this->emitDupPtr(E))
6206 return false;
6207 }
6208 }
6209
6211
6212 bool IsAssignmentOperatorCall = false;
6213 bool ActivateLHS = false;
6214 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
6215 OCE && OCE->isAssignmentOp()) {
6216 // Just like with regular assignments, we need to special-case assignment
6217 // operators here and evaluate the RHS (the second arg) before the LHS (the
6218 // first arg). We fix this by using a Flip op later.
6219 assert(Args.size() == 2);
6220 const CXXRecordDecl *LHSRecord = Args[0]->getType()->getAsCXXRecordDecl();
6221 ActivateLHS = LHSRecord && LHSRecord->hasTrivialDefaultConstructor();
6222 IsAssignmentOperatorCall = true;
6223 std::reverse(Args.begin(), Args.end());
6224 }
6225 // Calling a static operator will still
6226 // pass the instance, but we don't need it.
6227 // Discard it here.
6228 if (isa<CXXOperatorCallExpr>(E)) {
6229 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl);
6230 MD && MD->isStatic()) {
6231 if (!this->discard(E->getArg(0)))
6232 return false;
6233 // Drop first arg.
6234 Args.erase(Args.begin());
6235 }
6236 }
6237
6238 bool Devirtualized = false;
6239 UnsignedOrNone CalleeOffset = std::nullopt;
6240 // Add the (optional, implicit) This pointer.
6241 if (const auto *MC = dyn_cast<CXXMemberCallExpr>(E)) {
6242 if (!FuncDecl && classifyPrim(E->getCallee()) == PT_MemberPtr) {
6243 // If we end up creating a CallPtr op for this, we need the base of the
6244 // member pointer as the instance pointer, and later extract the function
6245 // decl as the function pointer.
6246 const Expr *Callee = E->getCallee();
6247 CalleeOffset =
6248 this->allocateLocalPrimitive(Callee, PT_MemberPtr, /*IsConst=*/true);
6249 if (!this->visit(Callee))
6250 return false;
6251 if (!this->emitSetLocal(PT_MemberPtr, *CalleeOffset, E))
6252 return false;
6253 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
6254 return false;
6255 if (!this->emitGetMemberPtrBase(E))
6256 return false;
6257 } else {
6258 const auto *InstancePtr = MC->getImplicitObjectArgument();
6259 if (isa_and_nonnull<CXXDestructorDecl>(CompilingFunction) ||
6260 isa_and_nonnull<CXXConstructorDecl>(CompilingFunction)) {
6261 const auto *Stripped = stripCheckedDerivedToBaseCasts(InstancePtr);
6262 if (isa<CXXThisExpr>(Stripped)) {
6263 FuncDecl =
6264 cast<CXXMethodDecl>(FuncDecl)->getCorrespondingMethodInClass(
6265 Stripped->getType()->getPointeeType()->getAsCXXRecordDecl());
6266 Devirtualized = true;
6267 if (!this->visit(Stripped))
6268 return false;
6269 } else {
6270 if (!this->visit(InstancePtr))
6271 return false;
6272 }
6273 } else {
6274 if (!this->visit(InstancePtr))
6275 return false;
6276 }
6277 }
6278 } else if (const auto *PD =
6279 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee())) {
6280 if (!this->emitCheckPseudoDtor(E))
6281 return false;
6282 const Expr *Base = PD->getBase();
6283 // E.g. `using T = int; 0.~T();`.
6284 if (OptPrimType BaseT = classify(Base); !BaseT || BaseT != PT_Ptr)
6285 return this->discard(Base);
6286 if (!this->visit(Base))
6287 return false;
6288 return this->emitPseudoDtor(E);
6289 } else if (!FuncDecl) {
6290 const Expr *Callee = E->getCallee();
6291 CalleeOffset =
6292 this->allocateLocalPrimitive(Callee, PT_Ptr, /*IsConst=*/true);
6293 if (!this->visit(Callee))
6294 return false;
6295 if (!this->emitSetLocal(PT_Ptr, *CalleeOffset, E))
6296 return false;
6297 }
6298
6299 if (!this->visitCallArgs(Args, FuncDecl, ActivateLHS,
6301 return false;
6302
6303 // Undo the argument reversal we did earlier.
6304 if (IsAssignmentOperatorCall) {
6305 assert(Args.size() == 2);
6306 PrimType Arg1T = classify(Args[0]).value_or(PT_Ptr);
6307 PrimType Arg2T = classify(Args[1]).value_or(PT_Ptr);
6308 if (!this->emitFlip(Arg2T, Arg1T, E))
6309 return false;
6310 }
6311
6312 if (FuncDecl) {
6313 const Function *Func = getFunction(FuncDecl);
6314 if (!Func)
6315 return false;
6316
6317 // In error cases, the function may be called with fewer arguments than
6318 // parameters.
6319 if (E->getNumArgs() < Func->getNumWrittenParams())
6320 return false;
6321
6322 assert(HasRVO == Func->hasRVO());
6323
6324 bool HasQualifier = false;
6325 if (const auto *ME = dyn_cast<MemberExpr>(E->getCallee()))
6326 HasQualifier = ME->hasQualifier();
6327
6328 bool IsVirtual = false;
6329 if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl))
6330 IsVirtual = !Devirtualized && MD->isVirtual();
6331
6332 // In any case call the function. The return value will end up on the stack
6333 // and if the function has RVO, we already have the pointer on the stack to
6334 // write the result into.
6335 if (IsVirtual && !HasQualifier) {
6336 uint32_t VarArgSize = 0;
6337 unsigned NumParams =
6338 Func->getNumWrittenParams() +
6339 (isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisPointer());
6340 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
6341 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6342
6343 if (!this->emitCallVirt(Func, VarArgSize, E))
6344 return false;
6345 } else if (Func->isVariadic()) {
6346 uint32_t VarArgSize = 0;
6347 unsigned NumParams =
6348 Func->getNumWrittenParams() +
6349 (isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisPointer());
6350 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
6351 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6352 if (!this->emitCallVar(Func, VarArgSize, E))
6353 return false;
6354 } else {
6355 if (!this->emitCall(Func, 0, E))
6356 return false;
6357 }
6358 } else {
6359 // Indirect call. Visit the callee, which will leave a FunctionPointer on
6360 // the stack. Cleanup of the returned value if necessary will be done after
6361 // the function call completed.
6362
6363 // Sum the size of all args from the call expr.
6364 uint32_t ArgSize = 0;
6365 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
6366 ArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6367
6368 // Get the callee, either from a member pointer or function pointer saved in
6369 // CalleeOffset.
6370 if (isa<CXXMemberCallExpr>(E) && CalleeOffset) {
6371 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
6372 return false;
6373 if (!this->emitGetMemberPtrDecl(E))
6374 return false;
6375 } else {
6376 if (!this->emitGetLocal(PT_Ptr, *CalleeOffset, E))
6377 return false;
6378 }
6379 if (!this->emitCallPtr(ArgSize, E, E))
6380 return false;
6381 }
6382
6383 // Cleanup for discarded return values.
6384 if (DiscardResult && !ReturnType->isVoidType() && T)
6385 return this->emitPop(*T, E) && CallScope.destroyLocals();
6386
6387 return CallScope.destroyLocals();
6388}
6389
6390template <class Emitter>
6392 SourceLocScope<Emitter> SLS(this, E);
6393
6394 return this->delegate(E->getExpr());
6395}
6396
6397template <class Emitter>
6399 SourceLocScope<Emitter> SLS(this, E);
6400
6401 return this->delegate(E->getExpr());
6402}
6403
6404template <class Emitter>
6406 if (DiscardResult)
6407 return true;
6408
6409 return this->emitConstBool(E->getValue(), E);
6410}
6411
6412template <class Emitter>
6414 const CXXNullPtrLiteralExpr *E) {
6415 if (DiscardResult)
6416 return true;
6417
6418 uint64_t Val = Ctx.getASTContext().getTargetNullPointerValue(E->getType());
6419 return this->emitNullPtr(Val, nullptr, E);
6420}
6421
6422template <class Emitter>
6424 if (DiscardResult)
6425 return true;
6426
6427 assert(E->getType()->isIntegerType());
6428
6430 return this->emitZero(T, E);
6431}
6432
6433template <class Emitter>
6435 if (DiscardResult)
6436 return true;
6437
6438 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
6439 if (this->LambdaThisCapture.Offset > 0) {
6440 if (this->LambdaThisCapture.IsPtr)
6441 return this->emitGetThisFieldPtr(this->LambdaThisCapture.Offset, E);
6442 return this->emitGetPtrThisField(this->LambdaThisCapture.Offset, E);
6443 }
6444 }
6445
6446 // In some circumstances, the 'this' pointer does not actually refer to the
6447 // instance pointer of the current function frame, but e.g. to the declaration
6448 // currently being initialized. Here we emit the necessary instruction(s) for
6449 // this scenario.
6450 if (!InitStackActive || InitStack.empty())
6451 return this->emitThis(E);
6452
6453 // If our init stack is, for example:
6454 // 0 Stack: 3 (decl)
6455 // 1 Stack: 6 (init list)
6456 // 2 Stack: 1 (field)
6457 // 3 Stack: 6 (init list)
6458 // 4 Stack: 1 (field)
6459 //
6460 // We want to find the LAST element in it that's an init list,
6461 // which is marked with the K_InitList marker. The index right
6462 // before that points to an init list. We need to find the
6463 // elements before the K_InitList element that point to a base
6464 // (e.g. a decl or This), optionally followed by field, elem, etc.
6465 // In the example above, we want to emit elements [0..2].
6466 unsigned StartIndex = 0;
6467 unsigned EndIndex = 0;
6468 // Find the init list.
6469 for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) {
6470 if (InitStack[StartIndex].Kind == InitLink::K_DIE) {
6471 EndIndex = StartIndex;
6472 --StartIndex;
6473 break;
6474 }
6475 }
6476
6477 // Walk backwards to find the base.
6478 for (; StartIndex > 0; --StartIndex) {
6479 if (InitStack[StartIndex].Kind == InitLink::K_InitList)
6480 continue;
6481
6482 if (InitStack[StartIndex].Kind != InitLink::K_Field &&
6483 InitStack[StartIndex].Kind != InitLink::K_Elem &&
6484 InitStack[StartIndex].Kind != InitLink::K_Base &&
6485 InitStack[StartIndex].Kind != InitLink::K_DIE)
6486 break;
6487 }
6488
6489 if (StartIndex == 0 && EndIndex == 0)
6490 EndIndex = InitStack.size() - 1;
6491
6492 assert(InitStack[StartIndex].Kind == InitLink::K_Decl ||
6493 InitStack[StartIndex].Kind == InitLink::K_This ||
6494 InitStack[StartIndex].Kind == InitLink::K_Temp ||
6495 InitStack[StartIndex].Kind == InitLink::K_RVO);
6496
6497 // NOTE: This could be StartIndex < EndIndex, but we're also abusing the
6498 // InitStack mechanism in visitWithSubstitutions to have the This pointer
6499 // _just_ be a local variable.
6500 assert(StartIndex <= EndIndex);
6501
6502 // Emit the instructions.
6503 for (unsigned I = StartIndex; I != (EndIndex + 1); ++I) {
6504 if (InitStack[I].Kind == InitLink::K_InitList ||
6505 InitStack[I].Kind == InitLink::K_DIE)
6506 continue;
6507 if (!InitStack[I].template emit<Emitter>(this, E))
6508 return false;
6509 }
6510 return true;
6511}
6512
6513template <class Emitter> bool Compiler<Emitter>::visitStmt(const Stmt *S) {
6514 switch (S->getStmtClass()) {
6515 case Stmt::CompoundStmtClass:
6517 case Stmt::DeclStmtClass:
6518 return visitDeclStmt(cast<DeclStmt>(S), /*EvaluateConditionDecl=*/true);
6519 case Stmt::ReturnStmtClass:
6521 case Stmt::IfStmtClass:
6522 return visitIfStmt(cast<IfStmt>(S));
6523 case Stmt::WhileStmtClass:
6525 case Stmt::DoStmtClass:
6526 return visitDoStmt(cast<DoStmt>(S));
6527 case Stmt::ForStmtClass:
6528 return visitForStmt(cast<ForStmt>(S));
6529 case Stmt::CXXForRangeStmtClass:
6531 case Stmt::BreakStmtClass:
6533 case Stmt::ContinueStmtClass:
6535 case Stmt::SwitchStmtClass:
6537 case Stmt::CaseStmtClass:
6538 return visitCaseStmt(cast<CaseStmt>(S));
6539 case Stmt::DefaultStmtClass:
6541 case Stmt::AttributedStmtClass:
6543 case Stmt::CXXTryStmtClass:
6545 case Stmt::NullStmtClass:
6546 return true;
6547 // Always invalid statements.
6548 case Stmt::GCCAsmStmtClass:
6549 case Stmt::MSAsmStmtClass:
6550 case Stmt::GotoStmtClass:
6551 return this->emitInvalid(S);
6552 case Stmt::LabelStmtClass:
6553 return this->visitStmt(cast<LabelStmt>(S)->getSubStmt());
6554 case Stmt::CXXExpansionStmtInstantiationClass:
6557 default: {
6558 if (const auto *E = dyn_cast<Expr>(S))
6559 return this->discard(E);
6560 return false;
6561 }
6562 }
6563}
6564
6565template <class Emitter>
6568 for (const auto *InnerStmt : S->body())
6569 if (!visitStmt(InnerStmt))
6570 return false;
6571 return Scope.destroyLocals();
6572}
6573
6574template <class Emitter>
6575bool Compiler<Emitter>::maybeEmitDeferredVarInit(const VarDecl *VD) {
6576 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
6577 for (auto *BD : DD->flat_bindings())
6578 if (auto *KD = BD->getHoldingVar();
6579 KD && !this->visitVarDecl(KD, KD->getInit()))
6580 return false;
6581 }
6582 return true;
6583}
6584
6586 assert(FD);
6587 assert(FD->getParent()->isUnion());
6588 const CXXRecordDecl *CXXRD =
6590 return !CXXRD || CXXRD->hasTrivialDefaultConstructor();
6591}
6592
6593template <class Emitter> bool Compiler<Emitter>::refersToUnion(const Expr *E) {
6594 for (;;) {
6595 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
6596 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6597 FD && FD->getParent()->isUnion() && hasTrivialDefaultCtorParent(FD))
6598 return true;
6599 E = ME->getBase();
6600 continue;
6601 }
6602
6603 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6604 E = ASE->getBase()->IgnoreImplicit();
6605 continue;
6606 }
6607
6608 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
6609 ICE && (ICE->getCastKind() == CK_NoOp ||
6610 ICE->getCastKind() == CK_DerivedToBase ||
6611 ICE->getCastKind() == CK_UncheckedDerivedToBase)) {
6612 E = ICE->getSubExpr();
6613 continue;
6614 }
6615
6616 if (const auto *This = dyn_cast<CXXThisExpr>(E)) {
6617 const auto *ThisRecord =
6618 This->getType()->getPointeeType()->getAsRecordDecl();
6619 if (!ThisRecord->isUnion())
6620 return false;
6621 // Otherwise, always activate if we're in the ctor.
6622 if (const auto *Ctor =
6623 dyn_cast_if_present<CXXConstructorDecl>(CompilingFunction))
6624 return Ctor->getParent() == ThisRecord;
6625 return false;
6626 }
6627
6628 break;
6629 }
6630 return false;
6631}
6632
6633template <class Emitter>
6635 bool EvaluateConditionDecl) {
6636 for (const auto *D : DS->decls()) {
6639 continue;
6640
6641 if (const auto *ESD = dyn_cast<CXXExpansionStmtDecl>(D)) {
6642 assert(ESD->getInstantiations() && "not expanded?");
6643 if (!this->visitStmt(ESD->getInstantiations()))
6644 return false;
6645 continue;
6646 }
6647
6648 const auto *VD = dyn_cast<VarDecl>(D);
6649 if (!VD)
6650 return false;
6651 if (!this->visitVarDecl(VD, VD->getInit()))
6652 return false;
6653
6654 // Register decomposition decl holding vars.
6655 if (EvaluateConditionDecl && !this->maybeEmitDeferredVarInit(VD))
6656 return false;
6657 }
6658
6659 return true;
6660}
6661
6662template <class Emitter>
6664 if (this->InStmtExpr)
6665 return this->emitUnsupported(RS);
6666
6667 if (const Expr *RE = RS->getRetValue()) {
6668 LocalScope<Emitter> RetScope(this);
6669 if (ReturnType) {
6670 // Primitive types are simply returned.
6671 if (!this->visit(RE))
6672 return false;
6673 this->emitCleanup();
6674 return this->emitRet(*ReturnType, RS);
6675 }
6676
6677 if (RE->getType()->isVoidType()) {
6678 if (!this->visit(RE))
6679 return false;
6680 } else {
6681 if (RE->containsErrors())
6682 return false;
6683
6685 // RVO - construct the value in the return location.
6686 if (!this->emitRVOPtr(RE))
6687 return false;
6688 if (!this->visitInitializerPop(RE))
6689 return false;
6690
6691 this->emitCleanup();
6692 return this->emitRetVoid(RS);
6693 }
6694 }
6695
6696 // Void return.
6697 this->emitCleanup();
6698 return this->emitRetVoid(RS);
6699}
6700
6701template <class Emitter> bool Compiler<Emitter>::visitIfStmt(const IfStmt *IS) {
6702 LocalScope<Emitter> IfScope(this);
6703
6704 auto visitChildStmt = [&](const Stmt *S) -> bool {
6705 LocalScope<Emitter> SScope(this);
6706 if (!visitStmt(S))
6707 return false;
6708 return SScope.destroyLocals();
6709 };
6710
6711 if (auto *CondInit = IS->getInit()) {
6712 if (!visitStmt(CondInit))
6713 return false;
6714 }
6715
6716 if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt()) {
6717 if (!visitDeclStmt(CondDecl))
6718 return false;
6719 }
6720
6721 // Save ourselves compiling some code and the jumps, etc. if the condition is
6722 // stataically known to be either true or false. We could look at more cases
6723 // here, but I think all the ones that actually happen are using a
6724 // ConstantExpr.
6725 if (std::optional<bool> BoolValue = getBoolValue(IS->getCond())) {
6726 if (*BoolValue)
6727 return visitChildStmt(IS->getThen());
6728 if (const Stmt *Else = IS->getElse())
6729 return visitChildStmt(Else);
6730 return true;
6731 }
6732
6733 // Otherwise, compile the condition.
6734 if (IS->isNonNegatedConsteval()) {
6735 if (!this->emitIsConstantContext(IS))
6736 return false;
6737 } else if (IS->isNegatedConsteval()) {
6738 if (!this->emitIsConstantContext(IS))
6739 return false;
6740 if (!this->emitInv(IS))
6741 return false;
6742 } else {
6744 if (!this->visitBool(IS->getCond()))
6745 return false;
6746 if (!CondScope.destroyLocals())
6747 return false;
6748 }
6749
6750 if (!this->maybeEmitDeferredVarInit(IS->getConditionVariable()))
6751 return false;
6752
6753 if (const Stmt *Else = IS->getElse()) {
6754 LabelTy LabelElse = this->getLabel();
6755 LabelTy LabelEnd = this->getLabel();
6756 if (!this->jumpFalse(LabelElse, IS))
6757 return false;
6758 if (!visitChildStmt(IS->getThen()))
6759 return false;
6760 if (!this->jump(LabelEnd, IS))
6761 return false;
6762 this->emitLabel(LabelElse);
6763 if (!visitChildStmt(Else))
6764 return false;
6765 this->emitLabel(LabelEnd);
6766 } else {
6767 LabelTy LabelEnd = this->getLabel();
6768 if (!this->jumpFalse(LabelEnd, IS))
6769 return false;
6770 if (!visitChildStmt(IS->getThen()))
6771 return false;
6772 this->emitLabel(LabelEnd);
6773 }
6774
6775 if (!IfScope.destroyLocals())
6776 return false;
6777
6778 return true;
6779}
6780
6781template <class Emitter>
6783 const Expr *Cond = S->getCond();
6784 const Stmt *Body = S->getBody();
6785
6786 LabelTy CondLabel = this->getLabel(); // Label before the condition.
6787 LabelTy EndLabel = this->getLabel(); // Label after the loop.
6788 LocalScope<Emitter> WholeLoopScope(this);
6789 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
6790
6791 this->fallthrough(CondLabel);
6792 this->emitLabel(CondLabel);
6793
6794 // Start of the loop body {
6795 LocalScope<Emitter> CondScope(this);
6796
6797 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
6798 if (!visitDeclStmt(CondDecl))
6799 return false;
6800 }
6801
6802 if (!this->visitBool(Cond))
6803 return false;
6804
6805 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
6806 return false;
6807
6808 if (!this->jumpFalse(EndLabel, S))
6809 return false;
6810
6811 if (!this->visitStmt(Body))
6812 return false;
6813
6814 if (!CondScope.destroyLocals())
6815 return false;
6816 // } End of loop body.
6817
6818 if (!this->jump(CondLabel, S))
6819 return false;
6820 this->fallthrough(EndLabel);
6821 this->emitLabel(EndLabel);
6822
6823 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
6824}
6825
6826template <class Emitter> bool Compiler<Emitter>::visitDoStmt(const DoStmt *S) {
6827 const Expr *Cond = S->getCond();
6828 const Stmt *Body = S->getBody();
6829
6830 LabelTy StartLabel = this->getLabel();
6831 LabelTy EndLabel = this->getLabel();
6832 LabelTy CondLabel = this->getLabel();
6833 LocalScope<Emitter> WholeLoopScope(this);
6834 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
6835
6836 this->fallthrough(StartLabel);
6837 this->emitLabel(StartLabel);
6838
6839 {
6840 LocalScope<Emitter> CondScope(this);
6841 if (!this->visitStmt(Body))
6842 return false;
6843 this->fallthrough(CondLabel);
6844 this->emitLabel(CondLabel);
6845 if (!this->visitBool(Cond))
6846 return false;
6847
6848 if (!CondScope.destroyLocals())
6849 return false;
6850 }
6851 if (!this->jumpTrue(StartLabel, S))
6852 return false;
6853
6854 this->fallthrough(EndLabel);
6855 this->emitLabel(EndLabel);
6856 return WholeLoopScope.destroyLocals();
6857}
6858
6859template <class Emitter>
6861 // for (Init; Cond; Inc) { Body }
6862 const Stmt *Init = S->getInit();
6863 const Expr *Cond = S->getCond();
6864 const Expr *Inc = S->getInc();
6865 const Stmt *Body = S->getBody();
6866
6867 LabelTy EndLabel = this->getLabel();
6868 LabelTy CondLabel = this->getLabel();
6869 LabelTy IncLabel = this->getLabel();
6870
6871 LocalScope<Emitter> WholeLoopScope(this);
6872 if (Init && !this->visitStmt(Init))
6873 return false;
6874
6875 // Start of the loop body {
6876 this->fallthrough(CondLabel);
6877 this->emitLabel(CondLabel);
6878
6879 LocalScope<Emitter> CondScope(this);
6880 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
6881 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
6882 if (!visitDeclStmt(CondDecl))
6883 return false;
6884 }
6885
6886 if (Cond) {
6887 if (!this->visitBool(Cond))
6888 return false;
6889 if (!this->jumpFalse(EndLabel, S))
6890 return false;
6891 }
6892 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
6893 return false;
6894
6895 if (Body && !this->visitStmt(Body))
6896 return false;
6897
6898 this->fallthrough(IncLabel);
6899 this->emitLabel(IncLabel);
6900 if (Inc && !this->discard(Inc))
6901 return false;
6902
6903 if (!CondScope.destroyLocals())
6904 return false;
6905 if (!this->jump(CondLabel, S))
6906 return false;
6907 // } End of loop body.
6908
6909 this->emitLabel(EndLabel);
6910 // If we jumped out of the loop above, we still need to clean up the condition
6911 // scope.
6912 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
6913}
6914
6915template <class Emitter>
6917 const Stmt *Init = S->getInit();
6918 const Expr *Cond = S->getCond();
6919 const Expr *Inc = S->getInc();
6920 const Stmt *Body = S->getBody();
6921 const Stmt *BeginStmt = S->getBeginStmt();
6922 const Stmt *RangeStmt = S->getRangeStmt();
6923 const Stmt *EndStmt = S->getEndStmt();
6924
6925 LabelTy EndLabel = this->getLabel();
6926 LabelTy CondLabel = this->getLabel();
6927 LabelTy IncLabel = this->getLabel();
6928 LocalScope<Emitter> WholeLoopScope(this);
6929 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
6930
6931 // Emit declarations needed in the loop.
6932 if (Init && !this->visitStmt(Init))
6933 return false;
6934 if (!this->visitStmt(RangeStmt))
6935 return false;
6936 if (!this->visitStmt(BeginStmt))
6937 return false;
6938 if (!this->visitStmt(EndStmt))
6939 return false;
6940
6941 // Now the condition as well as the loop variable assignment.
6942 this->fallthrough(CondLabel);
6943 this->emitLabel(CondLabel);
6944 if (!this->visitBool(Cond))
6945 return false;
6946 if (!this->jumpFalse(EndLabel, S))
6947 return false;
6948
6949 if (!this->visitDeclStmt(S->getLoopVarStmt(), /*EvaluateConditionDecl=*/true))
6950 return false;
6951
6952 // Body.
6953 {
6954 if (!this->visitStmt(Body))
6955 return false;
6956
6957 this->fallthrough(IncLabel);
6958 this->emitLabel(IncLabel);
6959 if (!this->discard(Inc))
6960 return false;
6961 }
6962
6963 if (!this->jump(CondLabel, S))
6964 return false;
6965
6966 this->fallthrough(EndLabel);
6967 this->emitLabel(EndLabel);
6968 return WholeLoopScope.destroyLocals();
6969}
6970
6971template <class Emitter>
6973 if (LabelInfoStack.empty())
6974 return false;
6975
6976 OptLabelTy TargetLabel = std::nullopt;
6977 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
6978 const VariableScope<Emitter> *BreakScope = nullptr;
6979
6980 if (!TargetLoop) {
6981 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
6982 if (LI.BreakLabel) {
6983 TargetLabel = *LI.BreakLabel;
6984 BreakScope = LI.BreakOrContinueScope;
6985 break;
6986 }
6987 }
6988 } else {
6989 for (const auto &LI : LabelInfoStack) {
6990 if (LI.Name == TargetLoop) {
6991 TargetLabel = *LI.BreakLabel;
6992 BreakScope = LI.BreakOrContinueScope;
6993 break;
6994 }
6995 }
6996 }
6997
6998 // Faulty break statement (e.g. label redefined or named loops disabled).
6999 if (!TargetLabel)
7000 return false;
7001
7002 for (VariableScope<Emitter> *C = this->VarScope; C != BreakScope;
7003 C = C->getParent()) {
7004 if (!C->destroyLocals())
7005 return false;
7006 }
7007
7008 return this->jump(*TargetLabel, S);
7009}
7010
7011template <class Emitter>
7013 if (LabelInfoStack.empty())
7014 return false;
7015
7016 OptLabelTy TargetLabel = std::nullopt;
7017 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
7018 const VariableScope<Emitter> *ContinueScope = nullptr;
7019
7020 if (!TargetLoop) {
7021 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
7022 if (LI.ContinueLabel) {
7023 TargetLabel = *LI.ContinueLabel;
7024 ContinueScope = LI.BreakOrContinueScope;
7025 break;
7026 }
7027 }
7028 } else {
7029 for (auto LI : LabelInfoStack) {
7030 if (LI.Name == TargetLoop) {
7031 TargetLabel = *LI.ContinueLabel;
7032 ContinueScope = LI.BreakOrContinueScope;
7033 break;
7034 }
7035 }
7036 }
7037
7038 if (!TargetLabel)
7039 return false;
7040
7041 for (VariableScope<Emitter> *C = VarScope; C != ContinueScope;
7042 C = C->getParent()) {
7043 if (!C->destroyLocals())
7044 return false;
7045 }
7046
7047 return this->jump(*TargetLabel, S);
7048}
7049
7050template <class Emitter>
7052 const Expr *Cond = S->getCond();
7053 if (Cond->containsErrors())
7054 return false;
7055
7056 PrimType CondT = this->classifyPrim(Cond->getType());
7057 LocalScope<Emitter> LS(this);
7058 llvm::SaveAndRestore StmtExprSAR(this->SwitchInStmtExpr, this->InStmtExpr);
7059
7060 LabelTy EndLabel = this->getLabel();
7061 UnsignedOrNone DefaultLabel = std::nullopt;
7062 unsigned CondVar =
7063 this->allocateLocalPrimitive(Cond, CondT, /*IsConst=*/true);
7064
7065 if (const auto *CondInit = S->getInit())
7066 if (!visitStmt(CondInit))
7067 return false;
7068
7069 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
7070 if (!visitDeclStmt(CondDecl))
7071 return false;
7072
7073 // Initialize condition variable.
7074 if (!this->visit(Cond))
7075 return false;
7076 if (!this->emitSetLocal(CondT, CondVar, S))
7077 return false;
7078
7079 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
7080 return false;
7081
7083 // Create labels and comparison ops for all case statements.
7084 for (const SwitchCase *SC = S->getSwitchCaseList(); SC;
7085 SC = SC->getNextSwitchCase()) {
7086 if (const auto *CS = dyn_cast<CaseStmt>(SC)) {
7087 CaseLabels[SC] = this->getLabel();
7088
7089 if (CS->caseStmtIsGNURange()) {
7090 LabelTy EndOfRangeCheck = this->getLabel();
7091 const Expr *Low = CS->getLHS();
7092 const Expr *High = CS->getRHS();
7093 if (Low->isValueDependent() || High->isValueDependent())
7094 return false;
7095
7096 if (!this->emitGetLocal(CondT, CondVar, CS))
7097 return false;
7098 if (!this->visit(Low))
7099 return false;
7100 PrimType LT = this->classifyPrim(Low->getType());
7101 if (!this->emitGE(LT, S))
7102 return false;
7103 if (!this->jumpFalse(EndOfRangeCheck, S))
7104 return false;
7105
7106 if (!this->emitGetLocal(CondT, CondVar, CS))
7107 return false;
7108 if (!this->visit(High))
7109 return false;
7110 PrimType HT = this->classifyPrim(High->getType());
7111 if (!this->emitLE(HT, S))
7112 return false;
7113 if (!this->jumpTrue(CaseLabels[CS], S))
7114 return false;
7115 this->emitLabel(EndOfRangeCheck);
7116 continue;
7117 }
7118
7119 const Expr *Value = CS->getLHS();
7120 if (Value->isValueDependent())
7121 return false;
7122 PrimType ValueT = this->classifyPrim(Value->getType());
7123
7124 // Compare the case statement's value to the switch condition.
7125 if (!this->emitGetLocal(CondT, CondVar, CS))
7126 return false;
7127 if (!this->visit(Value))
7128 return false;
7129
7130 // Compare and jump to the case label.
7131 if (!this->emitEQ(ValueT, S))
7132 return false;
7133 if (!this->jumpTrue(CaseLabels[CS], S))
7134 return false;
7135 } else {
7136 assert(!DefaultLabel);
7137 DefaultLabel = this->getLabel();
7138 }
7139 }
7140
7141 // If none of the conditions above were true, fall through to the default
7142 // statement or jump after the switch statement.
7143 if (DefaultLabel) {
7144 if (!this->jump(*DefaultLabel, S))
7145 return false;
7146 } else {
7147 if (!this->jump(EndLabel, S))
7148 return false;
7149 }
7150
7151 SwitchScope<Emitter> SS(this, S, std::move(CaseLabels), EndLabel,
7152 DefaultLabel);
7153 if (!this->visitStmt(S->getBody()))
7154 return false;
7155 this->fallthrough(EndLabel);
7156 this->emitLabel(EndLabel);
7157
7158 return LS.destroyLocals();
7159}
7160
7161template <class Emitter>
7163 this->fallthrough(CaseLabels[S]);
7164 this->emitLabel(CaseLabels[S]);
7165
7166 // We can't jump from an outer switch statement to a case label
7167 // that's inside a StmtExpr.
7168 if (this->InStmtExpr && !this->SwitchInStmtExpr)
7169 return this->emitUnsupported(S);
7170
7171 return this->visitStmt(S->getSubStmt());
7172}
7173
7174template <class Emitter>
7176 if (LabelInfoStack.empty())
7177 return false;
7178
7179 LabelTy DefaultLabel;
7180 for (const LabelInfo &LI : llvm::reverse(LabelInfoStack)) {
7181 if (LI.DefaultLabel) {
7182 DefaultLabel = *LI.DefaultLabel;
7183 break;
7184 }
7185 }
7186
7187 this->emitLabel(DefaultLabel);
7188 return this->visitStmt(S->getSubStmt());
7189}
7190
7191template <class Emitter>
7193 const Stmt *SubStmt = S->getSubStmt();
7194
7195 bool IsMSVCConstexprAttr = isa<ReturnStmt>(SubStmt) &&
7197
7198 if (IsMSVCConstexprAttr && !this->emitPushMSVCCE(S))
7199 return false;
7200
7201 if (this->Ctx.getLangOpts().CXXAssumptions &&
7202 !this->Ctx.getLangOpts().MSVCCompat) {
7203 for (const Attr *A : S->getAttrs()) {
7204 auto *AA = dyn_cast<CXXAssumeAttr>(A);
7205 if (!AA)
7206 continue;
7207
7208 assert(isa<NullStmt>(SubStmt));
7209
7210 const Expr *Assumption = AA->getAssumption();
7211 if (Assumption->isValueDependent())
7212 return false;
7213
7214 if (Assumption->HasSideEffects(this->Ctx.getASTContext()))
7215 continue;
7216
7217 // Evaluate assumption.
7218 if (!this->visitBool(Assumption))
7219 return false;
7220
7221 if (!this->emitAssume(Assumption))
7222 return false;
7223 }
7224 }
7225
7226 // Ignore other attributes.
7227 if (!this->visitStmt(SubStmt))
7228 return false;
7229
7230 if (IsMSVCConstexprAttr)
7231 return this->emitPopMSVCCE(S);
7232 return true;
7233}
7234
7235template <class Emitter>
7237 // Ignore all handlers.
7238 return this->visitStmt(S->getTryBlock());
7239}
7240
7241/// template for (auto x : {1, 2}) {}
7242///
7243/// This is not a loop from an AST perspective at all since it has already
7244/// been instantiated to a list of compound statements.
7245///
7246/// Since we can have control flow in those compound statements, we need to
7247/// handle it mostly like a loop though.
7248template <class Emitter>
7251 LocalScope<Emitter> WholeLoopScope(this, ScopeKind::Block);
7252
7253 for (const Stmt *PreambleStmt : S->getPreambleStmts()) {
7254 if (!this->visitDeclStmt(cast<DeclStmt>(PreambleStmt), true))
7255 return false;
7256 }
7257
7258 LabelTy EndLabel = this->getLabel();
7259 for (const Stmt *Instantiation : S->getInstantiations()) {
7260 LabelTy ContinueLabel = this->getLabel();
7261 LoopScope<Emitter> LS(this, S, EndLabel, ContinueLabel);
7262
7263 if (!this->visitStmt(Instantiation))
7264 return false;
7265 this->emitLabel(ContinueLabel);
7266 }
7267
7268 this->emitLabel(EndLabel);
7269
7270 return WholeLoopScope.destroyLocals();
7271}
7272
7273template <class Emitter>
7274bool Compiler<Emitter>::emitLambdaStaticInvokerBody(const CXXMethodDecl *MD) {
7275 assert(MD->isLambdaStaticInvoker());
7276 assert(MD->hasBody());
7277 assert(cast<CompoundStmt>(MD->getBody())->body_empty());
7278
7279 const CXXRecordDecl *ClosureClass = MD->getParent();
7280 const FunctionDecl *LambdaCallOp;
7281 assert(ClosureClass->captures().empty());
7282 if (ClosureClass->isGenericLambda()) {
7283 LambdaCallOp = ClosureClass->getLambdaCallOperator();
7284 assert(MD->isFunctionTemplateSpecialization() &&
7285 "A generic lambda's static-invoker function must be a "
7286 "template specialization");
7288 FunctionTemplateDecl *CallOpTemplate =
7289 LambdaCallOp->getDescribedFunctionTemplate();
7290 void *InsertPos = nullptr;
7291 const FunctionDecl *CorrespondingCallOpSpecialization =
7292 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7293 assert(CorrespondingCallOpSpecialization);
7294 LambdaCallOp = CorrespondingCallOpSpecialization;
7295 } else {
7296 LambdaCallOp = ClosureClass->getLambdaCallOperator();
7297 }
7298 assert(ClosureClass->captures().empty());
7299 const Function *Func = this->getFunction(LambdaCallOp);
7300 if (!Func)
7301 return false;
7302 assert(Func->hasThisPointer());
7303 assert(Func->getNumParams() == (MD->getNumParams() + 1 + Func->hasRVO()));
7304
7305 if (Func->hasRVO()) {
7306 if (!this->emitRVOPtr(MD))
7307 return false;
7308 }
7309
7310 // The lambda call operator needs an instance pointer, but we don't have
7311 // one here, and we don't need one either because the lambda cannot have
7312 // any captures, as verified above. Emit a null pointer. This is then
7313 // special-cased when interpreting to not emit any misleading diagnostics.
7314 if (!this->emitNullPtr(0, nullptr, MD))
7315 return false;
7316
7317 // Forward all arguments from the static invoker to the lambda call operator.
7318 for (const ParmVarDecl *PVD : MD->parameters()) {
7319 auto It = this->Params.find(PVD);
7320 assert(It != this->Params.end());
7321
7322 // We do the lvalue-to-rvalue conversion manually here, so no need
7323 // to care about references.
7324 PrimType ParamType = this->classify(PVD->getType()).value_or(PT_Ptr);
7325 if (!this->emitGetParam(ParamType, It->second.Index, MD))
7326 return false;
7327 }
7328
7329 if (!this->emitCall(Func, 0, LambdaCallOp))
7330 return false;
7331
7332 this->emitCleanup();
7333 if (ReturnType)
7334 return this->emitRet(*ReturnType, MD);
7335
7336 // Nothing to do, since we emitted the RVO pointer above.
7337 return this->emitRetVoid(MD);
7338}
7339
7340template <class Emitter>
7341bool Compiler<Emitter>::checkLiteralType(const Expr *E) {
7342 if (Ctx.getLangOpts().CPlusPlus23)
7343 return true;
7344
7345 if (!E->isPRValue() || E->getType()->isLiteralType(Ctx.getASTContext()))
7346 return true;
7347
7348 return this->emitCheckLiteralType(E->getType().getTypePtr(), E);
7349}
7350
7352 const Expr *InitExpr = Init->getInit();
7353
7354 if (!Init->isWritten() && !Init->isInClassMemberInitializer() &&
7355 !isa<CXXConstructExpr>(InitExpr))
7356 return true;
7357
7358 if (const auto *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
7359 const CXXConstructorDecl *Ctor = CE->getConstructor();
7360 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
7361 Ctor->isTrivial())
7362 return true;
7363 }
7364
7365 return false;
7366}
7367
7368template <class Emitter>
7369bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
7370 assert(!ReturnType);
7371
7372 // Only start the lifetime of the instance pointer.
7373 if (!this->emitStartThisLifetime1(Ctor))
7374 return false;
7375
7376 auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset,
7377 const Expr *InitExpr,
7378 bool Activate = false) -> bool {
7379 // We don't know what to do with these, so just return false.
7380 if (InitExpr->getType().isNull())
7381 return false;
7382
7383 if (OptPrimType T = this->classify(InitExpr)) {
7384 if (Activate && !this->emitActivateThisField(FieldOffset, InitExpr))
7385 return false;
7386
7387 if (!this->visit(InitExpr))
7388 return false;
7389
7390 if (F->isBitField())
7391 return this->emitInitThisBitField(*T, FieldOffset, F->bitWidth(),
7392 InitExpr);
7393 return this->emitInitThisField(*T, FieldOffset, InitExpr);
7394 }
7395 // Non-primitive case. Get a pointer to the field-to-initialize
7396 // on the stack and call visitInitialzer() for it.
7397 InitLinkScope<Emitter> FieldScope(this, InitLink::Field(F->Offset));
7398 if (!this->emitGetPtrThisField(FieldOffset, InitExpr))
7399 return false;
7400
7401 if (Activate && !this->emitActivate(InitExpr))
7402 return false;
7403
7404 return this->visitInitializerPop(InitExpr);
7405 };
7406
7407 const RecordDecl *RD = Ctor->getParent();
7408 const Record *R = this->getRecord(RD);
7409 if (!R)
7410 return false;
7411 bool IsUnion = R->isUnion();
7412
7413 // Default union copy and move ctors are special.
7414 if (IsUnion && Ctor->isCopyOrMoveConstructor() && Ctor->isDefaulted()) {
7416
7417 // No special case for NumFields == 0 here, so the Memcpy op
7418 // below also does its checks in those cases.
7419
7420 assert(cast<CompoundStmt>(Ctor->getBody())->body_empty());
7421 if (!this->emitThis(Ctor))
7422 return false;
7423
7424 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, Ctor))
7425 return false;
7426
7427 return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) &&
7428 this->emitRetVoid(Ctor);
7429 }
7430
7431 unsigned FieldInits = 0;
7433 // First, initialize virtual bases if the records has them.
7434 if (R->getNumVirtualBases() > 0) {
7435 if (!this->emitThis(Ctor))
7436 return false;
7437 LabelTy AfterVirtBasesLabel = this->getLabel();
7438
7439 // If the instance pointer is a base class, skip the virtual bases.
7440 if (!this->emitIsBaseClass({}))
7441 return false;
7442 if (!this->jumpTrue(AfterVirtBasesLabel, {}))
7443 return false;
7444
7445 for (const auto *Init : Ctor->inits()) {
7446 if (const Type *Base = Init->getBaseClass();
7447 Base && Init->isBaseVirtual()) {
7448 const auto *BaseDecl = Base->getAsCXXRecordDecl();
7449 assert(BaseDecl);
7450 assert(R->getVirtualBase(BaseDecl));
7451 if (!this->emitGetPtrThisVirtBase(BaseDecl, Ctor))
7452 return false;
7453 if (!this->visitInitializerPop(Init->getInit()))
7454 return false;
7455 }
7456 }
7457
7458 this->fallthrough(AfterVirtBasesLabel);
7459 this->emitLabel(AfterVirtBasesLabel);
7460
7461 if (!this->emitPopPtr(Ctor))
7462 return false;
7463 }
7464
7465 for (const auto *Init : Ctor->inits()) {
7466 // Scope needed for the initializers.
7467 LocalScope<Emitter> Scope(this, ScopeKind::FullExpression);
7468
7469 const Expr *InitExpr = Init->getInit();
7470 if (const FieldDecl *Member = Init->getMember()) {
7471 const Record::Field *F = R->getField(Member);
7472
7475 if (!emitFieldInitializer(F, F->Offset, InitExpr, IsUnion))
7476 return false;
7477 ++FieldInits;
7478 } else if (const Type *Base = Init->getBaseClass()) {
7479 const auto *BaseDecl = Base->getAsCXXRecordDecl();
7480 assert(BaseDecl);
7481
7482 if (Init->isBaseVirtual()) {
7483 // See above.
7484 continue;
7485 } else {
7486 // Base class initializer.
7487 // Get This Base and call initializer on it.
7488 const Record::Base *B = R->getBase(BaseDecl);
7489 assert(B);
7490 if (!this->emitGetPtrThisBase(B->Offset, InitExpr))
7491 return false;
7492 }
7493
7494 if (!this->visitInitializerPop(InitExpr))
7495 return false;
7496 } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) {
7499 unsigned ChainSize = IFD->getChainingSize();
7500 assert(ChainSize >= 2);
7501
7502 unsigned NestedFieldOffset = 0;
7503 const Record::Field *NestedField = nullptr;
7504 for (unsigned I = 0; I != ChainSize; ++I) {
7505 const auto *FD = cast<FieldDecl>(IFD->chain()[I]);
7506 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7507 assert(FieldRecord);
7508
7509 NestedField = FieldRecord->getField(FD);
7510 assert(NestedField);
7511 IsUnion = IsUnion || FieldRecord->isUnion();
7512
7513 NestedFieldOffset += NestedField->Offset;
7514
7515 // Add a new InitChainLink for the record, but not for the final field.
7516 if (I != ChainSize - 1)
7517 InitStack.push_back(InitLink::Field(NestedField->Offset));
7518 }
7519 assert(NestedField);
7520
7522 if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr,
7523 IsUnion))
7524 return false;
7525
7526 // Mark all chain links as initialized.
7527 unsigned InitFieldOffset = 0;
7528 for (const NamedDecl *ND : IFD->chain().drop_back()) {
7529 const auto *FD = cast<FieldDecl>(ND);
7530 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7531 assert(FieldRecord);
7532 NestedField = FieldRecord->getField(FD);
7533 InitFieldOffset += NestedField->Offset;
7534 assert(NestedField);
7535 if (!this->emitGetPtrThisField(InitFieldOffset, InitExpr))
7536 return false;
7537 if (!this->emitFinishInitPop(InitExpr))
7538 return false;
7539 }
7540
7541 InitStack.pop_back_n(ChainSize - 1);
7542
7543 } else {
7544 assert(Init->isDelegatingInitializer());
7545 if (!this->emitThis(InitExpr))
7546 return false;
7547 if (!this->visitInitializerPop(Init->getInit()))
7548 return false;
7549 }
7550
7551 if (!Scope.destroyLocals())
7552 return false;
7553 }
7554
7555 if (FieldInits != R->getNumFields()) {
7556 assert(FieldInits < R->getNumFields());
7557 // Start the lifetime of all members.
7558 if (!this->emitStartThisLifetime(Ctor))
7559 return false;
7560 }
7561
7562 if (const Stmt *Body = Ctor->getBody()) {
7563 // Only emit the CtorCheck op for non-empty CompoundStmt bodies.
7564 // For non-CompoundStmts, always assume they are non-empty and emit it.
7565 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
7566 if (!CS->body_empty() && !this->emitCtorCheck(SourceInfo{}))
7567 return false;
7568 } else {
7569 if (!this->emitCtorCheck(SourceInfo{}))
7570 return false;
7571 }
7572
7573 if (!visitStmt(Body))
7574 return false;
7575 }
7576
7577 return this->emitRetVoid(SourceInfo{});
7578}
7579
7580template <class Emitter>
7581bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) {
7582 const RecordDecl *RD = Dtor->getParent();
7583 const Record *R = this->getRecord(RD);
7584 if (!R)
7585 return false;
7586
7587 if (!Dtor->isTrivial() && Dtor->getBody()) {
7588 if (!this->visitStmt(Dtor->getBody()))
7589 return false;
7590 }
7591
7592 if (!this->emitThis(Dtor))
7593 return false;
7594
7595 if (!this->emitCheckDestruction(Dtor))
7596 return false;
7597
7598 assert(R);
7599 if (!R->isUnion()) {
7600
7602 // First, destroy all fields.
7603 for (const Record::Field &Field : llvm::reverse(R->fields())) {
7604 const Descriptor *D = Field.Desc;
7605 if (D->hasTrivialDtor())
7606 continue;
7607 if (!this->emitGetPtrField(Field.Offset, SourceInfo{}))
7608 return false;
7609 if (!this->emitDestructionPop(D, SourceInfo{}))
7610 return false;
7611 }
7612 }
7613
7614 for (const Record::Base &Base : llvm::reverse(R->bases())) {
7615 if (Base.R->hasTrivialDtor())
7616 continue;
7617 if (!this->emitGetPtrBase(Base.Offset, SourceInfo{}))
7618 return false;
7619 if (!this->emitRecordDestructionPop(Base.R, {}))
7620 return false;
7621 }
7622
7623 if (R->getNumVirtualBases() > 0) {
7624 LabelTy EndLabel = this->getLabel();
7625 // If this is a base class, skip the virtual bases.
7626 if (!this->emitIsBaseClass({}))
7627 return false;
7628 if (!this->jumpTrue(EndLabel, {}))
7629 return false;
7630
7631 for (const Record::Base &Base : llvm::reverse(R->virtual_bases())) {
7632 if (Base.R->hasTrivialDtor())
7633 continue;
7634 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(Base.R->getDecl()),
7635 SourceInfo{}))
7636 return false;
7637 if (!this->emitRecordDestructionPop(Base.R, {}))
7638 return false;
7639 }
7640
7641 this->fallthrough(EndLabel);
7642 this->emitLabel(EndLabel);
7643 }
7644
7645 if (!this->emitMarkDestroyed(Dtor))
7646 return false;
7647
7648 return this->emitPopPtr(Dtor) && this->emitRetVoid(Dtor);
7649}
7650
7651template <class Emitter>
7652bool Compiler<Emitter>::compileUnionAssignmentOperator(
7653 const CXXMethodDecl *MD) {
7654 if (!this->emitThis(MD))
7655 return false;
7656
7657 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, MD))
7658 return false;
7659
7660 return this->emitMemcpy(MD) && this->emitRet(PT_Ptr, MD);
7661}
7662
7663template <class Emitter>
7665 if (F->getReturnType()->isDependentType())
7666 return false;
7667
7668 // Classify the return type.
7669 ReturnType = this->classify(F->getReturnType());
7670
7671 this->CompilingFunction = F;
7672
7673 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F))
7674 return this->compileConstructor(Ctor);
7675 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F))
7676 return this->compileDestructor(Dtor);
7677
7678 // Emit custom code if this is a lambda static invoker.
7679 if (const auto *MD = dyn_cast<CXXMethodDecl>(F)) {
7680 const RecordDecl *RD = MD->getParent();
7681
7682 if (RD->isUnion() &&
7684 return this->compileUnionAssignmentOperator(MD);
7685
7686 if (MD->isLambdaStaticInvoker())
7687 return this->emitLambdaStaticInvokerBody(MD);
7688 }
7689
7690 // Regular functions.
7691 if (const auto *Body = F->getBody())
7692 if (!visitStmt(Body))
7693 return false;
7694
7695 // Emit a guard return to protect against a code path missing one.
7696 if (F->getReturnType()->isVoidType())
7697 return this->emitRetVoid(SourceInfo{});
7698 return this->emitNoRet(SourceInfo{});
7699}
7700
7701static uint32_t getBitWidth(const Expr *E) {
7702 assert(E->refersToBitField());
7703 const auto *ME = cast<MemberExpr>(E);
7704 const auto *FD = cast<FieldDecl>(ME->getMemberDecl());
7705 return FD->getBitWidthValue();
7706}
7707
7708template <class Emitter>
7710 if (E->containsErrors())
7711 return false;
7712
7713 const Expr *SubExpr = E->getSubExpr();
7714 if (SubExpr->getType()->isAnyComplexType())
7715 return this->VisitComplexUnaryOperator(E);
7716 if (SubExpr->getType()->isVectorType())
7717 return this->VisitVectorUnaryOperator(E);
7718 if (SubExpr->getType()->isFixedPointType())
7719 return this->VisitFixedPointUnaryOperator(E);
7720 OptPrimType T = classify(SubExpr->getType());
7721
7722 switch (E->getOpcode()) {
7723 case UO_PostInc: { // x++
7724 if (!Ctx.getLangOpts().CPlusPlus14)
7725 return this->emitInvalid(E);
7726 if (!T)
7727 return this->emitError(E);
7728
7729 if (!this->visit(SubExpr))
7730 return false;
7731
7732 if (T == PT_Ptr) {
7733 if (!this->emitIncPtr(E))
7734 return false;
7735
7736 return DiscardResult ? this->emitPopPtr(E) : true;
7737 }
7738
7739 if (T == PT_Float)
7740 return DiscardResult ? this->emitIncfPop(getFPOptions(E), E)
7741 : this->emitIncf(getFPOptions(E), E);
7742
7743 if (SubExpr->refersToBitField())
7744 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
7745 getBitWidth(SubExpr), E)
7746 : this->emitIncBitfield(*T, E->canOverflow(),
7747 getBitWidth(SubExpr), E);
7748
7749 return DiscardResult ? this->emitIncPop(*T, E->canOverflow(), E)
7750 : this->emitInc(*T, E->canOverflow(), E);
7751 }
7752 case UO_PostDec: { // x--
7753 if (!Ctx.getLangOpts().CPlusPlus14)
7754 return this->emitInvalid(E);
7755 if (!T)
7756 return this->emitError(E);
7757
7758 if (!this->visit(SubExpr))
7759 return false;
7760
7761 if (T == PT_Ptr) {
7762 if (!this->emitDecPtr(E))
7763 return false;
7764
7765 return DiscardResult ? this->emitPopPtr(E) : true;
7766 }
7767
7768 if (T == PT_Float)
7769 return DiscardResult ? this->emitDecfPop(getFPOptions(E), E)
7770 : this->emitDecf(getFPOptions(E), E);
7771
7772 if (SubExpr->refersToBitField()) {
7773 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
7774 getBitWidth(SubExpr), E)
7775 : this->emitDecBitfield(*T, E->canOverflow(),
7776 getBitWidth(SubExpr), E);
7777 }
7778
7779 return DiscardResult ? this->emitDecPop(*T, E->canOverflow(), E)
7780 : this->emitDec(*T, E->canOverflow(), E);
7781 }
7782 case UO_PreInc: { // ++x
7783 if (!Ctx.getLangOpts().CPlusPlus14)
7784 return this->emitInvalid(E);
7785 if (!T)
7786 return this->emitError(E);
7787
7788 if (!this->visit(SubExpr))
7789 return false;
7790
7791 if (T == PT_Ptr) {
7792 if (!this->emitLoadPtr(E))
7793 return false;
7794 if (!this->emitConstUint8(1, E))
7795 return false;
7796 if (!this->emitAddOffsetUint8(E))
7797 return false;
7798 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
7799 }
7800
7801 // Post-inc and pre-inc are the same if the value is to be discarded.
7802 if (DiscardResult) {
7803 if (T == PT_Float)
7804 return this->emitIncfPop(getFPOptions(E), E);
7805 if (SubExpr->refersToBitField())
7806 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
7807 getBitWidth(SubExpr), E)
7808 : this->emitIncBitfield(*T, E->canOverflow(),
7809 getBitWidth(SubExpr), E);
7810 return this->emitIncPop(*T, E->canOverflow(), E);
7811 }
7812
7813 if (T == PT_Float) {
7814 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
7815 if (!this->emitLoadFloat(E))
7816 return false;
7817 APFloat F(TargetSemantics, 1);
7818 if (!this->emitFloat(F, E))
7819 return false;
7820
7821 if (!this->emitAddf(getFPOptions(E), E))
7822 return false;
7823 if (!this->emitStoreFloat(E))
7824 return false;
7825 } else if (SubExpr->refersToBitField()) {
7826 assert(isIntegerOrBoolType(*T));
7827 if (!this->emitPreIncBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
7828 E))
7829 return false;
7830 } else {
7831 assert(isIntegerOrBoolType(*T));
7832 if (!this->emitPreInc(*T, E->canOverflow(), E))
7833 return false;
7834 }
7835 return E->isGLValue() || this->emitLoadPop(*T, E);
7836 }
7837 case UO_PreDec: { // --x
7838 if (!Ctx.getLangOpts().CPlusPlus14)
7839 return this->emitInvalid(E);
7840 if (!T)
7841 return this->emitError(E);
7842
7843 if (!this->visit(SubExpr))
7844 return false;
7845
7846 if (T == PT_Ptr) {
7847 if (!this->emitLoadPtr(E))
7848 return false;
7849 if (!this->emitConstUint8(1, E))
7850 return false;
7851 if (!this->emitSubOffsetUint8(E))
7852 return false;
7853 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
7854 }
7855
7856 // Post-dec and pre-dec are the same if the value is to be discarded.
7857 if (DiscardResult) {
7858 if (T == PT_Float)
7859 return this->emitDecfPop(getFPOptions(E), E);
7860 if (SubExpr->refersToBitField())
7861 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
7862 getBitWidth(SubExpr), E)
7863 : this->emitDecBitfield(*T, E->canOverflow(),
7864 getBitWidth(SubExpr), E);
7865 return this->emitDecPop(*T, E->canOverflow(), E);
7866 }
7867
7868 if (T == PT_Float) {
7869 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
7870 if (!this->emitLoadFloat(E))
7871 return false;
7872 APFloat F(TargetSemantics, 1);
7873 if (!this->emitFloat(F, E))
7874 return false;
7875
7876 if (!this->emitSubf(getFPOptions(E), E))
7877 return false;
7878 if (!this->emitStoreFloat(E))
7879 return false;
7880 } else if (SubExpr->refersToBitField()) {
7881 assert(isIntegerOrBoolType(*T));
7882 if (!this->emitPreDecBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
7883 E))
7884 return false;
7885 } else {
7886 assert(isIntegerOrBoolType(*T));
7887 if (!this->emitPreDec(*T, E->canOverflow(), E))
7888 return false;
7889 }
7890 return E->isGLValue() || this->emitLoadPop(*T, E);
7891 }
7892 case UO_LNot: // !x
7893 if (!T)
7894 return this->emitError(E);
7895
7896 if (DiscardResult)
7897 return this->discard(SubExpr);
7898
7899 if (!this->visitBool(SubExpr))
7900 return false;
7901
7902 if (!this->emitInv(E))
7903 return false;
7904
7905 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
7906 return this->emitCast(PT_Bool, ET, E);
7907 return true;
7908 case UO_Minus: // -x
7909 if (!T)
7910 return this->emitError(E);
7911
7912 if (!this->visit(SubExpr))
7913 return false;
7914 return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E);
7915 case UO_Plus: // +x
7916 if (!T)
7917 return this->emitError(E);
7918
7919 if (!this->visit(SubExpr)) // noop
7920 return false;
7921 return DiscardResult ? this->emitPop(*T, E) : true;
7922 case UO_AddrOf: // &x
7923 if (E->getType()->isMemberPointerType()) {
7924 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7925 // member can be formed.
7926 if (DiscardResult)
7927 return true;
7928 return this->emitGetMemberPtr(cast<DeclRefExpr>(SubExpr)->getDecl(), E);
7929 }
7930 // [C11 6.5.3.2p3]: if the operand of '&' is the result of a unary '*'
7931 // operator, neither operator is evaluated and the result is as if both
7932 // were omitted. So '&*q' is just 'q' with no dereference; delegate to the
7933 // pointer operand directly instead of to the '*' (which would emit a null
7934 // check), so that e.g. '&*(int *)0' is not rejected.
7935 if (!Ctx.getLangOpts().CPlusPlus) {
7936 const Expr *Sub = SubExpr->IgnoreParens();
7937 if (const auto *Deref = dyn_cast<UnaryOperator>(Sub);
7938 Deref && Deref->getOpcode() == UO_Deref)
7939 return this->delegate(Deref->getSubExpr());
7940 }
7941 // We should already have a pointer when we get here.
7942 return this->delegate(SubExpr);
7943 case UO_Deref: // *x
7944 if (DiscardResult)
7945 return this->discard(SubExpr);
7946
7947 if (!this->visit(SubExpr))
7948 return false;
7949
7950 if (!SubExpr->getType()->isFunctionPointerType() && !this->emitCheckNull(E))
7951 return false;
7952
7953 if (classifyPrim(SubExpr) == PT_Ptr)
7954 return this->emitNarrowPtr(E);
7955 return true;
7956
7957 case UO_Not: // ~x
7958 if (!T)
7959 return this->emitError(E);
7960
7961 if (!this->visit(SubExpr))
7962 return false;
7963 return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
7964 case UO_Real: // __real x
7965 if (!T)
7966 return false;
7967 return this->delegate(SubExpr);
7968 case UO_Imag: { // __imag x
7969 if (!T)
7970 return false;
7971 if (!this->discard(SubExpr))
7972 return false;
7973 return DiscardResult
7974 ? true
7975 : this->visitZeroInitializer(*T, SubExpr->getType(), SubExpr);
7976 }
7977 case UO_Extension:
7978 return this->delegate(SubExpr);
7979 case UO_Coawait:
7980 assert(false && "Unhandled opcode");
7981 }
7982
7983 return false;
7984}
7985
7986template <class Emitter>
7988 const Expr *SubExpr = E->getSubExpr();
7989 assert(SubExpr->getType()->isAnyComplexType());
7990
7991 if (DiscardResult)
7992 return this->discard(SubExpr);
7993
7994 OptPrimType ResT = classify(E);
7995 auto prepareResult = [=]() -> bool {
7996 if (!ResT && !Initializing) {
7997 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
7998 if (!LocalIndex)
7999 return false;
8000 return this->emitGetPtrLocal(*LocalIndex, E);
8001 }
8002
8003 return true;
8004 };
8005
8006 // The offset of the temporary, if we created one.
8007 unsigned SubExprOffset = ~0u;
8008 auto createTemp = [=, &SubExprOffset]() -> bool {
8009 SubExprOffset =
8010 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
8011 if (!this->visit(SubExpr))
8012 return false;
8013 return this->emitSetLocal(PT_Ptr, SubExprOffset, E);
8014 };
8015
8016 PrimType ElemT = classifyComplexElementType(SubExpr->getType());
8017 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
8018 if (!this->emitGetLocal(PT_Ptr, Offset, E))
8019 return false;
8020 return this->emitArrayElemPop(ElemT, Index, E);
8021 };
8022
8023 switch (E->getOpcode()) {
8024 case UO_Minus: // -x
8025 if (!prepareResult())
8026 return false;
8027 if (!createTemp())
8028 return false;
8029 for (unsigned I = 0; I != 2; ++I) {
8030 if (!getElem(SubExprOffset, I))
8031 return false;
8032 if (!this->emitNeg(ElemT, E))
8033 return false;
8034 if (!this->emitInitElem(ElemT, I, E))
8035 return false;
8036 }
8037 break;
8038
8039 case UO_Plus: // +x
8040 case UO_AddrOf: // &x
8041 case UO_Deref: // *x
8042 return this->delegate(SubExpr);
8043
8044 case UO_LNot:
8045 if (!this->visit(SubExpr))
8046 return false;
8047 if (!this->emitComplexBoolCast(SubExpr))
8048 return false;
8049 if (!this->emitInv(E))
8050 return false;
8051 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
8052 return this->emitCast(PT_Bool, ET, E);
8053 return true;
8054
8055 case UO_Real:
8056 return this->emitComplexReal(SubExpr);
8057
8058 case UO_Imag:
8059 if (!this->visit(SubExpr))
8060 return false;
8061
8062 if (SubExpr->isLValue()) {
8063 if (!this->emitConstUint8(1, E))
8064 return false;
8065 return this->emitArrayElemPtrPopUint8(E);
8066 }
8067
8068 // Since our _Complex implementation does not map to a primitive type,
8069 // we sometimes have to do the lvalue-to-rvalue conversion here manually.
8070 return this->emitArrayElemPop(classifyPrim(E->getType()), 1, E);
8071
8072 case UO_Not: // ~x
8073 if (!this->delegate(SubExpr))
8074 return false;
8075 // Negate the imaginary component.
8076 if (!this->emitArrayElem(ElemT, 1, E))
8077 return false;
8078 if (!this->emitNeg(ElemT, E))
8079 return false;
8080 if (!this->emitInitElem(ElemT, 1, E))
8081 return false;
8082 return DiscardResult ? this->emitPopPtr(E) : true;
8083
8084 case UO_Extension:
8085 return this->delegate(SubExpr);
8086
8087 default:
8088 return this->emitInvalid(E);
8089 }
8090
8091 return true;
8092}
8093
8094template <class Emitter>
8096 const Expr *SubExpr = E->getSubExpr();
8097 assert(SubExpr->getType()->isVectorType());
8098
8099 if (DiscardResult)
8100 return this->discard(SubExpr);
8101
8102 auto UnaryOp = E->getOpcode();
8103 if (UnaryOp == UO_Extension)
8104 return this->delegate(SubExpr);
8105
8106 if (UnaryOp != UO_Plus && UnaryOp != UO_Minus && UnaryOp != UO_LNot &&
8107 UnaryOp != UO_Not && UnaryOp != UO_AddrOf)
8108 return this->emitInvalid(E);
8109
8110 // Nothing to do here.
8111 if (UnaryOp == UO_Plus || UnaryOp == UO_AddrOf)
8112 return this->delegate(SubExpr);
8113
8114 if (!Initializing) {
8115 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
8116 if (!LocalIndex)
8117 return false;
8118 if (!this->emitGetPtrLocal(*LocalIndex, E))
8119 return false;
8120 }
8121
8122 // The offset of the temporary, if we created one.
8123 unsigned SubExprOffset =
8124 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
8125 if (!this->visit(SubExpr))
8126 return false;
8127 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E))
8128 return false;
8129
8130 const auto *VecTy = SubExpr->getType()->getAs<VectorType>();
8131 PrimType ElemT = classifyVectorElementType(SubExpr->getType());
8132 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
8133 if (!this->emitGetLocal(PT_Ptr, Offset, E))
8134 return false;
8135 return this->emitArrayElemPop(ElemT, Index, E);
8136 };
8137
8138 switch (UnaryOp) {
8139 case UO_Minus:
8140 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8141 if (!getElem(SubExprOffset, I))
8142 return false;
8143 if (!this->emitNeg(ElemT, E))
8144 return false;
8145 if (!this->emitInitElem(ElemT, I, E))
8146 return false;
8147 }
8148 break;
8149 case UO_LNot: { // !x
8150 // In C++, the logic operators !, &&, || are available for vectors. !v is
8151 // equivalent to v == 0.
8152 //
8153 // The result of the comparison is a vector of the same width and number of
8154 // elements as the comparison operands with a signed integral element type.
8155 //
8156 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
8157 QualType ResultVecTy = E->getType();
8158 PrimType ResultVecElemT =
8159 classifyPrim(ResultVecTy->getAs<VectorType>()->getElementType());
8160 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8161 if (!getElem(SubExprOffset, I))
8162 return false;
8163 // operator ! on vectors returns -1 for 'truth', so negate it.
8164 if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
8165 return false;
8166 if (!this->emitInv(E))
8167 return false;
8168 if (!this->emitPrimCast(PT_Bool, ElemT, VecTy->getElementType(), E))
8169 return false;
8170 if (!this->emitNeg(ElemT, E))
8171 return false;
8172 if (ElemT != ResultVecElemT &&
8173 !this->emitPrimCast(ElemT, ResultVecElemT, ResultVecTy, E))
8174 return false;
8175 if (!this->emitInitElem(ResultVecElemT, I, E))
8176 return false;
8177 }
8178 break;
8179 }
8180 case UO_Not: // ~x
8181 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8182 if (!getElem(SubExprOffset, I))
8183 return false;
8184 if (ElemT == PT_Bool) {
8185 if (!this->emitInv(E))
8186 return false;
8187 } else {
8188 if (!this->emitComp(ElemT, E))
8189 return false;
8190 }
8191 if (!this->emitInitElem(ElemT, I, E))
8192 return false;
8193 }
8194 break;
8195 default:
8196 llvm_unreachable("Unsupported unary operators should be handled up front");
8197 }
8198 return true;
8199}
8200
8201template <class Emitter>
8203 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
8204 if (DiscardResult)
8205 return true;
8206 return this->emitConst(ECD->getInitVal(), E);
8207 }
8208 if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) {
8209 if (DiscardResult)
8210 return true;
8211 const Function *F = getFunction(FuncDecl);
8212 return F && this->emitGetFnPtr(F, E);
8213 }
8214 if (const auto *TPOD = dyn_cast<TemplateParamObjectDecl>(D)) {
8215 TPOD = TPOD->getFirstDecl();
8216 if (DiscardResult)
8217 return true;
8218 if (UnsignedOrNone GlobalIndex = P.getGlobal(TPOD))
8219 return this->emitGetPtrGlobal(*GlobalIndex, E);
8220
8221 if (UnsignedOrNone Index = P.getOrCreateGlobal(TPOD)) {
8222 if (OptPrimType T = classify(TPOD->getType())) {
8223 if (!this->visitAPValue(TPOD->getValue(), *T, E))
8224 return false;
8225 return this->emitInitGlobal(*T, *Index, E);
8226 }
8227
8228 if (!this->emitGetPtrGlobal(*Index, E))
8229 return false;
8230 if (!this->visitAPValueInitializer(TPOD->getValue(), E, TPOD->getType()))
8231 return false;
8232 return this->emitFinishInit(E);
8233 }
8234 return false;
8235 }
8236
8237 // References are implemented via pointers, so when we see a DeclRefExpr
8238 // pointing to a reference, we need to get its value directly (i.e. the
8239 // pointer to the actual value) instead of a pointer to the pointer to the
8240 // value.
8241 QualType DeclType = D->getType();
8242 bool IsReference = DeclType->isReferenceType();
8243
8244 auto maybePopPtr = [&]() -> bool {
8245 if (DiscardResult)
8246 return this->emitPopPtr(E);
8247 return true;
8248 };
8249
8250 // Function parameters.
8251 // Note that it's important to check them first since we might have a local
8252 // variable created for a ParmVarDecl as well.
8253 if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
8254 if (DiscardResult)
8255 return true;
8256
8257 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
8258 !DeclType->isIntegralOrEnumerationType()) {
8259 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8260 /*InitializerFailed=*/false, E);
8261 }
8262 if (auto It = this->Params.find(PVD); It != this->Params.end()) {
8263 if (IsReference || !It->second.IsPtr)
8264 return this->emitGetParam(classifyPrim(E), It->second.Index, E);
8265
8266 return this->emitGetPtrParam(It->second.Index, E);
8267 }
8268
8269 if (!Ctx.getLangOpts().CPlusPlus23 && IsReference && !Locals.contains(D))
8270 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8271 /*InitializerFailed=*/false, E);
8272 }
8273
8274 // Local variables.
8275 if (auto It = Locals.find(D); It != Locals.end()) {
8276 const unsigned Offset = It->second.Offset;
8277 if (IsReference) {
8278 assert(classifyPrim(E) == PT_Ptr);
8279 return this->emitGetRefLocal(Offset, E) && maybePopPtr();
8280 }
8281 return this->emitGetPtrLocal(Offset, E) && maybePopPtr();
8282 }
8283 // Global variables.
8284 if (auto GlobalIndex = P.getGlobal(D)) {
8285 if (IsReference) {
8286 if (!Ctx.getLangOpts().CPlusPlus11)
8287 return this->emitGetGlobal(classifyPrim(E), *GlobalIndex, E);
8288 if (!Ctx.getLangOpts().CPlusPlus23)
8289 return this->emitGetGlobalUnchecked(classifyPrim(E), *GlobalIndex, E);
8290
8291 return this->emitGetRefGlobal(*GlobalIndex, E) && maybePopPtr();
8292 }
8293
8294 return this->emitGetPtrGlobal(*GlobalIndex, E) && maybePopPtr();
8295 }
8296
8297 // In case we need to re-visit a declaration.
8298 auto revisit = [&](const VarDecl *VD,
8299 bool IsConstexprUnknown = true) -> bool {
8301 IsConstexprUnknown);
8302 if constexpr (std::is_same_v<Emitter, EvalEmitter>) {
8303 if (!this->emitPushCC(VD->hasConstantInitialization(), E))
8304 return false;
8305 }
8306 auto VarState = this->visitDecl(VD);
8307
8308 if constexpr (std::is_same_v<Emitter, EvalEmitter>) {
8309 if (!this->emitPopCC(E))
8310 return false;
8311 }
8312
8313 if (VarState.notCreated())
8314 return true;
8315 if (!VarState)
8316 return false;
8317 // Retry.
8318 return this->visitDeclRef(D, E);
8319 };
8320
8321 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
8322 // Lambda captures.
8323 if (auto It = this->LambdaCaptures.find(D);
8324 It != this->LambdaCaptures.end()) {
8325 auto [Offset, IsPtr] = It->second;
8326
8327 if (IsPtr)
8328 return this->emitGetThisFieldPtr(Offset, E) && maybePopPtr();
8329 return this->emitGetPtrThisField(Offset, E) && maybePopPtr();
8330 }
8331 }
8332
8333 if (const auto *DRE = dyn_cast<DeclRefExpr>(E);
8334 DRE && DRE->refersToEnclosingVariableOrCapture()) {
8335 if (const auto *VD = dyn_cast<VarDecl>(D); VD && VD->isInitCapture())
8336 return revisit(VD);
8337 }
8338
8339 if (const auto *BD = dyn_cast<BindingDecl>(D))
8340 return this->delegate(BD->getBinding());
8341
8342 // Avoid infinite recursion.
8343 if (D == InitializingDecl) {
8344 if (DiscardResult)
8345 return true;
8346 return this->emitDummyPtr(D, E);
8347 }
8348
8349 // Try to lazily visit (or emit dummy pointers for) declarations
8350 // we haven't seen yet.
8351 const auto *VD = dyn_cast<VarDecl>(D);
8352 if (!VD)
8353 return this->emitError(E);
8354
8355 // For C.
8356 if (!Ctx.getLangOpts().CPlusPlus) {
8357 if (VD->getInit() && !VD->getInit()->isValueDependent() &&
8358 DeclType.isConstant(Ctx.getASTContext()) && !VD->isWeak() &&
8359 VD->evaluateValue())
8360 return revisit(VD, /*IsConstexprUnknown=*/false);
8361
8362 if (DiscardResult)
8363 return true;
8364 return this->emitDummyPtr(D, E);
8365 }
8366
8367 // ... and C++.
8368 const auto typeShouldBeVisited = [&](QualType T) -> bool {
8369 if (T.isConstant(Ctx.getASTContext()))
8370 return true;
8371 return T->isReferenceType();
8372 };
8373
8374 if ((VD->hasGlobalStorage() || VD->isStaticDataMember()) &&
8375 typeShouldBeVisited(DeclType)) {
8376 if (const Expr *Init = VD->getAnyInitializer();
8377 Init && !Init->isValueDependent()) {
8378 // Whether or not the evaluation is successul doesn't really matter
8379 // here -- we will create a global variable in any case, and that
8380 // will have the state of initializer evaluation attached.
8382 (void)Init->EvaluateAsInitializer(Ctx.getASTContext(), VD, Result, true);
8383 return this->visitDeclRef(D, E);
8384 }
8385 return revisit(VD, !VD->isConstexpr() && DeclType->isReferenceType());
8386 }
8387
8388 // FIXME: The evaluateValue() check here is a little ridiculous, since
8389 // it will ultimately call into Context::evaluateAsInitializer(). In
8390 // other words, we're evaluating the initializer, just to know if we can
8391 // evaluate the initializer.
8392 if (VD->isLocalVarDecl() && typeShouldBeVisited(DeclType) && VD->getInit() &&
8393 !VD->getInit()->isValueDependent()) {
8394 if (VD->evaluateValue()) {
8395 bool IsConstexprUnknown = !DeclType.isConstant(Ctx.getASTContext()) &&
8396 !DeclType->isReferenceType();
8397 // Revisit the variable declaration, but make sure it's associated with a
8398 // different evaluation, so e.g. mutable reads don't work on it.
8399 EvalIDScope _(Ctx);
8400 return revisit(VD, IsConstexprUnknown);
8401 } else if (Ctx.getLangOpts().CPlusPlus23 && IsReference)
8402 return revisit(VD, /*IsConstexprUnknown=*/true);
8403
8404 if (IsReference)
8405 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8406 /*InitializerFailed=*/true, E);
8407 }
8408
8409 if (DiscardResult)
8410 return true;
8411 return this->emitDummyPtr(
8412 D, E, Ctx.getLangOpts().CPlusPlus23 && DeclType->isReferenceType());
8413}
8414
8415template <class Emitter>
8417 const auto *D = E->getDecl();
8418 return this->visitDeclRef(D, E);
8419}
8420
8421template <class Emitter>
8423 const DesignatedInitUpdateExpr *E) {
8424 if (!this->visitInitializer(E->getBase()))
8425 return false;
8426 return this->visitInitializer(E->getUpdater());
8427}
8428
8429template <class Emitter> bool Compiler<Emitter>::emitCleanup() {
8430 for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent()) {
8431 if (!C->destroyLocals())
8432 return false;
8433 }
8434 return true;
8435}
8436
8437template <class Emitter>
8438unsigned Compiler<Emitter>::collectBaseOffset(const QualType BaseType,
8439 const QualType DerivedType) {
8440 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
8441 if (const auto *R = Ty->getPointeeCXXRecordDecl())
8442 return R;
8443 return Ty->getAsCXXRecordDecl();
8444 };
8445 const CXXRecordDecl *BaseDecl = extractRecordDecl(BaseType);
8446 const CXXRecordDecl *DerivedDecl = extractRecordDecl(DerivedType);
8447
8448 return Ctx.collectBaseOffset(BaseDecl, DerivedDecl);
8449}
8450
8451/// Emit casts from a PrimType to another PrimType.
8452template <class Emitter>
8453bool Compiler<Emitter>::emitPrimCast(PrimType FromT, PrimType ToT,
8454 QualType ToQT, const Expr *E) {
8455
8456 if (FromT == PT_Float) {
8457 // Floating to floating.
8458 if (ToT == PT_Float) {
8459 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8460 return this->emitCastFP(ToSem, getRoundingMode(E), E);
8461 }
8462
8463 if (ToT == PT_IntAP)
8464 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(ToQT),
8465 getFPOptions(E), E);
8466 if (ToT == PT_IntAPS)
8467 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(ToQT),
8468 getFPOptions(E), E);
8469
8470 // Float to integral.
8471 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8472 return this->emitCastFloatingIntegral(ToT, getFPOptions(E), E);
8473 }
8474
8475 if (isIntegerOrBoolType(FromT) || FromT == PT_Bool) {
8476 if (ToT == PT_IntAP)
8477 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8478 if (ToT == PT_IntAPS)
8479 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8480
8481 // Integral to integral.
8482 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8483 return FromT != ToT ? this->emitCast(FromT, ToT, E) : true;
8484
8485 if (ToT == PT_Float) {
8486 // Integral to floating.
8487 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8488 return this->emitCastIntegralFloating(FromT, ToSem, getFPOptions(E), E);
8489 }
8490 }
8491
8492 return false;
8493}
8494
8495template <class Emitter>
8496bool Compiler<Emitter>::emitIntegralCast(PrimType FromT, PrimType ToT,
8497 QualType ToQT, const Expr *E) {
8498 assert(FromT != ToT);
8499
8500 if (ToT == PT_IntAP)
8501 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8502 if (ToT == PT_IntAPS)
8503 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8504
8505 return this->emitCast(FromT, ToT, E);
8506}
8507
8508/// Emits __real(SubExpr)
8509template <class Emitter>
8510bool Compiler<Emitter>::emitComplexReal(const Expr *SubExpr) {
8511 assert(SubExpr->getType()->isAnyComplexType());
8512
8513 if (DiscardResult)
8514 return this->discard(SubExpr);
8515
8516 if (!this->visit(SubExpr))
8517 return false;
8518 if (SubExpr->isLValue()) {
8519 if (!this->emitConstUint8(0, SubExpr))
8520 return false;
8521 return this->emitArrayElemPtrPopUint8(SubExpr);
8522 }
8523
8524 // Rvalue, load the actual element.
8525 return this->emitArrayElemPop(classifyComplexElementType(SubExpr->getType()),
8526 0, SubExpr);
8527}
8528
8529template <class Emitter>
8530bool Compiler<Emitter>::emitComplexBoolCast(const Expr *E) {
8531 assert(!DiscardResult);
8532 PrimType ElemT = classifyComplexElementType(E->getType());
8533 // We emit the expression (__real(E) != 0 || __imag(E) != 0)
8534 // for us, that means (bool)E[0] || (bool)E[1]
8535 if (!this->emitArrayElem(ElemT, 0, E))
8536 return false;
8537 if (ElemT == PT_Float) {
8538 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8539 return false;
8540 } else {
8541 if (!this->emitCast(ElemT, PT_Bool, E))
8542 return false;
8543 }
8544
8545 // We now have the bool value of E[0] on the stack.
8546 LabelTy LabelTrue = this->getLabel();
8547 if (!this->jumpTrue(LabelTrue, E))
8548 return false;
8549
8550 if (!this->emitArrayElemPop(ElemT, 1, E))
8551 return false;
8552 if (ElemT == PT_Float) {
8553 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8554 return false;
8555 } else {
8556 if (!this->emitCast(ElemT, PT_Bool, E))
8557 return false;
8558 }
8559 // Leave the boolean value of E[1] on the stack.
8560 LabelTy EndLabel = this->getLabel();
8561 this->jump(EndLabel, E);
8562
8563 this->emitLabel(LabelTrue);
8564 if (!this->emitPopPtr(E))
8565 return false;
8566 if (!this->emitConstBool(true, E))
8567 return false;
8568
8569 this->fallthrough(EndLabel);
8570 this->emitLabel(EndLabel);
8571
8572 return true;
8573}
8574
8575template <class Emitter>
8576bool Compiler<Emitter>::emitComplexComparison(const Expr *LHS, const Expr *RHS,
8577 const BinaryOperator *E) {
8578 assert(E->isComparisonOp());
8579 assert(!Initializing);
8580 if (DiscardResult)
8581 return this->discard(LHS) && this->discard(RHS);
8582
8583 PrimType ElemT;
8584 bool LHSIsComplex;
8585 unsigned LHSOffset;
8586 if (LHS->getType()->isAnyComplexType()) {
8587 LHSIsComplex = true;
8588 ElemT = classifyComplexElementType(LHS->getType());
8589 LHSOffset = allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
8590 if (!this->visit(LHS))
8591 return false;
8592 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
8593 return false;
8594 } else {
8595 LHSIsComplex = false;
8596 PrimType LHST = classifyPrim(LHS->getType());
8597 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, /*IsConst=*/true);
8598 if (!this->visit(LHS))
8599 return false;
8600 if (!this->emitSetLocal(LHST, LHSOffset, E))
8601 return false;
8602 }
8603
8604 bool RHSIsComplex;
8605 unsigned RHSOffset;
8606 if (RHS->getType()->isAnyComplexType()) {
8607 RHSIsComplex = true;
8608 ElemT = classifyComplexElementType(RHS->getType());
8609 RHSOffset = allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
8610 if (!this->visit(RHS))
8611 return false;
8612 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
8613 return false;
8614 } else {
8615 RHSIsComplex = false;
8616 PrimType RHST = classifyPrim(RHS->getType());
8617 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, /*IsConst=*/true);
8618 if (!this->visit(RHS))
8619 return false;
8620 if (!this->emitSetLocal(RHST, RHSOffset, E))
8621 return false;
8622 }
8623
8624 auto getElem = [&](unsigned LocalOffset, unsigned Index,
8625 bool IsComplex) -> bool {
8626 if (IsComplex) {
8627 if (!this->emitGetLocal(PT_Ptr, LocalOffset, E))
8628 return false;
8629 return this->emitArrayElemPop(ElemT, Index, E);
8630 }
8631 return this->emitGetLocal(ElemT, LocalOffset, E);
8632 };
8633
8634 for (unsigned I = 0; I != 2; ++I) {
8635 // Get both values.
8636 if (!getElem(LHSOffset, I, LHSIsComplex))
8637 return false;
8638 if (!getElem(RHSOffset, I, RHSIsComplex))
8639 return false;
8640 // And compare them.
8641 if (!this->emitEQ(ElemT, E))
8642 return false;
8643
8644 if (!this->emitCastBoolUint8(E))
8645 return false;
8646 }
8647
8648 // We now have two bool values on the stack. Compare those.
8649 if (!this->emitAddUint8(E))
8650 return false;
8651 if (!this->emitConstUint8(2, E))
8652 return false;
8653
8654 if (E->getOpcode() == BO_EQ) {
8655 if (!this->emitEQUint8(E))
8656 return false;
8657 } else if (E->getOpcode() == BO_NE) {
8658 if (!this->emitNEUint8(E))
8659 return false;
8660 } else
8661 return false;
8662
8663 // In C, this returns an int.
8664 if (PrimType ResT = classifyPrim(E->getType()); ResT != PT_Bool)
8665 return this->emitCast(PT_Bool, ResT, E);
8666 return true;
8667}
8668
8669/// When calling this, we have a pointer of the local-to-destroy
8670/// on the stack.
8671/// Emit destruction of record types (or arrays of record types).
8672template <class Emitter>
8673bool Compiler<Emitter>::emitRecordDestructionPop(const Record *R,
8674 SourceInfo Loc) {
8675 assert(R);
8676 assert(!R->hasTrivialDtor());
8677 const CXXDestructorDecl *Dtor = R->getDestructor();
8678 assert(Dtor);
8679 const Function *DtorFunc = getFunction(Dtor);
8680 if (!DtorFunc)
8681 return false;
8682 assert(DtorFunc->hasThisPointer());
8683 assert(DtorFunc->getNumParams() == 1);
8684 return this->emitCall(DtorFunc, 0, Loc);
8685}
8686/// When calling this, we have a pointer of the local-to-destroy
8687/// on the stack.
8688/// Emit destruction of record types (or arrays of record types).
8689template <class Emitter>
8690bool Compiler<Emitter>::emitDestructionPop(const Descriptor *Desc,
8691 SourceInfo Loc) {
8692 assert(Desc);
8693 assert(!Desc->hasTrivialDtor());
8694
8695 // Arrays.
8696 if (Desc->isArray()) {
8697 const Descriptor *ElemDesc = Desc->ElemDesc;
8698 assert(ElemDesc);
8699
8700 unsigned N = Desc->getNumElems();
8701 if (N == 0)
8702 return this->emitPopPtr(Loc);
8703
8704 for (ssize_t I = N - 1; I >= 1; --I) {
8705 if (!this->emitConstUint64(I, Loc))
8706 return false;
8707 if (!this->emitArrayElemPtrUint64(Loc))
8708 return false;
8709 if (!this->emitDestructionPop(ElemDesc, Loc))
8710 return false;
8711 }
8712 // Last iteration, removes the instance pointer from the stack.
8713 if (!this->emitConstUint64(0, Loc))
8714 return false;
8715 if (!this->emitArrayElemPtrPopUint64(Loc))
8716 return false;
8717 return this->emitDestructionPop(ElemDesc, Loc);
8718 }
8719
8720 assert(Desc->ElemRecord);
8721 assert(!Desc->ElemRecord->hasTrivialDtor());
8722 return this->emitRecordDestructionPop(Desc->ElemRecord, Loc);
8723}
8724
8725/// Create a dummy pointer for the given decl (or expr) and
8726/// push a pointer to it on the stack.
8727template <class Emitter>
8728bool Compiler<Emitter>::emitDummyPtr(DeclOrExpr D, const Expr *E, bool CU) {
8729 assert(!DiscardResult && "Should've been checked before");
8730 unsigned DummyID = P.getOrCreateDummy(D, CU);
8731
8732 if (!this->emitGetPtrGlobal(DummyID, E))
8733 return false;
8734 if (E->getType()->isVoidType())
8735 return true;
8736
8737 // Convert the dummy pointer to another pointer type if we have to.
8738 if (PrimType PT = classifyPrim(E); PT != PT_Ptr) {
8739 if (isPtrType(PT))
8740 return this->emitDecayPtr(PT_Ptr, PT, E);
8741 return false;
8742 }
8743 return true;
8744}
8745
8746template <class Emitter>
8747bool Compiler<Emitter>::emitFloat(const APFloat &F, SourceInfo Info) {
8748 if (Floating::singleWord(F.getSemantics()))
8749 return this->emitConstFloat(Floating(F), Info);
8750
8751 APInt I = F.bitcastToAPInt();
8752 return this->emitConstFloat(
8753 Floating(const_cast<uint64_t *>(I.getRawData()),
8754 llvm::APFloatBase::SemanticsToEnum(F.getSemantics())),
8755 Info);
8756}
8757
8758// This function is constexpr if and only if To, From, and the types of
8759// all subobjects of To and From are types T such that...
8760// (3.1) - is_union_v<T> is false;
8761// (3.2) - is_pointer_v<T> is false;
8762// (3.3) - is_member_pointer_v<T> is false;
8763// (3.4) - is_volatile_v<T> is false; and
8764// (3.5) - T has no non-static data members of reference type
8765template <class Emitter>
8766bool Compiler<Emitter>::emitBuiltinBitCast(const CastExpr *E) {
8767 const Expr *SubExpr = E->getSubExpr();
8768 QualType FromType = SubExpr->getType();
8769 QualType ToType = E->getType();
8770 OptPrimType ToT = classify(ToType);
8771
8772 assert(!ToType->isReferenceType());
8773
8774 // Prepare storage for the result in case we discard.
8775 if (DiscardResult && !Initializing && !ToT) {
8776 UnsignedOrNone LocalIndex = allocateLocal(E);
8777 if (!LocalIndex)
8778 return false;
8779 if (!this->emitGetPtrLocal(*LocalIndex, E))
8780 return false;
8781 }
8782
8783 // Get a pointer to the value-to-cast on the stack.
8784 // For CK_LValueToRValueBitCast, this is always an lvalue and
8785 // we later assume it to be one (i.e. a PT_Ptr). However,
8786 // we call this function for other utility methods where
8787 // a bitcast might be useful, so convert it to a PT_Ptr in that case.
8788 if (SubExpr->isGLValue() || FromType->isVectorType()) {
8789 if (!this->visit(SubExpr))
8790 return false;
8791 } else if (OptPrimType FromT = classify(SubExpr)) {
8792 unsigned TempOffset =
8793 allocateLocalPrimitive(SubExpr, *FromT, /*IsConst=*/true);
8794 if (!this->visit(SubExpr))
8795 return false;
8796 if (!this->emitSetLocal(*FromT, TempOffset, E))
8797 return false;
8798 if (!this->emitGetPtrLocal(TempOffset, E))
8799 return false;
8800 } else {
8801 return false;
8802 }
8803
8804 if (!ToT) {
8805 if (!this->emitBitCast(E))
8806 return false;
8807 return DiscardResult ? this->emitPopPtr(E) : true;
8808 }
8809 assert(ToT);
8810
8811 const llvm::fltSemantics *TargetSemantics = nullptr;
8812 if (ToT == PT_Float)
8813 TargetSemantics = &Ctx.getFloatSemantics(ToType);
8814
8815 // Conversion to a primitive type. FromType can be another
8816 // primitive type, or a record/array.
8817 bool ToTypeIsUChar = (ToType->isSpecificBuiltinType(BuiltinType::UChar) ||
8818 ToType->isSpecificBuiltinType(BuiltinType::Char_U));
8819 uint32_t ResultBitWidth = std::max(Ctx.getBitWidth(ToType), 8u);
8820
8821 if (!this->emitBitCastPrim(*ToT, ToTypeIsUChar || ToType->isStdByteType(),
8822 ResultBitWidth, TargetSemantics,
8823 ToType.getTypePtr(), E))
8824 return false;
8825
8826 if (DiscardResult)
8827 return this->emitPop(*ToT, E);
8828
8829 return true;
8830}
8831
8832/// Replicate a scalar value into every scalar element of an aggregate.
8833/// The scalar is stored in a local at \p SrcOffset and a pointer to the
8834/// destination must be on top of the interpreter stack. Each element receives
8835/// the scalar, cast to its own type.
8836template <class Emitter>
8837bool Compiler<Emitter>::emitHLSLAggregateSplat(PrimType SrcT,
8838 unsigned SrcOffset,
8839 QualType DestType,
8840 const Expr *E) {
8841 // Vectors and matrices are treated as flat sequences of elements.
8842 unsigned NumElems = 0;
8843 QualType ElemType;
8844 if (const auto *VT = DestType->getAs<VectorType>()) {
8845 NumElems = VT->getNumElements();
8846 ElemType = VT->getElementType();
8847 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
8848 NumElems = MT->getNumElementsFlattened();
8849 ElemType = MT->getElementType();
8850 }
8851 if (NumElems > 0) {
8852 PrimType ElemT = classifyPrim(ElemType);
8853 for (unsigned I = 0; I != NumElems; ++I) {
8854 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8855 return false;
8856 if (!this->emitPrimCast(SrcT, ElemT, ElemType, E))
8857 return false;
8858 if (!this->emitInitElem(ElemT, I, E))
8859 return false;
8860 }
8861 return true;
8862 }
8863
8864 // Arrays: primitive elements are filled directly; composite elements
8865 // require recursion into each sub-aggregate.
8866 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
8867 const auto *CAT = cast<ConstantArrayType>(AT);
8868 QualType ArrElemType = CAT->getElementType();
8869 unsigned ArrSize = CAT->getZExtSize();
8870
8871 if (OptPrimType ElemT = classify(ArrElemType)) {
8872 for (unsigned I = 0; I != ArrSize; ++I) {
8873 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8874 return false;
8875 if (!this->emitPrimCast(SrcT, *ElemT, ArrElemType, E))
8876 return false;
8877 if (!this->emitInitElem(*ElemT, I, E))
8878 return false;
8879 }
8880 } else {
8881 for (unsigned I = 0; I != ArrSize; ++I) {
8882 if (!this->emitConstUint32(I, E))
8883 return false;
8884 if (!this->emitArrayElemPtrUint32(E))
8885 return false;
8886 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, ArrElemType, E))
8887 return false;
8888 if (!this->emitFinishInitPop(E))
8889 return false;
8890 }
8891 }
8892 return true;
8893 }
8894
8895 // Records: fill base classes first, then named fields in declaration
8896 // order.
8897 if (DestType->isRecordType()) {
8898 const Record *R = getRecord(DestType);
8899 if (!R)
8900 return false;
8901
8902 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
8903 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
8904 const Record::Base *B = R->getBase(BS.getType());
8905 assert(B);
8906 if (!this->emitGetPtrBase(B->Offset, E))
8907 return false;
8908 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, BS.getType(), E))
8909 return false;
8910 if (!this->emitFinishInitPop(E))
8911 return false;
8912 }
8913 }
8914
8915 for (const Record::Field &F : R->fields()) {
8916 if (F.isUnnamedBitField())
8917 continue;
8918
8919 QualType FieldType = F.Decl->getType();
8920 if (OptPrimType FieldT = classify(FieldType)) {
8921 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8922 return false;
8923 if (!this->emitPrimCast(SrcT, *FieldT, FieldType, E))
8924 return false;
8925 if (F.isBitField()) {
8926 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
8927 return false;
8928 } else {
8929 if (!this->emitInitField(*FieldT, F.Offset, E))
8930 return false;
8931 }
8932 } else {
8933 if (!this->emitGetPtrField(F.Offset, E))
8934 return false;
8935 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, FieldType, E))
8936 return false;
8937 if (!this->emitPopPtr(E))
8938 return false;
8939 }
8940 }
8941 return true;
8942 }
8943
8944 return false;
8945}
8946
8947/// Return the total number of scalar elements in a type. This is used
8948/// to cap how many source elements are extracted during an elementwise cast,
8949/// so we never flatten more than the destination can hold.
8950template <class Emitter>
8951unsigned Compiler<Emitter>::countHLSLFlatElements(QualType Ty) {
8952 // Vector and matrix types are treated as flat sequences of elements.
8953 if (const auto *VT = Ty->getAs<VectorType>())
8954 return VT->getNumElements();
8955 if (const auto *MT = Ty->getAs<ConstantMatrixType>())
8956 return MT->getNumElementsFlattened();
8957 // Arrays: total count is array size * scalar elements per element.
8958 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
8959 const auto *CAT = cast<ConstantArrayType>(AT);
8960 return CAT->getZExtSize() * countHLSLFlatElements(CAT->getElementType());
8961 }
8962 // Records: sum scalar element counts of base classes and named fields.
8963 if (Ty->isRecordType()) {
8964 const Record *R = getRecord(Ty);
8965 if (!R)
8966 return 0;
8967 unsigned Count = 0;
8968 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
8969 for (const CXXBaseSpecifier &BS : CXXRD->bases())
8970 Count += countHLSLFlatElements(BS.getType());
8971 }
8972 for (const Record::Field &F : R->fields()) {
8973 if (F.isUnnamedBitField())
8974 continue;
8975 Count += countHLSLFlatElements(F.Decl->getType());
8976 }
8977 return Count;
8978 }
8979 // Scalar primitive types contribute one element.
8980 if (canClassify(Ty))
8981 return 1;
8982 return 0;
8983}
8984
8985/// Walk a source aggregate and extract every scalar element into its own local
8986/// variable. The results are appended to \p Elements in declaration order,
8987/// stopping once \p MaxElements have been collected. A pointer to the
8988/// source aggregate must be stored in the local at \p SrcOffset.
8989template <class Emitter>
8990bool Compiler<Emitter>::emitHLSLFlattenAggregate(
8991 QualType SrcType, unsigned SrcOffset,
8992 SmallVectorImpl<HLSLFlatElement> &Elements, unsigned MaxElements,
8993 const Expr *E) {
8994
8995 // Save a scalar value from the stack into a new local and record it.
8996 auto saveToLocal = [&](PrimType T) -> bool {
8997 unsigned Offset = allocateLocalPrimitive(E, T, /*IsConst=*/true);
8998 if (!this->emitSetLocal(T, Offset, E))
8999 return false;
9000 Elements.push_back({Offset, T});
9001 return true;
9002 };
9003
9004 // Save a pointer from the stack into a new local for later use.
9005 auto savePtrToLocal = [&]() -> UnsignedOrNone {
9006 unsigned Offset = allocateLocalPrimitive(E, PT_Ptr, /*IsConst=*/true);
9007 if (!this->emitSetLocal(PT_Ptr, Offset, E))
9008 return std::nullopt;
9009 return Offset;
9010 };
9011
9012 // Vectors and matrices are flat sequences of elements.
9013 unsigned NumElems = 0;
9014 QualType ElemType;
9015 if (const auto *VT = SrcType->getAs<VectorType>()) {
9016 NumElems = VT->getNumElements();
9017 ElemType = VT->getElementType();
9018 } else if (const auto *MT = SrcType->getAs<ConstantMatrixType>()) {
9019 NumElems = MT->getNumElementsFlattened();
9020 ElemType = MT->getElementType();
9021 }
9022 if (NumElems > 0) {
9023 PrimType ElemT = classifyPrim(ElemType);
9024 for (unsigned I = 0; I != NumElems && Elements.size() < MaxElements; ++I) {
9025 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9026 return false;
9027 if (!this->emitArrayElemPop(ElemT, I, E))
9028 return false;
9029 if (!saveToLocal(ElemT))
9030 return false;
9031 }
9032 return true;
9033 }
9034
9035 // Arrays: primitive elements are extracted directly; composite elements
9036 // require recursion into each sub-aggregate.
9037 if (const auto *AT = SrcType->getAsArrayTypeUnsafe()) {
9038 const auto *CAT = cast<ConstantArrayType>(AT);
9039 QualType ArrElemType = CAT->getElementType();
9040 unsigned ArrSize = CAT->getZExtSize();
9041
9042 if (OptPrimType ElemT = classify(ArrElemType)) {
9043 for (unsigned I = 0; I != ArrSize && Elements.size() < MaxElements; ++I) {
9044 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9045 return false;
9046 if (!this->emitArrayElemPop(*ElemT, I, E))
9047 return false;
9048 if (!saveToLocal(*ElemT))
9049 return false;
9050 }
9051 } else {
9052 for (unsigned I = 0; I != ArrSize && Elements.size() < MaxElements; ++I) {
9053 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9054 return false;
9055 if (!this->emitConstUint32(I, E))
9056 return false;
9057 if (!this->emitArrayElemPtrPopUint32(E))
9058 return false;
9059 UnsignedOrNone ElemPtrOffset = savePtrToLocal();
9060 if (!ElemPtrOffset)
9061 return false;
9062 if (!emitHLSLFlattenAggregate(ArrElemType, *ElemPtrOffset, Elements,
9063 MaxElements, E))
9064 return false;
9065 }
9066 }
9067 return true;
9068 }
9069
9070 // Records: base classes come first, then named fields in declaration
9071 // order.
9072 if (SrcType->isRecordType()) {
9073 const Record *R = getRecord(SrcType);
9074 if (!R)
9075 return false;
9076
9077 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9078 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9079 if (Elements.size() >= MaxElements)
9080 break;
9081 const Record::Base *B = R->getBase(BS.getType());
9082 assert(B);
9083 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9084 return false;
9085 if (!this->emitGetPtrBasePop(B->Offset, /*NullOK=*/false, E))
9086 return false;
9087 UnsignedOrNone BasePtrOffset = savePtrToLocal();
9088 if (!BasePtrOffset)
9089 return false;
9090 if (!emitHLSLFlattenAggregate(BS.getType(), *BasePtrOffset, Elements,
9091 MaxElements, E))
9092 return false;
9093 }
9094 }
9095
9096 for (const Record::Field &F : R->fields()) {
9097 if (Elements.size() >= MaxElements)
9098 break;
9099 if (F.isUnnamedBitField())
9100 continue;
9101
9102 QualType FieldType = F.Decl->getType();
9103 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9104 return false;
9105 if (!this->emitGetPtrFieldPop(F.Offset, E))
9106 return false;
9107
9108 if (OptPrimType FieldT = classify(FieldType)) {
9109 if (!this->emitLoadPop(*FieldT, E))
9110 return false;
9111 if (!saveToLocal(*FieldT))
9112 return false;
9113 } else {
9114 UnsignedOrNone FieldPtrOffset = savePtrToLocal();
9115 if (!FieldPtrOffset)
9116 return false;
9117 if (!emitHLSLFlattenAggregate(FieldType, *FieldPtrOffset, Elements,
9118 MaxElements, E))
9119 return false;
9120 }
9121 }
9122 return true;
9123 }
9124
9125 return false;
9126}
9127
9128/// Populate an HLSL aggregate from a flat list of previously extracted source
9129/// elements, casting each to the corresponding destination element type.
9130/// \p ElemIdx tracks the current position in \p Elements and is advanced as
9131/// elements are consumed. A pointer to the destination must be on top of the
9132/// interpreter stack.
9133template <class Emitter>
9134bool Compiler<Emitter>::emitHLSLConstructAggregate(
9135 QualType DestType, ArrayRef<HLSLFlatElement> Elements, unsigned &ElemIdx,
9136 const Expr *E) {
9137
9138 // Consume the next source element, cast it, and leave it on the stack.
9139 auto loadAndCast = [&](PrimType DestT, QualType DestQT) -> bool {
9140 const auto &Src = Elements[ElemIdx++];
9141 if (!this->emitGetLocal(Src.Type, Src.LocalOffset, E))
9142 return false;
9143 return this->emitPrimCast(Src.Type, DestT, DestQT, E);
9144 };
9145
9146 // Vectors and matrices are flat sequences of elements.
9147 unsigned NumElems = 0;
9148 QualType ElemType;
9149 if (const auto *VT = DestType->getAs<VectorType>()) {
9150 NumElems = VT->getNumElements();
9151 ElemType = VT->getElementType();
9152 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
9153 NumElems = MT->getNumElementsFlattened();
9154 ElemType = MT->getElementType();
9155 }
9156 if (NumElems > 0) {
9157 PrimType DestElemT = classifyPrim(ElemType);
9158 for (unsigned I = 0; I != NumElems; ++I) {
9159 if (!loadAndCast(DestElemT, ElemType))
9160 return false;
9161 if (!this->emitInitElem(DestElemT, I, E))
9162 return false;
9163 }
9164 return true;
9165 }
9166
9167 // Arrays: primitive elements are filled directly; composite elements
9168 // require recursion into each sub-aggregate.
9169 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
9170 const auto *CAT = cast<ConstantArrayType>(AT);
9171 QualType ArrElemType = CAT->getElementType();
9172 unsigned ArrSize = CAT->getZExtSize();
9173
9174 if (OptPrimType ElemT = classify(ArrElemType)) {
9175 for (unsigned I = 0; I != ArrSize; ++I) {
9176 if (!loadAndCast(*ElemT, ArrElemType))
9177 return false;
9178 if (!this->emitInitElem(*ElemT, I, E))
9179 return false;
9180 }
9181 } else {
9182 for (unsigned I = 0; I != ArrSize; ++I) {
9183 if (!this->emitConstUint32(I, E))
9184 return false;
9185 if (!this->emitArrayElemPtrUint32(E))
9186 return false;
9187 if (!emitHLSLConstructAggregate(ArrElemType, Elements, ElemIdx, E))
9188 return false;
9189 if (!this->emitFinishInitPop(E))
9190 return false;
9191 }
9192 }
9193 return true;
9194 }
9195
9196 // Records: base classes come first, then named fields in declaration
9197 // order.
9198 if (DestType->isRecordType()) {
9199 const Record *R = getRecord(DestType);
9200 if (!R)
9201 return false;
9202
9203 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9204 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9205 const Record::Base *B = R->getBase(BS.getType());
9206 assert(B);
9207 if (!this->emitGetPtrBase(B->Offset, E))
9208 return false;
9209 if (!emitHLSLConstructAggregate(BS.getType(), Elements, ElemIdx, E))
9210 return false;
9211 if (!this->emitFinishInitPop(E))
9212 return false;
9213 }
9214 }
9215
9216 for (const Record::Field &F : R->fields()) {
9217 if (F.isUnnamedBitField())
9218 continue;
9219
9220 QualType FieldType = F.Decl->getType();
9221 if (OptPrimType FieldT = classify(FieldType)) {
9222 if (!loadAndCast(*FieldT, FieldType))
9223 return false;
9224 if (F.isBitField()) {
9225 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
9226 return false;
9227 } else {
9228 if (!this->emitInitField(*FieldT, F.Offset, E))
9229 return false;
9230 }
9231 } else {
9232 if (!this->emitGetPtrField(F.Offset, E))
9233 return false;
9234 if (!emitHLSLConstructAggregate(FieldType, Elements, ElemIdx, E))
9235 return false;
9236 if (!this->emitPopPtr(E))
9237 return false;
9238 }
9239 }
9240 return true;
9241 }
9242
9243 return false;
9244}
9245
9246namespace clang {
9247namespace interp {
9248
9249template class Compiler<ByteCodeEmitter>;
9250template class Compiler<EvalEmitter>;
9251
9252} // namespace interp
9253} // 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:1018
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:629
ArrayRef< LValuePathEntry > getLValuePath() const
Definition APValue.cpp:1038
APSInt & getInt()
Definition APValue.h:511
APValue & getStructField(unsigned i)
Definition APValue.h:674
const FieldDecl * getUnionField() const
Definition APValue.h:695
unsigned getStructNumFields() const
Definition APValue.h:661
APValue & getStructVirtualBase(unsigned i)
Definition APValue.h:679
bool isArray() const
Definition APValue.h:496
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1108
unsigned getArrayInitializedElts() const
Definition APValue.h:648
bool isFloat() const
Definition APValue.h:489
unsigned getStructNumBases() const
Definition APValue.h:657
unsigned getStructNumVirtualBases() const
Definition APValue.h:665
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1101
APValue & getUnionValue()
Definition APValue.h:699
APValue & getArrayFiller()
Definition APValue.h:640
bool isLValue() const
Definition APValue.h:493
bool isIndeterminate() const
Definition APValue.h:485
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1115
bool isMemberPointer() const
Definition APValue.h:499
bool isInt() const
Definition APValue.h:488
unsigned getArraySize() const
Definition APValue.h:652
bool isUnion() const
Definition APValue.h:498
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isStruct() const
Definition APValue.h:497
bool isNullPointer() const
Definition APValue.cpp:1054
APFloat & getFloat()
Definition APValue.h:525
APValue & getStructBase(unsigned i)
Definition APValue.h:669
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h: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:981
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:4373
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4551
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4557
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4563
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition Expr.h:4570
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition Expr.h:6047
Represents a loop initializing the elements of an array.
Definition Expr.h:5994
llvm::APInt getArraySize() const
Definition Expr.h:6016
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:6009
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6014
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2741
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2770
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition ExprCXX.h:3010
uint64_t getValue() const
Definition ExprCXX.h:3058
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3836
QualType getElementType() const
Definition TypeBase.h:3848
Attr - This represents one attribute.
Definition Attr.h:46
Represents an attribute applied to a statement.
Definition Stmt.h:2215
Stmt * getSubStmt()
Definition Stmt.h:2251
ArrayRef< const Attr * > getAttrs() const
Definition Stmt.h:2247
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3521
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4058
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4191
Expr * getLHS() const
Definition Expr.h:4108
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4158
static bool isShiftOp(Opcode Opc)
Definition Expr.h:4146
static bool isCommaOp(Opcode Opc)
Definition Expr.h:4161
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4205
Expr * getRHS() const
Definition Expr.h:4110
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4135
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4194
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4199
Opcode getOpcode() const
Definition Expr.h:4103
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4149
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6698
BreakStmt - This represents a break.
Definition Stmt.h:3147
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition ExprCXX.h:5527
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents binding an expression to a temporary.
Definition ExprCXX.h:1497
const Expr * getSubExpr() const
Definition ExprCXX.h:1519
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:727
bool getValue() const
Definition ExprCXX.h:744
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1621
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
arg_range arguments()
Definition ExprCXX.h:1676
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1654
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
Represents a C++ constructor within a class.
Definition DeclCXX.h:2637
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:2402
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1274
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1381
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1138
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2630
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2669
bool isArrayForm() const
Definition ExprCXX.h:2656
bool isGlobalDelete() const
Definition ExprCXX.h:2655
Represents a C++ destructor within a class.
Definition DeclCXX.h:2902
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition ExprCXX.h:485
Represents the code generated for an expanded expansion statement.
Definition StmtCXX.h:1028
ArrayRef< Stmt * > getInstantiations() const
Definition StmtCXX.h:1069
ArrayRef< Stmt * > getPreambleStmts() const
Definition StmtCXX.h:1073
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:136
DeclStmt * getBeginStmt()
Definition StmtCXX.h:164
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:170
DeclStmt * getEndStmt()
Definition StmtCXX.h:167
DeclStmt * getRangeStmt()
Definition StmtCXX.h:163
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1755
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1792
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h: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:2288
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2730
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2895
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2359
bool isArray() const
Definition ExprCXX.h:2468
QualType getAllocatedType() const
Definition ExprCXX.h:2438
std::optional< Expr * > getArraySize()
This might return std::nullopt even if isArray() returns true, since there might not be an array size...
Definition ExprCXX.h:2473
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2507
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2498
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2463
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2537
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition ExprCXX.h:4360
bool getValue() const
Definition ExprCXX.h:4383
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5192
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5232
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:530
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:290
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:308
An expression "T()" which creates an rvalue of a non-class type T.
Definition ExprCXX.h:2200
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition ExprCXX.h:804
Represents the this expression in C++.
Definition ExprCXX.h:1158
A C++ throw-expression (C++ [except.throw]).
Definition ExprCXX.h:1212
const Expr * getSubExpr() const
Definition ExprCXX.h:1232
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:70
CompoundStmt * getTryBlock()
Definition StmtCXX.h:101
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:852
bool isTypeOperand() const
Definition ExprCXX.h:888
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:167
Expr * getExprOperand() const
Definition ExprCXX.h:899
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:135
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1072
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1118
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2963
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3167
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3146
Expr * getCallee()
Definition Expr.h:3110
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3154
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3157
arg_range arguments()
Definition Expr.h:3215
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:1932
Stmt * getSubStmt()
Definition Stmt.h:2045
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3696
path_iterator path_begin()
Definition Expr.h:3766
CastKind getCastKind() const
Definition Expr.h:3740
llvm::iterator_range< path_iterator > path()
Path through the class hierarchy taken by casts between base and derived classes (see implementation ...
Definition Expr.h:3783
const FieldDecl * getTargetUnionField() const
Definition Expr.h:3790
path_iterator path_end()
Definition Expr.h:3767
Expr * getSubExpr()
Definition Expr.h:3746
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
unsigned getValue() const
Definition Expr.h:1649
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4868
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4904
const ValueInfo * getValueInfo(ComparisonCategoryResult ValueKind) const
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3355
QualType getElementType() const
Definition TypeBase.h:3365
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4320
QualType getComputationLHSType() const
Definition Expr.h:4354
QualType getComputationResultType() const
Definition Expr.h:4357
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3625
bool isFileScope() const
Definition Expr.h:3657
const Expr * getInitializer() const
Definition Expr.h:3653
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1752
body_range body()
Definition Stmt.h:1815
Stmt * body_back()
Definition Stmt.h:1820
Represents the specialization of a concept - evaluates to a prvalue of type bool.
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3874
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3950
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1102
APValue getAPValueResult() const
Definition Expr.cpp:419
bool hasAPValueResult() const
Definition Expr.h:1177
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4501
ContinueStmt - This represents a continue.
Definition Stmt.h:3131
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition Expr.h:4739
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4829
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1290
ValueDecl * getDecl()
Definition Expr.h:1358
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1643
decl_range decls()
Definition Stmt.h:1691
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInvalidDecl() const
Definition DeclBase.h:596
bool hasAttr() const
Definition DeclBase.h:585
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
Stmt * getSubStmt()
Definition Stmt.h:2093
InitListExpr * getUpdater() const
Definition Expr.h:5962
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2844
Stmt * getBody()
Definition Stmt.h:2869
Expr * getCond()
Definition Stmt.h:2862
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
Recursively visit a statement or expression, by dispatching to Traverse*() based on the argument's dy...
const Expr * getBase() const
Definition Expr.h:6607
Represents a reference to emded data.
Definition Expr.h:5155
ChildElementIter< false > begin()
Definition Expr.h:5261
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3712
This represents one expression.
Definition Expr.h:113
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:85
bool isGLValue() const
Definition Expr.h:288
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:178
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3089
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:247
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3097
bool isPRValue() const
Definition Expr.h:286
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:285
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp: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:480
QualType getType() const
Definition Expr.h:145
An expression trait intrinsic.
Definition ExprCXX.h:3083
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6636
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4563
Represents a member of a struct/union/class.
Definition Decl.h:3294
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3530
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1595
llvm::APFloat getValue() const
Definition Expr.h:1686
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2900
Stmt * getInit()
Definition Stmt.h:2915
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2944
Expr * getInc()
Definition Stmt.h:2943
Expr * getCond()
Definition Stmt.h:2942
DeclStmt * getConditionVariableDeclStmt()
If this ForStmt has a condition variable, return the faux DeclStmt associated with the creation of th...
Definition Stmt.h:2930
const Expr * getSubExpr() const
Definition Expr.h:1082
Represents a function declaration or definition.
Definition Decl.h:2058
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2927
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3267
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4248
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4236
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3805
QualType getReturnType() const
Definition Decl.h:2975
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2904
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2503
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4372
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:3469
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2511
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3869
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3187
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:4943
Represents a C11 generic selection.
Definition Expr.h:6208
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6494
IfStmt - This represents an if/then/else.
Definition Stmt.h:2271
Stmt * getThen()
Definition Stmt.h:2360
Stmt * getInit()
Definition Stmt.h:2421
bool isNonNegatedConsteval() const
Definition Stmt.h:2456
Expr * getCond()
Definition Stmt.h:2348
bool isNegatedConsteval() const
Definition Stmt.h:2460
Stmt * getElse()
Definition Stmt.h:2369
DeclStmt * getConditionVariableDeclStmt()
If this IfStmt has a condition variable, return the faux DeclStmt associated with the creation of tha...
Definition Stmt.h:2404
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1751
const Expr * getSubExpr() const
Definition Expr.h:1763
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6083
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3601
Describes an C or C++ initializer list.
Definition Expr.h:5328
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5431
ArrayRef< Expr * > inits() const
Definition Expr.h:5381
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1972
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2098
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1433
bool isCompatibleWith(ClangABI Version) const
Implicit declaration of a temporary that was materialized by a MaterializeTemporaryExpr and lifetime-...
Definition DeclCXX.h:3333
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:4428
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:4971
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4996
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4988
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:5021
LifetimeExtendedTemporaryDecl * getLifetimeExtendedTemporaryDecl()
Definition ExprCXX.h:5011
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3384
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3467
Expr * getBase() const
Definition Expr.h:3461
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3767
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:3226
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:2547
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2606
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2594
unsigned getNumComponents() const
Definition Expr.h:2602
Helper class for OffsetOfExpr.
Definition Expr.h:2441
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2499
@ Array
An index into an array.
Definition Expr.h:2446
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2495
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1198
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1248
Expr * getSelectedExpr() const
Definition ExprCXX.h:4690
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2202
const Expr * getSubExpr() const
Definition Expr.h:2219
Represents a parameter to a function.
Definition Decl.h:1819
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3408
QualType getPointeeType() const
Definition TypeBase.h:3418
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2025
StringLiteral * getFunctionName()
Definition Expr.h:2069
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6830
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6878
ArrayRef< Expr * > semantics()
Definition Expr.h:6902
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8586
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:8502
bool isConstant(const ASTContext &Ctx) const
Definition TypeBase.h:1098
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8575
Represents a struct/union/class.
Definition Decl.h:4459
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7529
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3687
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
bool isSatisfied() const
Whether or not the requires clause is satisfied.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3172
Expr * getRetValue()
Definition Stmt.h:3199
SourceLocation getLocation() const
Definition Expr.h:2175
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:4663
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4715
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4696
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4702
Represents an expression that computes the length of a parameter pack.
Definition ExprCXX.h:4492
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4566
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition Expr.h:5046
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:4161
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4615
CompoundStmt * getSubStmt()
Definition Expr.h:4632
Stmt - This represents one statement.
Definition Stmt.h:85
StmtClass getStmtClass() const
Definition Stmt.h:1505
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1819
unsigned getLength() const
Definition Expr.h:1929
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:1902
unsigned getCharByteWidth() const
Definition Expr.h:1930
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4715
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1905
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2521
Expr * getCond()
Definition Stmt.h:2584
Stmt * getBody()
Definition Stmt.h:2596
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2601
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2652
DeclStmt * getConditionVariableDeclStmt()
If this SwitchStmt has a condition variable, return the faux DeclStmt associated with the creation of...
Definition Stmt.h:2635
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3851
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3952
bool isUnion() const
Definition Decl.h:4062
A template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition ExprCXX.h:2900
bool getBoolValue() const
Definition ExprCXX.h:2961
bool isStoredAsComparisonResult() const
Definition ExprCXX.h:2957
const APValue & getAPValue() const
Definition ExprCXX.h:2966
bool isStoredAsBoolean() const
Definition ExprCXX.h:2953
The base class of the type hierarchy.
Definition TypeBase.h:1879
bool isVoidType() const
Definition TypeBase.h:9111
bool isBooleanType() const
Definition TypeBase.h:9248
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3145
bool isIncompleteArrayType() const
Definition TypeBase.h:8846
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:3329
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:2549
bool isArrayType() const
Definition TypeBase.h:8838
bool isFunctionPointerType() const
Definition TypeBase.h:8806
bool isConstantMatrixType() const
Definition TypeBase.h:8906
bool isPointerType() const
Definition TypeBase.h:8739
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9155
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9405
bool isReferenceType() const
Definition TypeBase.h:8763
bool isEnumeralType() const
Definition TypeBase.h:8870
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:9233
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9080
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2859
bool isAnyComplexType() const
Definition TypeBase.h:8874
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9171
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9291
bool isMemberPointerType() const
Definition TypeBase.h:8820
bool isAtomicType() const
Definition TypeBase.h:8931
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isStdByteType() const
Definition Type.cpp:3348
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9391
bool isPointerOrReferenceType() const
Definition TypeBase.h:8743
bool isFunctionType() const
Definition TypeBase.h:8735
bool isVectorType() const
Definition TypeBase.h:8878
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2437
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2998
bool isFloatingType() const
Definition Type.cpp:2421
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9338
bool isRecordType() const
Definition TypeBase.h:8866
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2695
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3696
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2645
QualType getArgumentType() const
Definition Expr.h:2688
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2714
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2677
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2264
Expr * getSubExpr() const
Definition Expr.h:2305
Opcode getOpcode() const
Definition Expr.h:2300
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2318
Represents C++ using-directive.
Definition DeclCXX.h:3121
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:5644
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:2640
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:4289
unsigned getNumElements() const
Definition TypeBase.h:4304
QualType getElementType() const
Definition TypeBase.h:4303
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2709
Expr * getCond()
Definition Stmt.h:2761
DeclStmt * getConditionVariableDeclStmt()
If this WhileStmt has a condition variable, return the faux DeclStmt associated with the creation of ...
Definition Stmt.h:2797
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2773
ArrayIndexScope(Compiler< Emitter > *Ctx, uint64_t Index)
Definition Compiler.cpp:219
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:43
void invokeDtor()
Invokes the Destructor.
Compilation context for expressions.
Definition Compiler.h:119
llvm::SmallVector< InitLink > InitStack
Definition Compiler.h: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:147
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:203
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3176
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:2807
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:2293
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2410
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)
constexpr bool isIntegerType(PrimType T)
Definition PrimType.h:53
llvm::APSInt APSInt
Definition FixedPoint.h:20
Top level wrappers for InstallAPI frontend operations.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool hasSpecificAttr(const Container &container)
@ Success
Annotation was successful.
Definition Parser.h:65
@ Link
'link' clause, allowed on 'declare' construct.
DynamicRecursiveASTVisitorBase< true > ConstDynamicRecursiveASTVisitor
Expr * Cond
};
ComparisonCategoryResult
An enumeration representing the possible results of a three-way comparison.
@ SD_Static
Static storage duration.
Definition Specifiers.h:342
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:339
@ Result
The result type of a method or function.
Definition TypeBase.h:906
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327
int const char * function
Definition c++config.h:31
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#define true
Definition stdbool.h:25
llvm::APSInt getIntValue() const
Get the constant integer value used by this variable to represent the comparison category result type...
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:666
A quantity in bits.
Describes a memory block created by an allocation site.
Definition Descriptor.h:122
unsigned getNumElems() const
Returns the number of elements stored in the block.
Definition Descriptor.h:246
bool isPrimitive() const
Checks if the descriptor is of a primitive.
Definition Descriptor.h:260
QualType getElemQualType() const
bool hasTrivialDtor() const
Whether variables of this descriptor need their destructor called or not.
bool isCompositeArray() const
Checks if the descriptor is of an array of composites.
Definition Descriptor.h:253
QualType getType() const
const Descriptor *const ElemDesc
Descriptor of the array element.
Definition Descriptor.h:148
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition Descriptor.h:251
PrimType getPrimType() const
Definition Descriptor.h:231
bool isRecord() const
Checks if the descriptor is of a record.
Definition Descriptor.h:265
const Record *const ElemRecord
Pointer to the record, if block contains records.
Definition Descriptor.h:146
bool isArray() const
Checks if the descriptor is of an array.
Definition Descriptor.h:263
Descriptor used for global variables.
Definition Descriptor.h:49
Information about a local's storage.
Definition Function.h: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