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