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 tempoarary
41/// variables and is supposed to be a quick check, not exhausite. 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 if (auto It = this->Ctx->OpaqueExprs.find(OVE);
210 It != this->Ctx->OpaqueExprs.end())
211 this->Ctx->OpaqueExprs.erase(It);
212 };
213 }
214
215 /// Index of the scope in the chain.
216 UnsignedOrNone Idx = std::nullopt;
217};
218
219template <class Emitter> class ArrayIndexScope final {
220public:
221 ArrayIndexScope(Compiler<Emitter> *Ctx, uint64_t Index) : Ctx(Ctx) {
222 OldArrayIndex = Ctx->ArrayIndex;
223 Ctx->ArrayIndex = Index;
224 }
225
226 ~ArrayIndexScope() { Ctx->ArrayIndex = OldArrayIndex; }
227
228private:
230 std::optional<uint64_t> OldArrayIndex;
231};
232
233template <class Emitter> class SourceLocScope final {
234public:
235 SourceLocScope(Compiler<Emitter> *Ctx, const Expr *DefaultExpr) : Ctx(Ctx) {
236 assert(DefaultExpr);
237 // We only switch if the current SourceLocDefaultExpr is null.
238 if (!Ctx->SourceLocDefaultExpr) {
239 Enabled = true;
240 Ctx->SourceLocDefaultExpr = DefaultExpr;
241 }
242 }
243
245 if (Enabled)
246 Ctx->SourceLocDefaultExpr = nullptr;
247 }
248
249private:
251 bool Enabled = false;
252};
253
254template <class Emitter> class InitLinkScope final {
255public:
257 Ctx->InitStack.push_back(std::move(Link));
258 }
259
260 ~InitLinkScope() { this->Ctx->InitStack.pop_back(); }
261
262public:
264};
265
266template <class Emitter> class InitStackScope final {
267public:
269 : Ctx(Ctx), OldValue(Ctx->InitStackActive), Active(Active) {
270 Ctx->InitStackActive = Active;
271 if (Active)
272 Ctx->InitStack.push_back(InitLink::DIE());
273 }
274
276 this->Ctx->InitStackActive = OldValue;
277 if (Active)
278 Ctx->InitStack.pop_back();
279 }
280
281private:
283 bool OldValue;
284 bool Active;
285};
286
287/// Scope used to handle temporaries in toplevel variable declarations.
288template <class Emitter> class DeclScope final : public LocalScope<Emitter> {
289public:
291 : LocalScope<Emitter>(Ctx), Scope(Ctx->P),
292 OldInitializingDecl(Ctx->InitializingDecl) {
293 Ctx->InitializingDecl = VD;
294 Ctx->InitStack.push_back(InitLink::Decl(VD));
295 }
296
298 this->Ctx->InitializingDecl = OldInitializingDecl;
299 this->Ctx->InitStack.pop_back();
300 }
301
302private:
304 const VarDecl *OldInitializingDecl;
305};
306
307/// Scope used to handle initialization methods.
308template <class Emitter> class OptionScope final {
309public:
310 /// Root constructor, compiling or discarding primitives.
311 OptionScope(Compiler<Emitter> *Ctx, bool NewDiscardResult,
312 bool NewInitializing, bool NewToLValue)
313 : Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult),
314 OldInitializing(Ctx->Initializing), OldToLValue(Ctx->ToLValue) {
315 Ctx->DiscardResult = NewDiscardResult;
316 Ctx->Initializing = NewInitializing;
317 Ctx->ToLValue = NewToLValue;
318 }
319
321 Ctx->DiscardResult = OldDiscardResult;
322 Ctx->Initializing = OldInitializing;
323 Ctx->ToLValue = OldToLValue;
324 }
325
326private:
327 /// Parent context.
329 /// Old discard flag to restore.
330 bool OldDiscardResult;
331 bool OldInitializing;
332 bool OldToLValue;
333};
334
335template <class Emitter>
336bool InitLink::emit(Compiler<Emitter> *Ctx, const Expr *E) const {
337 switch (Kind) {
338 case K_This:
339 return Ctx->emitThis(E);
340 case K_Field:
341 // We're assuming there's a base pointer on the stack already.
342 return Ctx->emitGetPtrFieldPop(Offset, 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);
2401 if (!this->emitGetPtrBase(B->Offset, Init))
2402 return false;
2403 if (!this->visitInitializerPop(Init))
2404 return false;
2405 }
2406
2407 unsigned FieldIndex = 0;
2408 for (unsigned FI = R->getNumBases(); FI != Inits.size();) {
2409 const Record::Field *FieldToInit = R->getField(FieldIndex);
2410 if (FieldToInit->isUnnamedBitField()) {
2411 ++FieldIndex;
2412 continue;
2413 }
2414
2415 const Expr *Init = Inits[FI];
2416 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
2417 // aren't supposed to be modified.
2418 if (isa<NoInitExpr>(Init)) {
2419 ++FieldIndex;
2420 ++FI;
2421 continue;
2422 }
2423
2424 if (OptPrimType T = classify(Init)) {
2425 if (!initPrimitiveField(FieldToInit, Init, *T))
2426 return false;
2427 } else if (!initCompositeField(FieldToInit, Init)) {
2428 return false;
2429 }
2430
2431 ++FI;
2432 ++FieldIndex;
2433 }
2434
2435 assert(R->getNumVirtualBases() == 0);
2436
2437 return this->emitFinishInit(E);
2438 }
2439
2440 if (QT->isArrayType()) {
2441 const ConstantArrayType *CAT =
2442 Ctx.getASTContext().getAsConstantArrayType(QT);
2443 uint64_t NumElems = CAT->getZExtSize();
2444
2445 if (Initializing &&
2446 (!InitializingDecl || InitializingDecl->hasLocalStorage()) &&
2447 !this->emitCheckArrayDestSize(NumElems, E))
2448 return false;
2449
2450 if (Inits.size() == 1 && QT == Inits[0]->getType())
2451 return this->delegate(Inits[0]);
2452
2453 OptPrimType InitT = classify(CAT->getElementType());
2454 unsigned ElementIndex = 0;
2455 for (const Expr *Init : Inits) {
2456 if (const auto *EmbedS =
2457 dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
2458 PrimType TargetT = classifyPrim(Init->getType());
2459
2460 auto Eval = [&](const IntegerLiteral *IL, unsigned ElemIndex) {
2461 if (TargetT == PT_Float) {
2462 if (!this->emitConst(IL->getValue(), classifyPrim(IL), Init))
2463 return false;
2464 const auto *Sem = &Ctx.getFloatSemantics(CAT->getElementType());
2465 if (!this->emitCastIntegralFloating(classifyPrim(IL), Sem,
2466 getFPOptions(E), E))
2467 return false;
2468 } else {
2469 if (!this->emitConst(IL->getValue(), TargetT, Init))
2470 return false;
2471 }
2472 return this->emitInitElem(TargetT, ElemIndex, IL);
2473 };
2474 if (!EmbedS->doForEachDataElement(Eval, ElementIndex))
2475 return false;
2476 } else if (isa<NoInitExpr>(Init)) {
2477 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
2478 // aren't supposed to be modified.
2479 ++ElementIndex;
2480 } else {
2481 if (!this->visitArrayElemInit(ElementIndex, Init, InitT))
2482 return false;
2483 ++ElementIndex;
2484 }
2485 }
2486
2487 // Expand the filler expression.
2488 // FIXME: This should go away.
2489 if (ArrayFiller && !isa<NoInitExpr>(ArrayFiller)) {
2490 for (; ElementIndex != NumElems; ++ElementIndex) {
2491 if (!this->visitArrayElemInit(ElementIndex, ArrayFiller, InitT))
2492 return false;
2493 }
2494 }
2495
2496 return this->emitFinishInit(E);
2497 }
2498
2499 if (const auto *ComplexTy = QT->getAs<ComplexType>()) {
2500 unsigned NumInits = Inits.size();
2501
2502 if (NumInits == 1)
2503 return this->delegate(Inits[0]);
2504
2505 QualType ElemQT = ComplexTy->getElementType();
2506 PrimType ElemT = classifyPrim(ElemQT);
2507 if (NumInits == 0) {
2508 // Zero-initialize both elements.
2509 for (unsigned I = 0; I < 2; ++I) {
2510 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2511 return false;
2512 if (!this->emitInitElem(ElemT, I, E))
2513 return false;
2514 }
2515 } else if (NumInits == 2) {
2516 unsigned InitIndex = 0;
2517 for (const Expr *Init : Inits) {
2518 if (!this->visit(Init))
2519 return false;
2520
2521 if (!this->emitInitElem(ElemT, InitIndex, E))
2522 return false;
2523 ++InitIndex;
2524 }
2525 }
2526 return true;
2527 }
2528
2529 if (const auto *VecT = QT->getAs<VectorType>()) {
2530 unsigned NumVecElements = VecT->getNumElements();
2531 assert(NumVecElements >= Inits.size());
2532
2533 QualType ElemQT = VecT->getElementType();
2534 PrimType ElemT = classifyPrim(ElemQT);
2535
2536 // All initializer elements.
2537 unsigned InitIndex = 0;
2538 for (const Expr *Init : Inits) {
2539 if (!this->visit(Init))
2540 return false;
2541
2542 // If the initializer is of vector type itself, we have to deconstruct
2543 // that and initialize all the target fields from the initializer fields.
2544 if (const auto *InitVecT = Init->getType()->getAs<VectorType>()) {
2545 if (!this->emitCopyArray(ElemT, 0, InitIndex,
2546 InitVecT->getNumElements(), E))
2547 return false;
2548 InitIndex += InitVecT->getNumElements();
2549 } else {
2550 if (!this->emitInitElem(ElemT, InitIndex, E))
2551 return false;
2552 ++InitIndex;
2553 }
2554 }
2555
2556 assert(InitIndex <= NumVecElements);
2557
2558 // Fill the rest with zeroes.
2559 for (; InitIndex != NumVecElements; ++InitIndex) {
2560 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2561 return false;
2562 if (!this->emitInitElem(ElemT, InitIndex, E))
2563 return false;
2564 }
2565 return true;
2566 }
2567
2568 if (const auto *MT = QT->getAs<ConstantMatrixType>()) {
2569 unsigned NumElems = MT->getNumElementsFlattened();
2570 assert(Inits.size() == NumElems);
2571
2572 QualType ElemQT = MT->getElementType();
2573 PrimType ElemT = classifyPrim(ElemQT);
2574
2575 // Matrix initializer list elements are in row-major order, which matches
2576 // the matrix APValue convention and therefore no index remapping is
2577 // required.
2578 for (unsigned I = 0; I != NumElems; ++I) {
2579 if (!this->visit(Inits[I]))
2580 return false;
2581 if (!this->emitInitElem(ElemT, I, E))
2582 return false;
2583 }
2584 return true;
2585 }
2586
2587 return false;
2588}
2589
2590/// Pointer to the array(not the element!) must be on the stack when calling
2591/// this.
2592template <class Emitter>
2593bool Compiler<Emitter>::visitArrayElemInit(unsigned ElemIndex, const Expr *Init,
2594 OptPrimType InitT) {
2595 if (InitT) {
2596 // Visit the primitive element like normal.
2597 if (!this->visit(Init))
2598 return false;
2599 return this->emitInitElem(*InitT, ElemIndex, Init);
2600 }
2601
2602 InitLinkScope<Emitter> ILS(this, InitLink::Elem(ElemIndex));
2603 // Advance the pointer currently on the stack to the given
2604 // dimension.
2605 if (!this->emitConstUint32(ElemIndex, Init))
2606 return false;
2607 if (!this->emitArrayElemPtrUint32(Init))
2608 return false;
2609 return this->visitInitializerPop(Init);
2610}
2611
2612template <class Emitter>
2614 const FunctionDecl *FuncDecl,
2615 bool Activate, bool IsOperatorCall) {
2616 assert(VarScope->getKind() == ScopeKind::Call);
2617 llvm::BitVector NonNullArgs;
2618 if (FuncDecl && FuncDecl->hasAttr<NonNullAttr>())
2619 NonNullArgs = collectNonNullArgs(FuncDecl, Args);
2620
2621 bool ExplicitMemberFn = false;
2622 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl))
2623 ExplicitMemberFn = MD->isExplicitObjectMemberFunction();
2624
2625 unsigned ArgIndex = 0;
2626 for (const Expr *Arg : Args) {
2627 if (canClassify(Arg)) {
2628 if (!this->visit(Arg))
2629 return false;
2630 } else {
2631
2632 DeclTy Source = Arg;
2633 if (FuncDecl) {
2634 // Try to use the parameter declaration instead of the argument
2635 // expression as a source.
2636 unsigned DeclIndex = ArgIndex - IsOperatorCall + ExplicitMemberFn;
2637 if (DeclIndex < FuncDecl->getNumParams())
2638 Source = FuncDecl->getParamDecl(ArgIndex - IsOperatorCall +
2639 ExplicitMemberFn);
2640 }
2641
2642 UnsignedOrNone LocalIndex =
2643 allocateLocal(std::move(Source), Arg->getType(), ScopeKind::Call);
2644 if (!LocalIndex)
2645 return false;
2646
2647 if (!this->emitGetPtrLocal(*LocalIndex, Arg))
2648 return false;
2649 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
2650 if (!this->visitInitializer(Arg))
2651 return false;
2652 }
2653
2654 if (ArgIndex == 1 && Activate) {
2655 if (!this->emitActivate(Arg))
2656 return false;
2657 }
2658
2659 if (!NonNullArgs.empty() && NonNullArgs[ArgIndex]) {
2660 PrimType ArgT = classify(Arg).value_or(PT_Ptr);
2661 if (ArgT == PT_Ptr) {
2662 if (!this->emitCheckNonNullArg(ArgT, Arg))
2663 return false;
2664 }
2665 }
2666
2667 ++ArgIndex;
2668 }
2669
2670 return true;
2671}
2672
2673template <class Emitter>
2675 return this->visitInitList(E->inits(), E->getArrayFiller(), E);
2676}
2677
2678template <class Emitter>
2683
2684template <class Emitter>
2689
2690template <class Emitter>
2692 if (!E->hasAPValueResult())
2693 return this->delegate(E->getSubExpr());
2694
2695 if (OptPrimType T = classify(E)) {
2696 // Try to emit the APValue directly, without visiting the subexpr.
2697 // This will only fail if we can't emit the APValue, so won't emit any
2698 // diagnostics or any double values.
2699 if (DiscardResult)
2700 return true;
2701 return this->visitAPValue(E->getAPValueResult(), *T, E);
2702 }
2703
2704 // Fall back to the subexpr for non-primitive APValues.
2705 return this->delegate(E->getSubExpr());
2706}
2707
2708template <class Emitter>
2710 auto It = E->begin();
2711 return this->visit(*It);
2712}
2713
2715 UnaryExprOrTypeTrait Kind) {
2716 bool AlignOfReturnsPreferred =
2717 ASTCtx.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver7);
2718
2719 // C++ [expr.alignof]p3:
2720 // When alignof is applied to a reference type, the result is the
2721 // alignment of the referenced type.
2722 if (const auto *Ref = T->getAs<ReferenceType>())
2723 T = Ref->getPointeeType();
2724
2725 if (T.getQualifiers().hasUnaligned())
2726 return CharUnits::One();
2727
2728 // __alignof is defined to return the preferred alignment.
2729 // Before 8, clang returned the preferred alignment for alignof and
2730 // _Alignof as well.
2731 if (Kind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
2732 return ASTCtx.toCharUnitsFromBits(ASTCtx.getPreferredTypeAlign(T));
2733
2734 return ASTCtx.getTypeAlignInChars(T);
2735}
2736
2737template <class Emitter>
2739 const UnaryExprOrTypeTraitExpr *E) {
2740
2741 UnaryExprOrTypeTrait Kind = E->getKind();
2742 const ASTContext &ASTCtx = Ctx.getASTContext();
2743
2744 if (Kind == UETT_SizeOf || Kind == UETT_DataSizeOf) {
2746
2747 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2748 // the result is the size of the referenced type."
2749 if (const auto *Ref = ArgType->getAs<ReferenceType>())
2750 ArgType = Ref->getPointeeType();
2751
2752 CharUnits Size;
2753 if (ArgType->isVoidType() || ArgType->isFunctionType())
2754 Size = CharUnits::One();
2755 else {
2756 if (ArgType->isDependentType() || !ArgType->isConstantSizeType())
2757 return this->emitInvalid(E);
2758
2759 if (Kind == UETT_SizeOf)
2760 Size = ASTCtx.getTypeSizeInChars(ArgType);
2761 else
2763 }
2764
2765 if (DiscardResult)
2766 return true;
2767
2768 return this->emitConst(Size.getQuantity(), E);
2769 }
2770
2771 if (Kind == UETT_CountOf) {
2772 QualType Ty = E->getTypeOfArgument();
2773 assert(Ty->isArrayType());
2774
2775 // We don't need to worry about array element qualifiers, so getting the
2776 // unsafe array type is fine.
2777 if (const auto *CAT =
2778 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
2779 if (DiscardResult)
2780 return true;
2781 return this->emitConst(CAT->getSize(), E);
2782 }
2783
2784 assert(!Ty->isConstantSizeType());
2785
2786 // If it's a variable-length array type, we need to check whether it is a
2787 // multidimensional array. If so, we need to check the size expression of
2788 // the VLA to see if it's a constant size. If so, we can return that value.
2789 const auto *VAT = ASTCtx.getAsVariableArrayType(Ty);
2790 assert(VAT);
2791 if (VAT->getElementType()->isArrayType()) {
2792 std::optional<APSInt> Res =
2793 VAT->getSizeExpr()
2794 ? VAT->getSizeExpr()->getIntegerConstantExpr(ASTCtx)
2795 : std::nullopt;
2796 if (Res) {
2797 if (DiscardResult)
2798 return true;
2799 return this->emitConst(*Res, E);
2800 }
2801 }
2802 }
2803
2804 if (Kind == UETT_AlignOf || Kind == UETT_PreferredAlignOf) {
2805 CharUnits Size;
2806
2807 if (E->isArgumentType()) {
2809
2810 Size = AlignOfType(ArgType, ASTCtx, Kind);
2811 } else {
2812 // Argument is an expression, not a type.
2813 const Expr *Arg = E->getArgumentExpr()->IgnoreParens();
2814
2815 if (Arg->getType()->isDependentType())
2816 return false;
2817
2818 // The kinds of expressions that we have special-case logic here for
2819 // should be kept up to date with the special checks for those
2820 // expressions in Sema.
2821
2822 // alignof decl is always accepted, even if it doesn't make sense: we
2823 // default to 1 in those cases.
2824 if (const auto *DRE = dyn_cast<DeclRefExpr>(Arg))
2825 Size = ASTCtx.getDeclAlign(DRE->getDecl(),
2826 /*RefAsPointee*/ true);
2827 else if (const auto *ME = dyn_cast<MemberExpr>(Arg))
2828 Size = ASTCtx.getDeclAlign(ME->getMemberDecl(),
2829 /*RefAsPointee*/ true);
2830 else
2831 Size = AlignOfType(Arg->getType(), ASTCtx, Kind);
2832 }
2833
2834 if (DiscardResult)
2835 return true;
2836
2837 return this->emitConst(Size.getQuantity(), E);
2838 }
2839
2840 if (Kind == UETT_VectorElements) {
2841 if (E->containsErrors())
2842 return false;
2843
2844 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>())
2845 return this->emitConst(VT->getNumElements(), E);
2847 return this->emitSizelessVectorElementSize(E);
2848 }
2849
2850 if (Kind == UETT_VecStep) {
2851 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>()) {
2852 unsigned N = VT->getNumElements();
2853
2854 // The vec_step built-in functions that take a 3-component
2855 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2856 if (N == 3)
2857 N = 4;
2858
2859 return this->emitConst(N, E);
2860 }
2861 return this->emitConst(1, E);
2862 }
2863
2864 if (Kind == UETT_OpenMPRequiredSimdAlign) {
2865 if (E->containsErrors())
2866 return false;
2867 assert(E->isArgumentType());
2868 unsigned Bits = ASTCtx.getOpenMPDefaultSimdAlign(E->getArgumentType());
2869
2870 return this->emitConst(ASTCtx.toCharUnitsFromBits(Bits).getQuantity(), E);
2871 }
2872
2873 if (Kind == UETT_PtrAuthTypeDiscriminator) {
2874 if (E->getArgumentType()->isDependentType())
2875 return this->emitInvalid(E);
2876
2877 return this->emitConst(
2878 const_cast<ASTContext &>(ASTCtx).getPointerAuthTypeDiscriminator(
2879 E->getArgumentType()),
2880 E);
2881 }
2882
2883 return false;
2884}
2885
2886template <class Emitter>
2888 // 'Base.Member'
2889 const Expr *Base = E->getBase();
2890 const ValueDecl *Member = E->getMemberDecl();
2891
2892 if (DiscardResult)
2893 return this->discard(Base);
2894
2895 if (const auto *VD = dyn_cast<VarDecl>(Member)) {
2896 // I am almost confident in saying that a var decl must be static
2897 // and therefore registered as a global variable.
2898 if (auto GlobalIndex = P.getGlobal(VD)) {
2899 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2900 return false;
2901 if (Member->getType()->isReferenceType())
2902 return this->emitLoadPopPtr(E);
2903 return true;
2904 }
2905 return false;
2906 }
2907
2908 if (!isa<FieldDecl>(Member)) {
2909 // A non-static member function access only makes sense as part of the
2910 // enclosing call here. Don't try to evaluate it in isolation.
2911 if (const auto *MD = dyn_cast<CXXMethodDecl>(Member);
2912 MD && !MD->isStatic()) {
2913 return false;
2914 }
2915
2916 if (!this->discard(Base) && !this->emitSideEffect(E))
2917 return false;
2918
2919 return this->visitDeclRef(Member, E);
2920 }
2921
2922 if (!this->visit(Base))
2923 return false;
2924
2925 // Base above gives us a pointer on the stack.
2926 const auto *FD = cast<FieldDecl>(Member);
2927 const RecordDecl *RD = FD->getParent();
2928 const Record *R = getRecord(RD);
2929 if (!R)
2930 return false;
2931 const Record::Field *F = R->getField(FD);
2932
2933 // MemberExprs are almost always lvalues, in which case we don't need to
2934 // do the load. But sometimes they aren't.
2935 const auto maybeLoadValue = [&]() -> bool {
2936 if (E->isGLValue())
2937 return true;
2938 if (OptPrimType T = classify(E))
2939 return this->emitLoadPop(*T, E);
2940 return false;
2941 };
2942
2943 // Leave a pointer to the field on the stack.
2944 if (F->Decl->getType()->isReferenceType())
2945 return this->emitGetFieldPop(PT_Ptr, F->Offset, E) && maybeLoadValue();
2946 return this->emitGetPtrFieldPop(F->Offset, E) && maybeLoadValue();
2947}
2948
2949template <class Emitter>
2951 assert(!DiscardResult);
2952 // ArrayIndex might not be set if a ArrayInitIndexExpr is being evaluated
2953 // stand-alone, e.g. via EvaluateAsInt().
2954 if (!ArrayIndex)
2955 return false;
2956 return this->emitConst(*ArrayIndex, E);
2957}
2958
2959template <class Emitter>
2961 assert(Initializing);
2962 assert(!DiscardResult);
2963
2964 const Expr *Common = E->getCommonExpr();
2965 const Expr *SubExpr = E->getSubExpr();
2966 OptPrimType SubExprT = classify(SubExpr);
2967 size_t Size = E->getArraySize().getZExtValue();
2968
2969 if (SubExprT) {
2970 // Unwrap the OpaqueValueExpr so we don't cache something we won't reuse.
2971 Common = cast<OpaqueValueExpr>(Common)->getSourceExpr();
2972
2973 if (!this->visit(Common))
2974 return false;
2975 return this->emitCopyArray(*SubExprT, 0, 0, Size, E);
2976 }
2977
2978 // We visit the common opaque expression here once so we have its value
2979 // cached.
2980 if (!this->discard(Common))
2981 return false;
2982
2983 // TODO: This compiles to quite a lot of bytecode if the array is larger.
2984 // Investigate compiling this to a loop.
2985
2986 // So, every iteration, we execute an assignment here
2987 // where the LHS is on the stack (the target array)
2988 // and the RHS is our SubExpr.
2989 for (size_t I = 0; I != Size; ++I) {
2990 ArrayIndexScope<Emitter> IndexScope(this, I);
2992
2993 if (!this->visitArrayElemInit(I, SubExpr, SubExprT))
2994 return false;
2995 if (!BS.destroyLocals())
2996 return false;
2997 }
2998 return true;
2999}
3000
3001template <class Emitter>
3003 const Expr *SourceExpr = E->getSourceExpr();
3004 if (!SourceExpr)
3005 return false;
3006
3007 if (Initializing) {
3008 assert(!DiscardResult);
3009 return this->visitInitializer(SourceExpr);
3010 }
3011
3012 PrimType SubExprT = classify(SourceExpr).value_or(PT_Ptr);
3013 if (auto It = OpaqueExprs.find(E); It != OpaqueExprs.end()) {
3014 if (DiscardResult)
3015 return true;
3016 return this->emitGetLocal(SubExprT, It->second, E);
3017 }
3018
3019 if (!this->visit(SourceExpr))
3020 return false;
3021
3022 // At this point we either have the evaluated source expression or a pointer
3023 // to an object on the stack. We want to create a local variable that stores
3024 // this value.
3025 unsigned LocalIndex = allocateLocalPrimitive(E, SubExprT, /*IsConst=*/true);
3026 if (!this->emitSetLocal(SubExprT, LocalIndex, E))
3027 return false;
3028
3029 // This is cleaned up when the local variable is destroyed.
3030 OpaqueExprs.insert({E, LocalIndex});
3031
3032 // Here the local variable is created but the value is removed from the stack,
3033 // so we put it back if the caller needs it.
3034 if (!DiscardResult)
3035 return this->emitGetLocal(SubExprT, LocalIndex, E);
3036 return true;
3037}
3038
3039template <class Emitter>
3041 const AbstractConditionalOperator *E) {
3042 const Expr *Condition = E->getCond();
3043 const Expr *TrueExpr = E->getTrueExpr();
3044 const Expr *FalseExpr = E->getFalseExpr();
3045
3046 if (std::optional<bool> BoolValue = getBoolValue(Condition)) {
3047 if (*BoolValue)
3048 return this->delegate(TrueExpr);
3049 return this->delegate(FalseExpr);
3050 }
3051
3052 bool IsBcpCall = false;
3053 if (const auto *CE = dyn_cast<CallExpr>(Condition->IgnoreParenCasts());
3054 CE && CE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) {
3055 IsBcpCall = true;
3056 }
3057
3058 LabelTy LabelEnd = this->getLabel(); // Label after the operator.
3059 LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
3060
3061 if (IsBcpCall) {
3062 if (!this->emitPushIgnoreDiags(E))
3063 return false;
3064 }
3065
3066 if (!this->visitBool(Condition)) {
3067 // If the condition failed and we're checking for undefined behavior
3068 // (which only happens with EvalEmitter) check the TrueExpr and FalseExpr
3069 // as well.
3070 if (this->checkingForUndefinedBehavior()) {
3071 if (!this->discard(TrueExpr))
3072 return false;
3073 if (!this->discard(FalseExpr))
3074 return false;
3075 }
3076 return false;
3077 }
3078
3079 // Force-init the scope, which creates a InitScope op. This is necessary so
3080 // the scope is not only initialized in one arm of the conditional operator.
3081 this->VarScope->forceInit();
3082 // The TrueExpr and FalseExpr of a conditional operator do _not_ create a
3083 // scope, which means the local variables created within them unconditionally
3084 // always exist. However, we need to later differentiate which branch was
3085 // taken and only destroy the varibles of the active branch. This is what the
3086 // "enabled" flags on local variables are used for.
3087 llvm::SaveAndRestore LAAA(this->VarScope->LocalsAlwaysEnabled,
3088 /*NewValue=*/false);
3089
3090 if (!this->jumpFalse(LabelFalse, E))
3091 return false;
3092 if (!this->delegate(TrueExpr))
3093 return false;
3094
3095 if (!this->jump(LabelEnd, E))
3096 return false;
3097 this->emitLabel(LabelFalse);
3098 if (!this->delegate(FalseExpr))
3099 return false;
3100
3101 this->fallthrough(LabelEnd);
3102 this->emitLabel(LabelEnd);
3103
3104 if (IsBcpCall)
3105 return this->emitPopIgnoreDiags(E);
3106 return true;
3107}
3108
3109template <class Emitter>
3111 if (DiscardResult)
3112 return true;
3113
3114 if (!Initializing) {
3115 unsigned StringIndex = P.createGlobalString(E);
3116 return this->emitGetPtrGlobal(StringIndex, E);
3117 }
3118
3119 // We are initializing an array on the stack.
3120 const ConstantArrayType *CAT =
3121 Ctx.getASTContext().getAsConstantArrayType(E->getType());
3122 assert(CAT && "a string literal that's not a constant array?");
3123
3124 // If the initializer string is too long, a diagnostic has already been
3125 // emitted. Read only the array length from the string literal.
3126 unsigned ArraySize = CAT->getZExtSize();
3127 unsigned N = std::min(ArraySize, E->getLength());
3128 unsigned CharWidth = E->getCharByteWidth();
3129
3130 for (unsigned I = 0; I != N; ++I) {
3131 uint32_t CodeUnit = E->getCodeUnit(I);
3132
3133 if (CharWidth == 1) {
3134 this->emitConstSint8(CodeUnit, E);
3135 this->emitInitElemSint8(I, E);
3136 } else if (CharWidth == 2) {
3137 this->emitConstUint16(CodeUnit, E);
3138 this->emitInitElemUint16(I, E);
3139 } else if (CharWidth == 4) {
3140 this->emitConstUint32(CodeUnit, E);
3141 this->emitInitElemUint32(I, E);
3142 } else {
3143 llvm_unreachable("unsupported character width");
3144 }
3145 }
3146
3147 // Fill up the rest of the char array with NUL bytes.
3148 for (unsigned I = N; I != ArraySize; ++I) {
3149 if (CharWidth == 1) {
3150 this->emitConstSint8(0, E);
3151 this->emitInitElemSint8(I, E);
3152 } else if (CharWidth == 2) {
3153 this->emitConstUint16(0, E);
3154 this->emitInitElemUint16(I, E);
3155 } else if (CharWidth == 4) {
3156 this->emitConstUint32(0, E);
3157 this->emitInitElemUint32(I, E);
3158 } else {
3159 llvm_unreachable("unsupported character width");
3160 }
3161 }
3162
3163 return true;
3164}
3165
3166template <class Emitter>
3168 if (DiscardResult)
3169 return true;
3170 return this->emitDummyPtr(E, E);
3171}
3172
3173template <class Emitter>
3175 auto &A = Ctx.getASTContext();
3176 std::string Str;
3177 A.getObjCEncodingForType(E->getEncodedType(), Str);
3178 StringLiteral *SL =
3180 /*Pascal=*/false, E->getType(), E->getAtLoc());
3181 return this->delegate(SL);
3182}
3183
3184template <class Emitter>
3186 const SYCLUniqueStableNameExpr *E) {
3187 if (DiscardResult)
3188 return true;
3189
3190 assert(!Initializing);
3191
3192 auto &A = Ctx.getASTContext();
3193 std::string ResultStr = E->ComputeName(A);
3194
3195 QualType CharTy = A.CharTy.withConst();
3196 APInt Size(A.getTypeSize(A.getSizeType()), ResultStr.size() + 1);
3197 QualType ArrayTy = A.getConstantArrayType(CharTy, Size, nullptr,
3199
3200 StringLiteral *SL =
3202 /*Pascal=*/false, ArrayTy, E->getLocation());
3203
3204 unsigned StringIndex = P.createGlobalString(SL);
3205 return this->emitGetPtrGlobal(StringIndex, E);
3206}
3207
3208template <class Emitter>
3210 if (DiscardResult)
3211 return true;
3212 return this->emitConst(E->getValue(), E);
3213}
3214
3215template <class Emitter>
3217 const CompoundAssignOperator *E) {
3218
3219 const Expr *LHS = E->getLHS();
3220 const Expr *RHS = E->getRHS();
3221 QualType LHSType = LHS->getType();
3222 QualType LHSComputationType = E->getComputationLHSType();
3223 QualType ResultType = E->getComputationResultType();
3224 OptPrimType LT = classify(LHSComputationType);
3225 OptPrimType RT = classify(ResultType);
3226
3227 assert(ResultType->isFloatingType());
3228
3229 if (!LT || !RT)
3230 return false;
3231
3232 PrimType LHST = classifyPrim(LHSType);
3233
3234 if (isSideEffectFree(RHS)) {
3235 if (!visit(LHS))
3236 return false;
3237 if (!this->emitLoad(LHST, E))
3238 return false;
3239 // If necessary, convert LHS to its computation type.
3240 if (!this->emitPrimCast(LHST, classifyPrim(LHSComputationType),
3241 LHSComputationType, E))
3242 return false;
3243 if (!visit(RHS))
3244 return false;
3245
3246 } else {
3247 // C++17 onwards require that we evaluate the RHS first.
3248 // Compute RHS and save it in a temporary variable so we can
3249 // load it again later.
3250 if (!visit(RHS))
3251 return false;
3252
3253 unsigned TempOffset =
3254 this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
3255 if (!this->emitSetLocal(*RT, TempOffset, E))
3256 return false;
3257
3258 // First, visit LHS.
3259 if (!visit(LHS))
3260 return false;
3261 if (!this->emitLoad(LHST, E))
3262 return false;
3263
3264 // If necessary, convert LHS to its computation type.
3265 if (!this->emitPrimCast(LHST, classifyPrim(LHSComputationType),
3266 LHSComputationType, E))
3267 return false;
3268
3269 // Now load RHS.
3270 if (!this->emitGetLocal(*RT, TempOffset, E))
3271 return false;
3272 }
3273
3274 switch (E->getOpcode()) {
3275 case BO_AddAssign:
3276 if (!this->emitAddf(getFPOptions(E), E))
3277 return false;
3278 break;
3279 case BO_SubAssign:
3280 if (!this->emitSubf(getFPOptions(E), E))
3281 return false;
3282 break;
3283 case BO_MulAssign:
3284 if (!this->emitMulf(getFPOptions(E), E))
3285 return false;
3286 break;
3287 case BO_DivAssign:
3288 if (!this->emitDivf(getFPOptions(E), E))
3289 return false;
3290 break;
3291 default:
3292 return false;
3293 }
3294
3295 if (!this->emitPrimCast(classifyPrim(ResultType), LHST, LHS->getType(), E))
3296 return false;
3297
3298 if (DiscardResult)
3299 return this->emitStorePop(LHST, E);
3300 return this->emitStore(LHST, E);
3301}
3302
3303template <class Emitter>
3305 const CompoundAssignOperator *E) {
3306 BinaryOperatorKind Op = E->getOpcode();
3307 const Expr *LHS = E->getLHS();
3308 const Expr *RHS = E->getRHS();
3309 OptPrimType LT = classify(LHS->getType());
3310 OptPrimType RT = classify(RHS->getType());
3311
3312 if (Op != BO_AddAssign && Op != BO_SubAssign)
3313 return false;
3314
3315 if (!LT || !RT)
3316 return false;
3317
3318 if (!visit(LHS))
3319 return false;
3320
3321 if (!this->emitLoad(*LT, LHS))
3322 return false;
3323
3324 if (!visit(RHS))
3325 return false;
3326
3327 if (Op == BO_AddAssign) {
3328 if (!this->emitAddOffset(*RT, E))
3329 return false;
3330 } else {
3331 if (!this->emitSubOffset(*RT, E))
3332 return false;
3333 }
3334
3335 if (DiscardResult)
3336 return this->emitStorePopPtr(E);
3337 return this->emitStorePtr(E);
3338}
3339
3340template <class Emitter>
3342 const CompoundAssignOperator *E) {
3343 if (E->getType()->isVectorType())
3344 return VisitVectorBinOp(E);
3345
3346 const Expr *LHS = E->getLHS();
3347 const Expr *RHS = E->getRHS();
3348 OptPrimType LHSComputationT = classify(E->getComputationLHSType());
3349 OptPrimType LT = classify(LHS->getType());
3350 OptPrimType RT = classify(RHS->getType());
3351 OptPrimType ResultT = classify(E->getType());
3352
3353 if (!Ctx.getLangOpts().CPlusPlus14)
3354 return this->visit(RHS) && this->visit(LHS) && this->emitError(E);
3355
3356 if (!LT || !RT || !ResultT || !LHSComputationT)
3357 return false;
3358
3359 // Handle floating point operations separately here, since they
3360 // require special care.
3361 if (ResultT == PT_Float || RT == PT_Float)
3363
3364 if (E->getType()->isPointerType())
3366
3367 assert(!E->getType()->isPointerType() && "Handled above");
3368 assert(!E->getType()->isFloatingType() && "Handled above");
3369
3370 if (isSideEffectFree(RHS)) {
3371 if (!visit(LHS))
3372 return false;
3373 if (!this->emitLoad(*LT, E))
3374 return false;
3375 if (LT != LHSComputationT &&
3376 !this->emitIntegralCast(*LT, *LHSComputationT,
3377 E->getComputationLHSType(), E))
3378 return false;
3379 if (!visit(RHS))
3380 return false;
3381 } else {
3382 // C++17 onwards require that we evaluate the RHS first.
3383 // Compute RHS and save it in a temporary variable so we can
3384 // load it again later.
3385 // FIXME: Compound assignments are unsequenced in C, so we might
3386 // have to figure out how to reject them.
3387 if (!visit(RHS))
3388 return false;
3389
3390 unsigned TempOffset =
3391 this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
3392
3393 if (!this->emitSetLocal(*RT, TempOffset, E))
3394 return false;
3395
3396 // Get LHS pointer, load its value and cast it to the
3397 // computation type if necessary.
3398 if (!visit(LHS))
3399 return false;
3400 if (!this->emitLoad(*LT, E))
3401 return false;
3402 if (LT != LHSComputationT &&
3403 !this->emitIntegralCast(*LT, *LHSComputationT,
3404 E->getComputationLHSType(), E))
3405 return false;
3406
3407 // Get the RHS value on the stack.
3408 if (!this->emitGetLocal(*RT, TempOffset, E))
3409 return false;
3410 }
3411
3412 // Perform operation.
3413 switch (E->getOpcode()) {
3414 case BO_AddAssign:
3415 if (!this->emitAdd(*LHSComputationT, E))
3416 return false;
3417 break;
3418 case BO_SubAssign:
3419 if (!this->emitSub(*LHSComputationT, E))
3420 return false;
3421 break;
3422 case BO_MulAssign:
3423 if (!this->emitMul(*LHSComputationT, E))
3424 return false;
3425 break;
3426 case BO_DivAssign:
3427 if (!this->emitDiv(*LHSComputationT, E))
3428 return false;
3429 break;
3430 case BO_RemAssign:
3431 if (!this->emitRem(*LHSComputationT, E))
3432 return false;
3433 break;
3434 case BO_ShlAssign:
3435 if (!this->emitShl(*LHSComputationT, *RT, E))
3436 return false;
3437 break;
3438 case BO_ShrAssign:
3439 if (!this->emitShr(*LHSComputationT, *RT, E))
3440 return false;
3441 break;
3442 case BO_AndAssign:
3443 if (!this->emitBitAnd(*LHSComputationT, E))
3444 return false;
3445 break;
3446 case BO_XorAssign:
3447 if (!this->emitBitXor(*LHSComputationT, E))
3448 return false;
3449 break;
3450 case BO_OrAssign:
3451 if (!this->emitBitOr(*LHSComputationT, E))
3452 return false;
3453 break;
3454 default:
3455 llvm_unreachable("Unimplemented compound assign operator");
3456 }
3457
3458 // And now cast from LHSComputationT to ResultT.
3459 if (ResultT != LHSComputationT &&
3460 !this->emitIntegralCast(*LHSComputationT, *ResultT, E->getType(), E))
3461 return false;
3462
3463 // And store the result in LHS.
3464 if (DiscardResult) {
3465 if (LHS->refersToBitField())
3466 return this->emitStoreBitFieldPop(*ResultT, E);
3467 return this->emitStorePop(*ResultT, E);
3468 }
3469 if (LHS->refersToBitField())
3470 return this->emitStoreBitField(*ResultT, E);
3471 return this->emitStore(*ResultT, E);
3472}
3473
3474template <class Emitter>
3477 const Expr *SubExpr = E->getSubExpr();
3478
3479 return this->delegate(SubExpr) && ES.destroyLocals(E);
3480}
3481
3482template <class Emitter>
3484 const MaterializeTemporaryExpr *E) {
3485 if (Initializing) {
3486 // We already have a value, just initialize that.
3487 return this->delegate(E->getSubExpr());
3488 }
3489 // If we don't end up using the materialized temporary anyway, don't
3490 // bother creating it.
3491 if (DiscardResult)
3492 return this->discard(E->getSubExpr());
3493
3496 const Expr *Inner;
3497 if (!Ctx.getLangOpts().CPlusPlus11)
3498 Inner =
3499 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
3500 else
3501 Inner = E->getSubExpr();
3502
3503 // If we passed any comma operators, evaluate their LHSs.
3504 for (const Expr *LHS : CommaLHSs) {
3505 if (!this->discard(LHS))
3506 return false;
3507 }
3508
3509 // FIXME: Find a test case where Adjustments matters.
3510
3511 // When we're extending a global variable *or* the storage duration of
3512 // the temporary is explicitly static, create a global variable.
3513 OptPrimType InnerT = classify(Inner);
3514 const ValueDecl *ExtendingDecl = E->getExtendingDecl();
3515 bool IsStatic = E->getStorageDuration() == SD_Static;
3516 if (IsStatic ||
3517 (ExtendingDecl && Context::shouldBeGloballyIndexed(ExtendingDecl))) {
3518 UnsignedOrNone GlobalIndex = P.createGlobal(E, Inner->getType());
3519 if (!GlobalIndex)
3520 return false;
3521
3522 const LifetimeExtendedTemporaryDecl *TempDecl =
3524
3525 if (InnerT) {
3526 if (!this->visit(Inner))
3527 return false;
3528
3529 if (IsStatic) {
3530 assert(TempDecl);
3531 if (!this->emitInitGlobalTemp(*InnerT, *GlobalIndex, TempDecl, E))
3532 return false;
3533 } else {
3534 if (!this->emitInitGlobal(*InnerT, *GlobalIndex, E))
3535 return false;
3536 }
3537 return this->emitGetPtrGlobal(*GlobalIndex, E);
3538 }
3539
3540 if (!this->checkLiteralType(Inner))
3541 return false;
3542 // Non-primitive values.
3543 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3544 return false;
3545 if (!this->visitInitializer(Inner))
3546 return false;
3547 if (IsStatic) {
3548 assert(TempDecl);
3549 return this->emitInitGlobalTempComp(TempDecl, E);
3550 }
3551 return true;
3552 }
3553
3557
3558 // For everyhing else, use local variables.
3559 if (InnerT) {
3560 bool IsConst = Inner->getType().isConstQualified();
3561 bool IsVolatile = Inner->getType().isVolatileQualified();
3562 unsigned LocalIndex =
3563 allocateLocalPrimitive(E, *InnerT, IsConst, IsVolatile, VarScope);
3564 if (!this->VarScope->LocalsAlwaysEnabled &&
3565 !this->emitEnableLocal(LocalIndex, E))
3566 return false;
3567
3568 if (!this->visit(Inner))
3569 return false;
3570 if (!this->emitSetLocal(*InnerT, LocalIndex, E))
3571 return false;
3572
3573 return this->emitGetPtrLocal(LocalIndex, E);
3574 }
3575
3576 if (!this->checkLiteralType(Inner))
3577 return false;
3578
3579 if (UnsignedOrNone LocalIndex =
3580 allocateLocal(E, Inner->getType(), VarScope)) {
3581 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
3582
3583 if (!this->VarScope->LocalsAlwaysEnabled &&
3584 !this->emitEnableLocal(*LocalIndex, E))
3585 return false;
3586
3587 if (!this->emitGetPtrLocal(*LocalIndex, E))
3588 return false;
3589 return this->visitInitializer(Inner);
3590 }
3591 return false;
3592}
3593
3594template <class Emitter>
3596 const CXXBindTemporaryExpr *E) {
3597 const Expr *SubExpr = E->getSubExpr();
3598
3599 if (Initializing)
3600 return this->delegate(SubExpr);
3601
3602 // Make sure we create a temporary even if we're discarding, since that will
3603 // make sure we will also call the destructor.
3604
3605 if (!this->visit(SubExpr))
3606 return false;
3607
3608 if (DiscardResult)
3609 return this->emitPopPtr(E);
3610 return true;
3611}
3612
3613template <class Emitter>
3615 const Expr *Init = E->getInitializer();
3616 if (DiscardResult)
3617 return this->discard(Init);
3618
3619 if (Initializing) {
3620 // We already have a value, just initialize that.
3621 return this->visitInitializer(Init);
3622 }
3623
3624 OptPrimType T = classify(E->getType());
3625 if (E->isFileScope()) {
3626 // Avoid creating a variable if this is a primitive RValue anyway.
3627 if (T && !E->isLValue())
3628 return this->delegate(Init);
3629
3630 UnsignedOrNone GlobalIndex = P.createGlobal(E, E->getType());
3631 if (!GlobalIndex)
3632 return false;
3633
3634 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3635 return false;
3636
3637 // Since this is a global variable, we might've already seen,
3638 // don't do it again.
3639 if (P.isGlobalInitialized(*GlobalIndex))
3640 return true;
3641
3642 if (T) {
3643 if (!this->visit(Init))
3644 return false;
3645 return this->emitInitGlobal(*T, *GlobalIndex, E);
3646 }
3647
3648 return this->visitInitializer(Init);
3649 }
3650
3651 // Otherwise, use a local variable.
3652 if (T && !E->isLValue()) {
3653 // For primitive types, we just visit the initializer.
3654 return this->delegate(Init);
3655 }
3656
3657 unsigned LocalIndex;
3658 if (T)
3659 LocalIndex = this->allocateLocalPrimitive(Init, *T, /*IsConst=*/false);
3660 else if (UnsignedOrNone MaybeIndex = this->allocateLocal(Init))
3661 LocalIndex = *MaybeIndex;
3662 else
3663 return false;
3664
3665 if (!this->emitGetPtrLocal(LocalIndex, E))
3666 return false;
3667
3668 if (T)
3669 return this->visit(Init) && this->emitInit(*T, E);
3670 return this->visitInitializer(Init);
3671}
3672
3673template <class Emitter>
3675 if (DiscardResult)
3676 return true;
3677 if (E->isStoredAsBoolean()) {
3678 if (E->getType()->isBooleanType())
3679 return this->emitConstBool(E->getBoolValue(), E);
3680 return this->emitConst(E->getBoolValue(), E);
3681 }
3683 return this->visitAPValue(E->getAPValue(), T, E);
3684}
3685
3686template <class Emitter>
3688 if (DiscardResult)
3689 return true;
3690 return this->emitConst(E->getValue(), E);
3691}
3692
3693template <class Emitter>
3695 if (DiscardResult)
3696 return true;
3697
3698 assert(Initializing);
3699 const Record *R = P.getOrCreateRecord(E->getLambdaClass());
3700 if (!R)
3701 return false;
3702
3703 auto *CaptureInitIt = E->capture_init_begin();
3704 // Initialize all fields (which represent lambda captures) of the
3705 // record with their initializers.
3706 for (const Record::Field &F : R->fields()) {
3707 const Expr *Init = *CaptureInitIt;
3708 if (!Init || Init->containsErrors())
3709 continue;
3710 ++CaptureInitIt;
3711
3712 if (OptPrimType T = classify(Init)) {
3713 if (!this->visit(Init))
3714 return false;
3715
3716 if (!this->emitInitField(*T, F.Offset, E))
3717 return false;
3718 } else {
3719 if (!this->emitGetPtrField(F.Offset, E))
3720 return false;
3721
3722 if (!this->visitInitializerPop(Init))
3723 return false;
3724 }
3725 }
3726
3727 return true;
3728}
3729
3730template <class Emitter>
3732 if (DiscardResult)
3733 return true;
3734
3735 if (!Initializing) {
3736 unsigned StringIndex = P.createGlobalString(E->getFunctionName(), E);
3737 return this->emitGetPtrGlobal(StringIndex, E);
3738 }
3739
3740 return this->delegate(E->getFunctionName());
3741}
3742
3743template <class Emitter>
3745 if (E->getSubExpr() && !this->discard(E->getSubExpr()))
3746 return false;
3747
3748 return this->emitInvalid(E);
3749}
3750
3751template <class Emitter>
3753 const CXXReinterpretCastExpr *E) {
3754 const Expr *SubExpr = E->getSubExpr();
3755
3756 OptPrimType FromT = classify(SubExpr);
3757 OptPrimType ToT = classify(E);
3758
3759 if (!FromT || !ToT)
3760 return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, E);
3761
3762 if (FromT == PT_Ptr || ToT == PT_Ptr) {
3763 if (!this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/false, E))
3764 return false;
3765 if (E->getCastKind() == CK_LValueBitCast)
3766 return this->delegate(SubExpr);
3767 return this->VisitCastExpr(E);
3768 }
3769
3770 // Try to actually do the cast.
3771 bool Fatal = (ToT != FromT);
3772 if (!this->emitInvalidCast(CastKind::Reinterpret, Fatal, E))
3773 return false;
3774
3775 return this->VisitCastExpr(E);
3776}
3777
3778template <class Emitter>
3780 if (!Ctx.getLangOpts().CPlusPlus20) {
3781 if (!this->emitInvalidCast(CastKind::Dynamic, /*Fatal=*/false, E))
3782 return false;
3783 }
3784
3785 if (E->getCastKind() != CK_Dynamic)
3786 return this->VisitCastExpr(E);
3787
3788 QualType DestType = E->getType();
3789 // "target type must be a reference or pointer type to a defined class"
3790 if (DestType->isRecordType()) {
3791 assert(E->isGLValue());
3792 } else {
3793 assert(DestType->isPointerOrReferenceType());
3794 assert(DestType->isVoidPointerType() ||
3795 DestType->getPointeeType()->isRecordType());
3796 DestType = DestType->getPointeeType();
3797 }
3798
3799 if (!this->visit(E->getSubExpr()))
3800 return false;
3801 if (!this->emitDynamicCast(DestType.getTypePtr(),
3802 /*IsReferenceCast=*/E->isGLValue(), E))
3803 return false;
3804
3805 if (DiscardResult)
3806 return this->emitPopPtr(E);
3807 return true;
3808}
3809
3810template <class Emitter>
3812 assert(E->getType()->isBooleanType());
3813
3814 if (DiscardResult)
3815 return true;
3816 return this->emitConstBool(E->getValue(), E);
3817}
3818
3819template <class Emitter>
3821 QualType T = E->getType();
3822 assert(!canClassify(T));
3823
3824 if (T->isRecordType()) {
3825 const CXXConstructorDecl *Ctor = E->getConstructor();
3826
3827 // If we're discarding a construct expression, we still need
3828 // to allocate a variable and call the constructor and destructor.
3829 if (DiscardResult) {
3830 if (Ctor->isTrivial())
3831 return true;
3832 assert(!Initializing);
3833 UnsignedOrNone LocalIndex = allocateLocal(E);
3834
3835 if (!LocalIndex)
3836 return false;
3837
3838 if (!this->emitGetPtrLocal(*LocalIndex, E))
3839 return false;
3840 }
3841
3842 // Trivial copy/move constructor. Avoid copy.
3843 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
3844 Ctor->isTrivial() &&
3845 E->getArg(0)->isTemporaryObject(Ctx.getASTContext(),
3846 T->getAsCXXRecordDecl()))
3847 return this->visitInitializer(E->getArg(0));
3848
3849 // Zero initialization.
3850 bool ZeroInit = E->requiresZeroInitialization();
3851 if (ZeroInit) {
3852 const Record *R = getRecord(E->getType());
3853 if (!R)
3854 return false;
3855
3856 if (!this->visitZeroRecordInitializer(R, E))
3857 return false;
3858
3859 // If the constructor is trivial anyway, we're done.
3860 if (Ctor->isTrivial())
3861 return true;
3862 }
3863
3864 // Avoid materializing a temporary for an elidable copy/move constructor.
3865 if (!ZeroInit && E->isElidable()) {
3866 const Expr *SrcObj = E->getArg(0);
3867 assert(SrcObj->isTemporaryObject(Ctx.getASTContext(), Ctor->getParent()));
3868 assert(Ctx.getASTContext().hasSameUnqualifiedType(E->getType(),
3869 SrcObj->getType()));
3870 if (const auto *ME = dyn_cast<MaterializeTemporaryExpr>(SrcObj)) {
3871 if (!this->emitCheckFunctionDecl(Ctor, E))
3872 return false;
3873 return this->visitInitializer(ME->getSubExpr());
3874 }
3875 }
3876
3877 const Function *Func = getFunction(Ctor);
3878
3879 if (!Func)
3880 return false;
3881
3882 assert(Func->hasThisPointer());
3883 assert(!Func->hasRVO());
3884
3885 // The This pointer is already on the stack because this is an initializer,
3886 // but we need to dup() so the call() below has its own copy.
3887 if (!this->emitDupPtr(E))
3888 return false;
3889
3890 // Constructor arguments.
3891 for (const auto *Arg : E->arguments()) {
3892 if (!this->visit(Arg))
3893 return false;
3894 }
3895
3896 if (Func->isVariadic()) {
3897 uint32_t VarArgSize = 0;
3898 unsigned NumParams = Func->getNumWrittenParams();
3899 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) {
3900 VarArgSize +=
3901 align(primSize(classify(E->getArg(I)->getType()).value_or(PT_Ptr)));
3902 }
3903 if (!this->emitCallVar(Func, VarArgSize, E))
3904 return false;
3905 } else {
3906 if (!this->emitCall(Func, 0, E)) {
3907 // When discarding, we don't need the result anyway, so clean up
3908 // the instance dup we did earlier in case surrounding code wants
3909 // to keep evaluating.
3910 if (DiscardResult)
3911 (void)this->emitPopPtr(E);
3912 return false;
3913 }
3914 }
3915
3916 if (DiscardResult)
3917 return this->emitPopPtr(E);
3918 return true;
3919 }
3920
3921 if (T->isArrayType()) {
3922 const Function *Func = getFunction(E->getConstructor());
3923 if (!Func)
3924 return false;
3925
3926 if (!this->emitDupPtr(E))
3927 return false;
3928
3929 std::function<bool(QualType)> initArrayDimension;
3930 initArrayDimension = [&](QualType T) -> bool {
3931 if (!T->isArrayType()) {
3932 // Constructor arguments.
3933 for (const auto *Arg : E->arguments()) {
3934 if (!this->visit(Arg))
3935 return false;
3936 }
3937
3938 return this->emitCall(Func, 0, E);
3939 }
3940
3941 const ConstantArrayType *CAT =
3942 Ctx.getASTContext().getAsConstantArrayType(T);
3943 if (!CAT)
3944 return false;
3945 QualType ElemTy = CAT->getElementType();
3946 unsigned NumElems = CAT->getZExtSize();
3947 for (size_t I = 0; I != NumElems; ++I) {
3948 if (!this->emitConstUint64(I, E))
3949 return false;
3950 if (!this->emitArrayElemPtrUint64(E))
3951 return false;
3952 if (!initArrayDimension(ElemTy))
3953 return false;
3954 }
3955 return this->emitPopPtr(E);
3956 };
3957
3958 return initArrayDimension(E->getType());
3959 }
3960
3961 return false;
3962}
3963
3964template <class Emitter>
3966 if (DiscardResult)
3967 return true;
3968
3969 const APValue Val =
3970 E->EvaluateInContext(Ctx.getASTContext(), SourceLocDefaultExpr);
3971
3972 // Things like __builtin_LINE().
3973 if (E->getType()->isIntegerType()) {
3974 assert(Val.isInt());
3975 const APSInt &I = Val.getInt();
3976 return this->emitConst(I, E);
3977 }
3978 // Otherwise, the APValue is an LValue, with only one element.
3979 // Theoretically, we don't need the APValue at all of course.
3980 assert(E->getType()->isPointerType());
3981 assert(Val.isLValue());
3982 const APValue::LValueBase &Base = Val.getLValueBase();
3983 if (const Expr *LValueExpr = Base.dyn_cast<const Expr *>())
3984 return this->visit(LValueExpr);
3985
3986 // Otherwise, we have a decl (which is the case for
3987 // __builtin_source_location).
3988 assert(Base.is<const ValueDecl *>());
3989 assert(Val.getLValuePath().size() == 0);
3990 const auto *BaseDecl = Base.dyn_cast<const ValueDecl *>();
3991 assert(BaseDecl);
3992
3993 auto *UGCD = cast<UnnamedGlobalConstantDecl>(BaseDecl);
3994
3995 UnsignedOrNone GlobalIndex = P.getOrCreateGlobal(UGCD);
3996 if (!GlobalIndex)
3997 return false;
3998
3999 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
4000 return false;
4001
4002 const Record *R = getRecord(E->getType());
4003 const APValue &V = UGCD->getValue();
4004 for (unsigned I = 0, N = R->getNumFields(); I != N; ++I) {
4005 const Record::Field *F = R->getField(I);
4006 const APValue &FieldValue = V.getStructField(I);
4007
4008 PrimType FieldT = classifyPrim(F->Decl->getType());
4009
4010 if (!this->visitAPValue(FieldValue, FieldT, E))
4011 return false;
4012 if (!this->emitInitField(FieldT, F->Offset, E))
4013 return false;
4014 }
4015
4016 // Leave the pointer to the global on the stack.
4017 return true;
4018}
4019
4020template <class Emitter>
4022 unsigned N = E->getNumComponents();
4023 if (N == 0)
4024 return false;
4025
4026 for (unsigned I = 0; I != N; ++I) {
4027 const OffsetOfNode &Node = E->getComponent(I);
4028 if (Node.getKind() == OffsetOfNode::Array) {
4029 const Expr *ArrayIndexExpr = E->getIndexExpr(Node.getArrayExprIndex());
4030 PrimType IndexT = classifyPrim(ArrayIndexExpr->getType());
4031
4032 if (DiscardResult) {
4033 if (!this->discard(ArrayIndexExpr))
4034 return false;
4035 continue;
4036 }
4037
4038 if (IndexT == PT_IntAP || IndexT == PT_IntAPS) {
4039 if (!this->visit(ArrayIndexExpr))
4040 return false;
4041 if (!this->emitCastNoOverflow(IndexT, E))
4042 return false;
4043 continue;
4044 }
4045 if (!this->visit(ArrayIndexExpr))
4046 return false;
4047 // Cast to Sint64.
4048 if (IndexT != PT_Sint64) {
4049 if (!this->emitCast(IndexT, PT_Sint64, E))
4050 return false;
4051 }
4052 }
4053 }
4054
4055 if (DiscardResult)
4056 return true;
4057
4059 return this->emitOffsetOf(T, E, E);
4060}
4061
4062template <class Emitter>
4064 const CXXScalarValueInitExpr *E) {
4065 QualType Ty = E->getType();
4066
4067 if (DiscardResult || Ty->isVoidType())
4068 return true;
4069
4070 if (OptPrimType T = classify(Ty))
4071 return this->visitZeroInitializer(*T, Ty, E);
4072
4073 if (Ty->isAnyComplexType() || Ty->isVectorType()) {
4074 if (!Initializing) {
4075 UnsignedOrNone LocalIndex = allocateLocal(E);
4076 if (!LocalIndex)
4077 return false;
4078 if (!this->emitGetPtrLocal(*LocalIndex, E))
4079 return false;
4080 }
4081
4082 QualType ElemQT;
4083 unsigned NumElems;
4084 if (const auto *CT = Ty->getAs<ComplexType>()) {
4085 NumElems = 2;
4086 ElemQT = CT->getElementType();
4087 } else {
4088 const auto *VT = Ty->castAs<VectorType>();
4089 NumElems = VT->getNumElements();
4090 ElemQT = VT->getElementType();
4091 }
4092
4093 PrimType ElemT = classifyPrim(ElemQT);
4094
4095 // Initialize all fields to 0.
4096 for (unsigned I = 0; I != NumElems; ++I) {
4097 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
4098 return false;
4099 if (!this->emitInitElem(ElemT, I, E))
4100 return false;
4101 }
4102 return true;
4103 }
4104
4105 return false;
4106}
4107
4108template <class Emitter>
4110 return this->emitConst(E->getPackLength(), E);
4111}
4112
4113template <class Emitter>
4118
4119template <class Emitter>
4121 return this->delegate(E->getChosenSubExpr());
4122}
4123
4124template <class Emitter>
4126 if (DiscardResult)
4127 return true;
4128
4129 return this->emitConst(E->getValue(), E);
4130}
4131
4132template <class Emitter>
4134 const CXXInheritedCtorInitExpr *E) {
4135 const CXXConstructorDecl *Ctor = E->getConstructor();
4136 assert(!Ctor->isTrivial() &&
4137 "Trivial CXXInheritedCtorInitExpr, implement. (possible?)");
4138 const Function *F = this->getFunction(Ctor);
4139 if (!F)
4140 return false;
4141 assert(!F->hasRVO());
4142 assert(F->hasThisPointer());
4143
4144 if (!this->emitDupPtr(SourceInfo{}))
4145 return false;
4146
4147 // Forward all arguments of the current function (which should be a
4148 // constructor itself) to the inherited ctor.
4149 // This is necessary because the calling code has pushed the pointer
4150 // of the correct base for us already, but the arguments need
4151 // to come after.
4152 unsigned ParamIndex = 0;
4153 for (const ParmVarDecl *PD : Ctor->parameters()) {
4154 PrimType PT = this->classify(PD->getType()).value_or(PT_Ptr);
4155
4156 if (!this->emitGetParam(PT, ParamIndex, E))
4157 return false;
4158 ++ParamIndex;
4159 }
4160
4161 return this->emitCall(F, 0, E);
4162}
4163
4164// FIXME: This function has become rather unwieldy, especially
4165// the part where we initialize an array allocation of dynamic size.
4166template <class Emitter>
4168 assert(classifyPrim(E->getType()) == PT_Ptr);
4169 const Expr *Init = E->getInitializer();
4170 QualType ElementType = E->getAllocatedType();
4171 OptPrimType ElemT = classify(ElementType);
4172 unsigned PlacementArgs = E->getNumPlacementArgs();
4173 const FunctionDecl *OperatorNew = E->getOperatorNew();
4174 const Expr *PlacementDest = nullptr;
4175 bool IsNoThrow = false;
4176
4177 if (E->containsErrors())
4178 return false;
4179
4180 if (PlacementArgs != 0) {
4181 // FIXME: There is no restriction on this, but it's not clear that any
4182 // other form makes any sense. We get here for cases such as:
4183 //
4184 // new (std::align_val_t{N}) X(int)
4185 //
4186 // (which should presumably be valid only if N is a multiple of
4187 // alignof(int), and in any case can't be deallocated unless N is
4188 // alignof(X) and X has new-extended alignment).
4189 if (PlacementArgs == 1) {
4190 const Expr *Arg1 = E->getPlacementArg(0);
4191 if (Arg1->getType()->isNothrowT()) {
4192 if (!this->discard(Arg1))
4193 return false;
4194 IsNoThrow = true;
4195 } else {
4196 // Invalid unless we have C++26 or are in a std:: function.
4197 if (!this->emitInvalidNewDeleteExpr(E, E))
4198 return false;
4199
4200 // If we have a placement-new destination, we'll later use that instead
4201 // of allocating.
4202 if (OperatorNew->isReservedGlobalPlacementOperator())
4203 PlacementDest = Arg1;
4204 }
4205 } else {
4206 // Always invalid.
4207 return this->emitInvalid(E);
4208 }
4209 } else if (!OperatorNew
4210 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
4211 return this->emitInvalidNewDeleteExpr(E, E);
4212
4213 const Descriptor *Desc;
4214 if (!PlacementDest) {
4215 if (ElemT) {
4216 if (E->isArray())
4217 Desc = nullptr; // We're not going to use it in this case.
4218 else
4219 Desc = P.createDescriptor(E, *ElemT, /*SourceTy=*/nullptr,
4221 } else {
4222 Desc = P.createDescriptor(
4223 E, ElementType.getTypePtr(),
4224 E->isArray() ? std::nullopt : Descriptor::InlineDescMD,
4225 /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false,
4226 /*IsVolatile=*/false, Init);
4227 }
4228 }
4229
4230 if (E->isArray()) {
4231 std::optional<const Expr *> ArraySizeExpr = E->getArraySize();
4232 if (!ArraySizeExpr)
4233 return false;
4234
4235 const Expr *Stripped = *ArraySizeExpr;
4236 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
4237 Stripped = ICE->getSubExpr())
4238 if (ICE->getCastKind() != CK_NoOp &&
4239 ICE->getCastKind() != CK_IntegralCast)
4240 break;
4241
4242 PrimType SizeT = classifyPrim(Stripped->getType());
4243
4244 // Save evaluated array size to a variable.
4245 unsigned ArrayLen =
4246 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
4247 if (!this->visit(Stripped))
4248 return false;
4249 if (!this->emitSetLocal(SizeT, ArrayLen, E))
4250 return false;
4251
4252 if (PlacementDest) {
4253 if (!this->visit(PlacementDest))
4254 return false;
4255 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4256 return false;
4257 if (!this->emitCheckNewTypeMismatchArray(SizeT, E, E))
4258 return false;
4259 } else {
4260 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4261 return false;
4262
4263 if (ElemT) {
4264 // N primitive elements.
4265 if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E))
4266 return false;
4267 } else {
4268 // N Composite elements.
4269 if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E))
4270 return false;
4271 }
4272 }
4273
4274 if (Init) {
4275 QualType InitType = Init->getType();
4276 size_t StaticInitElems = 0;
4277 const Expr *DynamicInit = nullptr;
4278 OptPrimType ElemT;
4279
4280 if (const ConstantArrayType *CAT =
4281 Ctx.getASTContext().getAsConstantArrayType(InitType)) {
4282 StaticInitElems = CAT->getZExtSize();
4283 // Initialize the first S element from the initializer.
4284 if (!this->visitInitializer(Init))
4285 return false;
4286
4287 if (const auto *ILE = dyn_cast<InitListExpr>(Init)) {
4288 if (ILE->hasArrayFiller())
4289 DynamicInit = ILE->getArrayFiller();
4290 else if (StaticInitElems > 0 && isa<StringLiteral>(ILE->getInit(0)))
4291 ElemT = classifyPrim(CAT->getElementType());
4292 }
4293 }
4294
4295 // The initializer initializes a certain number of elements, S.
4296 // However, the complete number of elements, N, might be larger than that.
4297 // In this case, we need to get an initializer for the remaining elements.
4298 // There are three cases:
4299 // 1) For the form 'new Struct[n];', the initializer is a
4300 // CXXConstructExpr and its type is an IncompleteArrayType.
4301 // 2) For the form 'new Struct[n]{1,2,3}', the initializer is an
4302 // InitListExpr and the initializer for the remaining elements
4303 // is the array filler.
4304 // 3) StringLiterals don't have an array filler, so we need to zero
4305 // the remaining elements.
4306
4307 if (DynamicInit || ElemT || InitType->isIncompleteArrayType()) {
4308 const Function *CtorFunc = nullptr;
4309 if (const auto *CE = dyn_cast<CXXConstructExpr>(Init)) {
4310 CtorFunc = getFunction(CE->getConstructor());
4311 if (!CtorFunc)
4312 return false;
4313 } else if (!DynamicInit && !ElemT)
4314 DynamicInit = Init;
4315
4316 LabelTy EndLabel = this->getLabel();
4317 LabelTy StartLabel = this->getLabel();
4318
4319 // In the nothrow case, the alloc above might have returned nullptr.
4320 // Don't call any constructors that case.
4321 if (IsNoThrow) {
4322 if (!this->emitDupPtr(E))
4323 return false;
4324 if (!this->emitNullPtr(0, nullptr, E))
4325 return false;
4326 if (!this->emitEQPtr(E))
4327 return false;
4328 if (!this->jumpTrue(EndLabel, E))
4329 return false;
4330 }
4331
4332 // Create loop variables.
4333 unsigned Iter =
4334 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
4335 if (!this->emitConst(StaticInitElems, SizeT, E))
4336 return false;
4337 if (!this->emitSetLocal(SizeT, Iter, E))
4338 return false;
4339
4340 this->fallthrough(StartLabel);
4341 this->emitLabel(StartLabel);
4342 // Condition. Iter < ArrayLen?
4343 if (!this->emitGetLocal(SizeT, Iter, E))
4344 return false;
4345 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4346 return false;
4347 if (!this->emitLT(SizeT, E))
4348 return false;
4349 if (!this->jumpFalse(EndLabel, E))
4350 return false;
4351
4352 // Pointer to the allocated array is already on the stack.
4353 if (!this->emitGetLocal(SizeT, Iter, E))
4354 return false;
4355 if (!this->emitArrayElemPtr(SizeT, E))
4356 return false;
4357
4358 if (isa_and_nonnull<ImplicitValueInitExpr>(DynamicInit) &&
4359 DynamicInit->getType()->isArrayType()) {
4360 QualType ElemType =
4361 DynamicInit->getType()->getAsArrayTypeUnsafe()->getElementType();
4362 if (OptPrimType InitT = classify(ElemType)) {
4363 if (!this->visitZeroInitializer(*InitT, ElemType, E))
4364 return false;
4365 if (!this->emitStorePop(*InitT, E))
4366 return false;
4367 } else {
4368 assert(ElemType->isArrayType());
4369 if (!this->visitZeroArrayInitializer(ElemType, E))
4370 return false;
4371 }
4372 } else if (DynamicInit) {
4373 if (OptPrimType InitT = classify(DynamicInit)) {
4374 if (!this->visit(DynamicInit))
4375 return false;
4376 if (!this->emitStorePop(*InitT, E))
4377 return false;
4378 } else {
4379 if (!this->visitInitializerPop(DynamicInit))
4380 return false;
4381 }
4382 } else if (ElemT) {
4383 if (!this->visitZeroInitializer(
4384 *ElemT, InitType->getAsArrayTypeUnsafe()->getElementType(),
4385 Init))
4386 return false;
4387 if (!this->emitStorePop(*ElemT, E))
4388 return false;
4389 } else {
4390 assert(CtorFunc);
4391 if (!this->emitCall(CtorFunc, 0, E))
4392 return false;
4393 }
4394
4395 // ++Iter;
4396 if (!this->emitGetPtrLocal(Iter, E))
4397 return false;
4398 if (!this->emitIncPop(SizeT, false, E))
4399 return false;
4400
4401 if (!this->jump(StartLabel, E))
4402 return false;
4403
4404 this->fallthrough(EndLabel);
4405 this->emitLabel(EndLabel);
4406 }
4407 }
4408 } else { // Non-array.
4409 if (PlacementDest) {
4410 if (!this->visit(PlacementDest))
4411 return false;
4412 if (!this->emitCheckNewTypeMismatch(E, E))
4413 return false;
4414
4415 } else {
4416 // Allocate just one element.
4417 if (!this->emitAlloc(Desc, E))
4418 return false;
4419 }
4420
4421 if (Init) {
4422 if (ElemT) {
4423 if (!this->visit(Init))
4424 return false;
4425
4426 if (!this->emitInit(*ElemT, E))
4427 return false;
4428 } else {
4429 // Composite.
4430 if (!this->visitInitializer(Init))
4431 return false;
4432 }
4433 }
4434 }
4435
4436 if (DiscardResult)
4437 return this->emitPopPtr(E);
4438
4439 return true;
4440}
4441
4442template <class Emitter>
4444 if (E->containsErrors())
4445 return false;
4446 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
4447
4448 if (!OperatorDelete->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
4449 return this->emitInvalidNewDeleteExpr(E, E);
4450
4451 // Arg must be an lvalue.
4452 if (!this->visit(E->getArgument()))
4453 return false;
4454
4455 return this->emitFree(E->isArrayForm(), E->isGlobalDelete(), E);
4456}
4457
4458template <class Emitter>
4460 if (DiscardResult)
4461 return true;
4462
4463 const Function *Func = nullptr;
4464 if (const Function *F = Ctx.getOrCreateObjCBlock(E))
4465 Func = F;
4466
4467 if (!Func)
4468 return false;
4469 return this->emitGetFnPtr(Func, E);
4470}
4471
4472template <class Emitter>
4474 const Type *TypeInfoType = E->getType().getTypePtr();
4475
4476 auto canonType = [](const Type *T) {
4477 return T->getCanonicalTypeUnqualified().getTypePtr();
4478 };
4479
4480 if (!E->isPotentiallyEvaluated()) {
4481 if (DiscardResult)
4482 return true;
4483
4484 if (E->isTypeOperand())
4485 return this->emitGetTypeid(
4486 canonType(E->getTypeOperand(Ctx.getASTContext()).getTypePtr()),
4487 TypeInfoType, E);
4488
4489 return this->emitGetTypeid(
4490 canonType(E->getExprOperand()->getType().getTypePtr()), TypeInfoType,
4491 E);
4492 }
4493
4494 // Otherwise, we need to evaluate the expression operand.
4495 assert(E->getExprOperand());
4496 assert(E->getExprOperand()->isLValue());
4497
4498 if (!Ctx.getLangOpts().CPlusPlus20 && !this->emitDiagTypeid(E))
4499 return false;
4500
4501 if (!this->visit(E->getExprOperand()))
4502 return false;
4503
4504 if (!this->emitGetTypeidPtr(TypeInfoType, E))
4505 return false;
4506 if (DiscardResult)
4507 return this->emitPopPtr(E);
4508 return true;
4509}
4510
4511template <class Emitter>
4513 const ObjCDictionaryLiteral *E) {
4515 return this->emitDummyPtr(E, E);
4516 return this->emitError(E);
4517}
4518
4519template <class Emitter>
4522 return this->emitDummyPtr(E, E);
4523 return this->emitError(E);
4524}
4525
4526template <class Emitter>
4528 assert(Ctx.getLangOpts().CPlusPlus);
4529 return this->emitConstBool(E->getValue(), E);
4530}
4531
4532template <class Emitter>
4534 if (DiscardResult)
4535 return true;
4536 assert(!Initializing);
4537
4538 const MSGuidDecl *GuidDecl = E->getGuidDecl();
4539 const RecordDecl *RD = GuidDecl->getType()->getAsRecordDecl();
4540 assert(RD);
4541 // If the definiton of the result type is incomplete, just return a dummy.
4542 // If (and when) that is read from, we will fail, but not now.
4543 if (!RD->isCompleteDefinition())
4544 return this->emitDummyPtr(GuidDecl, E);
4545
4546 UnsignedOrNone GlobalIndex = P.getOrCreateGlobal(GuidDecl);
4547 if (!GlobalIndex)
4548 return false;
4549 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
4550 return false;
4551
4552 assert(this->getRecord(E->getType()));
4553
4554 const APValue &V = GuidDecl->getAsAPValue();
4555 if (V.getKind() == APValue::None)
4556 return true;
4557
4558 assert(V.isStruct());
4559 assert(V.getStructNumBases() == 0);
4560 if (!this->visitAPValueInitializer(V, E, E->getType()))
4561 return false;
4562
4563 return this->emitFinishInit(E);
4564}
4565
4566template <class Emitter>
4568 assert(classifyPrim(E->getType()) == PT_Bool);
4569 if (E->isValueDependent())
4570 return false;
4571 if (DiscardResult)
4572 return true;
4573 return this->emitConstBool(E->isSatisfied(), E);
4574}
4575
4576template <class Emitter>
4578 const ConceptSpecializationExpr *E) {
4579 assert(classifyPrim(E->getType()) == PT_Bool);
4580 if (DiscardResult)
4581 return true;
4582 return this->emitConstBool(E->isSatisfied(), E);
4583}
4584
4585template <class Emitter>
4590
4591template <class Emitter>
4593
4594 for (const Expr *SemE : E->semantics()) {
4595 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
4596 if (SemE == E->getResultExpr())
4597 return false;
4598
4599 if (OVE->isUnique())
4600 continue;
4601
4602 if (!this->discard(OVE))
4603 return false;
4604 } else if (SemE == E->getResultExpr()) {
4605 if (!this->delegate(SemE))
4606 return false;
4607 } else {
4608 if (!this->discard(SemE))
4609 return false;
4610 }
4611 }
4612 return true;
4613}
4614
4615template <class Emitter>
4619
4620template <class Emitter>
4622 return this->emitError(E);
4623}
4624
4625template <class Emitter>
4627 assert(E->getType()->isVoidPointerType());
4628 if (DiscardResult)
4629 return true;
4630
4631 return this->emitDummyPtr(E, E);
4632}
4633
4634template <class Emitter>
4635bool Compiler<Emitter>::emitVectorConversion(const Expr *Src, const Expr *E) {
4636 if (Src->containsErrors())
4637 return false;
4638
4639 const auto *VT = E->getType()->castAs<VectorType>();
4640 QualType ElemType = VT->getElementType();
4641 PrimType ElemT = classifyPrim(ElemType);
4642 QualType SrcType = Src->getType();
4643 PrimType SrcElemT = classifyVectorElementType(SrcType);
4644
4645 if (!Initializing) {
4646 UnsignedOrNone LocalIndex = allocateLocal(E);
4647 if (!LocalIndex)
4648 return false;
4649 if (!this->emitGetPtrLocal(*LocalIndex, E))
4650 return false;
4651 }
4652
4653 unsigned SrcOffset =
4654 this->allocateLocalPrimitive(Src, PT_Ptr, /*IsConst=*/true);
4655 if (!this->visit(Src))
4656 return false;
4657 if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
4658 return false;
4659
4660 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
4661 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
4662 return false;
4663 if (!this->emitArrayElemPop(SrcElemT, I, E))
4664 return false;
4665
4666 // Cast to the desired result element type.
4667 if (SrcElemT != ElemT) {
4668 if (!this->emitPrimCast(SrcElemT, ElemT, ElemType, E))
4669 return false;
4670 } else if (ElemType->isFloatingType() && SrcType != ElemType) {
4671 const auto *TargetSemantics = &Ctx.getFloatSemantics(ElemType);
4672 if (!this->emitCastFP(TargetSemantics, getRoundingMode(E), E))
4673 return false;
4674 }
4675 if (!this->emitInitElem(ElemT, I, E))
4676 return false;
4677 }
4678 return true;
4679}
4680
4681template <class Emitter>
4683 return emitVectorConversion(E->getSrcExpr(), E);
4684}
4685
4686template <class Emitter>
4688 // FIXME: Unary shuffle with mask not currently supported.
4689 if (E->getNumSubExprs() == 2)
4690 return this->emitInvalid(E);
4691
4692 assert(E->getNumSubExprs() > 2);
4693
4694 const Expr *Vecs[] = {E->getExpr(0), E->getExpr(1)};
4695 const VectorType *VT = Vecs[0]->getType()->castAs<VectorType>();
4696 PrimType ElemT = classifyPrim(VT->getElementType());
4697 unsigned NumInputElems = VT->getNumElements();
4698 unsigned NumOutputElems = E->getNumSubExprs() - 2;
4699 assert(NumOutputElems > 0);
4700
4701 if (!Initializing) {
4702 UnsignedOrNone LocalIndex = allocateLocal(E);
4703 if (!LocalIndex)
4704 return false;
4705 if (!this->emitGetPtrLocal(*LocalIndex, E))
4706 return false;
4707 }
4708
4709 // Save both input vectors to a local variable.
4710 unsigned VectorOffsets[2];
4711 for (unsigned I = 0; I != 2; ++I) {
4712 VectorOffsets[I] =
4713 this->allocateLocalPrimitive(Vecs[I], PT_Ptr, /*IsConst=*/true);
4714 if (!this->visit(Vecs[I]))
4715 return false;
4716 if (!this->emitSetLocal(PT_Ptr, VectorOffsets[I], E))
4717 return false;
4718 }
4719 for (unsigned I = 0; I != NumOutputElems; ++I) {
4720 APSInt ShuffleIndex = E->getShuffleMaskIdx(I);
4721 assert(ShuffleIndex >= -1);
4722 if (ShuffleIndex == -1)
4723 return this->emitInvalidShuffleVectorIndex(I, E);
4724
4725 assert(ShuffleIndex < (NumInputElems * 2));
4726 if (!this->emitGetLocal(PT_Ptr,
4727 VectorOffsets[ShuffleIndex >= NumInputElems], E))
4728 return false;
4729 unsigned InputVectorIndex = ShuffleIndex.getZExtValue() % NumInputElems;
4730 if (!this->emitArrayElemPop(ElemT, InputVectorIndex, E))
4731 return false;
4732
4733 if (!this->emitInitElem(ElemT, I, E))
4734 return false;
4735 }
4736
4737 if (DiscardResult)
4738 return this->emitPopPtr(E);
4739
4740 return true;
4741}
4742
4743template <class Emitter>
4745 const ExtVectorElementExpr *E) {
4746 const Expr *Base = E->getBase();
4747 assert(
4748 Base->getType()->isVectorType() ||
4749 Base->getType()->getAs<PointerType>()->getPointeeType()->isVectorType());
4750
4752 E->getEncodedElementAccess(Indices);
4753
4754 if (Indices.size() == 1) {
4755 if (!this->visit(Base))
4756 return false;
4757
4758 if (E->isGLValue()) {
4759 if (!this->emitConstUint32(Indices[0], E))
4760 return false;
4761 return this->emitArrayElemPtrPop(PT_Uint32, E);
4762 }
4763 // Else, also load the value.
4764 return this->emitArrayElemPop(classifyPrim(E->getType()), Indices[0], E);
4765 }
4766
4767 // Create a local variable for the base.
4768 unsigned BaseOffset = allocateLocalPrimitive(Base, PT_Ptr, /*IsConst=*/true);
4769 if (!this->visit(Base))
4770 return false;
4771 if (!this->emitSetLocal(PT_Ptr, BaseOffset, E))
4772 return false;
4773
4774 // Now the vector variable for the return value.
4775 if (!Initializing) {
4776 UnsignedOrNone ResultIndex = allocateLocal(E);
4777 if (!ResultIndex)
4778 return false;
4779 if (!this->emitGetPtrLocal(*ResultIndex, E))
4780 return false;
4781 }
4782
4783 assert(Indices.size() == E->getType()->getAs<VectorType>()->getNumElements());
4784
4785 PrimType ElemT =
4787 uint32_t DstIndex = 0;
4788 for (uint32_t I : Indices) {
4789 if (!this->emitGetLocal(PT_Ptr, BaseOffset, E))
4790 return false;
4791 if (!this->emitArrayElemPop(ElemT, I, E))
4792 return false;
4793 if (!this->emitInitElem(ElemT, DstIndex, E))
4794 return false;
4795 ++DstIndex;
4796 }
4797
4798 // Leave the result pointer on the stack.
4799 assert(!DiscardResult);
4800 return true;
4801}
4802
4803template <class Emitter>
4805 const Expr *SubExpr = E->getSubExpr();
4807 return this->discard(SubExpr) && this->emitInvalid(E);
4808
4809 if (DiscardResult)
4810 return true;
4811
4812 assert(classifyPrim(E) == PT_Ptr);
4813 return this->emitDummyPtr(E, E);
4814}
4815
4816template <class Emitter>
4818 const CXXStdInitializerListExpr *E) {
4819 const Expr *SubExpr = E->getSubExpr();
4821 Ctx.getASTContext().getAsConstantArrayType(SubExpr->getType());
4822 const Record *R = getRecord(E->getType());
4823 assert(Initializing);
4824 assert(SubExpr->isGLValue());
4825
4826 if (!this->visit(SubExpr))
4827 return false;
4828 if (!this->emitConstUint8(0, E))
4829 return false;
4830 if (!this->emitArrayElemPtrPopUint8(E))
4831 return false;
4832 if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E))
4833 return false;
4834
4835 PrimType SecondFieldT = classifyPrim(R->getField(1u)->Decl->getType());
4836 if (isIntegerOrBoolType(SecondFieldT)) {
4837 if (!this->emitConst(ArrayType->getSize(), SecondFieldT, E))
4838 return false;
4839 return this->emitInitField(SecondFieldT, R->getField(1u)->Offset, E);
4840 }
4841 assert(SecondFieldT == PT_Ptr);
4842
4843 if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E))
4844 return false;
4845 if (!this->emitExpandPtr(E))
4846 return false;
4847 if (!this->emitConst(ArrayType->getSize(), PT_Uint64, E))
4848 return false;
4849 if (!this->emitArrayElemPtrPop(PT_Uint64, E))
4850 return false;
4851 return this->emitInitFieldPtr(R->getField(1u)->Offset, E);
4852}
4853
4854template <class Emitter>
4856 LocalScope<Emitter> BS(this);
4857 llvm::SaveAndRestore StmtExprSAR(this->InStmtExpr, true);
4858
4859 const CompoundStmt *CS = E->getSubStmt();
4860 const Stmt *Result = CS->body_back();
4861 for (const Stmt *S : CS->body()) {
4862 if (S != Result) {
4863 if (!this->visitStmt(S))
4864 return false;
4865 continue;
4866 }
4867
4868 assert(S == Result);
4869 if (const Expr *ResultExpr = dyn_cast<Expr>(S))
4870 return this->delegate(ResultExpr);
4871 if (!this->visitStmt(S))
4872 return false;
4873 return this->emitUnsupported(E);
4874 }
4875
4876 return BS.destroyLocals();
4877}
4878
4879template <class Emitter> bool Compiler<Emitter>::discard(const Expr *E) {
4880 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true,
4881 /*NewInitializing=*/false, /*ToLValue=*/false);
4882 return this->Visit(E);
4883}
4884
4885template <class Emitter> bool Compiler<Emitter>::delegate(const Expr *E) {
4886 // We're basically doing:
4887 // OptionScope<Emitter> Scope(this, DicardResult, Initializing, ToLValue);
4888 // but that's unnecessary of course.
4889 return this->Visit(E);
4890}
4891
4893 if (const auto *PE = dyn_cast<ParenExpr>(E))
4894 return stripCheckedDerivedToBaseCasts(PE->getSubExpr());
4895
4896 if (const auto *CE = dyn_cast<CastExpr>(E);
4897 CE &&
4898 (CE->getCastKind() == CK_DerivedToBase || CE->getCastKind() == CK_NoOp))
4899 return stripCheckedDerivedToBaseCasts(CE->getSubExpr());
4900
4901 return E;
4902}
4903
4904static const Expr *stripDerivedToBaseCasts(const Expr *E) {
4905 if (const auto *PE = dyn_cast<ParenExpr>(E))
4906 return stripDerivedToBaseCasts(PE->getSubExpr());
4907
4908 if (const auto *CE = dyn_cast<CastExpr>(E);
4909 CE && (CE->getCastKind() == CK_DerivedToBase ||
4910 CE->getCastKind() == CK_UncheckedDerivedToBase ||
4911 CE->getCastKind() == CK_NoOp))
4912 return stripDerivedToBaseCasts(CE->getSubExpr());
4913
4914 return E;
4915}
4916
4917template <class Emitter> bool Compiler<Emitter>::visit(const Expr *E) {
4918 if (E->getType().isNull())
4919 return false;
4920
4921 if (E->getType()->isVoidType())
4922 return this->discard(E);
4923
4924 // Create local variable to hold the return value.
4925 if (!E->isGLValue() && !canClassify(E->getType())) {
4926 UnsignedOrNone LocalIndex = allocateLocal(
4928 if (!LocalIndex)
4929 return false;
4930
4931 if (!this->emitGetPtrLocal(*LocalIndex, E))
4932 return false;
4933 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
4934 return this->visitInitializer(E);
4935 }
4936
4937 // Otherwise,we have a primitive return value, produce the value directly
4938 // and push it on the stack.
4939 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4940 /*NewInitializing=*/false, /*ToLValue=*/ToLValue);
4941 return this->Visit(E);
4942}
4943
4944template <class Emitter>
4946 assert(!canClassify(E->getType()));
4947
4948 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4949 /*NewInitializing=*/true, /*ToLValue=*/false);
4950 return this->Visit(E) && this->emitFinishInit(E);
4951}
4952
4953template <class Emitter>
4955 assert(!canClassify(E->getType()));
4956
4957 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4958 /*NewInitializing=*/true, /*ToLValue=*/false);
4959 return this->Visit(E) && this->emitFinishInitPop(E);
4960}
4961
4962template <class Emitter> bool Compiler<Emitter>::visitAsLValue(const Expr *E) {
4963 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4964 /*NewInitializing=*/false, /*ToLValue=*/true);
4965 return this->Visit(E);
4966}
4967
4968template <class Emitter> bool Compiler<Emitter>::visitBool(const Expr *E) {
4969 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4970 /*NewInitializing=*/false, /*ToLValue=*/ToLValue);
4971
4972 OptPrimType T = classify(E->getType());
4973 if (!T) {
4974 // Convert complex values to bool.
4975 if (E->getType()->isAnyComplexType()) {
4976 if (!this->visit(E))
4977 return false;
4978 return this->emitComplexBoolCast(E);
4979 }
4980 return false;
4981 }
4982
4983 if (!this->visit(E))
4984 return false;
4985
4986 if (T == PT_Bool)
4987 return true;
4988
4989 // Convert pointers to bool.
4990 if (T == PT_Ptr)
4991 return this->emitIsNonNullPtr(E);
4992
4993 // Or Floats.
4994 if (T == PT_Float)
4995 return this->emitCastFloatingIntegralBool(getFPOptions(E), E);
4996
4997 // Or anything else we can.
4998 return this->emitCast(*T, PT_Bool, E);
4999}
5000
5001template <class Emitter>
5002bool Compiler<Emitter>::visitZeroInitializer(PrimType T, QualType QT,
5003 const Expr *E) {
5004 if (const auto *AT = QT->getAs<AtomicType>())
5005 QT = AT->getValueType();
5006
5007 switch (T) {
5008 case PT_Bool:
5009 return this->emitZeroBool(E);
5010 case PT_Sint8:
5011 return this->emitZeroSint8(E);
5012 case PT_Uint8:
5013 return this->emitZeroUint8(E);
5014 case PT_Sint16:
5015 return this->emitZeroSint16(E);
5016 case PT_Uint16:
5017 return this->emitZeroUint16(E);
5018 case PT_Sint32:
5019 return this->emitZeroSint32(E);
5020 case PT_Uint32:
5021 return this->emitZeroUint32(E);
5022 case PT_Sint64:
5023 return this->emitZeroSint64(E);
5024 case PT_Uint64:
5025 return this->emitZeroUint64(E);
5026 case PT_IntAP:
5027 return this->emitZeroIntAP(Ctx.getBitWidth(QT), E);
5028 case PT_IntAPS:
5029 return this->emitZeroIntAPS(Ctx.getBitWidth(QT), E);
5030 case PT_Ptr:
5031 return this->emitNullPtr(Ctx.getASTContext().getTargetNullPointerValue(QT),
5032 nullptr, E);
5033 case PT_MemberPtr:
5034 return this->emitNullMemberPtr(0, nullptr, E);
5035 case PT_Float: {
5036 APFloat F = APFloat::getZero(Ctx.getFloatSemantics(QT));
5037 return this->emitFloat(F, E);
5038 }
5039 case PT_FixedPoint: {
5040 auto Sem = Ctx.getASTContext().getFixedPointSemantics(QT);
5041 return this->emitConstFixedPoint(FixedPoint::zero(Sem), E);
5042 }
5043 }
5044 llvm_unreachable("unknown primitive type");
5045}
5046
5047template <class Emitter>
5048bool Compiler<Emitter>::visitZeroRecordInitializer(const Record *R,
5049 const Expr *E,
5050 bool IsCompleteClass) {
5051 assert(E);
5052 assert(R);
5053 // Fields
5054 for (const Record::Field &Field : R->fields()) {
5055 if (Field.isUnnamedBitField())
5056 continue;
5057
5058 const Descriptor *D = Field.Desc;
5059 if (D->isPrimitive()) {
5060 QualType QT = D->getType();
5061 PrimType T = D->getPrimType();
5062 if (!this->visitZeroInitializer(T, QT, E))
5063 return false;
5064 if (R->isUnion()) {
5065 if (!this->emitInitFieldActivate(T, Field.Offset, E))
5066 return false;
5067 break;
5068 }
5069 if (!this->emitInitField(T, Field.Offset, E))
5070 return false;
5071 continue;
5072 }
5073
5074 if (!this->emitGetPtrField(Field.Offset, E))
5075 return false;
5076
5077 if (D->isPrimitiveArray()) {
5078 QualType ET = D->getElemQualType();
5079 PrimType T = D->getPrimType();
5080 for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
5081 if (!this->visitZeroInitializer(T, ET, E))
5082 return false;
5083 if (!this->emitInitElem(T, I, E))
5084 return false;
5085 }
5086 } else if (D->isCompositeArray()) {
5087 // Can't be a vector or complex field.
5088 if (!this->visitZeroArrayInitializer(D->getType(), E))
5089 return false;
5090 } else if (D->isRecord()) {
5091 if (!this->visitZeroRecordInitializer(D->ElemRecord, E))
5092 return false;
5093 } else
5094 return false;
5095
5096 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
5097 // object's first non-static named data member is zero-initialized
5098 if (R->isUnion()) {
5099 if (!this->emitFinishInitActivatePop(E))
5100 return false;
5101 break;
5102 }
5103 if (!this->emitFinishInitPop(E))
5104 return false;
5105 }
5106
5107 for (const Record::Base &B : R->bases()) {
5108 if (!this->emitGetPtrBase(B.Offset, E))
5109 return false;
5110 if (!this->visitZeroRecordInitializer(B.R, E, /*IsCompleteClass=*/false))
5111 return false;
5112 if (!this->emitFinishInitPop(E))
5113 return false;
5114 }
5115
5116 if (IsCompleteClass) {
5117 for (const Record::Base &B : R->virtual_bases()) {
5118 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(B.R->getDecl()), E))
5119 return false;
5120 if (!this->visitZeroRecordInitializer(B.R, E, /*IsCompleteClass=*/false))
5121 return false;
5122 if (!this->emitFinishInitPop(E))
5123 return false;
5124 }
5125 }
5126
5127 return true;
5128}
5129
5130template <class Emitter>
5131bool Compiler<Emitter>::visitZeroArrayInitializer(QualType T, const Expr *E) {
5132 assert(T->isArrayType() || T->isAnyComplexType() || T->isVectorType());
5133 const ArrayType *AT = T->getAsArrayTypeUnsafe();
5134 QualType ElemType = AT->getElementType();
5135 size_t NumElems = cast<ConstantArrayType>(AT)->getZExtSize();
5136
5137 if (OptPrimType ElemT = classify(ElemType)) {
5138 for (size_t I = 0; I != NumElems; ++I) {
5139 if (!this->visitZeroInitializer(*ElemT, ElemType, E))
5140 return false;
5141 if (!this->emitInitElem(*ElemT, I, E))
5142 return false;
5143 }
5144 return true;
5145 }
5146 if (ElemType->isRecordType()) {
5147 const Record *R = getRecord(ElemType);
5148 if (!R)
5149 return false;
5150
5151 for (size_t I = 0; I != NumElems; ++I) {
5152 if (!this->emitConstUint32(I, E))
5153 return false;
5154 if (!this->emitArrayElemPtr(PT_Uint32, E))
5155 return false;
5156 if (!this->visitZeroRecordInitializer(R, E))
5157 return false;
5158 if (!this->emitPopPtr(E))
5159 return false;
5160 }
5161 return true;
5162 }
5163 if (ElemType->isArrayType()) {
5164 for (size_t I = 0; I != NumElems; ++I) {
5165 if (!this->emitConstUint32(I, E))
5166 return false;
5167 if (!this->emitArrayElemPtr(PT_Uint32, E))
5168 return false;
5169 if (!this->visitZeroArrayInitializer(ElemType, E))
5170 return false;
5171 if (!this->emitPopPtr(E))
5172 return false;
5173 }
5174 return true;
5175 }
5176
5177 return false;
5178}
5179
5180template <class Emitter>
5181bool Compiler<Emitter>::visitAssignment(const Expr *LHS, const Expr *RHS,
5182 const Expr *E) {
5183 if (!canClassify(E->getType()))
5184 return false;
5185
5186 bool NeedsFlip = !isSideEffectFree(RHS);
5187 if (!NeedsFlip) {
5188 if (!this->visit(LHS))
5189 return false;
5190 if (!this->visit(RHS))
5191 return false;
5192 } else {
5193 if (!this->visit(RHS))
5194 return false;
5195 if (!this->visit(LHS))
5196 return false;
5197 }
5198
5199 if (LHS->getType().isVolatileQualified())
5200 return this->emitInvalidStore(LHS->getType().getTypePtr(), E);
5201
5202 // We don't support assignments in C.
5203 if (!Ctx.getLangOpts().CPlusPlus && !this->emitInvalid(E))
5204 return false;
5205
5206 PrimType RHT = classifyPrim(RHS);
5207 bool Activates = refersToUnion(LHS);
5208 bool BitField = LHS->refersToBitField();
5209
5210 if (NeedsFlip && !this->emitFlip(PT_Ptr, RHT, E))
5211 return false;
5212
5213 if (DiscardResult) {
5214 if (BitField && Activates)
5215 return this->emitStoreBitFieldActivatePop(RHT, E);
5216 if (BitField)
5217 return this->emitStoreBitFieldPop(RHT, E);
5218 if (Activates)
5219 return this->emitStoreActivatePop(RHT, E);
5220 // Otherwise, regular non-activating store.
5221 return this->emitStorePop(RHT, E);
5222 }
5223
5224 auto maybeLoad = [&](bool Result) -> bool {
5225 if (!Result)
5226 return false;
5227 // Assignments aren't necessarily lvalues in C.
5228 // Load from them in that case.
5229 if (!E->isLValue())
5230 return this->emitLoadPop(RHT, E);
5231 return true;
5232 };
5233
5234 if (BitField && Activates)
5235 return maybeLoad(this->emitStoreBitFieldActivate(RHT, E));
5236 if (BitField)
5237 return maybeLoad(this->emitStoreBitField(RHT, E));
5238 if (Activates)
5239 return maybeLoad(this->emitStoreActivate(RHT, E));
5240 // Otherwise, regular non-activating store.
5241 return maybeLoad(this->emitStore(RHT, E));
5242}
5243
5244template <class Emitter>
5245template <typename T>
5246bool Compiler<Emitter>::emitConst(T Value, PrimType Ty, SourceInfo Info) {
5247 switch (Ty) {
5248 case PT_Sint8:
5249 return this->emitConstSint8(Value, Info);
5250 case PT_Uint8:
5251 return this->emitConstUint8(Value, Info);
5252 case PT_Sint16:
5253 return this->emitConstSint16(Value, Info);
5254 case PT_Uint16:
5255 return this->emitConstUint16(Value, Info);
5256 case PT_Sint32:
5257 return this->emitConstSint32(Value, Info);
5258 case PT_Uint32:
5259 return this->emitConstUint32(Value, Info);
5260 case PT_Sint64:
5261 return this->emitConstSint64(Value, Info);
5262 case PT_Uint64:
5263 return this->emitConstUint64(Value, Info);
5264 case PT_Bool:
5265 return this->emitConstBool(Value, Info);
5266 case PT_Ptr:
5267 case PT_MemberPtr:
5268 case PT_Float:
5269 case PT_IntAP:
5270 case PT_IntAPS:
5271 case PT_FixedPoint:
5272 llvm_unreachable("Invalid integral type");
5273 break;
5274 }
5275 llvm_unreachable("unknown primitive type");
5276}
5277
5278template <class Emitter>
5279template <typename T>
5280bool Compiler<Emitter>::emitConst(T Value, const Expr *E) {
5281 return this->emitConst(Value, classifyPrim(E->getType()), E);
5282}
5283
5284template <class Emitter>
5285bool Compiler<Emitter>::emitConst(const APSInt &Value, PrimType Ty,
5286 SourceInfo Info) {
5287 if (Ty == PT_IntAPS)
5288 return this->emitConstIntAPS(Value, Info);
5289 if (Ty == PT_IntAP)
5290 return this->emitConstIntAP(Value, Info);
5291
5292 if (Value.isSigned())
5293 return this->emitConst(Value.getSExtValue(), Ty, Info);
5294 return this->emitConst(Value.getZExtValue(), Ty, Info);
5295}
5296
5297template <class Emitter>
5298bool Compiler<Emitter>::emitConst(const APInt &Value, PrimType Ty,
5299 SourceInfo Info) {
5300 if (Ty == PT_IntAPS)
5301 return this->emitConstIntAPS(Value, Info);
5302 if (Ty == PT_IntAP)
5303 return this->emitConstIntAP(Value, Info);
5304
5305 if (isSignedType(Ty))
5306 return this->emitConst(Value.getSExtValue(), Ty, Info);
5307 return this->emitConst(Value.getZExtValue(), Ty, Info);
5308}
5309
5310template <class Emitter>
5311bool Compiler<Emitter>::emitConst(const APSInt &Value, const Expr *E) {
5312 return this->emitConst(Value, classifyPrim(E->getType()), E);
5313}
5314
5315template <class Emitter>
5317 bool IsConst,
5318 bool IsVolatile,
5319 ScopeKind SC) {
5320 // FIXME: There are cases where Src.is<Expr*>() is wrong, e.g.
5321 // (int){12} in C. Consider using Expr::isTemporaryObject() instead
5322 // or isa<MaterializeTemporaryExpr>().
5323 Descriptor *D = P.createDescriptor(Src, Ty, nullptr, Descriptor::InlineDescMD,
5324 IsConst, isa<const Expr *>(Src),
5325 /*IsMutable=*/false, IsVolatile);
5327 Scope::Local Local = this->createLocal(D);
5328 if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>()))
5329 Locals.insert({VD, Local});
5330 VarScope->addForScopeKind(Local, SC);
5331 return Local.Offset;
5332}
5333
5334template <class Emitter>
5336 ScopeKind SC) {
5337 const ValueDecl *Key = nullptr;
5338 const Expr *Init = nullptr;
5339 bool IsTemporary = false;
5340 if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
5341 Key = VD;
5342
5343 if (const auto *VarD = dyn_cast<VarDecl>(VD))
5344 Init = VarD->getInit();
5345 }
5346 if (auto *E = Src.dyn_cast<const Expr *>()) {
5347 IsTemporary = true;
5348 if (Ty.isNull())
5349 Ty = E->getType();
5350 }
5351
5352 Descriptor *D = P.createDescriptor(
5354 IsTemporary, /*IsMutable=*/false, /*IsVolatile=*/Ty.isVolatileQualified(),
5355 Init);
5356 if (!D)
5357 return std::nullopt;
5359
5360 Scope::Local Local = this->createLocal(D);
5361 if (Key)
5362 Locals.insert({Key, Local});
5363 VarScope->addForScopeKind(Local, SC);
5364 return Local.Offset;
5365}
5366
5367template <class Emitter>
5369 QualType Ty = E->getType();
5370 assert(!Ty->isRecordType());
5371
5372 Descriptor *D = P.createDescriptor(
5374 /*IsTemporary=*/true);
5375
5376 if (!D)
5377 return std::nullopt;
5378
5379 Scope::Local Local = this->createLocal(D);
5381 assert(S);
5382 // Attach to topmost scope.
5383 while (S->getParent())
5384 S = S->getParent();
5385 assert(S && !S->getParent());
5386 S->addLocal(Local);
5387 return Local.Offset;
5388}
5389
5390template <class Emitter>
5392 if (const PointerType *PT = dyn_cast<PointerType>(Ty))
5393 return PT->getPointeeType()->getAsCanonical<RecordType>();
5394 return Ty->getAsCanonical<RecordType>();
5395}
5396
5397template <class Emitter> Record *Compiler<Emitter>::getRecord(QualType Ty) {
5398 if (const auto *RecordTy = getRecordTy(Ty))
5399 return getRecord(RecordTy->getDecl()->getDefinitionOrSelf());
5400 return nullptr;
5401}
5402
5403template <class Emitter>
5405 return P.getOrCreateRecord(RD);
5406}
5407
5408template <class Emitter>
5410 return Ctx.getOrCreateFunction(FD);
5411}
5412
5413template <class Emitter>
5414bool Compiler<Emitter>::visitExpr(const Expr *E, bool DestroyToplevelScope) {
5416
5417 auto maybeDestroyLocals = [&]() -> bool {
5418 if (DestroyToplevelScope)
5419 return RootScope.destroyLocals() && this->emitCheckAllocations(E);
5420 return this->emitCheckAllocations(E);
5421 };
5422
5423 // Void expressions.
5424 if (E->getType()->isVoidType()) {
5425 if (!visit(E))
5426 return false;
5427 return this->emitRetVoid(E) && maybeDestroyLocals();
5428 }
5429
5430 // Expressions with a primitive return type.
5431 if (OptPrimType T = classify(E)) {
5432 if (!visit(E))
5433 return false;
5434
5435 return this->emitRet(*T, E) && maybeDestroyLocals();
5436 }
5437
5438 // Expressions with a composite return type.
5439 // For us, that means everything we don't
5440 // have a PrimType for.
5441 if (UnsignedOrNone LocalOffset = this->allocateLocal(E)) {
5442 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalOffset));
5443 if (!this->emitGetPtrLocal(*LocalOffset, E))
5444 return false;
5445
5446 if (!visitInitializer(E))
5447 return false;
5448 // We are destroying the locals AFTER the Ret op.
5449 // The Ret op needs to copy the (alive) values, but the
5450 // destructors may still turn the entire expression invalid.
5451 return this->emitRetValue(E) && maybeDestroyLocals();
5452 }
5453
5454 return maybeDestroyLocals() && false;
5455}
5456
5457template <class Emitter>
5459 bool DestroyToplevelScope) {
5460 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5461 /*NewInitializing=*/false, /*ToLValue=*/true);
5462
5463 return this->visitExpr(E, DestroyToplevelScope);
5464}
5465
5466template <class Emitter>
5468
5469 auto R = this->visitVarDecl(VD, VD->getInit(), /*Toplevel=*/true);
5470
5471 if (R.notCreated())
5472 return R;
5473
5474 if (R)
5475 return true;
5476
5477 if (!R && Context::shouldBeGloballyIndexed(VD)) {
5478 if (auto GlobalIndex = P.getGlobal(VD)) {
5479 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
5480 auto &GD = GlobalBlock->getBlockDesc<GlobalInlineDescriptor>();
5481
5483 GlobalBlock->invokeDtor();
5484 }
5485 }
5486
5487 return R;
5488}
5489
5490/// Toplevel visitDeclAndReturn().
5491/// We get here from evaluateAsInitializer().
5492/// We need to evaluate the initializer and return its value.
5493template <class Emitter>
5495 bool ConstantContext) {
5496 // We only create variables if we're evaluating in a constant context.
5497 // Otherwise, just evaluate the initializer and return it.
5498 if (!ConstantContext) {
5499 DeclScope<Emitter> LS(this, VD);
5500 if (!this->visit(Init))
5501 return false;
5502 return this->emitRet(classify(Init).value_or(PT_Ptr), VD) &&
5503 LS.destroyLocals() && this->emitCheckAllocations(VD);
5504 }
5505
5506 LocalScope<Emitter> VDScope(this);
5507 if (!this->visitVarDecl(VD, Init, /*Toplevel=*/true))
5508 return false;
5509
5510 OptPrimType VarT = classify(VD->getType());
5511 bool IsReference = VD->getType()->isReferenceType();
5513 auto GlobalIndex = P.getGlobal(VD);
5514 assert(GlobalIndex); // visitVarDecl() didn't return false.
5515 if (VarT) {
5516 if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
5517 return false;
5518 } else {
5519 if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
5520 return false;
5521 }
5522 } else {
5523 auto Local = Locals.find(VD);
5524 assert(Local != Locals.end()); // Same here.
5525 if (VarT) {
5526 if (IsReference) {
5527 if (!this->emitGetRefLocal(Local->second.Offset, VD))
5528 return false;
5529 } else if (!this->emitGetLocal(*VarT, Local->second.Offset, VD))
5530 return false;
5531 } else {
5532 if (!this->emitGetPtrLocal(Local->second.Offset, VD))
5533 return false;
5534 }
5535 }
5536
5537 // Return the value.
5538 if (!this->emitRet(VarT.value_or(PT_Ptr), VD)) {
5539 // If the Ret above failed and this is a global variable, mark it as
5540 // uninitialized, even everything else succeeded.
5542 auto GlobalIndex = P.getGlobal(VD);
5543 assert(GlobalIndex);
5544 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
5545 auto &GD = GlobalBlock->getBlockDesc<GlobalInlineDescriptor>();
5546
5548 GlobalBlock->invokeDtor();
5549 }
5550 return false;
5551 }
5552
5553 return VDScope.destroyLocals() && this->emitCheckAllocations(VD);
5554}
5555
5556template <class Emitter>
5558 const Expr *Init,
5559 bool Toplevel) {
5560 QualType VarTy = VD->getType();
5561 // We don't know what to do with these, so just return false.
5562 if (VarTy.isNull())
5563 return false;
5564
5565 // This case is EvalEmitter-only. If we won't create any instructions for the
5566 // initializer anyway, don't bother creating the variable in the first place.
5567 if (!this->isActive())
5569
5570 OptPrimType VarT = classify(VD->getType());
5571
5572 if (Init && Init->isValueDependent())
5573 return false;
5574
5576 auto checkDecl = [&]() -> bool {
5577 bool NeedsOp = !Toplevel && VD->isLocalVarDecl() && VD->isStaticLocal();
5578 return !NeedsOp || this->emitCheckDecl(VD, VD);
5579 };
5580
5582 UnsignedOrNone GlobalIndex = P.getGlobal(VD);
5583 if (GlobalIndex) {
5584 // The global was previously created but the initializer failed.
5585 if (!P.getGlobal(*GlobalIndex)->isInitialized())
5586 return false;
5587 // We've already seen and initialized this global.
5588 if (P.isGlobalInitialized(*GlobalIndex))
5589 return checkDecl();
5590 // The previous attempt at initialization might've been unsuccessful,
5591 // so let's try this one.
5592 } else if ((GlobalIndex =
5593 P.createGlobal(VD, Init, VariablesAreConstexprUnknown))) {
5594 } else {
5595 return false;
5596 }
5597 if (!Init)
5598 return true;
5599
5600 if (!checkDecl())
5601 return false;
5602
5603 if (VarT) {
5604 if (!this->visit(Init))
5605 return false;
5606
5607 return this->emitInitGlobal(*VarT, *GlobalIndex, VD);
5608 }
5609
5610 if (!this->emitGetPtrGlobal(*GlobalIndex, Init))
5611 return false;
5612
5613 if (!this->emitStartInit(Init))
5614 return false;
5615
5616 if (!visitInitializer(Init))
5617 return false;
5618
5619 if (!this->emitEndInit(Init))
5620 return false;
5621
5622 return this->emitFinishInitGlobal(Init);
5623 }
5624 // Local variables.
5626
5627 if (VarT) {
5628 unsigned Offset = this->allocateLocalPrimitive(
5629 VD, *VarT, VarTy.isConstQualified(), VarTy.isVolatileQualified(),
5631
5632 if (!Init || Init->getType()->isVoidType())
5633 return true;
5634
5635 // If this is a toplevel declaration, create a scope for the
5636 // initializer.
5637 if (Toplevel) {
5639 if (!this->visit(Init))
5640 return false;
5641 return this->emitSetLocal(*VarT, Offset, VD) && Scope.destroyLocals();
5642 }
5643 if (!this->visit(Init))
5644 return false;
5645
5646 if (VarTy->isReferenceType()) {
5647 // [C++26][decl.ref]
5648 // The object designated by such a glvalue can be outside its lifetime
5649 // Because a null pointer value or a pointer past the end of an object
5650 // does not point to an object, a reference in a well-defined program
5651 // cannot refer to such things;
5652 assert(classifyPrim(VarTy) == PT_Ptr);
5653 if (!this->emitCheckRefInit(Init))
5654 return false;
5655 }
5656
5657 return this->emitSetLocal(*VarT, Offset, VD);
5658 }
5659 // Local composite variables.
5660 if (UnsignedOrNone Offset =
5661 this->allocateLocal(VD, VarTy, ScopeKind::Block)) {
5662 if (!Init)
5663 return true;
5664
5665 if (!this->emitGetPtrLocal(*Offset, Init))
5666 return false;
5667
5668 return visitInitializerPop(Init);
5669 }
5670 return false;
5671}
5672
5673template <class Emitter>
5675 assert(!canClassify(VD->getType()));
5676
5678 // Create a local variable to use as the instance.
5679 QualType Ty = VD->getType();
5680 Descriptor *D =
5681 P.createDescriptor(VD, Ty.getTypePtr(), Descriptor::InlineDescMD,
5682 /*IsConst=*/Ty.isConstQualified(),
5683 /*IsTemporary=*/false, /*IsMutable=*/false,
5684 /*IsVolatile=*/Ty.isVolatileQualified(), nullptr);
5685 if (!D)
5686 return false;
5687
5688 // FIXME: Would be nice if we didn't allocate the descriptor at all in this
5689 // case.
5690 if (D->hasTrivialDtor())
5691 return true;
5692
5693 Scope::Local Local = this->createLocal(D);
5694 Locals.insert({VD, Local});
5695 VarScope->addForScopeKind(Local, ScopeKind::Block);
5696
5697 if (!this->emitGetPtrLocal(Local.Offset, VD))
5698 return false;
5699
5700 if (!this->visitAPValueInitializer(Value, VD, Ty))
5701 return false;
5702
5703 return this->emitDestructionPop(D, VD);
5704}
5705
5707public:
5709 explicit ParamFinder() {}
5710
5711 bool VisitDeclRefExpr(const DeclRefExpr *E) override {
5712 if (const auto *P = dyn_cast<ParmVarDecl>(E->getDecl()))
5713 FoundParams.insert(P);
5714 return true;
5715 }
5716};
5717
5718/// Evaluate the \p Condition as if it was in the body of \p Callee.
5719/// Specifically, all the parameters of the callee are available to use
5720/// for the condition, and their values are given by \p Args (and \p This).
5721///
5722// Since this is a somewhat niche feature, we're abusing a few other mechanisms
5723// to implement this.
5724//
5725// We don't create an actual function frame but instead register the parameters
5726// as local variables.
5727//
5728// So we evaluate something like:
5729//
5730// bool thisfunc() {
5731// auto Arg0 = Args[0];
5732// ...
5733// return Condition;
5734// }
5735//
5736template <class Emitter>
5739 const Expr *This,
5740 const Expr *Condition) {
5741 // Instead of evaluating all parameters and trying to ignore failure,
5742 // we collect all the parameters used in the condition and only evaluate
5743 // those. Note that we still ignore failure in the loop below because the
5744 // failure might be inconsequential in the end,
5745 // e.g. in the case of `true || x`.
5746 ParamFinder PF;
5748
5749 LocalScope<Emitter> ArgScope(this);
5750 for (const ParmVarDecl *PVD : PF.FoundParams) {
5751 unsigned ParamIndex = 0;
5752 for (const ParmVarDecl *P : Callee->parameters()) {
5753 if (P == PVD)
5754 break;
5755 ++ParamIndex;
5756 }
5757
5758 const Expr *Arg = Args[ParamIndex];
5759 const ParmVarDecl *Param = Callee->getParamDecl(ParamIndex);
5760 if (OptPrimType ParamT = classify(Param->getType())) {
5761 unsigned ArgOffset =
5762 allocateLocalPrimitive(Param, *ParamT, /*IsConst=*/true);
5763 if (!this->visit(Arg))
5764 continue;
5765 if (!this->emitSetLocal(*ParamT, ArgOffset, Arg))
5766 return false;
5767 } else {
5768 UnsignedOrNone ArgOffset = this->allocateLocal(Param, Param->getType());
5769 if (!ArgOffset)
5770 return false;
5771 if (!this->emitGetPtrLocal(*ArgOffset, Arg))
5772 return false;
5773 if (!this->visitInitializerPop(Arg))
5774 continue;
5775 }
5776 }
5777
5778 if (This) {
5779 // We abuse the init stack for this and tell it to use
5780 // either a local variable or another decl for the This pointer.
5781 this->InitStackActive = true;
5782
5783 if (This->getType()->isPointerType()) {
5784 // Nothing to do here, the evaluation will fail if the instance
5785 // pointer is used.
5786 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(This)) {
5787 InitStack.push_back(InitLink::Decl(DRE->getDecl()));
5788 } else {
5789 assert(!canClassify(This->getType()));
5790 UnsignedOrNone ArgOffset = this->allocateLocal(This, This->getType());
5791 if (!ArgOffset)
5792 return false;
5793 if (!this->emitGetPtrLocal(*ArgOffset, This))
5794 return false;
5795 if (!this->visitInitializerPop(This))
5796 return false;
5797 this->InitStack.push_back(InitLink::Temp(*ArgOffset));
5798 }
5799 }
5800
5801 // Destruction of the argument values is part of the callee frame,
5802 // so we simply ignore them here.
5803 this->VarScope = nullptr;
5804
5805 LocalScope<Emitter> RetScope(this);
5806 if (!this->visit(Condition))
5807 return false;
5808 if (!RetScope.destroyLocals())
5809 return false;
5810
5811 // Result of the condition should be on the stack.
5812 return this->emitRet(PT_Bool, Condition);
5813}
5814
5815template <class Emitter>
5817 SourceInfo Info) {
5818 assert(!Val.isIndeterminate() && "Needs to be checked before");
5819 assert(!DiscardResult);
5820 if (Val.isInt())
5821 return this->emitConst(Val.getInt(), ValType, Info);
5822 if (Val.isFloat()) {
5823 APFloat F = Val.getFloat();
5824 return this->emitFloat(F, Info);
5825 }
5826
5827 if (Val.isMemberPointer()) {
5828 if (const ValueDecl *MemberDecl = Val.getMemberPointerDecl()) {
5829 if (!this->emitGetMemberPtr(MemberDecl, Info))
5830 return false;
5831
5832 bool IsDerived = Val.isMemberPointerToDerivedMember();
5833 // Apply the member pointer path.
5834 for (const CXXRecordDecl *PathEntry : Val.getMemberPointerPath()) {
5835 if (!this->emitCopyMemberPtrPath(PathEntry, IsDerived, Info))
5836 return false;
5837 }
5838
5839 return true;
5840 }
5841 return this->emitNullMemberPtr(0, nullptr, Info);
5842 }
5843
5844 if (Val.isLValue()) {
5845 if (Val.isNullPointer())
5846 return this->emitNull(ValType, 0, nullptr, Info);
5847
5850
5851 if (const Expr *BaseExpr = Base.dyn_cast<const Expr *>())
5852 return this->visit(BaseExpr);
5853 if (const auto *VD = Base.dyn_cast<const ValueDecl *>()) {
5854 if (!this->visitDeclRef(VD, Info.asExpr()))
5855 return false;
5856
5857 QualType EntryType = VD->getType();
5858 for (auto &Entry : Path) {
5859 if (EntryType->isArrayType()) {
5860 uint64_t Index = Entry.getAsArrayIndex();
5861 QualType ElemType =
5862 EntryType->getAsArrayTypeUnsafe()->getElementType();
5863 if (!this->emitConst(Index, PT_Uint64, Info))
5864 return false;
5865 if (!this->emitArrayElemPtrPop(PT_Uint64, Info))
5866 return false;
5867 EntryType = ElemType;
5868 } else {
5869 assert(EntryType->isRecordType());
5870 const Record *EntryRecord = getRecord(EntryType);
5871 if (!EntryRecord)
5872 return false;
5873
5874 const Decl *BaseOrMember = Entry.getAsBaseOrMember().getPointer();
5875 if (const auto *FD = dyn_cast<FieldDecl>(BaseOrMember)) {
5876 unsigned EntryOffset = EntryRecord->getField(FD)->Offset;
5877 if (!this->emitGetPtrFieldPop(EntryOffset, Info))
5878 return false;
5879 EntryType = FD->getType();
5880 } else {
5881 const auto *Base = cast<CXXRecordDecl>(BaseOrMember);
5882 if (const Record::Base *B = EntryRecord->getBaseOrNull(Base)) {
5883 if (!this->emitGetPtrBasePop(B->Offset, /*NullOK=*/false, Info))
5884 return false;
5885 } else {
5886 // Must be a virtual base.
5887 assert(EntryRecord->getVirtualBase(Base));
5888 if (!this->emitGetPtrVirtBasePop(Base, Info))
5889 return false;
5890 }
5891 EntryType = Ctx.getASTContext().getCanonicalTagType(Base);
5892 }
5893 }
5894 }
5895
5896 return true;
5897 }
5898 }
5899
5900 return false;
5901}
5902
5903template <class Emitter>
5905 SourceInfo Info, QualType T,
5906 bool IsCompleteClass) {
5907 if (Val.isStruct()) {
5908 const Record *R = this->getRecord(T);
5909 assert(R);
5910
5911 assert(R->getNumBases() == Val.getStructNumBases());
5912 if (IsCompleteClass)
5913 assert(R->getNumVirtualBases() == Val.getStructNumVirtualBases());
5914
5915 for (unsigned I = 0, N = Val.getStructNumBases(); I != N; ++I) {
5916 const APValue &B = Val.getStructBase(I);
5917 if (B.isIndeterminate())
5918 continue;
5919 const Record::Base *RB = R->getBase(I);
5920 QualType BaseType = Ctx.getASTContext().getCanonicalTagType(RB->Decl);
5921
5922 if (!this->emitGetPtrBase(RB->Offset, Info))
5923 return false;
5924 if (!this->visitAPValueInitializer(B, Info, BaseType,
5925 /*IsCompleteClass=*/false))
5926 return false;
5927 if (!this->emitFinishInitPop(Info))
5928 return false;
5929 }
5930
5931 for (unsigned I = 0, N = Val.getStructNumFields(); I != N; ++I) {
5932 const APValue &F = Val.getStructField(I);
5933 if (F.isIndeterminate())
5934 continue;
5935 const Record::Field *RF = R->getField(I);
5936 QualType FieldType = RF->Decl->getType();
5937 // Fields.
5938 if (OptPrimType PT = classify(FieldType)) {
5939 if (!this->visitAPValue(F, *PT, Info))
5940 return false;
5941 if (!this->emitInitField(*PT, RF->Offset, Info))
5942 return false;
5943 } else {
5944 if (!this->emitGetPtrField(RF->Offset, Info))
5945 return false;
5946 if (!this->visitAPValueInitializer(F, Info, FieldType))
5947 return false;
5948 if (!this->emitFinishInitPop(Info))
5949 return false;
5950 }
5951 }
5952
5953 // Virtual Bases.
5954 if (IsCompleteClass) {
5955 for (unsigned I = 0, N = Val.getStructNumVirtualBases(); I != N; ++I) {
5956 const APValue &B = Val.getStructVirtualBase(I);
5957 if (B.isIndeterminate())
5958 continue;
5959 const Record::Base *RB = R->getVirtualBase(I);
5960 QualType BaseType = Ctx.getASTContext().getCanonicalTagType(RB->Decl);
5961
5962 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(RB->R->getDecl()),
5963 Info))
5964 return false;
5965 if (!this->visitAPValueInitializer(B, Info, BaseType,
5966 /*IsCompleteClass=*/false))
5967 return false;
5968 if (!this->emitFinishInitPop(Info))
5969 return false;
5970 }
5971 }
5972
5973 return true;
5974 }
5975 if (Val.isUnion()) {
5976 const FieldDecl *UnionField = Val.getUnionField();
5977 if (!UnionField)
5978 return true;
5979 const Record *R = this->getRecord(T);
5980 assert(R);
5981 const APValue &F = Val.getUnionValue();
5982 if (F.isIndeterminate())
5983 return true;
5984 const Record::Field *RF = R->getField(UnionField);
5985 QualType FieldType = RF->Decl->getType();
5986
5987 if (OptPrimType PT = classify(FieldType)) {
5988 if (!this->visitAPValue(F, *PT, Info))
5989 return false;
5990 if (RF->isBitField())
5991 return this->emitInitBitFieldActivate(*PT, RF->Offset, RF->bitWidth(),
5992 Info);
5993 return this->emitInitFieldActivate(*PT, RF->Offset, Info);
5994 }
5995
5996 if (!this->emitGetPtrField(RF->Offset, Info))
5997 return false;
5998 if (!this->emitActivate(Info))
5999 return false;
6000 if (!this->visitAPValueInitializer(F, Info, FieldType))
6001 return false;
6002 return this->emitPopPtr(Info);
6003 }
6004 if (Val.isArray()) {
6005 unsigned InitializedElems = Val.getArrayInitializedElts();
6006 const auto *ArrType = T->getAsArrayTypeUnsafe();
6007 QualType ElemType = ArrType->getElementType();
6008 OptPrimType ElemT = classify(ElemType);
6009
6010 for (unsigned A = 0, AN = Val.getArraySize(); A != AN; ++A) {
6011 const APValue &Elem = A >= InitializedElems
6012 ? Val.getArrayFiller()
6013 : Val.getArrayInitializedElt(A);
6014 if (Elem.isIndeterminate())
6015 continue;
6016
6017 if (ElemT) {
6018 if (!this->visitAPValue(Elem, *ElemT, Info))
6019 return false;
6020 if (!this->emitInitElem(*ElemT, A, Info))
6021 return false;
6022 } else {
6023 if (!this->emitConstUint32(A, Info))
6024 return false;
6025 if (!this->emitArrayElemPtrUint32(Info))
6026 return false;
6027 if (!this->visitAPValueInitializer(Elem, Info, ElemType))
6028 return false;
6029 if (!this->emitPopPtr(Info))
6030 return false;
6031 }
6032 }
6033 return true;
6034 }
6035 // TODO: Other types.
6036
6037 return false;
6038}
6039
6040template <class Emitter>
6042 unsigned BuiltinID) {
6043 if (BuiltinID == Builtin::BI__builtin_constant_p) {
6044 // Void argument is always invalid and harder to handle later.
6045 if (E->getArg(0)->getType()->isVoidType()) {
6046 if (DiscardResult)
6047 return true;
6048 return this->emitConst(0, E);
6049 }
6050
6051 if (!this->emitStartSpeculation(E))
6052 return false;
6053 LabelTy EndLabel = this->getLabel();
6054 if (!this->speculate(E, EndLabel))
6055 return false;
6056 if (!this->emitEndSpeculation(E))
6057 return false;
6058 this->fallthrough(EndLabel);
6059 if (DiscardResult)
6060 return this->emitPop(classifyPrim(E), E);
6061 return true;
6062 }
6063
6064 // For these, we're expected to ultimately return an APValue pointing
6065 // to the CallExpr. This is needed to get the correct codegen.
6066 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
6067 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString ||
6068 BuiltinID == Builtin::BI__builtin_ptrauth_sign_constant ||
6069 BuiltinID == Builtin::BI__builtin_function_start) {
6070 if (DiscardResult)
6071 return true;
6072 return this->emitDummyPtr(E, E);
6073 }
6074
6076 OptPrimType ReturnT = classify(E);
6077
6078 // Non-primitive return type. Prepare storage.
6079 if (!Initializing && !ReturnT && !ReturnType->isVoidType()) {
6080 UnsignedOrNone LocalIndex = allocateLocal(E);
6081 if (!LocalIndex)
6082 return false;
6083 if (!this->emitGetPtrLocal(*LocalIndex, E))
6084 return false;
6085 }
6086
6087 // Prepare function arguments including special cases.
6088 switch (BuiltinID) {
6089 case Builtin::BI__builtin_object_size:
6090 case Builtin::BI__builtin_dynamic_object_size: {
6091 assert(E->getNumArgs() == 2);
6092 const Expr *Arg0 = E->getArg(0);
6093 if (Arg0->isGLValue()) {
6094 if (!this->visit(Arg0))
6095 return false;
6096
6097 } else {
6098 if (!this->visitAsLValue(Arg0))
6099 return false;
6100 }
6101 if (!this->visit(E->getArg(1)))
6102 return false;
6103
6104 } break;
6105 case Builtin::BI__assume:
6106 case Builtin::BI__builtin_assume:
6107 // Argument is not evaluated.
6108 break;
6109 case Builtin::BI__atomic_is_lock_free:
6110 case Builtin::BI__atomic_always_lock_free: {
6111 assert(E->getNumArgs() == 2);
6112 if (!this->visit(E->getArg(0)))
6113 return false;
6114 if (!this->visitAsLValue(E->getArg(1)))
6115 return false;
6116 } break;
6117
6118 default:
6119 if (!Context::isUnevaluatedBuiltin(BuiltinID)) {
6120 // Put arguments on the stack.
6121 for (const auto *Arg : E->arguments()) {
6122 if (!this->visit(Arg))
6123 return false;
6124 }
6125 }
6126 }
6127
6128 if (!this->emitCallBI(E, BuiltinID, E))
6129 return false;
6130
6131 if (DiscardResult && !ReturnType->isVoidType())
6132 return this->emitPop(ReturnT.value_or(PT_Ptr), E);
6133
6134 return true;
6135}
6136
6137template <class Emitter>
6139 if (E->containsErrors())
6140 return false;
6141 const FunctionDecl *FuncDecl = E->getDirectCallee();
6142
6143 if (FuncDecl) {
6144 if (unsigned BuiltinID = FuncDecl->getBuiltinID())
6145 return VisitBuiltinCallExpr(E, BuiltinID);
6146
6147 // Calls to replaceable operator new/operator delete.
6149 if (FuncDecl->getDeclName().isAnyOperatorNew())
6150 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_new);
6151 assert(FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
6152 FuncDecl->getDeclName().getCXXOverloadedOperator() ==
6153 OO_Array_Delete);
6154 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_delete);
6155 }
6156
6157 // Explicit calls to trivial destructors
6158 if (const auto *DD = dyn_cast<CXXDestructorDecl>(FuncDecl);
6159 DD && DD->isTrivial()) {
6160 const auto *MemberCall = cast<CXXMemberCallExpr>(E);
6161 if (!this->visit(MemberCall->getImplicitObjectArgument()))
6162 return false;
6163 return this->emitCheckDestruction(E) && this->emitEndLifetime(E) &&
6164 this->emitPopPtr(E);
6165 }
6166 }
6167
6168 LocalScope<Emitter> CallScope(this, ScopeKind::Call);
6169
6170 QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
6172 bool HasRVO = !ReturnType->isVoidType() && !T;
6173
6174 if (HasRVO) {
6175 if (DiscardResult) {
6176 // If we need to discard the return value but the function returns its
6177 // value via an RVO pointer, we need to create one such pointer just
6178 // for this call.
6179 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
6180 if (!this->emitGetPtrLocal(*LocalIndex, E))
6181 return false;
6182 }
6183 } else {
6184 // We need the result. Prepare a pointer to return or
6185 // dup the current one.
6186 if (!Initializing) {
6187 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
6188 if (!this->emitGetPtrLocal(*LocalIndex, E))
6189 return false;
6190 }
6191 }
6192 if (!this->emitDupPtr(E))
6193 return false;
6194 }
6195 }
6196
6198
6199 bool IsAssignmentOperatorCall = false;
6200 bool ActivateLHS = false;
6201 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
6202 OCE && OCE->isAssignmentOp()) {
6203 // Just like with regular assignments, we need to special-case assignment
6204 // operators here and evaluate the RHS (the second arg) before the LHS (the
6205 // first arg). We fix this by using a Flip op later.
6206 assert(Args.size() == 2);
6207 const CXXRecordDecl *LHSRecord = Args[0]->getType()->getAsCXXRecordDecl();
6208 ActivateLHS = LHSRecord && LHSRecord->hasTrivialDefaultConstructor();
6209 IsAssignmentOperatorCall = true;
6210 std::reverse(Args.begin(), Args.end());
6211 }
6212 // Calling a static operator will still
6213 // pass the instance, but we don't need it.
6214 // Discard it here.
6215 if (isa<CXXOperatorCallExpr>(E)) {
6216 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl);
6217 MD && MD->isStatic()) {
6218 if (!this->discard(E->getArg(0)))
6219 return false;
6220 // Drop first arg.
6221 Args.erase(Args.begin());
6222 }
6223 }
6224
6225 bool Devirtualized = false;
6226 UnsignedOrNone CalleeOffset = std::nullopt;
6227 // Add the (optional, implicit) This pointer.
6228 if (const auto *MC = dyn_cast<CXXMemberCallExpr>(E)) {
6229 if (!FuncDecl && classifyPrim(E->getCallee()) == PT_MemberPtr) {
6230 // If we end up creating a CallPtr op for this, we need the base of the
6231 // member pointer as the instance pointer, and later extract the function
6232 // decl as the function pointer.
6233 const Expr *Callee = E->getCallee();
6234 CalleeOffset =
6235 this->allocateLocalPrimitive(Callee, PT_MemberPtr, /*IsConst=*/true);
6236 if (!this->visit(Callee))
6237 return false;
6238 if (!this->emitSetLocal(PT_MemberPtr, *CalleeOffset, E))
6239 return false;
6240 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
6241 return false;
6242 if (!this->emitGetMemberPtrBase(E))
6243 return false;
6244 } else {
6245 const auto *InstancePtr = MC->getImplicitObjectArgument();
6246 if (isa_and_nonnull<CXXDestructorDecl>(CompilingFunction) ||
6247 isa_and_nonnull<CXXConstructorDecl>(CompilingFunction)) {
6248 const auto *Stripped = stripCheckedDerivedToBaseCasts(InstancePtr);
6249 if (isa<CXXThisExpr>(Stripped)) {
6250 FuncDecl =
6251 cast<CXXMethodDecl>(FuncDecl)->getCorrespondingMethodInClass(
6252 Stripped->getType()->getPointeeType()->getAsCXXRecordDecl());
6253 Devirtualized = true;
6254 if (!this->visit(Stripped))
6255 return false;
6256 } else {
6257 if (!this->visit(InstancePtr))
6258 return false;
6259 }
6260 } else {
6261 if (!this->visit(InstancePtr))
6262 return false;
6263 }
6264 }
6265 } else if (const auto *PD =
6266 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee())) {
6267 if (!this->emitCheckPseudoDtor(E))
6268 return false;
6269 const Expr *Base = PD->getBase();
6270 // E.g. `using T = int; 0.~T();`.
6271 if (OptPrimType BaseT = classify(Base); !BaseT || BaseT != PT_Ptr)
6272 return this->discard(Base);
6273 if (!this->visit(Base))
6274 return false;
6275 return this->emitPseudoDtor(E);
6276 } else if (!FuncDecl) {
6277 const Expr *Callee = E->getCallee();
6278 CalleeOffset =
6279 this->allocateLocalPrimitive(Callee, PT_Ptr, /*IsConst=*/true);
6280 if (!this->visit(Callee))
6281 return false;
6282 if (!this->emitSetLocal(PT_Ptr, *CalleeOffset, E))
6283 return false;
6284 }
6285
6286 if (!this->visitCallArgs(Args, FuncDecl, ActivateLHS,
6288 return false;
6289
6290 // Undo the argument reversal we did earlier.
6291 if (IsAssignmentOperatorCall) {
6292 assert(Args.size() == 2);
6293 PrimType Arg1T = classify(Args[0]).value_or(PT_Ptr);
6294 PrimType Arg2T = classify(Args[1]).value_or(PT_Ptr);
6295 if (!this->emitFlip(Arg2T, Arg1T, E))
6296 return false;
6297 }
6298
6299 if (FuncDecl) {
6300 const Function *Func = getFunction(FuncDecl);
6301 if (!Func)
6302 return false;
6303
6304 // In error cases, the function may be called with fewer arguments than
6305 // parameters.
6306 if (E->getNumArgs() < Func->getNumWrittenParams())
6307 return false;
6308
6309 assert(HasRVO == Func->hasRVO());
6310
6311 bool HasQualifier = false;
6312 if (const auto *ME = dyn_cast<MemberExpr>(E->getCallee()))
6313 HasQualifier = ME->hasQualifier();
6314
6315 bool IsVirtual = false;
6316 if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl))
6317 IsVirtual = !Devirtualized && MD->isVirtual();
6318
6319 // In any case call the function. The return value will end up on the stack
6320 // and if the function has RVO, we already have the pointer on the stack to
6321 // write the result into.
6322 if (IsVirtual && !HasQualifier) {
6323 uint32_t VarArgSize = 0;
6324 unsigned NumParams =
6325 Func->getNumWrittenParams() +
6326 (isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisPointer());
6327 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
6328 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6329
6330 if (!this->emitCallVirt(Func, VarArgSize, E))
6331 return false;
6332 } else if (Func->isVariadic()) {
6333 uint32_t VarArgSize = 0;
6334 unsigned NumParams =
6335 Func->getNumWrittenParams() +
6336 (isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisPointer());
6337 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
6338 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6339 if (!this->emitCallVar(Func, VarArgSize, E))
6340 return false;
6341 } else {
6342 if (!this->emitCall(Func, 0, E))
6343 return false;
6344 }
6345 } else {
6346 // Indirect call. Visit the callee, which will leave a FunctionPointer on
6347 // the stack. Cleanup of the returned value if necessary will be done after
6348 // the function call completed.
6349
6350 // Sum the size of all args from the call expr.
6351 uint32_t ArgSize = 0;
6352 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
6353 ArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6354
6355 // Get the callee, either from a member pointer or function pointer saved in
6356 // CalleeOffset.
6357 if (isa<CXXMemberCallExpr>(E) && CalleeOffset) {
6358 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
6359 return false;
6360 if (!this->emitGetMemberPtrDecl(E))
6361 return false;
6362 } else {
6363 if (!this->emitGetLocal(PT_Ptr, *CalleeOffset, E))
6364 return false;
6365 }
6366 if (!this->emitCallPtr(ArgSize, E, E))
6367 return false;
6368 }
6369
6370 // Cleanup for discarded return values.
6371 if (DiscardResult && !ReturnType->isVoidType() && T)
6372 return this->emitPop(*T, E) && CallScope.destroyLocals();
6373
6374 return CallScope.destroyLocals();
6375}
6376
6377template <class Emitter>
6379 SourceLocScope<Emitter> SLS(this, E);
6380
6381 return this->delegate(E->getExpr());
6382}
6383
6384template <class Emitter>
6386 SourceLocScope<Emitter> SLS(this, E);
6387
6388 return this->delegate(E->getExpr());
6389}
6390
6391template <class Emitter>
6393 if (DiscardResult)
6394 return true;
6395
6396 return this->emitConstBool(E->getValue(), E);
6397}
6398
6399template <class Emitter>
6401 const CXXNullPtrLiteralExpr *E) {
6402 if (DiscardResult)
6403 return true;
6404
6405 uint64_t Val = Ctx.getASTContext().getTargetNullPointerValue(E->getType());
6406 return this->emitNullPtr(Val, nullptr, E);
6407}
6408
6409template <class Emitter>
6411 if (DiscardResult)
6412 return true;
6413
6414 assert(E->getType()->isIntegerType());
6415
6417 return this->emitZero(T, E);
6418}
6419
6420template <class Emitter>
6422 if (DiscardResult)
6423 return true;
6424
6425 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
6426 if (this->LambdaThisCapture.Offset > 0) {
6427 if (this->LambdaThisCapture.IsPtr)
6428 return this->emitGetThisFieldPtr(this->LambdaThisCapture.Offset, E);
6429 return this->emitGetPtrThisField(this->LambdaThisCapture.Offset, E);
6430 }
6431 }
6432
6433 // In some circumstances, the 'this' pointer does not actually refer to the
6434 // instance pointer of the current function frame, but e.g. to the declaration
6435 // currently being initialized. Here we emit the necessary instruction(s) for
6436 // this scenario.
6437 if (!InitStackActive || InitStack.empty())
6438 return this->emitThis(E);
6439
6440 // If our init stack is, for example:
6441 // 0 Stack: 3 (decl)
6442 // 1 Stack: 6 (init list)
6443 // 2 Stack: 1 (field)
6444 // 3 Stack: 6 (init list)
6445 // 4 Stack: 1 (field)
6446 //
6447 // We want to find the LAST element in it that's an init list,
6448 // which is marked with the K_InitList marker. The index right
6449 // before that points to an init list. We need to find the
6450 // elements before the K_InitList element that point to a base
6451 // (e.g. a decl or This), optionally followed by field, elem, etc.
6452 // In the example above, we want to emit elements [0..2].
6453 unsigned StartIndex = 0;
6454 unsigned EndIndex = 0;
6455 // Find the init list.
6456 for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) {
6457 if (InitStack[StartIndex].Kind == InitLink::K_DIE) {
6458 EndIndex = StartIndex;
6459 --StartIndex;
6460 break;
6461 }
6462 }
6463
6464 // Walk backwards to find the base.
6465 for (; StartIndex > 0; --StartIndex) {
6466 if (InitStack[StartIndex].Kind == InitLink::K_InitList)
6467 continue;
6468
6469 if (InitStack[StartIndex].Kind != InitLink::K_Field &&
6470 InitStack[StartIndex].Kind != InitLink::K_Elem &&
6471 InitStack[StartIndex].Kind != InitLink::K_DIE)
6472 break;
6473 }
6474
6475 if (StartIndex == 0 && EndIndex == 0)
6476 EndIndex = InitStack.size() - 1;
6477
6478 // NOTE: This could be StartIndex < EndIndex, but we're also abusing the
6479 // InitStack mechanism in visitWithSubstitutions to have the This pointer
6480 // _just_ be a local variable.
6481 assert(StartIndex <= EndIndex);
6482
6483 // Emit the instructions.
6484 for (unsigned I = StartIndex; I != (EndIndex + 1); ++I) {
6485 if (InitStack[I].Kind == InitLink::K_InitList ||
6486 InitStack[I].Kind == InitLink::K_DIE)
6487 continue;
6488 if (!InitStack[I].template emit<Emitter>(this, E))
6489 return false;
6490 }
6491 return true;
6492}
6493
6494template <class Emitter> bool Compiler<Emitter>::visitStmt(const Stmt *S) {
6495 switch (S->getStmtClass()) {
6496 case Stmt::CompoundStmtClass:
6498 case Stmt::DeclStmtClass:
6499 return visitDeclStmt(cast<DeclStmt>(S), /*EvaluateConditionDecl=*/true);
6500 case Stmt::ReturnStmtClass:
6502 case Stmt::IfStmtClass:
6503 return visitIfStmt(cast<IfStmt>(S));
6504 case Stmt::WhileStmtClass:
6506 case Stmt::DoStmtClass:
6507 return visitDoStmt(cast<DoStmt>(S));
6508 case Stmt::ForStmtClass:
6509 return visitForStmt(cast<ForStmt>(S));
6510 case Stmt::CXXForRangeStmtClass:
6512 case Stmt::BreakStmtClass:
6514 case Stmt::ContinueStmtClass:
6516 case Stmt::SwitchStmtClass:
6518 case Stmt::CaseStmtClass:
6519 return visitCaseStmt(cast<CaseStmt>(S));
6520 case Stmt::DefaultStmtClass:
6522 case Stmt::AttributedStmtClass:
6524 case Stmt::CXXTryStmtClass:
6526 case Stmt::NullStmtClass:
6527 return true;
6528 // Always invalid statements.
6529 case Stmt::GCCAsmStmtClass:
6530 case Stmt::MSAsmStmtClass:
6531 case Stmt::GotoStmtClass:
6532 return this->emitInvalid(S);
6533 case Stmt::LabelStmtClass:
6534 return this->visitStmt(cast<LabelStmt>(S)->getSubStmt());
6535 case Stmt::CXXExpansionStmtInstantiationClass:
6538 default: {
6539 if (const auto *E = dyn_cast<Expr>(S))
6540 return this->discard(E);
6541 return false;
6542 }
6543 }
6544}
6545
6546template <class Emitter>
6549 for (const auto *InnerStmt : S->body())
6550 if (!visitStmt(InnerStmt))
6551 return false;
6552 return Scope.destroyLocals();
6553}
6554
6555template <class Emitter>
6556bool Compiler<Emitter>::maybeEmitDeferredVarInit(const VarDecl *VD) {
6557 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
6558 for (auto *BD : DD->flat_bindings())
6559 if (auto *KD = BD->getHoldingVar();
6560 KD && !this->visitVarDecl(KD, KD->getInit()))
6561 return false;
6562 }
6563 return true;
6564}
6565
6567 assert(FD);
6568 assert(FD->getParent()->isUnion());
6569 const CXXRecordDecl *CXXRD =
6571 return !CXXRD || CXXRD->hasTrivialDefaultConstructor();
6572}
6573
6574template <class Emitter> bool Compiler<Emitter>::refersToUnion(const Expr *E) {
6575 for (;;) {
6576 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
6577 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6578 FD && FD->getParent()->isUnion() && hasTrivialDefaultCtorParent(FD))
6579 return true;
6580 E = ME->getBase();
6581 continue;
6582 }
6583
6584 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6585 E = ASE->getBase()->IgnoreImplicit();
6586 continue;
6587 }
6588
6589 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
6590 ICE && (ICE->getCastKind() == CK_NoOp ||
6591 ICE->getCastKind() == CK_DerivedToBase ||
6592 ICE->getCastKind() == CK_UncheckedDerivedToBase)) {
6593 E = ICE->getSubExpr();
6594 continue;
6595 }
6596
6597 if (const auto *This = dyn_cast<CXXThisExpr>(E)) {
6598 const auto *ThisRecord =
6599 This->getType()->getPointeeType()->getAsRecordDecl();
6600 if (!ThisRecord->isUnion())
6601 return false;
6602 // Otherwise, always activate if we're in the ctor.
6603 if (const auto *Ctor =
6604 dyn_cast_if_present<CXXConstructorDecl>(CompilingFunction))
6605 return Ctor->getParent() == ThisRecord;
6606 return false;
6607 }
6608
6609 break;
6610 }
6611 return false;
6612}
6613
6614template <class Emitter>
6616 bool EvaluateConditionDecl) {
6617 for (const auto *D : DS->decls()) {
6620 continue;
6621
6622 if (const auto *ESD = dyn_cast<CXXExpansionStmtDecl>(D)) {
6623 assert(ESD->getInstantiations() && "not expanded?");
6624 if (!this->visitStmt(ESD->getInstantiations()))
6625 return false;
6626 continue;
6627 }
6628
6629 const auto *VD = dyn_cast<VarDecl>(D);
6630 if (!VD)
6631 return false;
6632 if (!this->visitVarDecl(VD, VD->getInit()))
6633 return false;
6634
6635 // Register decomposition decl holding vars.
6636 if (EvaluateConditionDecl && !this->maybeEmitDeferredVarInit(VD))
6637 return false;
6638 }
6639
6640 return true;
6641}
6642
6643template <class Emitter>
6645 if (this->InStmtExpr)
6646 return this->emitUnsupported(RS);
6647
6648 if (const Expr *RE = RS->getRetValue()) {
6649 LocalScope<Emitter> RetScope(this);
6650 if (ReturnType) {
6651 // Primitive types are simply returned.
6652 if (!this->visit(RE))
6653 return false;
6654 this->emitCleanup();
6655 return this->emitRet(*ReturnType, RS);
6656 }
6657
6658 if (RE->getType()->isVoidType()) {
6659 if (!this->visit(RE))
6660 return false;
6661 } else {
6662 if (RE->containsErrors())
6663 return false;
6664
6666 // RVO - construct the value in the return location.
6667 if (!this->emitRVOPtr(RE))
6668 return false;
6669 if (!this->visitInitializerPop(RE))
6670 return false;
6671
6672 this->emitCleanup();
6673 return this->emitRetVoid(RS);
6674 }
6675 }
6676
6677 // Void return.
6678 this->emitCleanup();
6679 return this->emitRetVoid(RS);
6680}
6681
6682template <class Emitter> bool Compiler<Emitter>::visitIfStmt(const IfStmt *IS) {
6683 LocalScope<Emitter> IfScope(this);
6684
6685 auto visitChildStmt = [&](const Stmt *S) -> bool {
6686 LocalScope<Emitter> SScope(this);
6687 if (!visitStmt(S))
6688 return false;
6689 return SScope.destroyLocals();
6690 };
6691
6692 if (auto *CondInit = IS->getInit()) {
6693 if (!visitStmt(CondInit))
6694 return false;
6695 }
6696
6697 if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt()) {
6698 if (!visitDeclStmt(CondDecl))
6699 return false;
6700 }
6701
6702 // Save ourselves compiling some code and the jumps, etc. if the condition is
6703 // stataically known to be either true or false. We could look at more cases
6704 // here, but I think all the ones that actually happen are using a
6705 // ConstantExpr.
6706 if (std::optional<bool> BoolValue = getBoolValue(IS->getCond())) {
6707 if (*BoolValue)
6708 return visitChildStmt(IS->getThen());
6709 if (const Stmt *Else = IS->getElse())
6710 return visitChildStmt(Else);
6711 return true;
6712 }
6713
6714 // Otherwise, compile the condition.
6715 if (IS->isNonNegatedConsteval()) {
6716 if (!this->emitIsConstantContext(IS))
6717 return false;
6718 } else if (IS->isNegatedConsteval()) {
6719 if (!this->emitIsConstantContext(IS))
6720 return false;
6721 if (!this->emitInv(IS))
6722 return false;
6723 } else {
6725 if (!this->visitBool(IS->getCond()))
6726 return false;
6727 if (!CondScope.destroyLocals())
6728 return false;
6729 }
6730
6731 if (!this->maybeEmitDeferredVarInit(IS->getConditionVariable()))
6732 return false;
6733
6734 if (const Stmt *Else = IS->getElse()) {
6735 LabelTy LabelElse = this->getLabel();
6736 LabelTy LabelEnd = this->getLabel();
6737 if (!this->jumpFalse(LabelElse, IS))
6738 return false;
6739 if (!visitChildStmt(IS->getThen()))
6740 return false;
6741 if (!this->jump(LabelEnd, IS))
6742 return false;
6743 this->emitLabel(LabelElse);
6744 if (!visitChildStmt(Else))
6745 return false;
6746 this->emitLabel(LabelEnd);
6747 } else {
6748 LabelTy LabelEnd = this->getLabel();
6749 if (!this->jumpFalse(LabelEnd, IS))
6750 return false;
6751 if (!visitChildStmt(IS->getThen()))
6752 return false;
6753 this->emitLabel(LabelEnd);
6754 }
6755
6756 if (!IfScope.destroyLocals())
6757 return false;
6758
6759 return true;
6760}
6761
6762template <class Emitter>
6764 const Expr *Cond = S->getCond();
6765 const Stmt *Body = S->getBody();
6766
6767 LabelTy CondLabel = this->getLabel(); // Label before the condition.
6768 LabelTy EndLabel = this->getLabel(); // Label after the loop.
6769 LocalScope<Emitter> WholeLoopScope(this);
6770 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
6771
6772 this->fallthrough(CondLabel);
6773 this->emitLabel(CondLabel);
6774
6775 // Start of the loop body {
6776 LocalScope<Emitter> CondScope(this);
6777
6778 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
6779 if (!visitDeclStmt(CondDecl))
6780 return false;
6781 }
6782
6783 if (!this->visitBool(Cond))
6784 return false;
6785
6786 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
6787 return false;
6788
6789 if (!this->jumpFalse(EndLabel, S))
6790 return false;
6791
6792 if (!this->visitStmt(Body))
6793 return false;
6794
6795 if (!CondScope.destroyLocals())
6796 return false;
6797 // } End of loop body.
6798
6799 if (!this->jump(CondLabel, S))
6800 return false;
6801 this->fallthrough(EndLabel);
6802 this->emitLabel(EndLabel);
6803
6804 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
6805}
6806
6807template <class Emitter> bool Compiler<Emitter>::visitDoStmt(const DoStmt *S) {
6808 const Expr *Cond = S->getCond();
6809 const Stmt *Body = S->getBody();
6810
6811 LabelTy StartLabel = this->getLabel();
6812 LabelTy EndLabel = this->getLabel();
6813 LabelTy CondLabel = this->getLabel();
6814 LocalScope<Emitter> WholeLoopScope(this);
6815 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
6816
6817 this->fallthrough(StartLabel);
6818 this->emitLabel(StartLabel);
6819
6820 {
6821 LocalScope<Emitter> CondScope(this);
6822 if (!this->visitStmt(Body))
6823 return false;
6824 this->fallthrough(CondLabel);
6825 this->emitLabel(CondLabel);
6826 if (!this->visitBool(Cond))
6827 return false;
6828
6829 if (!CondScope.destroyLocals())
6830 return false;
6831 }
6832 if (!this->jumpTrue(StartLabel, S))
6833 return false;
6834
6835 this->fallthrough(EndLabel);
6836 this->emitLabel(EndLabel);
6837 return WholeLoopScope.destroyLocals();
6838}
6839
6840template <class Emitter>
6842 // for (Init; Cond; Inc) { Body }
6843 const Stmt *Init = S->getInit();
6844 const Expr *Cond = S->getCond();
6845 const Expr *Inc = S->getInc();
6846 const Stmt *Body = S->getBody();
6847
6848 LabelTy EndLabel = this->getLabel();
6849 LabelTy CondLabel = this->getLabel();
6850 LabelTy IncLabel = this->getLabel();
6851
6852 LocalScope<Emitter> WholeLoopScope(this);
6853 if (Init && !this->visitStmt(Init))
6854 return false;
6855
6856 // Start of the loop body {
6857 this->fallthrough(CondLabel);
6858 this->emitLabel(CondLabel);
6859
6860 LocalScope<Emitter> CondScope(this);
6861 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
6862 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
6863 if (!visitDeclStmt(CondDecl))
6864 return false;
6865 }
6866
6867 if (Cond) {
6868 if (!this->visitBool(Cond))
6869 return false;
6870 if (!this->jumpFalse(EndLabel, S))
6871 return false;
6872 }
6873 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
6874 return false;
6875
6876 if (Body && !this->visitStmt(Body))
6877 return false;
6878
6879 this->fallthrough(IncLabel);
6880 this->emitLabel(IncLabel);
6881 if (Inc && !this->discard(Inc))
6882 return false;
6883
6884 if (!CondScope.destroyLocals())
6885 return false;
6886 if (!this->jump(CondLabel, S))
6887 return false;
6888 // } End of loop body.
6889
6890 this->emitLabel(EndLabel);
6891 // If we jumped out of the loop above, we still need to clean up the condition
6892 // scope.
6893 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
6894}
6895
6896template <class Emitter>
6898 const Stmt *Init = S->getInit();
6899 const Expr *Cond = S->getCond();
6900 const Expr *Inc = S->getInc();
6901 const Stmt *Body = S->getBody();
6902 const Stmt *BeginStmt = S->getBeginStmt();
6903 const Stmt *RangeStmt = S->getRangeStmt();
6904 const Stmt *EndStmt = S->getEndStmt();
6905
6906 LabelTy EndLabel = this->getLabel();
6907 LabelTy CondLabel = this->getLabel();
6908 LabelTy IncLabel = this->getLabel();
6909 LocalScope<Emitter> WholeLoopScope(this);
6910 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
6911
6912 // Emit declarations needed in the loop.
6913 if (Init && !this->visitStmt(Init))
6914 return false;
6915 if (!this->visitStmt(RangeStmt))
6916 return false;
6917 if (!this->visitStmt(BeginStmt))
6918 return false;
6919 if (!this->visitStmt(EndStmt))
6920 return false;
6921
6922 // Now the condition as well as the loop variable assignment.
6923 this->fallthrough(CondLabel);
6924 this->emitLabel(CondLabel);
6925 if (!this->visitBool(Cond))
6926 return false;
6927 if (!this->jumpFalse(EndLabel, S))
6928 return false;
6929
6930 if (!this->visitDeclStmt(S->getLoopVarStmt(), /*EvaluateConditionDecl=*/true))
6931 return false;
6932
6933 // Body.
6934 {
6935 if (!this->visitStmt(Body))
6936 return false;
6937
6938 this->fallthrough(IncLabel);
6939 this->emitLabel(IncLabel);
6940 if (!this->discard(Inc))
6941 return false;
6942 }
6943
6944 if (!this->jump(CondLabel, S))
6945 return false;
6946
6947 this->fallthrough(EndLabel);
6948 this->emitLabel(EndLabel);
6949 return WholeLoopScope.destroyLocals();
6950}
6951
6952template <class Emitter>
6954 if (LabelInfoStack.empty())
6955 return false;
6956
6957 OptLabelTy TargetLabel = std::nullopt;
6958 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
6959 const VariableScope<Emitter> *BreakScope = nullptr;
6960
6961 if (!TargetLoop) {
6962 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
6963 if (LI.BreakLabel) {
6964 TargetLabel = *LI.BreakLabel;
6965 BreakScope = LI.BreakOrContinueScope;
6966 break;
6967 }
6968 }
6969 } else {
6970 for (auto LI : LabelInfoStack) {
6971 if (LI.Name == TargetLoop) {
6972 TargetLabel = *LI.BreakLabel;
6973 BreakScope = LI.BreakOrContinueScope;
6974 break;
6975 }
6976 }
6977 }
6978
6979 // Faulty break statement (e.g. label redefined or named loops disabled).
6980 if (!TargetLabel)
6981 return false;
6982
6983 for (VariableScope<Emitter> *C = this->VarScope; C != BreakScope;
6984 C = C->getParent()) {
6985 if (!C->destroyLocals())
6986 return false;
6987 }
6988
6989 return this->jump(*TargetLabel, S);
6990}
6991
6992template <class Emitter>
6994 if (LabelInfoStack.empty())
6995 return false;
6996
6997 OptLabelTy TargetLabel = std::nullopt;
6998 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
6999 const VariableScope<Emitter> *ContinueScope = nullptr;
7000
7001 if (!TargetLoop) {
7002 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
7003 if (LI.ContinueLabel) {
7004 TargetLabel = *LI.ContinueLabel;
7005 ContinueScope = LI.BreakOrContinueScope;
7006 break;
7007 }
7008 }
7009 } else {
7010 for (auto LI : LabelInfoStack) {
7011 if (LI.Name == TargetLoop) {
7012 TargetLabel = *LI.ContinueLabel;
7013 ContinueScope = LI.BreakOrContinueScope;
7014 break;
7015 }
7016 }
7017 }
7018 assert(TargetLabel);
7019
7020 for (VariableScope<Emitter> *C = VarScope; C != ContinueScope;
7021 C = C->getParent()) {
7022 if (!C->destroyLocals())
7023 return false;
7024 }
7025
7026 return this->jump(*TargetLabel, S);
7027}
7028
7029template <class Emitter>
7031 const Expr *Cond = S->getCond();
7032 if (Cond->containsErrors())
7033 return false;
7034
7035 PrimType CondT = this->classifyPrim(Cond->getType());
7036 LocalScope<Emitter> LS(this);
7037 llvm::SaveAndRestore StmtExprSAR(this->SwitchInStmtExpr, this->InStmtExpr);
7038
7039 LabelTy EndLabel = this->getLabel();
7040 UnsignedOrNone DefaultLabel = std::nullopt;
7041 unsigned CondVar =
7042 this->allocateLocalPrimitive(Cond, CondT, /*IsConst=*/true);
7043
7044 if (const auto *CondInit = S->getInit())
7045 if (!visitStmt(CondInit))
7046 return false;
7047
7048 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
7049 if (!visitDeclStmt(CondDecl))
7050 return false;
7051
7052 // Initialize condition variable.
7053 if (!this->visit(Cond))
7054 return false;
7055 if (!this->emitSetLocal(CondT, CondVar, S))
7056 return false;
7057
7058 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
7059 return false;
7060
7062 // Create labels and comparison ops for all case statements.
7063 for (const SwitchCase *SC = S->getSwitchCaseList(); SC;
7064 SC = SC->getNextSwitchCase()) {
7065 if (const auto *CS = dyn_cast<CaseStmt>(SC)) {
7066 CaseLabels[SC] = this->getLabel();
7067
7068 if (CS->caseStmtIsGNURange()) {
7069 LabelTy EndOfRangeCheck = this->getLabel();
7070 const Expr *Low = CS->getLHS();
7071 const Expr *High = CS->getRHS();
7072 if (Low->isValueDependent() || High->isValueDependent())
7073 return false;
7074
7075 if (!this->emitGetLocal(CondT, CondVar, CS))
7076 return false;
7077 if (!this->visit(Low))
7078 return false;
7079 PrimType LT = this->classifyPrim(Low->getType());
7080 if (!this->emitGE(LT, S))
7081 return false;
7082 if (!this->jumpFalse(EndOfRangeCheck, S))
7083 return false;
7084
7085 if (!this->emitGetLocal(CondT, CondVar, CS))
7086 return false;
7087 if (!this->visit(High))
7088 return false;
7089 PrimType HT = this->classifyPrim(High->getType());
7090 if (!this->emitLE(HT, S))
7091 return false;
7092 if (!this->jumpTrue(CaseLabels[CS], S))
7093 return false;
7094 this->emitLabel(EndOfRangeCheck);
7095 continue;
7096 }
7097
7098 const Expr *Value = CS->getLHS();
7099 if (Value->isValueDependent())
7100 return false;
7101 PrimType ValueT = this->classifyPrim(Value->getType());
7102
7103 // Compare the case statement's value to the switch condition.
7104 if (!this->emitGetLocal(CondT, CondVar, CS))
7105 return false;
7106 if (!this->visit(Value))
7107 return false;
7108
7109 // Compare and jump to the case label.
7110 if (!this->emitEQ(ValueT, S))
7111 return false;
7112 if (!this->jumpTrue(CaseLabels[CS], S))
7113 return false;
7114 } else {
7115 assert(!DefaultLabel);
7116 DefaultLabel = this->getLabel();
7117 }
7118 }
7119
7120 // If none of the conditions above were true, fall through to the default
7121 // statement or jump after the switch statement.
7122 if (DefaultLabel) {
7123 if (!this->jump(*DefaultLabel, S))
7124 return false;
7125 } else {
7126 if (!this->jump(EndLabel, S))
7127 return false;
7128 }
7129
7130 SwitchScope<Emitter> SS(this, S, std::move(CaseLabels), EndLabel,
7131 DefaultLabel);
7132 if (!this->visitStmt(S->getBody()))
7133 return false;
7134 this->fallthrough(EndLabel);
7135 this->emitLabel(EndLabel);
7136
7137 return LS.destroyLocals();
7138}
7139
7140template <class Emitter>
7142 this->fallthrough(CaseLabels[S]);
7143 this->emitLabel(CaseLabels[S]);
7144
7145 // We can't jump from an outer switch statement to a case label
7146 // that's inside a StmtExpr.
7147 if (this->InStmtExpr && !this->SwitchInStmtExpr)
7148 return this->emitUnsupported(S);
7149
7150 return this->visitStmt(S->getSubStmt());
7151}
7152
7153template <class Emitter>
7155 if (LabelInfoStack.empty())
7156 return false;
7157
7158 LabelTy DefaultLabel;
7159 for (const LabelInfo &LI : llvm::reverse(LabelInfoStack)) {
7160 if (LI.DefaultLabel) {
7161 DefaultLabel = *LI.DefaultLabel;
7162 break;
7163 }
7164 }
7165
7166 this->emitLabel(DefaultLabel);
7167 return this->visitStmt(S->getSubStmt());
7168}
7169
7170template <class Emitter>
7172 const Stmt *SubStmt = S->getSubStmt();
7173
7174 bool IsMSVCConstexprAttr = isa<ReturnStmt>(SubStmt) &&
7176
7177 if (IsMSVCConstexprAttr && !this->emitPushMSVCCE(S))
7178 return false;
7179
7180 if (this->Ctx.getLangOpts().CXXAssumptions &&
7181 !this->Ctx.getLangOpts().MSVCCompat) {
7182 for (const Attr *A : S->getAttrs()) {
7183 auto *AA = dyn_cast<CXXAssumeAttr>(A);
7184 if (!AA)
7185 continue;
7186
7187 assert(isa<NullStmt>(SubStmt));
7188
7189 const Expr *Assumption = AA->getAssumption();
7190 if (Assumption->isValueDependent())
7191 return false;
7192
7193 if (Assumption->HasSideEffects(this->Ctx.getASTContext()))
7194 continue;
7195
7196 // Evaluate assumption.
7197 if (!this->visitBool(Assumption))
7198 return false;
7199
7200 if (!this->emitAssume(Assumption))
7201 return false;
7202 }
7203 }
7204
7205 // Ignore other attributes.
7206 if (!this->visitStmt(SubStmt))
7207 return false;
7208
7209 if (IsMSVCConstexprAttr)
7210 return this->emitPopMSVCCE(S);
7211 return true;
7212}
7213
7214template <class Emitter>
7216 // Ignore all handlers.
7217 return this->visitStmt(S->getTryBlock());
7218}
7219
7220/// template for (auto x : {1, 2}) {}
7221///
7222/// This is not a loop from an AST perspective at all since it has already
7223/// been instantiated to a list of compound statements.
7224///
7225/// Since we can have control flow in those compound statements, we need to
7226/// handle it mostly like a loop though.
7227template <class Emitter>
7230 LocalScope<Emitter> WholeLoopScope(this, ScopeKind::Block);
7231
7232 for (const Stmt *PreambleStmt : S->getPreambleStmts()) {
7233 if (!this->visitDeclStmt(cast<DeclStmt>(PreambleStmt), true))
7234 return false;
7235 }
7236
7237 LabelTy EndLabel = this->getLabel();
7238 for (const Stmt *Instantiation : S->getInstantiations()) {
7239 LabelTy ContinueLabel = this->getLabel();
7240 LoopScope<Emitter> LS(this, S, EndLabel, ContinueLabel);
7241
7242 if (!this->visitStmt(Instantiation))
7243 return false;
7244 this->emitLabel(ContinueLabel);
7245 }
7246
7247 this->emitLabel(EndLabel);
7248
7249 return WholeLoopScope.destroyLocals();
7250}
7251
7252template <class Emitter>
7253bool Compiler<Emitter>::emitLambdaStaticInvokerBody(const CXXMethodDecl *MD) {
7254 assert(MD->isLambdaStaticInvoker());
7255 assert(MD->hasBody());
7256 assert(cast<CompoundStmt>(MD->getBody())->body_empty());
7257
7258 const CXXRecordDecl *ClosureClass = MD->getParent();
7259 const FunctionDecl *LambdaCallOp;
7260 assert(ClosureClass->captures().empty());
7261 if (ClosureClass->isGenericLambda()) {
7262 LambdaCallOp = ClosureClass->getLambdaCallOperator();
7263 assert(MD->isFunctionTemplateSpecialization() &&
7264 "A generic lambda's static-invoker function must be a "
7265 "template specialization");
7267 FunctionTemplateDecl *CallOpTemplate =
7268 LambdaCallOp->getDescribedFunctionTemplate();
7269 void *InsertPos = nullptr;
7270 const FunctionDecl *CorrespondingCallOpSpecialization =
7271 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
7272 assert(CorrespondingCallOpSpecialization);
7273 LambdaCallOp = CorrespondingCallOpSpecialization;
7274 } else {
7275 LambdaCallOp = ClosureClass->getLambdaCallOperator();
7276 }
7277 assert(ClosureClass->captures().empty());
7278 const Function *Func = this->getFunction(LambdaCallOp);
7279 if (!Func)
7280 return false;
7281 assert(Func->hasThisPointer());
7282 assert(Func->getNumParams() == (MD->getNumParams() + 1 + Func->hasRVO()));
7283
7284 if (Func->hasRVO()) {
7285 if (!this->emitRVOPtr(MD))
7286 return false;
7287 }
7288
7289 // The lambda call operator needs an instance pointer, but we don't have
7290 // one here, and we don't need one either because the lambda cannot have
7291 // any captures, as verified above. Emit a null pointer. This is then
7292 // special-cased when interpreting to not emit any misleading diagnostics.
7293 if (!this->emitNullPtr(0, nullptr, MD))
7294 return false;
7295
7296 // Forward all arguments from the static invoker to the lambda call operator.
7297 for (const ParmVarDecl *PVD : MD->parameters()) {
7298 auto It = this->Params.find(PVD);
7299 assert(It != this->Params.end());
7300
7301 // We do the lvalue-to-rvalue conversion manually here, so no need
7302 // to care about references.
7303 PrimType ParamType = this->classify(PVD->getType()).value_or(PT_Ptr);
7304 if (!this->emitGetParam(ParamType, It->second.Index, MD))
7305 return false;
7306 }
7307
7308 if (!this->emitCall(Func, 0, LambdaCallOp))
7309 return false;
7310
7311 this->emitCleanup();
7312 if (ReturnType)
7313 return this->emitRet(*ReturnType, MD);
7314
7315 // Nothing to do, since we emitted the RVO pointer above.
7316 return this->emitRetVoid(MD);
7317}
7318
7319template <class Emitter>
7320bool Compiler<Emitter>::checkLiteralType(const Expr *E) {
7321 if (Ctx.getLangOpts().CPlusPlus23)
7322 return true;
7323
7324 if (!E->isPRValue() || E->getType()->isLiteralType(Ctx.getASTContext()))
7325 return true;
7326
7327 return this->emitCheckLiteralType(E->getType().getTypePtr(), E);
7328}
7329
7331 const Expr *InitExpr = Init->getInit();
7332
7333 if (!Init->isWritten() && !Init->isInClassMemberInitializer() &&
7334 !isa<CXXConstructExpr>(InitExpr))
7335 return true;
7336
7337 if (const auto *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
7338 const CXXConstructorDecl *Ctor = CE->getConstructor();
7339 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
7340 Ctor->isTrivial())
7341 return true;
7342 }
7343
7344 return false;
7345}
7346
7347template <class Emitter>
7348bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
7349 assert(!ReturnType);
7350
7351 // Only start the lifetime of the instance pointer.
7352 if (!this->emitStartThisLifetime1(Ctor))
7353 return false;
7354
7355 auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset,
7356 const Expr *InitExpr,
7357 bool Activate = false) -> bool {
7358 // We don't know what to do with these, so just return false.
7359 if (InitExpr->getType().isNull())
7360 return false;
7361
7362 if (OptPrimType T = this->classify(InitExpr)) {
7363 if (Activate && !this->emitActivateThisField(FieldOffset, InitExpr))
7364 return false;
7365
7366 if (!this->visit(InitExpr))
7367 return false;
7368
7369 if (F->isBitField())
7370 return this->emitInitThisBitField(*T, FieldOffset, F->bitWidth(),
7371 InitExpr);
7372 return this->emitInitThisField(*T, FieldOffset, InitExpr);
7373 }
7374 // Non-primitive case. Get a pointer to the field-to-initialize
7375 // on the stack and call visitInitialzer() for it.
7376 InitLinkScope<Emitter> FieldScope(this, InitLink::Field(F->Offset));
7377 if (!this->emitGetPtrThisField(FieldOffset, InitExpr))
7378 return false;
7379
7380 if (Activate && !this->emitActivate(InitExpr))
7381 return false;
7382
7383 return this->visitInitializerPop(InitExpr);
7384 };
7385
7386 const RecordDecl *RD = Ctor->getParent();
7387 const Record *R = this->getRecord(RD);
7388 if (!R)
7389 return false;
7390 bool IsUnion = R->isUnion();
7391
7392 // Default union copy and move ctors are special.
7393 if (IsUnion && Ctor->isCopyOrMoveConstructor() && Ctor->isDefaulted()) {
7395
7396 // No special case for NumFields == 0 here, so the Memcpy op
7397 // below also does its checks in those cases.
7398
7399 assert(cast<CompoundStmt>(Ctor->getBody())->body_empty());
7400 if (!this->emitThis(Ctor))
7401 return false;
7402
7403 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, Ctor))
7404 return false;
7405
7406 return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) &&
7407 this->emitRetVoid(Ctor);
7408 }
7409
7410 unsigned FieldInits = 0;
7412 // First, initialize virtual bases if the records has them.
7413 if (R->getNumVirtualBases() > 0) {
7414 if (!this->emitThis(Ctor))
7415 return false;
7416 LabelTy AfterVirtBasesLabel = this->getLabel();
7417
7418 // If the instance pointer is a base class, skip the virtual bases.
7419 if (!this->emitIsBaseClass({}))
7420 return false;
7421 if (!this->jumpTrue(AfterVirtBasesLabel, {}))
7422 return false;
7423
7424 for (const auto *Init : Ctor->inits()) {
7425 if (const Type *Base = Init->getBaseClass();
7426 Base && Init->isBaseVirtual()) {
7427 const auto *BaseDecl = Base->getAsCXXRecordDecl();
7428 assert(BaseDecl);
7429 assert(R->getVirtualBase(BaseDecl));
7430 if (!this->emitGetPtrThisVirtBase(BaseDecl, Ctor))
7431 return false;
7432 if (!this->visitInitializerPop(Init->getInit()))
7433 return false;
7434 }
7435 }
7436
7437 this->fallthrough(AfterVirtBasesLabel);
7438 this->emitLabel(AfterVirtBasesLabel);
7439
7440 if (!this->emitPopPtr(Ctor))
7441 return false;
7442 }
7443
7444 for (const auto *Init : Ctor->inits()) {
7445 // Scope needed for the initializers.
7446 LocalScope<Emitter> Scope(this, ScopeKind::FullExpression);
7447
7448 const Expr *InitExpr = Init->getInit();
7449 if (const FieldDecl *Member = Init->getMember()) {
7450 const Record::Field *F = R->getField(Member);
7451
7454 if (!emitFieldInitializer(F, F->Offset, InitExpr, IsUnion))
7455 return false;
7456 ++FieldInits;
7457 } else if (const Type *Base = Init->getBaseClass()) {
7458 const auto *BaseDecl = Base->getAsCXXRecordDecl();
7459 assert(BaseDecl);
7460
7461 if (Init->isBaseVirtual()) {
7462 // See above.
7463 continue;
7464 } else {
7465 // Base class initializer.
7466 // Get This Base and call initializer on it.
7467 const Record::Base *B = R->getBase(BaseDecl);
7468 assert(B);
7469 if (!this->emitGetPtrThisBase(B->Offset, InitExpr))
7470 return false;
7471 }
7472
7473 if (!this->visitInitializerPop(InitExpr))
7474 return false;
7475 } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) {
7478 unsigned ChainSize = IFD->getChainingSize();
7479 assert(ChainSize >= 2);
7480
7481 unsigned NestedFieldOffset = 0;
7482 const Record::Field *NestedField = nullptr;
7483 for (unsigned I = 0; I != ChainSize; ++I) {
7484 const auto *FD = cast<FieldDecl>(IFD->chain()[I]);
7485 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7486 assert(FieldRecord);
7487
7488 NestedField = FieldRecord->getField(FD);
7489 assert(NestedField);
7490 IsUnion = IsUnion || FieldRecord->isUnion();
7491
7492 NestedFieldOffset += NestedField->Offset;
7493
7494 // Add a new InitChainLink for the record, but not for the final field.
7495 if (I != ChainSize - 1)
7496 InitStack.push_back(InitLink::Field(NestedField->Offset));
7497 }
7498 assert(NestedField);
7499
7501 if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr,
7502 IsUnion))
7503 return false;
7504
7505 // Mark all chain links as initialized.
7506 unsigned InitFieldOffset = 0;
7507 for (const NamedDecl *ND : IFD->chain().drop_back()) {
7508 const auto *FD = cast<FieldDecl>(ND);
7509 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7510 assert(FieldRecord);
7511 NestedField = FieldRecord->getField(FD);
7512 InitFieldOffset += NestedField->Offset;
7513 assert(NestedField);
7514 if (!this->emitGetPtrThisField(InitFieldOffset, InitExpr))
7515 return false;
7516 if (!this->emitFinishInitPop(InitExpr))
7517 return false;
7518 }
7519
7520 InitStack.pop_back_n(ChainSize - 1);
7521
7522 } else {
7523 assert(Init->isDelegatingInitializer());
7524 if (!this->emitThis(InitExpr))
7525 return false;
7526 if (!this->visitInitializerPop(Init->getInit()))
7527 return false;
7528 }
7529
7530 if (!Scope.destroyLocals())
7531 return false;
7532 }
7533
7534 if (FieldInits != R->getNumFields()) {
7535 assert(FieldInits < R->getNumFields());
7536 // Start the lifetime of all members.
7537 if (!this->emitStartThisLifetime(Ctor))
7538 return false;
7539 }
7540
7541 if (const Stmt *Body = Ctor->getBody()) {
7542 // Only emit the CtorCheck op for non-empty CompoundStmt bodies.
7543 // For non-CompoundStmts, always assume they are non-empty and emit it.
7544 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
7545 if (!CS->body_empty() && !this->emitCtorCheck(SourceInfo{}))
7546 return false;
7547 } else {
7548 if (!this->emitCtorCheck(SourceInfo{}))
7549 return false;
7550 }
7551
7552 if (!visitStmt(Body))
7553 return false;
7554 }
7555
7556 return this->emitRetVoid(SourceInfo{});
7557}
7558
7559template <class Emitter>
7560bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) {
7561 const RecordDecl *RD = Dtor->getParent();
7562 const Record *R = this->getRecord(RD);
7563 if (!R)
7564 return false;
7565
7566 if (!Dtor->isTrivial() && Dtor->getBody()) {
7567 if (!this->visitStmt(Dtor->getBody()))
7568 return false;
7569 }
7570
7571 if (!this->emitThis(Dtor))
7572 return false;
7573
7574 if (!this->emitCheckDestruction(Dtor))
7575 return false;
7576
7577 assert(R);
7578 if (!R->isUnion()) {
7579
7581 // First, destroy all fields.
7582 for (const Record::Field &Field : llvm::reverse(R->fields())) {
7583 const Descriptor *D = Field.Desc;
7584 if (D->hasTrivialDtor())
7585 continue;
7586 if (!this->emitGetPtrField(Field.Offset, SourceInfo{}))
7587 return false;
7588 if (!this->emitDestructionPop(D, SourceInfo{}))
7589 return false;
7590 }
7591 }
7592
7593 for (const Record::Base &Base : llvm::reverse(R->bases())) {
7594 if (Base.R->hasTrivialDtor())
7595 continue;
7596 if (!this->emitGetPtrBase(Base.Offset, SourceInfo{}))
7597 return false;
7598 if (!this->emitRecordDestructionPop(Base.R, {}))
7599 return false;
7600 }
7601
7602 if (R->getNumVirtualBases() > 0) {
7603 LabelTy EndLabel = this->getLabel();
7604 // If this is a base class, skip the virtual bases.
7605 if (!this->emitIsBaseClass({}))
7606 return false;
7607 if (!this->jumpTrue(EndLabel, {}))
7608 return false;
7609
7610 for (const Record::Base &Base : llvm::reverse(R->virtual_bases())) {
7611 if (Base.R->hasTrivialDtor())
7612 continue;
7613 if (!this->emitGetPtrVirtBase(cast<CXXRecordDecl>(Base.R->getDecl()),
7614 SourceInfo{}))
7615 return false;
7616 if (!this->emitRecordDestructionPop(Base.R, {}))
7617 return false;
7618 }
7619
7620 this->fallthrough(EndLabel);
7621 this->emitLabel(EndLabel);
7622 }
7623
7624 if (!this->emitMarkDestroyed(Dtor))
7625 return false;
7626
7627 return this->emitPopPtr(Dtor) && this->emitRetVoid(Dtor);
7628}
7629
7630template <class Emitter>
7631bool Compiler<Emitter>::compileUnionAssignmentOperator(
7632 const CXXMethodDecl *MD) {
7633 if (!this->emitThis(MD))
7634 return false;
7635
7636 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, MD))
7637 return false;
7638
7639 return this->emitMemcpy(MD) && this->emitRet(PT_Ptr, MD);
7640}
7641
7642template <class Emitter>
7644 if (F->getReturnType()->isDependentType())
7645 return false;
7646
7647 // Classify the return type.
7648 ReturnType = this->classify(F->getReturnType());
7649
7650 this->CompilingFunction = F;
7651
7652 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F))
7653 return this->compileConstructor(Ctor);
7654 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F))
7655 return this->compileDestructor(Dtor);
7656
7657 // Emit custom code if this is a lambda static invoker.
7658 if (const auto *MD = dyn_cast<CXXMethodDecl>(F)) {
7659 const RecordDecl *RD = MD->getParent();
7660
7661 if (RD->isUnion() &&
7663 return this->compileUnionAssignmentOperator(MD);
7664
7665 if (MD->isLambdaStaticInvoker())
7666 return this->emitLambdaStaticInvokerBody(MD);
7667 }
7668
7669 // Regular functions.
7670 if (const auto *Body = F->getBody())
7671 if (!visitStmt(Body))
7672 return false;
7673
7674 // Emit a guard return to protect against a code path missing one.
7675 if (F->getReturnType()->isVoidType())
7676 return this->emitRetVoid(SourceInfo{});
7677 return this->emitNoRet(SourceInfo{});
7678}
7679
7680static uint32_t getBitWidth(const Expr *E) {
7681 assert(E->refersToBitField());
7682 const auto *ME = cast<MemberExpr>(E);
7683 const auto *FD = cast<FieldDecl>(ME->getMemberDecl());
7684 return FD->getBitWidthValue();
7685}
7686
7687template <class Emitter>
7689 if (E->containsErrors())
7690 return false;
7691
7692 const Expr *SubExpr = E->getSubExpr();
7693 if (SubExpr->getType()->isAnyComplexType())
7694 return this->VisitComplexUnaryOperator(E);
7695 if (SubExpr->getType()->isVectorType())
7696 return this->VisitVectorUnaryOperator(E);
7697 if (SubExpr->getType()->isFixedPointType())
7698 return this->VisitFixedPointUnaryOperator(E);
7699 OptPrimType T = classify(SubExpr->getType());
7700
7701 switch (E->getOpcode()) {
7702 case UO_PostInc: { // x++
7703 if (!Ctx.getLangOpts().CPlusPlus14)
7704 return this->emitInvalid(E);
7705 if (!T)
7706 return this->emitError(E);
7707
7708 if (!this->visit(SubExpr))
7709 return false;
7710
7711 if (T == PT_Ptr) {
7712 if (!this->emitIncPtr(E))
7713 return false;
7714
7715 return DiscardResult ? this->emitPopPtr(E) : true;
7716 }
7717
7718 if (T == PT_Float)
7719 return DiscardResult ? this->emitIncfPop(getFPOptions(E), E)
7720 : this->emitIncf(getFPOptions(E), E);
7721
7722 if (SubExpr->refersToBitField())
7723 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
7724 getBitWidth(SubExpr), E)
7725 : this->emitIncBitfield(*T, E->canOverflow(),
7726 getBitWidth(SubExpr), E);
7727
7728 return DiscardResult ? this->emitIncPop(*T, E->canOverflow(), E)
7729 : this->emitInc(*T, E->canOverflow(), E);
7730 }
7731 case UO_PostDec: { // x--
7732 if (!Ctx.getLangOpts().CPlusPlus14)
7733 return this->emitInvalid(E);
7734 if (!T)
7735 return this->emitError(E);
7736
7737 if (!this->visit(SubExpr))
7738 return false;
7739
7740 if (T == PT_Ptr) {
7741 if (!this->emitDecPtr(E))
7742 return false;
7743
7744 return DiscardResult ? this->emitPopPtr(E) : true;
7745 }
7746
7747 if (T == PT_Float)
7748 return DiscardResult ? this->emitDecfPop(getFPOptions(E), E)
7749 : this->emitDecf(getFPOptions(E), E);
7750
7751 if (SubExpr->refersToBitField()) {
7752 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
7753 getBitWidth(SubExpr), E)
7754 : this->emitDecBitfield(*T, E->canOverflow(),
7755 getBitWidth(SubExpr), E);
7756 }
7757
7758 return DiscardResult ? this->emitDecPop(*T, E->canOverflow(), E)
7759 : this->emitDec(*T, E->canOverflow(), E);
7760 }
7761 case UO_PreInc: { // ++x
7762 if (!Ctx.getLangOpts().CPlusPlus14)
7763 return this->emitInvalid(E);
7764 if (!T)
7765 return this->emitError(E);
7766
7767 if (!this->visit(SubExpr))
7768 return false;
7769
7770 if (T == PT_Ptr) {
7771 if (!this->emitLoadPtr(E))
7772 return false;
7773 if (!this->emitConstUint8(1, E))
7774 return false;
7775 if (!this->emitAddOffsetUint8(E))
7776 return false;
7777 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
7778 }
7779
7780 // Post-inc and pre-inc are the same if the value is to be discarded.
7781 if (DiscardResult) {
7782 if (T == PT_Float)
7783 return this->emitIncfPop(getFPOptions(E), E);
7784 if (SubExpr->refersToBitField())
7785 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
7786 getBitWidth(SubExpr), E)
7787 : this->emitIncBitfield(*T, E->canOverflow(),
7788 getBitWidth(SubExpr), E);
7789 return this->emitIncPop(*T, E->canOverflow(), E);
7790 }
7791
7792 if (T == PT_Float) {
7793 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
7794 if (!this->emitLoadFloat(E))
7795 return false;
7796 APFloat F(TargetSemantics, 1);
7797 if (!this->emitFloat(F, E))
7798 return false;
7799
7800 if (!this->emitAddf(getFPOptions(E), E))
7801 return false;
7802 if (!this->emitStoreFloat(E))
7803 return false;
7804 } else if (SubExpr->refersToBitField()) {
7805 assert(isIntegerOrBoolType(*T));
7806 if (!this->emitPreIncBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
7807 E))
7808 return false;
7809 } else {
7810 assert(isIntegerOrBoolType(*T));
7811 if (!this->emitPreInc(*T, E->canOverflow(), E))
7812 return false;
7813 }
7814 return E->isGLValue() || this->emitLoadPop(*T, E);
7815 }
7816 case UO_PreDec: { // --x
7817 if (!Ctx.getLangOpts().CPlusPlus14)
7818 return this->emitInvalid(E);
7819 if (!T)
7820 return this->emitError(E);
7821
7822 if (!this->visit(SubExpr))
7823 return false;
7824
7825 if (T == PT_Ptr) {
7826 if (!this->emitLoadPtr(E))
7827 return false;
7828 if (!this->emitConstUint8(1, E))
7829 return false;
7830 if (!this->emitSubOffsetUint8(E))
7831 return false;
7832 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
7833 }
7834
7835 // Post-dec and pre-dec are the same if the value is to be discarded.
7836 if (DiscardResult) {
7837 if (T == PT_Float)
7838 return this->emitDecfPop(getFPOptions(E), E);
7839 if (SubExpr->refersToBitField())
7840 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
7841 getBitWidth(SubExpr), E)
7842 : this->emitDecBitfield(*T, E->canOverflow(),
7843 getBitWidth(SubExpr), E);
7844 return this->emitDecPop(*T, E->canOverflow(), E);
7845 }
7846
7847 if (T == PT_Float) {
7848 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
7849 if (!this->emitLoadFloat(E))
7850 return false;
7851 APFloat F(TargetSemantics, 1);
7852 if (!this->emitFloat(F, E))
7853 return false;
7854
7855 if (!this->emitSubf(getFPOptions(E), E))
7856 return false;
7857 if (!this->emitStoreFloat(E))
7858 return false;
7859 } else if (SubExpr->refersToBitField()) {
7860 assert(isIntegerOrBoolType(*T));
7861 if (!this->emitPreDecBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
7862 E))
7863 return false;
7864 } else {
7865 assert(isIntegerOrBoolType(*T));
7866 if (!this->emitPreDec(*T, E->canOverflow(), E))
7867 return false;
7868 }
7869 return E->isGLValue() || this->emitLoadPop(*T, E);
7870 }
7871 case UO_LNot: // !x
7872 if (!T)
7873 return this->emitError(E);
7874
7875 if (DiscardResult)
7876 return this->discard(SubExpr);
7877
7878 if (!this->visitBool(SubExpr))
7879 return false;
7880
7881 if (!this->emitInv(E))
7882 return false;
7883
7884 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
7885 return this->emitCast(PT_Bool, ET, E);
7886 return true;
7887 case UO_Minus: // -x
7888 if (!T)
7889 return this->emitError(E);
7890
7891 if (!this->visit(SubExpr))
7892 return false;
7893 return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E);
7894 case UO_Plus: // +x
7895 if (!T)
7896 return this->emitError(E);
7897
7898 if (!this->visit(SubExpr)) // noop
7899 return false;
7900 return DiscardResult ? this->emitPop(*T, E) : true;
7901 case UO_AddrOf: // &x
7902 if (E->getType()->isMemberPointerType()) {
7903 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7904 // member can be formed.
7905 if (DiscardResult)
7906 return true;
7907 return this->emitGetMemberPtr(cast<DeclRefExpr>(SubExpr)->getDecl(), E);
7908 }
7909 // [C11 6.5.3.2p3]: if the operand of '&' is the result of a unary '*'
7910 // operator, neither operator is evaluated and the result is as if both
7911 // were omitted. So '&*q' is just 'q' with no dereference; delegate to the
7912 // pointer operand directly instead of to the '*' (which would emit a null
7913 // check), so that e.g. '&*(int *)0' is not rejected.
7914 if (!Ctx.getLangOpts().CPlusPlus) {
7915 const Expr *Sub = SubExpr->IgnoreParens();
7916 if (const auto *Deref = dyn_cast<UnaryOperator>(Sub);
7917 Deref && Deref->getOpcode() == UO_Deref)
7918 return this->delegate(Deref->getSubExpr());
7919 }
7920 // We should already have a pointer when we get here.
7921 return this->delegate(SubExpr);
7922 case UO_Deref: // *x
7923 if (DiscardResult)
7924 return this->discard(SubExpr);
7925
7926 if (!this->visit(SubExpr))
7927 return false;
7928
7929 if (!SubExpr->getType()->isFunctionPointerType() && !this->emitCheckNull(E))
7930 return false;
7931
7932 if (classifyPrim(SubExpr) == PT_Ptr)
7933 return this->emitNarrowPtr(E);
7934 return true;
7935
7936 case UO_Not: // ~x
7937 if (!T)
7938 return this->emitError(E);
7939
7940 if (!this->visit(SubExpr))
7941 return false;
7942 return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
7943 case UO_Real: // __real x
7944 if (!T)
7945 return false;
7946 return this->delegate(SubExpr);
7947 case UO_Imag: { // __imag x
7948 if (!T)
7949 return false;
7950 if (!this->discard(SubExpr))
7951 return false;
7952 return DiscardResult
7953 ? true
7954 : this->visitZeroInitializer(*T, SubExpr->getType(), SubExpr);
7955 }
7956 case UO_Extension:
7957 return this->delegate(SubExpr);
7958 case UO_Coawait:
7959 assert(false && "Unhandled opcode");
7960 }
7961
7962 return false;
7963}
7964
7965template <class Emitter>
7967 const Expr *SubExpr = E->getSubExpr();
7968 assert(SubExpr->getType()->isAnyComplexType());
7969
7970 if (DiscardResult)
7971 return this->discard(SubExpr);
7972
7973 OptPrimType ResT = classify(E);
7974 auto prepareResult = [=]() -> bool {
7975 if (!ResT && !Initializing) {
7976 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
7977 if (!LocalIndex)
7978 return false;
7979 return this->emitGetPtrLocal(*LocalIndex, E);
7980 }
7981
7982 return true;
7983 };
7984
7985 // The offset of the temporary, if we created one.
7986 unsigned SubExprOffset = ~0u;
7987 auto createTemp = [=, &SubExprOffset]() -> bool {
7988 SubExprOffset =
7989 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
7990 if (!this->visit(SubExpr))
7991 return false;
7992 return this->emitSetLocal(PT_Ptr, SubExprOffset, E);
7993 };
7994
7995 PrimType ElemT = classifyComplexElementType(SubExpr->getType());
7996 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
7997 if (!this->emitGetLocal(PT_Ptr, Offset, E))
7998 return false;
7999 return this->emitArrayElemPop(ElemT, Index, E);
8000 };
8001
8002 switch (E->getOpcode()) {
8003 case UO_Minus: // -x
8004 if (!prepareResult())
8005 return false;
8006 if (!createTemp())
8007 return false;
8008 for (unsigned I = 0; I != 2; ++I) {
8009 if (!getElem(SubExprOffset, I))
8010 return false;
8011 if (!this->emitNeg(ElemT, E))
8012 return false;
8013 if (!this->emitInitElem(ElemT, I, E))
8014 return false;
8015 }
8016 break;
8017
8018 case UO_Plus: // +x
8019 case UO_AddrOf: // &x
8020 case UO_Deref: // *x
8021 return this->delegate(SubExpr);
8022
8023 case UO_LNot:
8024 if (!this->visit(SubExpr))
8025 return false;
8026 if (!this->emitComplexBoolCast(SubExpr))
8027 return false;
8028 if (!this->emitInv(E))
8029 return false;
8030 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
8031 return this->emitCast(PT_Bool, ET, E);
8032 return true;
8033
8034 case UO_Real:
8035 return this->emitComplexReal(SubExpr);
8036
8037 case UO_Imag:
8038 if (!this->visit(SubExpr))
8039 return false;
8040
8041 if (SubExpr->isLValue()) {
8042 if (!this->emitConstUint8(1, E))
8043 return false;
8044 return this->emitArrayElemPtrPopUint8(E);
8045 }
8046
8047 // Since our _Complex implementation does not map to a primitive type,
8048 // we sometimes have to do the lvalue-to-rvalue conversion here manually.
8049 return this->emitArrayElemPop(classifyPrim(E->getType()), 1, E);
8050
8051 case UO_Not: // ~x
8052 if (!this->delegate(SubExpr))
8053 return false;
8054 // Negate the imaginary component.
8055 if (!this->emitArrayElem(ElemT, 1, E))
8056 return false;
8057 if (!this->emitNeg(ElemT, E))
8058 return false;
8059 if (!this->emitInitElem(ElemT, 1, E))
8060 return false;
8061 return DiscardResult ? this->emitPopPtr(E) : true;
8062
8063 case UO_Extension:
8064 return this->delegate(SubExpr);
8065
8066 default:
8067 return this->emitInvalid(E);
8068 }
8069
8070 return true;
8071}
8072
8073template <class Emitter>
8075 const Expr *SubExpr = E->getSubExpr();
8076 assert(SubExpr->getType()->isVectorType());
8077
8078 if (DiscardResult)
8079 return this->discard(SubExpr);
8080
8081 auto UnaryOp = E->getOpcode();
8082 if (UnaryOp == UO_Extension)
8083 return this->delegate(SubExpr);
8084
8085 if (UnaryOp != UO_Plus && UnaryOp != UO_Minus && UnaryOp != UO_LNot &&
8086 UnaryOp != UO_Not && UnaryOp != UO_AddrOf)
8087 return this->emitInvalid(E);
8088
8089 // Nothing to do here.
8090 if (UnaryOp == UO_Plus || UnaryOp == UO_AddrOf)
8091 return this->delegate(SubExpr);
8092
8093 if (!Initializing) {
8094 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
8095 if (!LocalIndex)
8096 return false;
8097 if (!this->emitGetPtrLocal(*LocalIndex, E))
8098 return false;
8099 }
8100
8101 // The offset of the temporary, if we created one.
8102 unsigned SubExprOffset =
8103 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
8104 if (!this->visit(SubExpr))
8105 return false;
8106 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E))
8107 return false;
8108
8109 const auto *VecTy = SubExpr->getType()->getAs<VectorType>();
8110 PrimType ElemT = classifyVectorElementType(SubExpr->getType());
8111 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
8112 if (!this->emitGetLocal(PT_Ptr, Offset, E))
8113 return false;
8114 return this->emitArrayElemPop(ElemT, Index, E);
8115 };
8116
8117 switch (UnaryOp) {
8118 case UO_Minus:
8119 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8120 if (!getElem(SubExprOffset, I))
8121 return false;
8122 if (!this->emitNeg(ElemT, E))
8123 return false;
8124 if (!this->emitInitElem(ElemT, I, E))
8125 return false;
8126 }
8127 break;
8128 case UO_LNot: { // !x
8129 // In C++, the logic operators !, &&, || are available for vectors. !v is
8130 // equivalent to v == 0.
8131 //
8132 // The result of the comparison is a vector of the same width and number of
8133 // elements as the comparison operands with a signed integral element type.
8134 //
8135 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
8136 QualType ResultVecTy = E->getType();
8137 PrimType ResultVecElemT =
8138 classifyPrim(ResultVecTy->getAs<VectorType>()->getElementType());
8139 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8140 if (!getElem(SubExprOffset, I))
8141 return false;
8142 // operator ! on vectors returns -1 for 'truth', so negate it.
8143 if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
8144 return false;
8145 if (!this->emitInv(E))
8146 return false;
8147 if (!this->emitPrimCast(PT_Bool, ElemT, VecTy->getElementType(), E))
8148 return false;
8149 if (!this->emitNeg(ElemT, E))
8150 return false;
8151 if (ElemT != ResultVecElemT &&
8152 !this->emitPrimCast(ElemT, ResultVecElemT, ResultVecTy, E))
8153 return false;
8154 if (!this->emitInitElem(ResultVecElemT, I, E))
8155 return false;
8156 }
8157 break;
8158 }
8159 case UO_Not: // ~x
8160 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
8161 if (!getElem(SubExprOffset, I))
8162 return false;
8163 if (ElemT == PT_Bool) {
8164 if (!this->emitInv(E))
8165 return false;
8166 } else {
8167 if (!this->emitComp(ElemT, E))
8168 return false;
8169 }
8170 if (!this->emitInitElem(ElemT, I, E))
8171 return false;
8172 }
8173 break;
8174 default:
8175 llvm_unreachable("Unsupported unary operators should be handled up front");
8176 }
8177 return true;
8178}
8179
8180template <class Emitter>
8182 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
8183 if (DiscardResult)
8184 return true;
8185 return this->emitConst(ECD->getInitVal(), E);
8186 }
8187 if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) {
8188 if (DiscardResult)
8189 return true;
8190 const Function *F = getFunction(FuncDecl);
8191 return F && this->emitGetFnPtr(F, E);
8192 }
8193 if (const auto *TPOD = dyn_cast<TemplateParamObjectDecl>(D)) {
8194 TPOD = TPOD->getFirstDecl();
8195 if (DiscardResult)
8196 return true;
8197 if (UnsignedOrNone GlobalIndex = P.getGlobal(TPOD))
8198 return this->emitGetPtrGlobal(*GlobalIndex, E);
8199
8200 if (UnsignedOrNone Index = P.getOrCreateGlobal(TPOD)) {
8201 if (OptPrimType T = classify(TPOD->getType())) {
8202 if (!this->visitAPValue(TPOD->getValue(), *T, E))
8203 return false;
8204 return this->emitInitGlobal(*T, *Index, E);
8205 }
8206
8207 if (!this->emitGetPtrGlobal(*Index, E))
8208 return false;
8209 if (!this->visitAPValueInitializer(TPOD->getValue(), E, TPOD->getType()))
8210 return false;
8211 return this->emitFinishInit(E);
8212 }
8213 return false;
8214 }
8215
8216 // References are implemented via pointers, so when we see a DeclRefExpr
8217 // pointing to a reference, we need to get its value directly (i.e. the
8218 // pointer to the actual value) instead of a pointer to the pointer to the
8219 // value.
8220 QualType DeclType = D->getType();
8221 bool IsReference = DeclType->isReferenceType();
8222
8223 auto maybePopPtr = [&]() -> bool {
8224 if (DiscardResult)
8225 return this->emitPopPtr(E);
8226 return true;
8227 };
8228
8229 // Function parameters.
8230 // Note that it's important to check them first since we might have a local
8231 // variable created for a ParmVarDecl as well.
8232 if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
8233 if (DiscardResult)
8234 return true;
8235
8236 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
8237 !DeclType->isIntegralOrEnumerationType()) {
8238 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8239 /*InitializerFailed=*/false, E);
8240 }
8241 if (auto It = this->Params.find(PVD); It != this->Params.end()) {
8242 if (IsReference || !It->second.IsPtr)
8243 return this->emitGetParam(classifyPrim(E), It->second.Index, E);
8244
8245 return this->emitGetPtrParam(It->second.Index, E);
8246 }
8247
8248 if (!Ctx.getLangOpts().CPlusPlus23 && IsReference && !Locals.contains(D))
8249 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8250 /*InitializerFailed=*/false, E);
8251 }
8252
8253 // Local variables.
8254 if (auto It = Locals.find(D); It != Locals.end()) {
8255 const unsigned Offset = It->second.Offset;
8256 if (IsReference) {
8257 assert(classifyPrim(E) == PT_Ptr);
8258 return this->emitGetRefLocal(Offset, E) && maybePopPtr();
8259 }
8260 return this->emitGetPtrLocal(Offset, E) && maybePopPtr();
8261 }
8262 // Global variables.
8263 if (auto GlobalIndex = P.getGlobal(D)) {
8264 if (IsReference) {
8265 if (!Ctx.getLangOpts().CPlusPlus11)
8266 return this->emitGetGlobal(classifyPrim(E), *GlobalIndex, E);
8267 if (!Ctx.getLangOpts().CPlusPlus23)
8268 return this->emitGetGlobalUnchecked(classifyPrim(E), *GlobalIndex, E);
8269
8270 return this->emitGetRefGlobal(*GlobalIndex, E) && maybePopPtr();
8271 }
8272
8273 return this->emitGetPtrGlobal(*GlobalIndex, E) && maybePopPtr();
8274 }
8275
8276 // In case we need to re-visit a declaration.
8277 auto revisit = [&](const VarDecl *VD,
8278 bool IsConstexprUnknown = true) -> bool {
8280 IsConstexprUnknown);
8281 if constexpr (std::is_same_v<Emitter, EvalEmitter>) {
8282 if (!this->emitPushCC(VD->hasConstantInitialization(), E))
8283 return false;
8284 }
8285 auto VarState = this->visitDecl(VD);
8286
8287 if constexpr (std::is_same_v<Emitter, EvalEmitter>) {
8288 if (!this->emitPopCC(E))
8289 return false;
8290 }
8291
8292 if (VarState.notCreated())
8293 return true;
8294 if (!VarState)
8295 return false;
8296 // Retry.
8297 return this->visitDeclRef(D, E);
8298 };
8299
8300 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
8301 // Lambda captures.
8302 if (auto It = this->LambdaCaptures.find(D);
8303 It != this->LambdaCaptures.end()) {
8304 auto [Offset, IsPtr] = It->second;
8305
8306 if (IsPtr)
8307 return this->emitGetThisFieldPtr(Offset, E) && maybePopPtr();
8308 return this->emitGetPtrThisField(Offset, E) && maybePopPtr();
8309 }
8310 }
8311
8312 if (const auto *DRE = dyn_cast<DeclRefExpr>(E);
8313 DRE && DRE->refersToEnclosingVariableOrCapture()) {
8314 if (const auto *VD = dyn_cast<VarDecl>(D); VD && VD->isInitCapture())
8315 return revisit(VD);
8316 }
8317
8318 if (const auto *BD = dyn_cast<BindingDecl>(D))
8319 return this->delegate(BD->getBinding());
8320
8321 // Avoid infinite recursion.
8322 if (D == InitializingDecl) {
8323 if (DiscardResult)
8324 return true;
8325 return this->emitDummyPtr(D, E);
8326 }
8327
8328 // Try to lazily visit (or emit dummy pointers for) declarations
8329 // we haven't seen yet.
8330 const auto *VD = dyn_cast<VarDecl>(D);
8331 if (!VD)
8332 return this->emitError(E);
8333
8334 // For C.
8335 if (!Ctx.getLangOpts().CPlusPlus) {
8336 if (VD->getInit() && !VD->getInit()->isValueDependent() &&
8337 DeclType.isConstant(Ctx.getASTContext()) && !VD->isWeak() &&
8338 VD->evaluateValue())
8339 return revisit(VD, /*IsConstexprUnknown=*/false);
8340
8341 if (DiscardResult)
8342 return true;
8343 return this->emitDummyPtr(D, E);
8344 }
8345
8346 // ... and C++.
8347 const auto typeShouldBeVisited = [&](QualType T) -> bool {
8348 if (T.isConstant(Ctx.getASTContext()))
8349 return true;
8350 return T->isReferenceType();
8351 };
8352
8353 if ((VD->hasGlobalStorage() || VD->isStaticDataMember()) &&
8354 typeShouldBeVisited(DeclType)) {
8355 if (const Expr *Init = VD->getAnyInitializer();
8356 Init && !Init->isValueDependent()) {
8357 // Whether or not the evaluation is successul doesn't really matter
8358 // here -- we will create a global variable in any case, and that
8359 // will have the state of initializer evaluation attached.
8361 (void)Init->EvaluateAsInitializer(Ctx.getASTContext(), VD, Result, true);
8362 return this->visitDeclRef(D, E);
8363 }
8364 return revisit(VD, !VD->isConstexpr() && DeclType->isReferenceType());
8365 }
8366
8367 // FIXME: The evaluateValue() check here is a little ridiculous, since
8368 // it will ultimately call into Context::evaluateAsInitializer(). In
8369 // other words, we're evaluating the initializer, just to know if we can
8370 // evaluate the initializer.
8371 if (VD->isLocalVarDecl() && typeShouldBeVisited(DeclType) && VD->getInit() &&
8372 !VD->getInit()->isValueDependent()) {
8373 if (VD->evaluateValue()) {
8374 bool IsConstexprUnknown = !DeclType.isConstant(Ctx.getASTContext()) &&
8375 !DeclType->isReferenceType();
8376 // Revisit the variable declaration, but make sure it's associated with a
8377 // different evaluation, so e.g. mutable reads don't work on it.
8378 EvalIDScope _(Ctx);
8379 return revisit(VD, IsConstexprUnknown);
8380 } else if (Ctx.getLangOpts().CPlusPlus23 && IsReference)
8381 return revisit(VD, /*IsConstexprUnknown=*/true);
8382
8383 if (IsReference)
8384 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
8385 /*InitializerFailed=*/true, E);
8386 }
8387
8388 if (DiscardResult)
8389 return true;
8390 return this->emitDummyPtr(
8391 D, E, Ctx.getLangOpts().CPlusPlus23 && DeclType->isReferenceType());
8392}
8393
8394template <class Emitter>
8396 const auto *D = E->getDecl();
8397 return this->visitDeclRef(D, E);
8398}
8399
8400template <class Emitter>
8402 const DesignatedInitUpdateExpr *E) {
8403 if (!this->visitInitializer(E->getBase()))
8404 return false;
8405 return this->visitInitializer(E->getUpdater());
8406}
8407
8408template <class Emitter> bool Compiler<Emitter>::emitCleanup() {
8409 for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent()) {
8410 if (!C->destroyLocals())
8411 return false;
8412 }
8413 return true;
8414}
8415
8416template <class Emitter>
8417unsigned Compiler<Emitter>::collectBaseOffset(const QualType BaseType,
8418 const QualType DerivedType) {
8419 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
8420 if (const auto *R = Ty->getPointeeCXXRecordDecl())
8421 return R;
8422 return Ty->getAsCXXRecordDecl();
8423 };
8424 const CXXRecordDecl *BaseDecl = extractRecordDecl(BaseType);
8425 const CXXRecordDecl *DerivedDecl = extractRecordDecl(DerivedType);
8426
8427 return Ctx.collectBaseOffset(BaseDecl, DerivedDecl);
8428}
8429
8430/// Emit casts from a PrimType to another PrimType.
8431template <class Emitter>
8432bool Compiler<Emitter>::emitPrimCast(PrimType FromT, PrimType ToT,
8433 QualType ToQT, const Expr *E) {
8434
8435 if (FromT == PT_Float) {
8436 // Floating to floating.
8437 if (ToT == PT_Float) {
8438 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8439 return this->emitCastFP(ToSem, getRoundingMode(E), E);
8440 }
8441
8442 if (ToT == PT_IntAP)
8443 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(ToQT),
8444 getFPOptions(E), E);
8445 if (ToT == PT_IntAPS)
8446 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(ToQT),
8447 getFPOptions(E), E);
8448
8449 // Float to integral.
8450 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8451 return this->emitCastFloatingIntegral(ToT, getFPOptions(E), E);
8452 }
8453
8454 if (isIntegerOrBoolType(FromT) || FromT == PT_Bool) {
8455 if (ToT == PT_IntAP)
8456 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8457 if (ToT == PT_IntAPS)
8458 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8459
8460 // Integral to integral.
8461 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8462 return FromT != ToT ? this->emitCast(FromT, ToT, E) : true;
8463
8464 if (ToT == PT_Float) {
8465 // Integral to floating.
8466 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8467 return this->emitCastIntegralFloating(FromT, ToSem, getFPOptions(E), E);
8468 }
8469 }
8470
8471 return false;
8472}
8473
8474template <class Emitter>
8475bool Compiler<Emitter>::emitIntegralCast(PrimType FromT, PrimType ToT,
8476 QualType ToQT, const Expr *E) {
8477 assert(FromT != ToT);
8478
8479 if (ToT == PT_IntAP)
8480 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8481 if (ToT == PT_IntAPS)
8482 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8483
8484 return this->emitCast(FromT, ToT, E);
8485}
8486
8487/// Emits __real(SubExpr)
8488template <class Emitter>
8489bool Compiler<Emitter>::emitComplexReal(const Expr *SubExpr) {
8490 assert(SubExpr->getType()->isAnyComplexType());
8491
8492 if (DiscardResult)
8493 return this->discard(SubExpr);
8494
8495 if (!this->visit(SubExpr))
8496 return false;
8497 if (SubExpr->isLValue()) {
8498 if (!this->emitConstUint8(0, SubExpr))
8499 return false;
8500 return this->emitArrayElemPtrPopUint8(SubExpr);
8501 }
8502
8503 // Rvalue, load the actual element.
8504 return this->emitArrayElemPop(classifyComplexElementType(SubExpr->getType()),
8505 0, SubExpr);
8506}
8507
8508template <class Emitter>
8509bool Compiler<Emitter>::emitComplexBoolCast(const Expr *E) {
8510 assert(!DiscardResult);
8511 PrimType ElemT = classifyComplexElementType(E->getType());
8512 // We emit the expression (__real(E) != 0 || __imag(E) != 0)
8513 // for us, that means (bool)E[0] || (bool)E[1]
8514 if (!this->emitArrayElem(ElemT, 0, E))
8515 return false;
8516 if (ElemT == PT_Float) {
8517 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8518 return false;
8519 } else {
8520 if (!this->emitCast(ElemT, PT_Bool, E))
8521 return false;
8522 }
8523
8524 // We now have the bool value of E[0] on the stack.
8525 LabelTy LabelTrue = this->getLabel();
8526 if (!this->jumpTrue(LabelTrue, E))
8527 return false;
8528
8529 if (!this->emitArrayElemPop(ElemT, 1, E))
8530 return false;
8531 if (ElemT == PT_Float) {
8532 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8533 return false;
8534 } else {
8535 if (!this->emitCast(ElemT, PT_Bool, E))
8536 return false;
8537 }
8538 // Leave the boolean value of E[1] on the stack.
8539 LabelTy EndLabel = this->getLabel();
8540 this->jump(EndLabel, E);
8541
8542 this->emitLabel(LabelTrue);
8543 if (!this->emitPopPtr(E))
8544 return false;
8545 if (!this->emitConstBool(true, E))
8546 return false;
8547
8548 this->fallthrough(EndLabel);
8549 this->emitLabel(EndLabel);
8550
8551 return true;
8552}
8553
8554template <class Emitter>
8555bool Compiler<Emitter>::emitComplexComparison(const Expr *LHS, const Expr *RHS,
8556 const BinaryOperator *E) {
8557 assert(E->isComparisonOp());
8558 assert(!Initializing);
8559 if (DiscardResult)
8560 return this->discard(LHS) && this->discard(RHS);
8561
8562 PrimType ElemT;
8563 bool LHSIsComplex;
8564 unsigned LHSOffset;
8565 if (LHS->getType()->isAnyComplexType()) {
8566 LHSIsComplex = true;
8567 ElemT = classifyComplexElementType(LHS->getType());
8568 LHSOffset = allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
8569 if (!this->visit(LHS))
8570 return false;
8571 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
8572 return false;
8573 } else {
8574 LHSIsComplex = false;
8575 PrimType LHST = classifyPrim(LHS->getType());
8576 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, /*IsConst=*/true);
8577 if (!this->visit(LHS))
8578 return false;
8579 if (!this->emitSetLocal(LHST, LHSOffset, E))
8580 return false;
8581 }
8582
8583 bool RHSIsComplex;
8584 unsigned RHSOffset;
8585 if (RHS->getType()->isAnyComplexType()) {
8586 RHSIsComplex = true;
8587 ElemT = classifyComplexElementType(RHS->getType());
8588 RHSOffset = allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
8589 if (!this->visit(RHS))
8590 return false;
8591 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
8592 return false;
8593 } else {
8594 RHSIsComplex = false;
8595 PrimType RHST = classifyPrim(RHS->getType());
8596 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, /*IsConst=*/true);
8597 if (!this->visit(RHS))
8598 return false;
8599 if (!this->emitSetLocal(RHST, RHSOffset, E))
8600 return false;
8601 }
8602
8603 auto getElem = [&](unsigned LocalOffset, unsigned Index,
8604 bool IsComplex) -> bool {
8605 if (IsComplex) {
8606 if (!this->emitGetLocal(PT_Ptr, LocalOffset, E))
8607 return false;
8608 return this->emitArrayElemPop(ElemT, Index, E);
8609 }
8610 return this->emitGetLocal(ElemT, LocalOffset, E);
8611 };
8612
8613 for (unsigned I = 0; I != 2; ++I) {
8614 // Get both values.
8615 if (!getElem(LHSOffset, I, LHSIsComplex))
8616 return false;
8617 if (!getElem(RHSOffset, I, RHSIsComplex))
8618 return false;
8619 // And compare them.
8620 if (!this->emitEQ(ElemT, E))
8621 return false;
8622
8623 if (!this->emitCastBoolUint8(E))
8624 return false;
8625 }
8626
8627 // We now have two bool values on the stack. Compare those.
8628 if (!this->emitAddUint8(E))
8629 return false;
8630 if (!this->emitConstUint8(2, E))
8631 return false;
8632
8633 if (E->getOpcode() == BO_EQ) {
8634 if (!this->emitEQUint8(E))
8635 return false;
8636 } else if (E->getOpcode() == BO_NE) {
8637 if (!this->emitNEUint8(E))
8638 return false;
8639 } else
8640 return false;
8641
8642 // In C, this returns an int.
8643 if (PrimType ResT = classifyPrim(E->getType()); ResT != PT_Bool)
8644 return this->emitCast(PT_Bool, ResT, E);
8645 return true;
8646}
8647
8648/// When calling this, we have a pointer of the local-to-destroy
8649/// on the stack.
8650/// Emit destruction of record types (or arrays of record types).
8651template <class Emitter>
8652bool Compiler<Emitter>::emitRecordDestructionPop(const Record *R,
8653 SourceInfo Loc) {
8654 assert(R);
8655 assert(!R->hasTrivialDtor());
8656 const CXXDestructorDecl *Dtor = R->getDestructor();
8657 assert(Dtor);
8658 const Function *DtorFunc = getFunction(Dtor);
8659 if (!DtorFunc)
8660 return false;
8661 assert(DtorFunc->hasThisPointer());
8662 assert(DtorFunc->getNumParams() == 1);
8663 return this->emitCall(DtorFunc, 0, Loc);
8664}
8665/// When calling this, we have a pointer of the local-to-destroy
8666/// on the stack.
8667/// Emit destruction of record types (or arrays of record types).
8668template <class Emitter>
8669bool Compiler<Emitter>::emitDestructionPop(const Descriptor *Desc,
8670 SourceInfo Loc) {
8671 assert(Desc);
8672 assert(!Desc->hasTrivialDtor());
8673
8674 // Arrays.
8675 if (Desc->isArray()) {
8676 const Descriptor *ElemDesc = Desc->ElemDesc;
8677 assert(ElemDesc);
8678
8679 unsigned N = Desc->getNumElems();
8680 if (N == 0)
8681 return this->emitPopPtr(Loc);
8682
8683 for (ssize_t I = N - 1; I >= 1; --I) {
8684 if (!this->emitConstUint64(I, Loc))
8685 return false;
8686 if (!this->emitArrayElemPtrUint64(Loc))
8687 return false;
8688 if (!this->emitDestructionPop(ElemDesc, Loc))
8689 return false;
8690 }
8691 // Last iteration, removes the instance pointer from the stack.
8692 if (!this->emitConstUint64(0, Loc))
8693 return false;
8694 if (!this->emitArrayElemPtrPopUint64(Loc))
8695 return false;
8696 return this->emitDestructionPop(ElemDesc, Loc);
8697 }
8698
8699 assert(Desc->ElemRecord);
8700 assert(!Desc->ElemRecord->hasTrivialDtor());
8701 return this->emitRecordDestructionPop(Desc->ElemRecord, Loc);
8702}
8703
8704/// Create a dummy pointer for the given decl (or expr) and
8705/// push a pointer to it on the stack.
8706template <class Emitter>
8707bool Compiler<Emitter>::emitDummyPtr(const DeclTy &D, const Expr *E, bool CU) {
8708 assert(!DiscardResult && "Should've been checked before");
8709 unsigned DummyID = P.getOrCreateDummy(D, CU);
8710
8711 if (!this->emitGetPtrGlobal(DummyID, E))
8712 return false;
8713 if (E->getType()->isVoidType())
8714 return true;
8715
8716 // Convert the dummy pointer to another pointer type if we have to.
8717 if (PrimType PT = classifyPrim(E); PT != PT_Ptr) {
8718 if (isPtrType(PT))
8719 return this->emitDecayPtr(PT_Ptr, PT, E);
8720 return false;
8721 }
8722 return true;
8723}
8724
8725template <class Emitter>
8726bool Compiler<Emitter>::emitFloat(const APFloat &F, SourceInfo Info) {
8727 if (Floating::singleWord(F.getSemantics()))
8728 return this->emitConstFloat(Floating(F), Info);
8729
8730 APInt I = F.bitcastToAPInt();
8731 return this->emitConstFloat(
8732 Floating(const_cast<uint64_t *>(I.getRawData()),
8733 llvm::APFloatBase::SemanticsToEnum(F.getSemantics())),
8734 Info);
8735}
8736
8737// This function is constexpr if and only if To, From, and the types of
8738// all subobjects of To and From are types T such that...
8739// (3.1) - is_union_v<T> is false;
8740// (3.2) - is_pointer_v<T> is false;
8741// (3.3) - is_member_pointer_v<T> is false;
8742// (3.4) - is_volatile_v<T> is false; and
8743// (3.5) - T has no non-static data members of reference type
8744template <class Emitter>
8745bool Compiler<Emitter>::emitBuiltinBitCast(const CastExpr *E) {
8746 const Expr *SubExpr = E->getSubExpr();
8747 QualType FromType = SubExpr->getType();
8748 QualType ToType = E->getType();
8749 OptPrimType ToT = classify(ToType);
8750
8751 assert(!ToType->isReferenceType());
8752
8753 // Prepare storage for the result in case we discard.
8754 if (DiscardResult && !Initializing && !ToT) {
8755 UnsignedOrNone LocalIndex = allocateLocal(E);
8756 if (!LocalIndex)
8757 return false;
8758 if (!this->emitGetPtrLocal(*LocalIndex, E))
8759 return false;
8760 }
8761
8762 // Get a pointer to the value-to-cast on the stack.
8763 // For CK_LValueToRValueBitCast, this is always an lvalue and
8764 // we later assume it to be one (i.e. a PT_Ptr). However,
8765 // we call this function for other utility methods where
8766 // a bitcast might be useful, so convert it to a PT_Ptr in that case.
8767 if (SubExpr->isGLValue() || FromType->isVectorType()) {
8768 if (!this->visit(SubExpr))
8769 return false;
8770 } else if (OptPrimType FromT = classify(SubExpr)) {
8771 unsigned TempOffset =
8772 allocateLocalPrimitive(SubExpr, *FromT, /*IsConst=*/true);
8773 if (!this->visit(SubExpr))
8774 return false;
8775 if (!this->emitSetLocal(*FromT, TempOffset, E))
8776 return false;
8777 if (!this->emitGetPtrLocal(TempOffset, E))
8778 return false;
8779 } else {
8780 return false;
8781 }
8782
8783 if (!ToT) {
8784 if (!this->emitBitCast(E))
8785 return false;
8786 return DiscardResult ? this->emitPopPtr(E) : true;
8787 }
8788 assert(ToT);
8789
8790 const llvm::fltSemantics *TargetSemantics = nullptr;
8791 if (ToT == PT_Float)
8792 TargetSemantics = &Ctx.getFloatSemantics(ToType);
8793
8794 // Conversion to a primitive type. FromType can be another
8795 // primitive type, or a record/array.
8796 bool ToTypeIsUChar = (ToType->isSpecificBuiltinType(BuiltinType::UChar) ||
8797 ToType->isSpecificBuiltinType(BuiltinType::Char_U));
8798 uint32_t ResultBitWidth = std::max(Ctx.getBitWidth(ToType), 8u);
8799
8800 if (!this->emitBitCastPrim(*ToT, ToTypeIsUChar || ToType->isStdByteType(),
8801 ResultBitWidth, TargetSemantics,
8802 ToType.getTypePtr(), E))
8803 return false;
8804
8805 if (DiscardResult)
8806 return this->emitPop(*ToT, E);
8807
8808 return true;
8809}
8810
8811/// Replicate a scalar value into every scalar element of an aggregate.
8812/// The scalar is stored in a local at \p SrcOffset and a pointer to the
8813/// destination must be on top of the interpreter stack. Each element receives
8814/// the scalar, cast to its own type.
8815template <class Emitter>
8816bool Compiler<Emitter>::emitHLSLAggregateSplat(PrimType SrcT,
8817 unsigned SrcOffset,
8818 QualType DestType,
8819 const Expr *E) {
8820 // Vectors and matrices are treated as flat sequences of elements.
8821 unsigned NumElems = 0;
8822 QualType ElemType;
8823 if (const auto *VT = DestType->getAs<VectorType>()) {
8824 NumElems = VT->getNumElements();
8825 ElemType = VT->getElementType();
8826 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
8827 NumElems = MT->getNumElementsFlattened();
8828 ElemType = MT->getElementType();
8829 }
8830 if (NumElems > 0) {
8831 PrimType ElemT = classifyPrim(ElemType);
8832 for (unsigned I = 0; I != NumElems; ++I) {
8833 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8834 return false;
8835 if (!this->emitPrimCast(SrcT, ElemT, ElemType, E))
8836 return false;
8837 if (!this->emitInitElem(ElemT, I, E))
8838 return false;
8839 }
8840 return true;
8841 }
8842
8843 // Arrays: primitive elements are filled directly; composite elements
8844 // require recursion into each sub-aggregate.
8845 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
8846 const auto *CAT = cast<ConstantArrayType>(AT);
8847 QualType ArrElemType = CAT->getElementType();
8848 unsigned ArrSize = CAT->getZExtSize();
8849
8850 if (OptPrimType ElemT = classify(ArrElemType)) {
8851 for (unsigned I = 0; I != ArrSize; ++I) {
8852 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8853 return false;
8854 if (!this->emitPrimCast(SrcT, *ElemT, ArrElemType, E))
8855 return false;
8856 if (!this->emitInitElem(*ElemT, I, E))
8857 return false;
8858 }
8859 } else {
8860 for (unsigned I = 0; I != ArrSize; ++I) {
8861 if (!this->emitConstUint32(I, E))
8862 return false;
8863 if (!this->emitArrayElemPtrUint32(E))
8864 return false;
8865 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, ArrElemType, E))
8866 return false;
8867 if (!this->emitFinishInitPop(E))
8868 return false;
8869 }
8870 }
8871 return true;
8872 }
8873
8874 // Records: fill base classes first, then named fields in declaration
8875 // order.
8876 if (DestType->isRecordType()) {
8877 const Record *R = getRecord(DestType);
8878 if (!R)
8879 return false;
8880
8881 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
8882 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
8883 const Record::Base *B = R->getBase(BS.getType());
8884 assert(B);
8885 if (!this->emitGetPtrBase(B->Offset, E))
8886 return false;
8887 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, BS.getType(), E))
8888 return false;
8889 if (!this->emitFinishInitPop(E))
8890 return false;
8891 }
8892 }
8893
8894 for (const Record::Field &F : R->fields()) {
8895 if (F.isUnnamedBitField())
8896 continue;
8897
8898 QualType FieldType = F.Decl->getType();
8899 if (OptPrimType FieldT = classify(FieldType)) {
8900 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8901 return false;
8902 if (!this->emitPrimCast(SrcT, *FieldT, FieldType, E))
8903 return false;
8904 if (F.isBitField()) {
8905 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
8906 return false;
8907 } else {
8908 if (!this->emitInitField(*FieldT, F.Offset, E))
8909 return false;
8910 }
8911 } else {
8912 if (!this->emitGetPtrField(F.Offset, E))
8913 return false;
8914 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, FieldType, E))
8915 return false;
8916 if (!this->emitPopPtr(E))
8917 return false;
8918 }
8919 }
8920 return true;
8921 }
8922
8923 return false;
8924}
8925
8926/// Return the total number of scalar elements in a type. This is used
8927/// to cap how many source elements are extracted during an elementwise cast,
8928/// so we never flatten more than the destination can hold.
8929template <class Emitter>
8930unsigned Compiler<Emitter>::countHLSLFlatElements(QualType Ty) {
8931 // Vector and matrix types are treated as flat sequences of elements.
8932 if (const auto *VT = Ty->getAs<VectorType>())
8933 return VT->getNumElements();
8934 if (const auto *MT = Ty->getAs<ConstantMatrixType>())
8935 return MT->getNumElementsFlattened();
8936 // Arrays: total count is array size * scalar elements per element.
8937 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
8938 const auto *CAT = cast<ConstantArrayType>(AT);
8939 return CAT->getZExtSize() * countHLSLFlatElements(CAT->getElementType());
8940 }
8941 // Records: sum scalar element counts of base classes and named fields.
8942 if (Ty->isRecordType()) {
8943 const Record *R = getRecord(Ty);
8944 if (!R)
8945 return 0;
8946 unsigned Count = 0;
8947 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
8948 for (const CXXBaseSpecifier &BS : CXXRD->bases())
8949 Count += countHLSLFlatElements(BS.getType());
8950 }
8951 for (const Record::Field &F : R->fields()) {
8952 if (F.isUnnamedBitField())
8953 continue;
8954 Count += countHLSLFlatElements(F.Decl->getType());
8955 }
8956 return Count;
8957 }
8958 // Scalar primitive types contribute one element.
8959 if (canClassify(Ty))
8960 return 1;
8961 return 0;
8962}
8963
8964/// Walk a source aggregate and extract every scalar element into its own local
8965/// variable. The results are appended to \p Elements in declaration order,
8966/// stopping once \p MaxElements have been collected. A pointer to the
8967/// source aggregate must be stored in the local at \p SrcOffset.
8968template <class Emitter>
8969bool Compiler<Emitter>::emitHLSLFlattenAggregate(
8970 QualType SrcType, unsigned SrcOffset,
8971 SmallVectorImpl<HLSLFlatElement> &Elements, unsigned MaxElements,
8972 const Expr *E) {
8973
8974 // Save a scalar value from the stack into a new local and record it.
8975 auto saveToLocal = [&](PrimType T) -> bool {
8976 unsigned Offset = allocateLocalPrimitive(E, T, /*IsConst=*/true);
8977 if (!this->emitSetLocal(T, Offset, E))
8978 return false;
8979 Elements.push_back({Offset, T});
8980 return true;
8981 };
8982
8983 // Save a pointer from the stack into a new local for later use.
8984 auto savePtrToLocal = [&]() -> UnsignedOrNone {
8985 unsigned Offset = allocateLocalPrimitive(E, PT_Ptr, /*IsConst=*/true);
8986 if (!this->emitSetLocal(PT_Ptr, Offset, E))
8987 return std::nullopt;
8988 return Offset;
8989 };
8990
8991 // Vectors and matrices are flat sequences of elements.
8992 unsigned NumElems = 0;
8993 QualType ElemType;
8994 if (const auto *VT = SrcType->getAs<VectorType>()) {
8995 NumElems = VT->getNumElements();
8996 ElemType = VT->getElementType();
8997 } else if (const auto *MT = SrcType->getAs<ConstantMatrixType>()) {
8998 NumElems = MT->getNumElementsFlattened();
8999 ElemType = MT->getElementType();
9000 }
9001 if (NumElems > 0) {
9002 PrimType ElemT = classifyPrim(ElemType);
9003 for (unsigned I = 0; I != NumElems && Elements.size() < MaxElements; ++I) {
9004 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9005 return false;
9006 if (!this->emitArrayElemPop(ElemT, I, E))
9007 return false;
9008 if (!saveToLocal(ElemT))
9009 return false;
9010 }
9011 return true;
9012 }
9013
9014 // Arrays: primitive elements are extracted directly; composite elements
9015 // require recursion into each sub-aggregate.
9016 if (const auto *AT = SrcType->getAsArrayTypeUnsafe()) {
9017 const auto *CAT = cast<ConstantArrayType>(AT);
9018 QualType ArrElemType = CAT->getElementType();
9019 unsigned ArrSize = CAT->getZExtSize();
9020
9021 if (OptPrimType ElemT = classify(ArrElemType)) {
9022 for (unsigned I = 0; I != ArrSize && 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 } else {
9031 for (unsigned I = 0; I != ArrSize && Elements.size() < MaxElements; ++I) {
9032 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9033 return false;
9034 if (!this->emitConstUint32(I, E))
9035 return false;
9036 if (!this->emitArrayElemPtrPopUint32(E))
9037 return false;
9038 UnsignedOrNone ElemPtrOffset = savePtrToLocal();
9039 if (!ElemPtrOffset)
9040 return false;
9041 if (!emitHLSLFlattenAggregate(ArrElemType, *ElemPtrOffset, Elements,
9042 MaxElements, E))
9043 return false;
9044 }
9045 }
9046 return true;
9047 }
9048
9049 // Records: base classes come first, then named fields in declaration
9050 // order.
9051 if (SrcType->isRecordType()) {
9052 const Record *R = getRecord(SrcType);
9053 if (!R)
9054 return false;
9055
9056 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9057 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9058 if (Elements.size() >= MaxElements)
9059 break;
9060 const Record::Base *B = R->getBase(BS.getType());
9061 assert(B);
9062 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9063 return false;
9064 if (!this->emitGetPtrBasePop(B->Offset, /*NullOK=*/false, E))
9065 return false;
9066 UnsignedOrNone BasePtrOffset = savePtrToLocal();
9067 if (!BasePtrOffset)
9068 return false;
9069 if (!emitHLSLFlattenAggregate(BS.getType(), *BasePtrOffset, Elements,
9070 MaxElements, E))
9071 return false;
9072 }
9073 }
9074
9075 for (const Record::Field &F : R->fields()) {
9076 if (Elements.size() >= MaxElements)
9077 break;
9078 if (F.isUnnamedBitField())
9079 continue;
9080
9081 QualType FieldType = F.Decl->getType();
9082 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
9083 return false;
9084 if (!this->emitGetPtrFieldPop(F.Offset, E))
9085 return false;
9086
9087 if (OptPrimType FieldT = classify(FieldType)) {
9088 if (!this->emitLoadPop(*FieldT, E))
9089 return false;
9090 if (!saveToLocal(*FieldT))
9091 return false;
9092 } else {
9093 UnsignedOrNone FieldPtrOffset = savePtrToLocal();
9094 if (!FieldPtrOffset)
9095 return false;
9096 if (!emitHLSLFlattenAggregate(FieldType, *FieldPtrOffset, Elements,
9097 MaxElements, E))
9098 return false;
9099 }
9100 }
9101 return true;
9102 }
9103
9104 return false;
9105}
9106
9107/// Populate an HLSL aggregate from a flat list of previously extracted source
9108/// elements, casting each to the corresponding destination element type.
9109/// \p ElemIdx tracks the current position in \p Elements and is advanced as
9110/// elements are consumed. A pointer to the destination must be on top of the
9111/// interpreter stack.
9112template <class Emitter>
9113bool Compiler<Emitter>::emitHLSLConstructAggregate(
9114 QualType DestType, ArrayRef<HLSLFlatElement> Elements, unsigned &ElemIdx,
9115 const Expr *E) {
9116
9117 // Consume the next source element, cast it, and leave it on the stack.
9118 auto loadAndCast = [&](PrimType DestT, QualType DestQT) -> bool {
9119 const auto &Src = Elements[ElemIdx++];
9120 if (!this->emitGetLocal(Src.Type, Src.LocalOffset, E))
9121 return false;
9122 return this->emitPrimCast(Src.Type, DestT, DestQT, E);
9123 };
9124
9125 // Vectors and matrices are flat sequences of elements.
9126 unsigned NumElems = 0;
9127 QualType ElemType;
9128 if (const auto *VT = DestType->getAs<VectorType>()) {
9129 NumElems = VT->getNumElements();
9130 ElemType = VT->getElementType();
9131 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
9132 NumElems = MT->getNumElementsFlattened();
9133 ElemType = MT->getElementType();
9134 }
9135 if (NumElems > 0) {
9136 PrimType DestElemT = classifyPrim(ElemType);
9137 for (unsigned I = 0; I != NumElems; ++I) {
9138 if (!loadAndCast(DestElemT, ElemType))
9139 return false;
9140 if (!this->emitInitElem(DestElemT, I, E))
9141 return false;
9142 }
9143 return true;
9144 }
9145
9146 // Arrays: primitive elements are filled directly; composite elements
9147 // require recursion into each sub-aggregate.
9148 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
9149 const auto *CAT = cast<ConstantArrayType>(AT);
9150 QualType ArrElemType = CAT->getElementType();
9151 unsigned ArrSize = CAT->getZExtSize();
9152
9153 if (OptPrimType ElemT = classify(ArrElemType)) {
9154 for (unsigned I = 0; I != ArrSize; ++I) {
9155 if (!loadAndCast(*ElemT, ArrElemType))
9156 return false;
9157 if (!this->emitInitElem(*ElemT, I, E))
9158 return false;
9159 }
9160 } else {
9161 for (unsigned I = 0; I != ArrSize; ++I) {
9162 if (!this->emitConstUint32(I, E))
9163 return false;
9164 if (!this->emitArrayElemPtrUint32(E))
9165 return false;
9166 if (!emitHLSLConstructAggregate(ArrElemType, Elements, ElemIdx, E))
9167 return false;
9168 if (!this->emitFinishInitPop(E))
9169 return false;
9170 }
9171 }
9172 return true;
9173 }
9174
9175 // Records: base classes come first, then named fields in declaration
9176 // order.
9177 if (DestType->isRecordType()) {
9178 const Record *R = getRecord(DestType);
9179 if (!R)
9180 return false;
9181
9182 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
9183 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
9184 const Record::Base *B = R->getBase(BS.getType());
9185 assert(B);
9186 if (!this->emitGetPtrBase(B->Offset, E))
9187 return false;
9188 if (!emitHLSLConstructAggregate(BS.getType(), Elements, ElemIdx, E))
9189 return false;
9190 if (!this->emitFinishInitPop(E))
9191 return false;
9192 }
9193 }
9194
9195 for (const Record::Field &F : R->fields()) {
9196 if (F.isUnnamedBitField())
9197 continue;
9198
9199 QualType FieldType = F.Decl->getType();
9200 if (OptPrimType FieldT = classify(FieldType)) {
9201 if (!loadAndCast(*FieldT, FieldType))
9202 return false;
9203 if (F.isBitField()) {
9204 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
9205 return false;
9206 } else {
9207 if (!this->emitInitField(*FieldT, F.Offset, E))
9208 return false;
9209 }
9210 } else {
9211 if (!this->emitGetPtrField(F.Offset, E))
9212 return false;
9213 if (!emitHLSLConstructAggregate(FieldType, Elements, ElemIdx, E))
9214 return false;
9215 if (!this->emitPopPtr(E))
9216 return false;
9217 }
9218 }
9219 return true;
9220 }
9221
9222 return false;
9223}
9224
9225namespace clang {
9226namespace interp {
9227
9228template class Compiler<ByteCodeEmitter>;
9229template class Compiler<EvalEmitter>;
9230
9231} // namespace interp
9232} // namespace clang
#define V(N, I)
static void emit(Program &P, llvm::SmallVectorImpl< std::byte > &Code, const T &Val, bool &Success)
Helper to write bytecode and bail out if 32-bit offsets become invalid.
static void emitCleanup(CIRGenFunction &cgf, cir::CleanupScopeOp cleanupScope, EHScopeStack::Cleanup *cleanup, EHScopeStack::Cleanup::Flags flags, Address activeFlag)
static uint32_t getBitWidth(const Expr *E)
#define EMIT_ARITH_OP(OP)
static CharUnits AlignOfType(QualType T, const ASTContext &ASTCtx, UnaryExprOrTypeTrait Kind)
static const Expr * stripDerivedToBaseCasts(const Expr *E)
static const Expr * stripCheckedDerivedToBaseCasts(const Expr *E)
static bool hasTrivialDefaultCtorParent(const FieldDecl *FD)
static bool initNeedsOverridenLoc(const CXXCtorInitializer *Init)
llvm::APSInt APSInt
Definition Compiler.cpp:25
Result
Implement __builtin_bit_cast and related operations.
llvm::SmallPtrSet< const ParmVarDecl *, 1 > FoundParams
bool VisitDeclRefExpr(const DeclRefExpr *E) override
a trap message and trap category.
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:1020
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:629
ArrayRef< LValuePathEntry > getLValuePath() const
Definition APValue.cpp:1040
APSInt & getInt()
Definition APValue.h:511
APValue & getStructField(unsigned i)
Definition APValue.h:674
const FieldDecl * getUnionField() const
Definition APValue.h:695
unsigned getStructNumFields() const
Definition APValue.h:661
APValue & getStructVirtualBase(unsigned i)
Definition APValue.h:679
bool isArray() const
Definition APValue.h:496
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1110
unsigned getArrayInitializedElts() const
Definition APValue.h:648
bool isFloat() const
Definition APValue.h:489
unsigned getStructNumBases() const
Definition APValue.h:657
unsigned getStructNumVirtualBases() const
Definition APValue.h:665
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1103
APValue & getUnionValue()
Definition APValue.h:699
APValue & getArrayFiller()
Definition APValue.h:640
bool isLValue() const
Definition APValue.h:493
bool isIndeterminate() const
Definition APValue.h:485
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1117
bool isMemberPointer() const
Definition APValue.h:499
bool isInt() const
Definition APValue.h:488
unsigned getArraySize() const
Definition APValue.h:652
bool isUnion() const
Definition APValue.h:498
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isStruct() const
Definition APValue.h:497
bool isNullPointer() const
Definition APValue.cpp:1056
APFloat & getFloat()
Definition APValue.h:525
APValue & getStructBase(unsigned i)
Definition APValue.h:669
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
const LangOptions & getLangOpts() const
Definition ASTContext.h:965
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4359
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4537
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4543
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4549
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition Expr.h:4556
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition Expr.h:6033
Represents a loop initializing the elements of an array.
Definition Expr.h:5980
llvm::APInt getArraySize() const
Definition Expr.h:6002
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5995
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:6000
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2727
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2756
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition ExprCXX.h:3000
uint64_t getValue() const
Definition ExprCXX.h:3048
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3821
QualType getElementType() const
Definition TypeBase.h:3833
Attr - This represents one attribute.
Definition Attr.h:46
Represents an attribute applied to a statement.
Definition Stmt.h:2213
Stmt * getSubStmt()
Definition Stmt.h:2249
ArrayRef< const Attr * > getAttrs() const
Definition Stmt.h:2245
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3517
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4177
Expr * getLHS() const
Definition Expr.h:4094
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4144
static bool isShiftOp(Opcode Opc)
Definition Expr.h:4132
static bool isCommaOp(Opcode Opc)
Definition Expr.h:4147
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4191
Expr * getRHS() const
Definition Expr.h:4096
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4121
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4180
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4185
Opcode getOpcode() const
Definition Expr.h:4089
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4135
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6684
BreakStmt - This represents a break.
Definition Stmt.h:3145
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition ExprCXX.h:5476
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:2633
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3069
Represents a C++ base or member initializer.
Definition DeclCXX.h:2398
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h: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:1112
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:2898
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:2284
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2751
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2730
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2895
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h: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:4309
bool getValue() const
Definition ExprCXX.h:4332
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5141
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
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:166
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:134
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:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
Expr * getCallee()
Definition Expr.h:3096
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3140
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3143
arg_range arguments()
Definition Expr.h:3201
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1609
CaseStmt - Represent a case statement.
Definition Stmt.h:1930
Stmt * getSubStmt()
Definition Stmt.h:2043
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3682
path_iterator path_begin()
Definition Expr.h:3752
CastKind getCastKind() const
Definition Expr.h:3726
llvm::iterator_range< path_iterator > path()
Path through the class hierarchy taken by casts between base and derived classes (see implementation ...
Definition Expr.h:3769
const FieldDecl * getTargetUnionField() const
Definition Expr.h:3776
path_iterator path_end()
Definition Expr.h:3753
Expr * getSubExpr()
Definition Expr.h:3732
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
unsigned getValue() const
Definition Expr.h:1635
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4854
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4890
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3340
QualType getElementType() const
Definition TypeBase.h:3350
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4306
QualType getComputationLHSType() const
Definition Expr.h:4340
QualType getComputationResultType() const
Definition Expr.h:4343
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3611
bool isFileScope() const
Definition Expr.h:3643
const Expr * getInitializer() const
Definition Expr.h:3639
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1750
body_range body()
Definition Stmt.h:1813
Stmt * body_back()
Definition Stmt.h:1818
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:3859
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3935
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1088
APValue getAPValueResult() const
Definition Expr.cpp:419
bool hasAPValueResult() const
Definition Expr.h:1163
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4486
ContinueStmt - This represents a continue.
Definition Stmt.h:3129
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition Expr.h:4725
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4815
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
ValueDecl * getDecl()
Definition Expr.h:1344
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1641
decl_range decls()
Definition Stmt.h:1689
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:2091
InitListExpr * getUpdater() const
Definition Expr.h:5948
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2842
Stmt * getBody()
Definition Stmt.h:2867
Expr * getCond()
Definition Stmt.h:2860
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
Recursively visit a statement or expression, by dispatching to Traverse*() based on the argument's dy...
const Expr * getBase() const
Definition Expr.h:6593
Represents a reference to emded data.
Definition Expr.h:5141
ChildElementIter< false > begin()
Definition Expr.h:5247
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3661
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:3699
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:3073
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6622
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4561
Represents a member of a struct/union/class.
Definition Decl.h:3204
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3440
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1581
llvm::APFloat getValue() const
Definition Expr.h:1672
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2898
Stmt * getInit()
Definition Stmt.h:2913
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2942
Expr * getInc()
Definition Stmt.h:2941
Expr * getCond()
Definition Stmt.h:2940
DeclStmt * getConditionVariableDeclStmt()
If this ForStmt has a condition variable, return the faux DeclStmt associated with the creation of th...
Definition Stmt.h:2928
const Expr * getSubExpr() const
Definition Expr.h:1068
Represents a function declaration or definition.
Definition Decl.h:2029
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2837
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3259
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4185
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4173
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3742
QualType getReturnType() const
Definition Decl.h:2885
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2814
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2413
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4309
bool isUsableAsGlobalAllocationFunctionInConstantEvaluation(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions described in i...
Definition Decl.cpp:3406
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2421
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3806
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3179
Declaration of a template function.
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4929
Represents a C11 generic selection.
Definition Expr.h:6194
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6480
IfStmt - This represents an if/then/else.
Definition Stmt.h:2269
Stmt * getThen()
Definition Stmt.h:2358
Stmt * getInit()
Definition Stmt.h:2419
bool isNonNegatedConsteval() const
Definition Stmt.h:2454
Expr * getCond()
Definition Stmt.h:2346
bool isNegatedConsteval() const
Definition Stmt.h:2458
Stmt * getElse()
Definition Stmt.h:2367
DeclStmt * getConditionVariableDeclStmt()
If this IfStmt has a condition variable, return the faux DeclStmt associated with the creation of tha...
Definition Stmt.h:2402
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1737
const Expr * getSubExpr() const
Definition Expr.h:1749
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6069
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3511
Describes an C or C++ initializer list.
Definition Expr.h:5314
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5417
ArrayRef< Expr * > inits() const
Definition Expr.h:5367
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h: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:1407
bool isCompatibleWith(ClangABI Version) const
Implicit declaration of a temporary that was materialized by a MaterializeTemporaryExpr and lifetime-...
Definition DeclCXX.h:3329
const Stmt * getNamedLoopOrSwitch() const
If this is a named break/continue, get the loop or switch statement that this targets.
Definition Stmt.cpp:1535
A global _GUID constant.
Definition DeclCXX.h:4424
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
Definition DeclCXX.cpp:3872
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4920
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4945
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4937
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:4970
LifetimeExtendedTemporaryDecl * getLifetimeExtendedTemporaryDecl()
Definition ExprCXX.h:4960
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
Expr * getBase() const
Definition Expr.h:3447
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3752
This represents a decl that may have a name.
Definition Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Represents a C++ namespace alias.
Definition DeclCXX.h:3222
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition ExprObjC.h:220
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition ExprObjC.h:119
ObjCBoxedExpr - used for generalized expression boxing.
Definition ExprObjC.h:159
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition ExprObjC.h:342
ObjCEncodeExpr, used for @encode in Objective-C.
Definition ExprObjC.h:441
QualType getEncodedType() const
Definition ExprObjC.h:460
SourceLocation getAtLoc() const
Definition ExprObjC.h:455
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:68
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:84
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2533
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2592
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2580
unsigned getNumComponents() const
Definition Expr.h:2588
Helper class for OffsetOfExpr.
Definition Expr.h:2427
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2485
@ Array
An index into an array.
Definition Expr.h:2432
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2481
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1184
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1234
Expr * getSelectedExpr() const
Definition ExprCXX.h:4639
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2188
const Expr * getSubExpr() const
Definition Expr.h:2205
Represents a parameter to a function.
Definition Decl.h:1819
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3393
QualType getPointeeType() const
Definition TypeBase.h:3403
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2011
StringLiteral * getFunctionName()
Definition Expr.h:2055
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6816
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6864
ArrayRef< Expr * > semantics()
Definition Expr.h:6888
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8573
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:8489
bool isConstant(const ASTContext &Ctx) const
Definition TypeBase.h:1098
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8562
Represents a struct/union/class.
Definition Decl.h:4369
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7515
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3672
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:3170
Expr * getRetValue()
Definition Stmt.h:3197
SourceLocation getLocation() const
Definition Expr.h:2161
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:593
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4649
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4701
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4682
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4688
Represents an expression that computes the length of a parameter pack.
Definition ExprCXX.h:4441
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4515
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition Expr.h:5032
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2291
Represents a C++11 static_assert declaration.
Definition DeclCXX.h:4157
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4601
CompoundStmt * getSubStmt()
Definition Expr.h:4618
Stmt - This represents one statement.
Definition Stmt.h:86
StmtClass getStmtClass() const
Definition Stmt.h:1503
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
unsigned getLength() const
Definition Expr.h:1915
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1194
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1888
unsigned getCharByteWidth() const
Definition Expr.h:1916
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4664
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1903
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2519
Expr * getCond()
Definition Stmt.h:2582
Stmt * getBody()
Definition Stmt.h:2594
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2599
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2650
DeclStmt * getConditionVariableDeclStmt()
If this SwitchStmt has a condition variable, return the faux DeclStmt associated with the creation of...
Definition Stmt.h:2633
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3761
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3862
bool isUnion() const
Definition Decl.h:3972
A template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition ExprCXX.h:2900
bool getBoolValue() const
Definition ExprCXX.h:2951
const APValue & getAPValue() const
Definition ExprCXX.h:2956
bool isStoredAsBoolean() const
Definition ExprCXX.h:2947
The base class of the type hierarchy.
Definition TypeBase.h:1876
bool isVoidType() const
Definition TypeBase.h:9092
bool isBooleanType() const
Definition TypeBase.h:9229
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3117
bool isIncompleteArrayType() const
Definition TypeBase.h:8833
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isNothrowT() const
Definition Type.cpp:3301
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:749
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2521
bool isArrayType() const
Definition TypeBase.h:8825
bool isFunctionPointerType() const
Definition TypeBase.h:8793
bool isConstantMatrixType() const
Definition TypeBase.h:8893
bool isPointerType() const
Definition TypeBase.h:8726
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9136
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9386
bool isReferenceType() const
Definition TypeBase.h:8750
bool isEnumeralType() const
Definition TypeBase.h:8857
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:9214
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9061
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2847
bool isAnyComplexType() const
Definition TypeBase.h:8861
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9152
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9272
bool isMemberPointerType() const
Definition TypeBase.h:8807
bool isAtomicType() const
Definition TypeBase.h:8918
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isStdByteType() const
Definition Type.cpp:3320
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9372
bool isPointerOrReferenceType() const
Definition TypeBase.h:8730
bool isFunctionType() const
Definition TypeBase.h:8722
bool isVectorType() const
Definition TypeBase.h:8865
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2409
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2986
bool isFloatingType() const
Definition Type.cpp:2393
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9319
bool isRecordType() const
Definition TypeBase.h:8853
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2667
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3606
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2631
QualType getArgumentType() const
Definition Expr.h:2674
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2700
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2663
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
Expr * getSubExpr() const
Definition Expr.h:2291
Opcode getOpcode() const
Definition Expr.h:2286
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2304
Represents C++ using-directive.
Definition DeclCXX.h:3117
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5581
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:932
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1593
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1602
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1306
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1247
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2632
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1214
const Expr * getInit() const
Definition Decl.h:1391
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2556
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1274
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1381
Represents a GCC generic vector type.
Definition TypeBase.h:4274
unsigned getNumElements() const
Definition TypeBase.h:4289
QualType getElementType() const
Definition TypeBase.h:4288
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2707
Expr * getCond()
Definition Stmt.h:2759
DeclStmt * getConditionVariableDeclStmt()
If this WhileStmt has a condition variable, return the faux DeclStmt associated with the creation of ...
Definition Stmt.h:2795
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2771
ArrayIndexScope(Compiler< Emitter > *Ctx, uint64_t Index)
Definition Compiler.cpp:221
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:44
void invokeDtor()
Invokes the Destructor.
Compilation context for expressions.
Definition Compiler.h:112
llvm::SmallVector< InitLink > InitStack
Definition Compiler.h:499
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.
UnsignedOrNone allocateLocal(DeclTy &&Decl, QualType Ty=QualType(), ScopeKind=ScopeKind::Block)
Allocates a space storing a local given its type.
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:290
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:474
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:480
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)
unsigned allocateLocalPrimitive(DeclTy &&Decl, PrimType Ty, bool IsConst, bool IsVolatile=false, ScopeKind SC=ScopeKind::Block)
Creates a local primitive value.
bool VisitComplexUnaryOperator(const UnaryOperator *E)
llvm::DenseMap< const SwitchCase *, LabelTy > CaseMap
Definition Compiler.h:118
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:135
const VarDecl * InitializingDecl
Definition Compiler.h:497
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:510
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:477
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:506
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:483
bool VisitObjCArrayLiteral(const ObjCArrayLiteral *E)
UnsignedOrNone OptLabelTy
Definition Compiler.h:117
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:115
VarCreationState visitDecl(const VarDecl *VD)
bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E)
bool visitStmt(const Stmt *S)
bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E)
bool VisitVectorUnaryOperator(const UnaryOperator *E)
bool VisitCXXConstructExpr(const CXXConstructExpr *E)
bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E)
bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E)
bool VisitRecoveryExpr(const RecoveryExpr *E)
bool VisitRequiresExpr(const RequiresExpr *E)
bool Initializing
Flag inidicating if we're initializing an already created variable.
Definition Compiler.h:496
bool visitReturnStmt(const ReturnStmt *RS)
bool VisitCXXThrowExpr(const CXXThrowExpr *E)
bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
bool VisitChooseExpr(const ChooseExpr *E)
bool visitFunc(const FunctionDecl *F) override
bool visitCXXForRangeStmt(const CXXForRangeStmt *S)
bool visitCaseStmt(const CaseStmt *S)
bool VisitComplexBinOp(const BinaryOperator *E)
llvm::DenseMap< const ValueDecl *, Scope::Local > Locals
Variable to storage mapping.
Definition Compiler.h:471
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:503
bool VisitUnaryOperator(const UnaryOperator *E)
bool VisitFloatCompoundAssignOperator(const CompoundAssignOperator *E)
OptPrimType classify(const Expr *E) const
Definition Compiler.h:284
llvm::SmallVector< LabelInfo > LabelInfoStack
Stack of label information for loops and switch statements.
Definition Compiler.h:508
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:486
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:286
bool VisitFloatingLiteral(const FloatingLiteral *E)
Program & P
Program to link to.
Definition Compiler.h:137
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:779
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:288
DeclScope(Compiler< Emitter > *Ctx, const VarDecl *VD)
Definition Compiler.cpp:290
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:256
Compiler< Emitter > * Ctx
Definition Compiler.cpp:263
InitStackScope(Compiler< Emitter > *Ctx, bool Active)
Definition Compiler.cpp:268
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:216
~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:308
OptionScope(Compiler< Emitter > *Ctx, bool NewDiscardResult, bool NewInitializing, bool NewToLValue)
Root constructor, compiling or discarding primitives.
Definition Compiler.cpp:311
Context to manage declaration lifetimes.
Definition Program.h:148
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:58
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:123
Describes a scope block.
Definition Function.h:36
Describes the statement/declaration an opcode was generated from.
Definition Source.h:76
const Expr * asExpr() const
Definition Source.cpp:35
SourceLocScope(Compiler< Emitter > *Ctx, const Expr *DefaultExpr)
Definition Compiler.cpp:235
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:436
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1518
static llvm::RoundingMode getRoundingMode(FPOptions FPO)
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
Definition Descriptor.h:29
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:781
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:3167
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:2799
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:1525
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:2283
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2400
bool Mul(InterpState &S, CodePtr OpPC)
Definition Interp.h:490
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:975
bool Add(InterpState &S, CodePtr OpPC)
Definition Interp.h:407
llvm::BitVector collectNonNullArgs(const FunctionDecl *F, ArrayRef< const Expr * > Args)
llvm::APSInt APSInt
Definition FixedPoint.h:20
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool hasSpecificAttr(const Container &container)
@ Success
Annotation was successful.
Definition Parser.h:65
@ Link
'link' clause, allowed on 'declare' construct.
DynamicRecursiveASTVisitorBase< true > ConstDynamicRecursiveASTVisitor
Expr * Cond
};
@ SD_Static
Static storage duration.
Definition Specifiers.h:344
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:341
@ Result
The result type of a method or function.
Definition TypeBase.h:906
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
U cast(CodeGen::Address addr)
Definition Address.h:327
int const char * function
Definition c++config.h:31
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#define true
Definition stdbool.h:25
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
A quantity in bits.
Describes a memory block created by an allocation site.
Definition Descriptor.h:123
unsigned getNumElems() const
Returns the number of elements stored in the block.
Definition Descriptor.h:260
bool isPrimitive() const
Checks if the descriptor is of a primitive.
Definition Descriptor.h:274
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:267
QualType getType() const
const Descriptor *const ElemDesc
Descriptor of the array element.
Definition Descriptor.h:156
static constexpr MetadataSize InlineDescMD
Definition Descriptor.h:145
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition Descriptor.h:265
PrimType getPrimType() const
Definition Descriptor.h:242
bool isRecord() const
Checks if the descriptor is of a record.
Definition Descriptor.h:279
const Record *const ElemRecord
Pointer to the record, if block contains records.
Definition Descriptor.h:154
bool isArray() const
Checks if the descriptor is of an array.
Definition Descriptor.h:277
Descriptor used for global variables.
Definition Descriptor.h:50
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:97
static VarCreationState NotCreated()
Definition Compiler.h:101