xref: /llvm-project/clang/lib/AST/ByteCode/Compiler.cpp (revision 6cbd8a309485329a4fbfe7abf7b85e0b8f154561)
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"
19 
20 using namespace clang;
21 using namespace clang::interp;
22 
23 using APSInt = llvm::APSInt;
24 
25 namespace clang {
26 namespace interp {
27 
28 /// Scope used to handle temporaries in toplevel variable declarations.
29 template <class Emitter> class DeclScope final : public LocalScope<Emitter> {
30 public:
31   DeclScope(Compiler<Emitter> *Ctx, const ValueDecl *VD)
32       : LocalScope<Emitter>(Ctx, VD), Scope(Ctx->P, VD),
33         OldInitializingDecl(Ctx->InitializingDecl) {
34     Ctx->InitializingDecl = VD;
35     Ctx->InitStack.push_back(InitLink::Decl(VD));
36   }
37 
38   void addExtended(const Scope::Local &Local) override {
39     return this->addLocal(Local);
40   }
41 
42   ~DeclScope() {
43     this->Ctx->InitializingDecl = OldInitializingDecl;
44     this->Ctx->InitStack.pop_back();
45   }
46 
47 private:
48   Program::DeclScope Scope;
49   const ValueDecl *OldInitializingDecl;
50 };
51 
52 /// Scope used to handle initialization methods.
53 template <class Emitter> class OptionScope final {
54 public:
55   /// Root constructor, compiling or discarding primitives.
56   OptionScope(Compiler<Emitter> *Ctx, bool NewDiscardResult,
57               bool NewInitializing)
58       : Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult),
59         OldInitializing(Ctx->Initializing) {
60     Ctx->DiscardResult = NewDiscardResult;
61     Ctx->Initializing = NewInitializing;
62   }
63 
64   ~OptionScope() {
65     Ctx->DiscardResult = OldDiscardResult;
66     Ctx->Initializing = OldInitializing;
67   }
68 
69 private:
70   /// Parent context.
71   Compiler<Emitter> *Ctx;
72   /// Old discard flag to restore.
73   bool OldDiscardResult;
74   bool OldInitializing;
75 };
76 
77 template <class Emitter>
78 bool InitLink::emit(Compiler<Emitter> *Ctx, const Expr *E) const {
79   switch (Kind) {
80   case K_This:
81     return Ctx->emitThis(E);
82   case K_Field:
83     // We're assuming there's a base pointer on the stack already.
84     return Ctx->emitGetPtrFieldPop(Offset, E);
85   case K_Temp:
86     return Ctx->emitGetPtrLocal(Offset, E);
87   case K_Decl:
88     return Ctx->visitDeclRef(D, E);
89   case K_Elem:
90     if (!Ctx->emitConstUint32(Offset, E))
91       return false;
92     return Ctx->emitArrayElemPtrPopUint32(E);
93   default:
94     llvm_unreachable("Unhandled InitLink kind");
95   }
96   return true;
97 }
98 
99 /// Scope managing label targets.
100 template <class Emitter> class LabelScope {
101 public:
102   virtual ~LabelScope() {}
103 
104 protected:
105   LabelScope(Compiler<Emitter> *Ctx) : Ctx(Ctx) {}
106   /// Compiler instance.
107   Compiler<Emitter> *Ctx;
108 };
109 
110 /// Sets the context for break/continue statements.
111 template <class Emitter> class LoopScope final : public LabelScope<Emitter> {
112 public:
113   using LabelTy = typename Compiler<Emitter>::LabelTy;
114   using OptLabelTy = typename Compiler<Emitter>::OptLabelTy;
115 
116   LoopScope(Compiler<Emitter> *Ctx, LabelTy BreakLabel, LabelTy ContinueLabel)
117       : LabelScope<Emitter>(Ctx), OldBreakLabel(Ctx->BreakLabel),
118         OldContinueLabel(Ctx->ContinueLabel),
119         OldBreakVarScope(Ctx->BreakVarScope),
120         OldContinueVarScope(Ctx->ContinueVarScope) {
121     this->Ctx->BreakLabel = BreakLabel;
122     this->Ctx->ContinueLabel = ContinueLabel;
123     this->Ctx->BreakVarScope = this->Ctx->VarScope;
124     this->Ctx->ContinueVarScope = this->Ctx->VarScope;
125   }
126 
127   ~LoopScope() {
128     this->Ctx->BreakLabel = OldBreakLabel;
129     this->Ctx->ContinueLabel = OldContinueLabel;
130     this->Ctx->ContinueVarScope = OldContinueVarScope;
131     this->Ctx->BreakVarScope = OldBreakVarScope;
132   }
133 
134 private:
135   OptLabelTy OldBreakLabel;
136   OptLabelTy OldContinueLabel;
137   VariableScope<Emitter> *OldBreakVarScope;
138   VariableScope<Emitter> *OldContinueVarScope;
139 };
140 
141 // Sets the context for a switch scope, mapping labels.
142 template <class Emitter> class SwitchScope final : public LabelScope<Emitter> {
143 public:
144   using LabelTy = typename Compiler<Emitter>::LabelTy;
145   using OptLabelTy = typename Compiler<Emitter>::OptLabelTy;
146   using CaseMap = typename Compiler<Emitter>::CaseMap;
147 
148   SwitchScope(Compiler<Emitter> *Ctx, CaseMap &&CaseLabels, LabelTy BreakLabel,
149               OptLabelTy DefaultLabel)
150       : LabelScope<Emitter>(Ctx), OldBreakLabel(Ctx->BreakLabel),
151         OldDefaultLabel(this->Ctx->DefaultLabel),
152         OldCaseLabels(std::move(this->Ctx->CaseLabels)),
153         OldLabelVarScope(Ctx->BreakVarScope) {
154     this->Ctx->BreakLabel = BreakLabel;
155     this->Ctx->DefaultLabel = DefaultLabel;
156     this->Ctx->CaseLabels = std::move(CaseLabels);
157     this->Ctx->BreakVarScope = this->Ctx->VarScope;
158   }
159 
160   ~SwitchScope() {
161     this->Ctx->BreakLabel = OldBreakLabel;
162     this->Ctx->DefaultLabel = OldDefaultLabel;
163     this->Ctx->CaseLabels = std::move(OldCaseLabels);
164     this->Ctx->BreakVarScope = OldLabelVarScope;
165   }
166 
167 private:
168   OptLabelTy OldBreakLabel;
169   OptLabelTy OldDefaultLabel;
170   CaseMap OldCaseLabels;
171   VariableScope<Emitter> *OldLabelVarScope;
172 };
173 
174 template <class Emitter> class StmtExprScope final {
175 public:
176   StmtExprScope(Compiler<Emitter> *Ctx) : Ctx(Ctx), OldFlag(Ctx->InStmtExpr) {
177     Ctx->InStmtExpr = true;
178   }
179 
180   ~StmtExprScope() { Ctx->InStmtExpr = OldFlag; }
181 
182 private:
183   Compiler<Emitter> *Ctx;
184   bool OldFlag;
185 };
186 
187 } // namespace interp
188 } // namespace clang
189 
190 template <class Emitter>
191 bool Compiler<Emitter>::VisitCastExpr(const CastExpr *CE) {
192   const Expr *SubExpr = CE->getSubExpr();
193   switch (CE->getCastKind()) {
194 
195   case CK_LValueToRValue: {
196     if (DiscardResult)
197       return this->discard(SubExpr);
198 
199     std::optional<PrimType> SubExprT = classify(SubExpr->getType());
200     // Prepare storage for the result.
201     if (!Initializing && !SubExprT) {
202       std::optional<unsigned> LocalIndex = allocateLocal(SubExpr);
203       if (!LocalIndex)
204         return false;
205       if (!this->emitGetPtrLocal(*LocalIndex, CE))
206         return false;
207     }
208 
209     if (!this->visit(SubExpr))
210       return false;
211 
212     if (SubExprT)
213       return this->emitLoadPop(*SubExprT, CE);
214 
215     // If the subexpr type is not primitive, we need to perform a copy here.
216     // This happens for example in C when dereferencing a pointer of struct
217     // type.
218     return this->emitMemcpy(CE);
219   }
220 
221   case CK_DerivedToBaseMemberPointer: {
222     assert(classifyPrim(CE->getType()) == PT_MemberPtr);
223     assert(classifyPrim(SubExpr->getType()) == PT_MemberPtr);
224     const auto *FromMP = SubExpr->getType()->getAs<MemberPointerType>();
225     const auto *ToMP = CE->getType()->getAs<MemberPointerType>();
226 
227     unsigned DerivedOffset = collectBaseOffset(QualType(ToMP->getClass(), 0),
228                                                QualType(FromMP->getClass(), 0));
229 
230     if (!this->delegate(SubExpr))
231       return false;
232 
233     return this->emitGetMemberPtrBasePop(DerivedOffset, CE);
234   }
235 
236   case CK_BaseToDerivedMemberPointer: {
237     assert(classifyPrim(CE) == PT_MemberPtr);
238     assert(classifyPrim(SubExpr) == PT_MemberPtr);
239     const auto *FromMP = SubExpr->getType()->getAs<MemberPointerType>();
240     const auto *ToMP = CE->getType()->getAs<MemberPointerType>();
241 
242     unsigned DerivedOffset = collectBaseOffset(QualType(FromMP->getClass(), 0),
243                                                QualType(ToMP->getClass(), 0));
244 
245     if (!this->delegate(SubExpr))
246       return false;
247     return this->emitGetMemberPtrBasePop(-DerivedOffset, CE);
248   }
249 
250   case CK_UncheckedDerivedToBase:
251   case CK_DerivedToBase: {
252     if (!this->delegate(SubExpr))
253       return false;
254 
255     const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
256       if (const auto *PT = dyn_cast<PointerType>(Ty))
257         return PT->getPointeeType()->getAsCXXRecordDecl();
258       return Ty->getAsCXXRecordDecl();
259     };
260 
261     // FIXME: We can express a series of non-virtual casts as a single
262     // GetPtrBasePop op.
263     QualType CurType = SubExpr->getType();
264     for (const CXXBaseSpecifier *B : CE->path()) {
265       if (B->isVirtual()) {
266         if (!this->emitGetPtrVirtBasePop(extractRecordDecl(B->getType()), CE))
267           return false;
268         CurType = B->getType();
269       } else {
270         unsigned DerivedOffset = collectBaseOffset(B->getType(), CurType);
271         if (!this->emitGetPtrBasePop(DerivedOffset, CE))
272           return false;
273         CurType = B->getType();
274       }
275     }
276 
277     return true;
278   }
279 
280   case CK_BaseToDerived: {
281     if (!this->delegate(SubExpr))
282       return false;
283 
284     unsigned DerivedOffset =
285         collectBaseOffset(SubExpr->getType(), CE->getType());
286 
287     return this->emitGetPtrDerivedPop(DerivedOffset, CE);
288   }
289 
290   case CK_FloatingCast: {
291     // HLSL uses CK_FloatingCast to cast between vectors.
292     if (!SubExpr->getType()->isFloatingType() ||
293         !CE->getType()->isFloatingType())
294       return false;
295     if (DiscardResult)
296       return this->discard(SubExpr);
297     if (!this->visit(SubExpr))
298       return false;
299     const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
300     return this->emitCastFP(TargetSemantics, getRoundingMode(CE), CE);
301   }
302 
303   case CK_IntegralToFloating: {
304     if (DiscardResult)
305       return this->discard(SubExpr);
306     std::optional<PrimType> FromT = classify(SubExpr->getType());
307     if (!FromT)
308       return false;
309 
310     if (!this->visit(SubExpr))
311       return false;
312 
313     const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType());
314     return this->emitCastIntegralFloating(*FromT, TargetSemantics,
315                                           getFPOptions(CE), CE);
316   }
317 
318   case CK_FloatingToBoolean:
319   case CK_FloatingToIntegral: {
320     if (DiscardResult)
321       return this->discard(SubExpr);
322 
323     std::optional<PrimType> ToT = classify(CE->getType());
324 
325     if (!ToT)
326       return false;
327 
328     if (!this->visit(SubExpr))
329       return false;
330 
331     if (ToT == PT_IntAP)
332       return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(CE->getType()),
333                                               getFPOptions(CE), CE);
334     if (ToT == PT_IntAPS)
335       return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(CE->getType()),
336                                                getFPOptions(CE), CE);
337 
338     return this->emitCastFloatingIntegral(*ToT, getFPOptions(CE), CE);
339   }
340 
341   case CK_NullToPointer:
342   case CK_NullToMemberPointer: {
343     if (!this->discard(SubExpr))
344       return false;
345     if (DiscardResult)
346       return true;
347 
348     const Descriptor *Desc = nullptr;
349     const QualType PointeeType = CE->getType()->getPointeeType();
350     if (!PointeeType.isNull()) {
351       if (std::optional<PrimType> T = classify(PointeeType))
352         Desc = P.createDescriptor(SubExpr, *T);
353       else
354         Desc = P.createDescriptor(SubExpr, PointeeType.getTypePtr(),
355                                   std::nullopt, true, false,
356                                   /*IsMutable=*/false, nullptr);
357     }
358     return this->emitNull(classifyPrim(CE->getType()), Desc, CE);
359   }
360 
361   case CK_PointerToIntegral: {
362     if (DiscardResult)
363       return this->discard(SubExpr);
364 
365     if (!this->visit(SubExpr))
366       return false;
367 
368     // If SubExpr doesn't result in a pointer, make it one.
369     if (PrimType FromT = classifyPrim(SubExpr->getType()); FromT != PT_Ptr) {
370       assert(isPtrType(FromT));
371       if (!this->emitDecayPtr(FromT, PT_Ptr, CE))
372         return false;
373     }
374 
375     PrimType T = classifyPrim(CE->getType());
376     if (T == PT_IntAP)
377       return this->emitCastPointerIntegralAP(Ctx.getBitWidth(CE->getType()),
378                                              CE);
379     if (T == PT_IntAPS)
380       return this->emitCastPointerIntegralAPS(Ctx.getBitWidth(CE->getType()),
381                                               CE);
382     return this->emitCastPointerIntegral(T, CE);
383   }
384 
385   case CK_ArrayToPointerDecay: {
386     if (!this->visit(SubExpr))
387       return false;
388     if (!this->emitArrayDecay(CE))
389       return false;
390     if (DiscardResult)
391       return this->emitPopPtr(CE);
392     return true;
393   }
394 
395   case CK_IntegralToPointer: {
396     QualType IntType = SubExpr->getType();
397     assert(IntType->isIntegralOrEnumerationType());
398     if (!this->visit(SubExpr))
399       return false;
400     // FIXME: I think the discard is wrong since the int->ptr cast might cause a
401     // diagnostic.
402     PrimType T = classifyPrim(IntType);
403     if (DiscardResult)
404       return this->emitPop(T, CE);
405 
406     QualType PtrType = CE->getType();
407     const Descriptor *Desc;
408     if (std::optional<PrimType> T = classify(PtrType->getPointeeType()))
409       Desc = P.createDescriptor(SubExpr, *T);
410     else if (PtrType->getPointeeType()->isVoidType())
411       Desc = nullptr;
412     else
413       Desc = P.createDescriptor(CE, PtrType->getPointeeType().getTypePtr(),
414                                 Descriptor::InlineDescMD, true, false,
415                                 /*IsMutable=*/false, nullptr);
416 
417     if (!this->emitGetIntPtr(T, Desc, CE))
418       return false;
419 
420     PrimType DestPtrT = classifyPrim(PtrType);
421     if (DestPtrT == PT_Ptr)
422       return true;
423 
424     // In case we're converting the integer to a non-Pointer.
425     return this->emitDecayPtr(PT_Ptr, DestPtrT, CE);
426   }
427 
428   case CK_AtomicToNonAtomic:
429   case CK_ConstructorConversion:
430   case CK_FunctionToPointerDecay:
431   case CK_NonAtomicToAtomic:
432   case CK_NoOp:
433   case CK_UserDefinedConversion:
434   case CK_AddressSpaceConversion:
435   case CK_CPointerToObjCPointerCast:
436     return this->delegate(SubExpr);
437 
438   case CK_BitCast: {
439     // Reject bitcasts to atomic types.
440     if (CE->getType()->isAtomicType()) {
441       if (!this->discard(SubExpr))
442         return false;
443       return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, CE);
444     }
445 
446     if (DiscardResult)
447       return this->discard(SubExpr);
448 
449     QualType SubExprTy = SubExpr->getType();
450     std::optional<PrimType> FromT = classify(SubExprTy);
451     std::optional<PrimType> ToT = classify(CE->getType());
452     if (!FromT || !ToT)
453       return false;
454 
455     assert(isPtrType(*FromT));
456     assert(isPtrType(*ToT));
457     if (FromT == ToT) {
458       if (CE->getType()->isVoidPointerType())
459         return this->delegate(SubExpr);
460 
461       if (!this->visit(SubExpr))
462         return false;
463       if (FromT == PT_Ptr)
464         return this->emitPtrPtrCast(SubExprTy->isVoidPointerType(), CE);
465       return true;
466     }
467 
468     if (!this->visit(SubExpr))
469       return false;
470     return this->emitDecayPtr(*FromT, *ToT, CE);
471   }
472 
473   case CK_IntegralToBoolean:
474   case CK_FixedPointToBoolean:
475   case CK_BooleanToSignedIntegral:
476   case CK_IntegralCast: {
477     if (DiscardResult)
478       return this->discard(SubExpr);
479     std::optional<PrimType> FromT = classify(SubExpr->getType());
480     std::optional<PrimType> ToT = classify(CE->getType());
481 
482     if (!FromT || !ToT)
483       return false;
484 
485     if (!this->visit(SubExpr))
486       return false;
487 
488     // Possibly diagnose casts to enum types if the target type does not
489     // have a fixed size.
490     if (Ctx.getLangOpts().CPlusPlus && CE->getType()->isEnumeralType()) {
491       if (const auto *ET = CE->getType().getCanonicalType()->getAs<EnumType>();
492           ET && !ET->getDecl()->isFixed()) {
493         if (!this->emitCheckEnumValue(*FromT, ET->getDecl(), CE))
494           return false;
495       }
496     }
497 
498     auto maybeNegate = [&]() -> bool {
499       if (CE->getCastKind() == CK_BooleanToSignedIntegral)
500         return this->emitNeg(*ToT, CE);
501       return true;
502     };
503 
504     if (ToT == PT_IntAP)
505       return this->emitCastAP(*FromT, Ctx.getBitWidth(CE->getType()), CE) &&
506              maybeNegate();
507     if (ToT == PT_IntAPS)
508       return this->emitCastAPS(*FromT, Ctx.getBitWidth(CE->getType()), CE) &&
509              maybeNegate();
510 
511     if (FromT == ToT)
512       return true;
513     if (!this->emitCast(*FromT, *ToT, CE))
514       return false;
515 
516     return maybeNegate();
517   }
518 
519   case CK_PointerToBoolean:
520   case CK_MemberPointerToBoolean: {
521     PrimType PtrT = classifyPrim(SubExpr->getType());
522 
523     if (!this->visit(SubExpr))
524       return false;
525     return this->emitIsNonNull(PtrT, CE);
526   }
527 
528   case CK_IntegralComplexToBoolean:
529   case CK_FloatingComplexToBoolean: {
530     if (DiscardResult)
531       return this->discard(SubExpr);
532     if (!this->visit(SubExpr))
533       return false;
534     return this->emitComplexBoolCast(SubExpr);
535   }
536 
537   case CK_IntegralComplexToReal:
538   case CK_FloatingComplexToReal:
539     return this->emitComplexReal(SubExpr);
540 
541   case CK_IntegralRealToComplex:
542   case CK_FloatingRealToComplex: {
543     // We're creating a complex value here, so we need to
544     // allocate storage for it.
545     if (!Initializing) {
546       unsigned LocalIndex = allocateTemporary(CE);
547       if (!this->emitGetPtrLocal(LocalIndex, CE))
548         return false;
549     }
550 
551     // Init the complex value to {SubExpr, 0}.
552     if (!this->visitArrayElemInit(0, SubExpr))
553       return false;
554     // Zero-init the second element.
555     PrimType T = classifyPrim(SubExpr->getType());
556     if (!this->visitZeroInitializer(T, SubExpr->getType(), SubExpr))
557       return false;
558     return this->emitInitElem(T, 1, SubExpr);
559   }
560 
561   case CK_IntegralComplexCast:
562   case CK_FloatingComplexCast:
563   case CK_IntegralComplexToFloatingComplex:
564   case CK_FloatingComplexToIntegralComplex: {
565     assert(CE->getType()->isAnyComplexType());
566     assert(SubExpr->getType()->isAnyComplexType());
567     if (DiscardResult)
568       return this->discard(SubExpr);
569 
570     if (!Initializing) {
571       std::optional<unsigned> LocalIndex = allocateLocal(CE);
572       if (!LocalIndex)
573         return false;
574       if (!this->emitGetPtrLocal(*LocalIndex, CE))
575         return false;
576     }
577 
578     // Location for the SubExpr.
579     // Since SubExpr is of complex type, visiting it results in a pointer
580     // anyway, so we just create a temporary pointer variable.
581     unsigned SubExprOffset = allocateLocalPrimitive(
582         SubExpr, PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false);
583     if (!this->visit(SubExpr))
584       return false;
585     if (!this->emitSetLocal(PT_Ptr, SubExprOffset, CE))
586       return false;
587 
588     PrimType SourceElemT = classifyComplexElementType(SubExpr->getType());
589     QualType DestElemType =
590         CE->getType()->getAs<ComplexType>()->getElementType();
591     PrimType DestElemT = classifyPrim(DestElemType);
592     // Cast both elements individually.
593     for (unsigned I = 0; I != 2; ++I) {
594       if (!this->emitGetLocal(PT_Ptr, SubExprOffset, CE))
595         return false;
596       if (!this->emitArrayElemPop(SourceElemT, I, CE))
597         return false;
598 
599       // Do the cast.
600       if (!this->emitPrimCast(SourceElemT, DestElemT, DestElemType, CE))
601         return false;
602 
603       // Save the value.
604       if (!this->emitInitElem(DestElemT, I, CE))
605         return false;
606     }
607     return true;
608   }
609 
610   case CK_VectorSplat: {
611     assert(!classify(CE->getType()));
612     assert(classify(SubExpr->getType()));
613     assert(CE->getType()->isVectorType());
614 
615     if (DiscardResult)
616       return this->discard(SubExpr);
617 
618     if (!Initializing) {
619       std::optional<unsigned> LocalIndex = allocateLocal(CE);
620       if (!LocalIndex)
621         return false;
622       if (!this->emitGetPtrLocal(*LocalIndex, CE))
623         return false;
624     }
625 
626     const auto *VT = CE->getType()->getAs<VectorType>();
627     PrimType ElemT = classifyPrim(SubExpr->getType());
628     unsigned ElemOffset = allocateLocalPrimitive(
629         SubExpr, ElemT, /*IsConst=*/true, /*IsExtended=*/false);
630 
631     // Prepare a local variable for the scalar value.
632     if (!this->visit(SubExpr))
633       return false;
634     if (classifyPrim(SubExpr) == PT_Ptr && !this->emitLoadPop(ElemT, CE))
635       return false;
636 
637     if (!this->emitSetLocal(ElemT, ElemOffset, CE))
638       return false;
639 
640     for (unsigned I = 0; I != VT->getNumElements(); ++I) {
641       if (!this->emitGetLocal(ElemT, ElemOffset, CE))
642         return false;
643       if (!this->emitInitElem(ElemT, I, CE))
644         return false;
645     }
646 
647     return true;
648   }
649 
650   case CK_HLSLVectorTruncation: {
651     assert(SubExpr->getType()->isVectorType());
652     if (std::optional<PrimType> ResultT = classify(CE)) {
653       assert(!DiscardResult);
654       // Result must be either a float or integer. Take the first element.
655       if (!this->visit(SubExpr))
656         return false;
657       return this->emitArrayElemPop(*ResultT, 0, CE);
658     }
659     // Otherwise, this truncates from one vector type to another.
660     assert(CE->getType()->isVectorType());
661 
662     if (!Initializing) {
663       unsigned LocalIndex = allocateTemporary(CE);
664       if (!this->emitGetPtrLocal(LocalIndex, CE))
665         return false;
666     }
667     unsigned ToSize = CE->getType()->getAs<VectorType>()->getNumElements();
668     assert(SubExpr->getType()->getAs<VectorType>()->getNumElements() > ToSize);
669     if (!this->visit(SubExpr))
670       return false;
671     return this->emitCopyArray(classifyVectorElementType(CE->getType()), 0, 0,
672                                ToSize, CE);
673   };
674 
675   case CK_IntegralToFixedPoint: {
676     if (!this->visit(SubExpr))
677       return false;
678 
679     auto Sem = Ctx.getASTContext().getFixedPointSemantics(CE->getType());
680     uint32_t I;
681     std::memcpy(&I, &Sem, sizeof(Sem));
682     return this->emitCastIntegralFixedPoint(classifyPrim(SubExpr->getType()), I,
683                                             CE);
684   }
685   case CK_FloatingToFixedPoint: {
686     if (!this->visit(SubExpr))
687       return false;
688 
689     auto Sem = Ctx.getASTContext().getFixedPointSemantics(CE->getType());
690     uint32_t I;
691     std::memcpy(&I, &Sem, sizeof(Sem));
692     return this->emitCastFloatingFixedPoint(I, CE);
693   }
694 
695   case CK_ToVoid:
696     return discard(SubExpr);
697 
698   default:
699     return this->emitInvalid(CE);
700   }
701   llvm_unreachable("Unhandled clang::CastKind enum");
702 }
703 
704 template <class Emitter>
705 bool Compiler<Emitter>::VisitIntegerLiteral(const IntegerLiteral *LE) {
706   if (DiscardResult)
707     return true;
708 
709   return this->emitConst(LE->getValue(), LE);
710 }
711 
712 template <class Emitter>
713 bool Compiler<Emitter>::VisitFloatingLiteral(const FloatingLiteral *E) {
714   if (DiscardResult)
715     return true;
716 
717   return this->emitConstFloat(E->getValue(), E);
718 }
719 
720 template <class Emitter>
721 bool Compiler<Emitter>::VisitImaginaryLiteral(const ImaginaryLiteral *E) {
722   assert(E->getType()->isAnyComplexType());
723   if (DiscardResult)
724     return true;
725 
726   if (!Initializing) {
727     unsigned LocalIndex = allocateTemporary(E);
728     if (!this->emitGetPtrLocal(LocalIndex, E))
729       return false;
730   }
731 
732   const Expr *SubExpr = E->getSubExpr();
733   PrimType SubExprT = classifyPrim(SubExpr->getType());
734 
735   if (!this->visitZeroInitializer(SubExprT, SubExpr->getType(), SubExpr))
736     return false;
737   if (!this->emitInitElem(SubExprT, 0, SubExpr))
738     return false;
739   return this->visitArrayElemInit(1, SubExpr);
740 }
741 
742 template <class Emitter>
743 bool Compiler<Emitter>::VisitFixedPointLiteral(const FixedPointLiteral *E) {
744   assert(E->getType()->isFixedPointType());
745   assert(classifyPrim(E) == PT_FixedPoint);
746 
747   auto Sem = Ctx.getASTContext().getFixedPointSemantics(E->getType());
748   APInt Value = E->getValue();
749   return this->emitConstFixedPoint(FixedPoint(Value, Sem), E);
750 }
751 
752 template <class Emitter>
753 bool Compiler<Emitter>::VisitParenExpr(const ParenExpr *E) {
754   return this->delegate(E->getSubExpr());
755 }
756 
757 template <class Emitter>
758 bool Compiler<Emitter>::VisitBinaryOperator(const BinaryOperator *BO) {
759   // Need short-circuiting for these.
760   if (BO->isLogicalOp() && !BO->getType()->isVectorType())
761     return this->VisitLogicalBinOp(BO);
762 
763   const Expr *LHS = BO->getLHS();
764   const Expr *RHS = BO->getRHS();
765 
766   // Handle comma operators. Just discard the LHS
767   // and delegate to RHS.
768   if (BO->isCommaOp()) {
769     if (!this->discard(LHS))
770       return false;
771     if (RHS->getType()->isVoidType())
772       return this->discard(RHS);
773 
774     return this->delegate(RHS);
775   }
776 
777   if (BO->getType()->isAnyComplexType())
778     return this->VisitComplexBinOp(BO);
779   if (BO->getType()->isVectorType())
780     return this->VisitVectorBinOp(BO);
781   if ((LHS->getType()->isAnyComplexType() ||
782        RHS->getType()->isAnyComplexType()) &&
783       BO->isComparisonOp())
784     return this->emitComplexComparison(LHS, RHS, BO);
785   if (LHS->getType()->isFixedPointType() || RHS->getType()->isFixedPointType())
786     return this->VisitFixedPointBinOp(BO);
787 
788   if (BO->isPtrMemOp()) {
789     if (!this->visit(LHS))
790       return false;
791 
792     if (!this->visit(RHS))
793       return false;
794 
795     if (!this->emitToMemberPtr(BO))
796       return false;
797 
798     if (classifyPrim(BO) == PT_MemberPtr)
799       return true;
800 
801     if (!this->emitCastMemberPtrPtr(BO))
802       return false;
803     return DiscardResult ? this->emitPopPtr(BO) : true;
804   }
805 
806   // Typecheck the args.
807   std::optional<PrimType> LT = classify(LHS);
808   std::optional<PrimType> RT = classify(RHS);
809   std::optional<PrimType> T = classify(BO->getType());
810 
811   // Special case for C++'s three-way/spaceship operator <=>, which
812   // returns a std::{strong,weak,partial}_ordering (which is a class, so doesn't
813   // have a PrimType).
814   if (!T && BO->getOpcode() == BO_Cmp) {
815     if (DiscardResult)
816       return true;
817     const ComparisonCategoryInfo *CmpInfo =
818         Ctx.getASTContext().CompCategories.lookupInfoForType(BO->getType());
819     assert(CmpInfo);
820 
821     // We need a temporary variable holding our return value.
822     if (!Initializing) {
823       std::optional<unsigned> ResultIndex = this->allocateLocal(BO);
824       if (!this->emitGetPtrLocal(*ResultIndex, BO))
825         return false;
826     }
827 
828     if (!visit(LHS) || !visit(RHS))
829       return false;
830 
831     return this->emitCMP3(*LT, CmpInfo, BO);
832   }
833 
834   if (!LT || !RT || !T)
835     return false;
836 
837   // Pointer arithmetic special case.
838   if (BO->getOpcode() == BO_Add || BO->getOpcode() == BO_Sub) {
839     if (isPtrType(*T) || (isPtrType(*LT) && isPtrType(*RT)))
840       return this->VisitPointerArithBinOp(BO);
841   }
842 
843   // Assignmentes require us to evalute the RHS first.
844   if (BO->getOpcode() == BO_Assign) {
845     if (!visit(RHS) || !visit(LHS))
846       return false;
847     if (!this->emitFlip(*LT, *RT, BO))
848       return false;
849   } else {
850     if (!visit(LHS) || !visit(RHS))
851       return false;
852   }
853 
854   // For languages such as C, cast the result of one
855   // of our comparision opcodes to T (which is usually int).
856   auto MaybeCastToBool = [this, T, BO](bool Result) {
857     if (!Result)
858       return false;
859     if (DiscardResult)
860       return this->emitPop(*T, BO);
861     if (T != PT_Bool)
862       return this->emitCast(PT_Bool, *T, BO);
863     return true;
864   };
865 
866   auto Discard = [this, T, BO](bool Result) {
867     if (!Result)
868       return false;
869     return DiscardResult ? this->emitPop(*T, BO) : true;
870   };
871 
872   switch (BO->getOpcode()) {
873   case BO_EQ:
874     return MaybeCastToBool(this->emitEQ(*LT, BO));
875   case BO_NE:
876     return MaybeCastToBool(this->emitNE(*LT, BO));
877   case BO_LT:
878     return MaybeCastToBool(this->emitLT(*LT, BO));
879   case BO_LE:
880     return MaybeCastToBool(this->emitLE(*LT, BO));
881   case BO_GT:
882     return MaybeCastToBool(this->emitGT(*LT, BO));
883   case BO_GE:
884     return MaybeCastToBool(this->emitGE(*LT, BO));
885   case BO_Sub:
886     if (BO->getType()->isFloatingType())
887       return Discard(this->emitSubf(getFPOptions(BO), BO));
888     return Discard(this->emitSub(*T, BO));
889   case BO_Add:
890     if (BO->getType()->isFloatingType())
891       return Discard(this->emitAddf(getFPOptions(BO), BO));
892     return Discard(this->emitAdd(*T, BO));
893   case BO_Mul:
894     if (BO->getType()->isFloatingType())
895       return Discard(this->emitMulf(getFPOptions(BO), BO));
896     return Discard(this->emitMul(*T, BO));
897   case BO_Rem:
898     return Discard(this->emitRem(*T, BO));
899   case BO_Div:
900     if (BO->getType()->isFloatingType())
901       return Discard(this->emitDivf(getFPOptions(BO), BO));
902     return Discard(this->emitDiv(*T, BO));
903   case BO_Assign:
904     if (DiscardResult)
905       return LHS->refersToBitField() ? this->emitStoreBitFieldPop(*T, BO)
906                                      : this->emitStorePop(*T, BO);
907     if (LHS->refersToBitField()) {
908       if (!this->emitStoreBitField(*T, BO))
909         return false;
910     } else {
911       if (!this->emitStore(*T, BO))
912         return false;
913     }
914     // Assignments aren't necessarily lvalues in C.
915     // Load from them in that case.
916     if (!BO->isLValue())
917       return this->emitLoadPop(*T, BO);
918     return true;
919   case BO_And:
920     return Discard(this->emitBitAnd(*T, BO));
921   case BO_Or:
922     return Discard(this->emitBitOr(*T, BO));
923   case BO_Shl:
924     return Discard(this->emitShl(*LT, *RT, BO));
925   case BO_Shr:
926     return Discard(this->emitShr(*LT, *RT, BO));
927   case BO_Xor:
928     return Discard(this->emitBitXor(*T, BO));
929   case BO_LOr:
930   case BO_LAnd:
931     llvm_unreachable("Already handled earlier");
932   default:
933     return false;
934   }
935 
936   llvm_unreachable("Unhandled binary op");
937 }
938 
939 /// Perform addition/subtraction of a pointer and an integer or
940 /// subtraction of two pointers.
941 template <class Emitter>
942 bool Compiler<Emitter>::VisitPointerArithBinOp(const BinaryOperator *E) {
943   BinaryOperatorKind Op = E->getOpcode();
944   const Expr *LHS = E->getLHS();
945   const Expr *RHS = E->getRHS();
946 
947   if ((Op != BO_Add && Op != BO_Sub) ||
948       (!LHS->getType()->isPointerType() && !RHS->getType()->isPointerType()))
949     return false;
950 
951   std::optional<PrimType> LT = classify(LHS);
952   std::optional<PrimType> RT = classify(RHS);
953 
954   if (!LT || !RT)
955     return false;
956 
957   // Visit the given pointer expression and optionally convert to a PT_Ptr.
958   auto visitAsPointer = [&](const Expr *E, PrimType T) -> bool {
959     if (!this->visit(E))
960       return false;
961     if (T != PT_Ptr)
962       return this->emitDecayPtr(T, PT_Ptr, E);
963     return true;
964   };
965 
966   if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) {
967     if (Op != BO_Sub)
968       return false;
969 
970     assert(E->getType()->isIntegerType());
971     if (!visitAsPointer(RHS, *RT) || !visitAsPointer(LHS, *LT))
972       return false;
973 
974     return this->emitSubPtr(classifyPrim(E->getType()), E);
975   }
976 
977   PrimType OffsetType;
978   if (LHS->getType()->isIntegerType()) {
979     if (!visitAsPointer(RHS, *RT))
980       return false;
981     if (!this->visit(LHS))
982       return false;
983     OffsetType = *LT;
984   } else if (RHS->getType()->isIntegerType()) {
985     if (!visitAsPointer(LHS, *LT))
986       return false;
987     if (!this->visit(RHS))
988       return false;
989     OffsetType = *RT;
990   } else {
991     return false;
992   }
993 
994   // Do the operation and optionally transform to
995   // result pointer type.
996   if (Op == BO_Add) {
997     if (!this->emitAddOffset(OffsetType, E))
998       return false;
999 
1000     if (classifyPrim(E) != PT_Ptr)
1001       return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
1002     return true;
1003   } else if (Op == BO_Sub) {
1004     if (!this->emitSubOffset(OffsetType, E))
1005       return false;
1006 
1007     if (classifyPrim(E) != PT_Ptr)
1008       return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E);
1009     return true;
1010   }
1011 
1012   return false;
1013 }
1014 
1015 template <class Emitter>
1016 bool Compiler<Emitter>::VisitLogicalBinOp(const BinaryOperator *E) {
1017   assert(E->isLogicalOp());
1018   BinaryOperatorKind Op = E->getOpcode();
1019   const Expr *LHS = E->getLHS();
1020   const Expr *RHS = E->getRHS();
1021   std::optional<PrimType> T = classify(E->getType());
1022 
1023   if (Op == BO_LOr) {
1024     // Logical OR. Visit LHS and only evaluate RHS if LHS was FALSE.
1025     LabelTy LabelTrue = this->getLabel();
1026     LabelTy LabelEnd = this->getLabel();
1027 
1028     if (!this->visitBool(LHS))
1029       return false;
1030     if (!this->jumpTrue(LabelTrue))
1031       return false;
1032 
1033     if (!this->visitBool(RHS))
1034       return false;
1035     if (!this->jump(LabelEnd))
1036       return false;
1037 
1038     this->emitLabel(LabelTrue);
1039     this->emitConstBool(true, E);
1040     this->fallthrough(LabelEnd);
1041     this->emitLabel(LabelEnd);
1042 
1043   } else {
1044     assert(Op == BO_LAnd);
1045     // Logical AND.
1046     // Visit LHS. Only visit RHS if LHS was TRUE.
1047     LabelTy LabelFalse = this->getLabel();
1048     LabelTy LabelEnd = this->getLabel();
1049 
1050     if (!this->visitBool(LHS))
1051       return false;
1052     if (!this->jumpFalse(LabelFalse))
1053       return false;
1054 
1055     if (!this->visitBool(RHS))
1056       return false;
1057     if (!this->jump(LabelEnd))
1058       return false;
1059 
1060     this->emitLabel(LabelFalse);
1061     this->emitConstBool(false, E);
1062     this->fallthrough(LabelEnd);
1063     this->emitLabel(LabelEnd);
1064   }
1065 
1066   if (DiscardResult)
1067     return this->emitPopBool(E);
1068 
1069   // For C, cast back to integer type.
1070   assert(T);
1071   if (T != PT_Bool)
1072     return this->emitCast(PT_Bool, *T, E);
1073   return true;
1074 }
1075 
1076 template <class Emitter>
1077 bool Compiler<Emitter>::VisitComplexBinOp(const BinaryOperator *E) {
1078   // Prepare storage for result.
1079   if (!Initializing) {
1080     unsigned LocalIndex = allocateTemporary(E);
1081     if (!this->emitGetPtrLocal(LocalIndex, E))
1082       return false;
1083   }
1084 
1085   // Both LHS and RHS might _not_ be of complex type, but one of them
1086   // needs to be.
1087   const Expr *LHS = E->getLHS();
1088   const Expr *RHS = E->getRHS();
1089 
1090   PrimType ResultElemT = this->classifyComplexElementType(E->getType());
1091   unsigned ResultOffset = ~0u;
1092   if (!DiscardResult)
1093     ResultOffset = this->allocateLocalPrimitive(E, PT_Ptr, true, false);
1094 
1095   // Save result pointer in ResultOffset
1096   if (!this->DiscardResult) {
1097     if (!this->emitDupPtr(E))
1098       return false;
1099     if (!this->emitSetLocal(PT_Ptr, ResultOffset, E))
1100       return false;
1101   }
1102   QualType LHSType = LHS->getType();
1103   if (const auto *AT = LHSType->getAs<AtomicType>())
1104     LHSType = AT->getValueType();
1105   QualType RHSType = RHS->getType();
1106   if (const auto *AT = RHSType->getAs<AtomicType>())
1107     RHSType = AT->getValueType();
1108 
1109   bool LHSIsComplex = LHSType->isAnyComplexType();
1110   unsigned LHSOffset;
1111   bool RHSIsComplex = RHSType->isAnyComplexType();
1112 
1113   // For ComplexComplex Mul, we have special ops to make their implementation
1114   // easier.
1115   BinaryOperatorKind Op = E->getOpcode();
1116   if (Op == BO_Mul && LHSIsComplex && RHSIsComplex) {
1117     assert(classifyPrim(LHSType->getAs<ComplexType>()->getElementType()) ==
1118            classifyPrim(RHSType->getAs<ComplexType>()->getElementType()));
1119     PrimType ElemT =
1120         classifyPrim(LHSType->getAs<ComplexType>()->getElementType());
1121     if (!this->visit(LHS))
1122       return false;
1123     if (!this->visit(RHS))
1124       return false;
1125     return this->emitMulc(ElemT, E);
1126   }
1127 
1128   if (Op == BO_Div && RHSIsComplex) {
1129     QualType ElemQT = RHSType->getAs<ComplexType>()->getElementType();
1130     PrimType ElemT = classifyPrim(ElemQT);
1131     // If the LHS is not complex, we still need to do the full complex
1132     // division, so just stub create a complex value and stub it out with
1133     // the LHS and a zero.
1134 
1135     if (!LHSIsComplex) {
1136       // This is using the RHS type for the fake-complex LHS.
1137       LHSOffset = allocateTemporary(RHS);
1138 
1139       if (!this->emitGetPtrLocal(LHSOffset, E))
1140         return false;
1141 
1142       if (!this->visit(LHS))
1143         return false;
1144       // real is LHS
1145       if (!this->emitInitElem(ElemT, 0, E))
1146         return false;
1147       // imag is zero
1148       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1149         return false;
1150       if (!this->emitInitElem(ElemT, 1, E))
1151         return false;
1152     } else {
1153       if (!this->visit(LHS))
1154         return false;
1155     }
1156 
1157     if (!this->visit(RHS))
1158       return false;
1159     return this->emitDivc(ElemT, E);
1160   }
1161 
1162   // Evaluate LHS and save value to LHSOffset.
1163   if (LHSType->isAnyComplexType()) {
1164     LHSOffset = this->allocateLocalPrimitive(LHS, PT_Ptr, true, false);
1165     if (!this->visit(LHS))
1166       return false;
1167     if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
1168       return false;
1169   } else {
1170     PrimType LHST = classifyPrim(LHSType);
1171     LHSOffset = this->allocateLocalPrimitive(LHS, LHST, true, false);
1172     if (!this->visit(LHS))
1173       return false;
1174     if (!this->emitSetLocal(LHST, LHSOffset, E))
1175       return false;
1176   }
1177 
1178   // Same with RHS.
1179   unsigned RHSOffset;
1180   if (RHSType->isAnyComplexType()) {
1181     RHSOffset = this->allocateLocalPrimitive(RHS, PT_Ptr, true, false);
1182     if (!this->visit(RHS))
1183       return false;
1184     if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
1185       return false;
1186   } else {
1187     PrimType RHST = classifyPrim(RHSType);
1188     RHSOffset = this->allocateLocalPrimitive(RHS, RHST, true, false);
1189     if (!this->visit(RHS))
1190       return false;
1191     if (!this->emitSetLocal(RHST, RHSOffset, E))
1192       return false;
1193   }
1194 
1195   // For both LHS and RHS, either load the value from the complex pointer, or
1196   // directly from the local variable. For index 1 (i.e. the imaginary part),
1197   // just load 0 and do the operation anyway.
1198   auto loadComplexValue = [this](bool IsComplex, bool LoadZero,
1199                                  unsigned ElemIndex, unsigned Offset,
1200                                  const Expr *E) -> bool {
1201     if (IsComplex) {
1202       if (!this->emitGetLocal(PT_Ptr, Offset, E))
1203         return false;
1204       return this->emitArrayElemPop(classifyComplexElementType(E->getType()),
1205                                     ElemIndex, E);
1206     }
1207     if (ElemIndex == 0 || !LoadZero)
1208       return this->emitGetLocal(classifyPrim(E->getType()), Offset, E);
1209     return this->visitZeroInitializer(classifyPrim(E->getType()), E->getType(),
1210                                       E);
1211   };
1212 
1213   // Now we can get pointers to the LHS and RHS from the offsets above.
1214   for (unsigned ElemIndex = 0; ElemIndex != 2; ++ElemIndex) {
1215     // Result pointer for the store later.
1216     if (!this->DiscardResult) {
1217       if (!this->emitGetLocal(PT_Ptr, ResultOffset, E))
1218         return false;
1219     }
1220 
1221     // The actual operation.
1222     switch (Op) {
1223     case BO_Add:
1224       if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1225         return false;
1226 
1227       if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1228         return false;
1229       if (ResultElemT == PT_Float) {
1230         if (!this->emitAddf(getFPOptions(E), E))
1231           return false;
1232       } else {
1233         if (!this->emitAdd(ResultElemT, E))
1234           return false;
1235       }
1236       break;
1237     case BO_Sub:
1238       if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1239         return false;
1240 
1241       if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1242         return false;
1243       if (ResultElemT == PT_Float) {
1244         if (!this->emitSubf(getFPOptions(E), E))
1245           return false;
1246       } else {
1247         if (!this->emitSub(ResultElemT, E))
1248           return false;
1249       }
1250       break;
1251     case BO_Mul:
1252       if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1253         return false;
1254 
1255       if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1256         return false;
1257 
1258       if (ResultElemT == PT_Float) {
1259         if (!this->emitMulf(getFPOptions(E), E))
1260           return false;
1261       } else {
1262         if (!this->emitMul(ResultElemT, E))
1263           return false;
1264       }
1265       break;
1266     case BO_Div:
1267       assert(!RHSIsComplex);
1268       if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1269         return false;
1270 
1271       if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1272         return false;
1273 
1274       if (ResultElemT == PT_Float) {
1275         if (!this->emitDivf(getFPOptions(E), E))
1276           return false;
1277       } else {
1278         if (!this->emitDiv(ResultElemT, E))
1279           return false;
1280       }
1281       break;
1282 
1283     default:
1284       return false;
1285     }
1286 
1287     if (!this->DiscardResult) {
1288       // Initialize array element with the value we just computed.
1289       if (!this->emitInitElemPop(ResultElemT, ElemIndex, E))
1290         return false;
1291     } else {
1292       if (!this->emitPop(ResultElemT, E))
1293         return false;
1294     }
1295   }
1296   return true;
1297 }
1298 
1299 template <class Emitter>
1300 bool Compiler<Emitter>::VisitVectorBinOp(const BinaryOperator *E) {
1301   assert(!E->isCommaOp() &&
1302          "Comma op should be handled in VisitBinaryOperator");
1303   assert(E->getType()->isVectorType());
1304   assert(E->getLHS()->getType()->isVectorType());
1305   assert(E->getRHS()->getType()->isVectorType());
1306 
1307   // Prepare storage for result.
1308   if (!Initializing && !E->isCompoundAssignmentOp()) {
1309     unsigned LocalIndex = allocateTemporary(E);
1310     if (!this->emitGetPtrLocal(LocalIndex, E))
1311       return false;
1312   }
1313 
1314   const Expr *LHS = E->getLHS();
1315   const Expr *RHS = E->getRHS();
1316   const auto *VecTy = E->getType()->getAs<VectorType>();
1317   auto Op = E->isCompoundAssignmentOp()
1318                 ? BinaryOperator::getOpForCompoundAssignment(E->getOpcode())
1319                 : E->getOpcode();
1320 
1321   PrimType ElemT = this->classifyVectorElementType(LHS->getType());
1322   PrimType RHSElemT = this->classifyVectorElementType(RHS->getType());
1323   PrimType ResultElemT = this->classifyVectorElementType(E->getType());
1324 
1325   // Evaluate LHS and save value to LHSOffset.
1326   unsigned LHSOffset = this->allocateLocalPrimitive(LHS, PT_Ptr, true, false);
1327   if (!this->visit(LHS))
1328     return false;
1329   if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
1330     return false;
1331 
1332   // Evaluate RHS and save value to RHSOffset.
1333   unsigned RHSOffset = this->allocateLocalPrimitive(RHS, PT_Ptr, true, false);
1334   if (!this->visit(RHS))
1335     return false;
1336   if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
1337     return false;
1338 
1339   if (E->isCompoundAssignmentOp() && !this->emitGetLocal(PT_Ptr, LHSOffset, E))
1340     return false;
1341 
1342   // BitAdd/BitOr/BitXor/Shl/Shr doesn't support bool type, we need perform the
1343   // integer promotion.
1344   bool NeedIntPromot = ElemT == PT_Bool && (E->isBitwiseOp() || E->isShiftOp());
1345   QualType PromotTy =
1346       Ctx.getASTContext().getPromotedIntegerType(Ctx.getASTContext().BoolTy);
1347   PrimType PromotT = classifyPrim(PromotTy);
1348   PrimType OpT = NeedIntPromot ? PromotT : ElemT;
1349 
1350   auto getElem = [=](unsigned Offset, PrimType ElemT, unsigned Index) {
1351     if (!this->emitGetLocal(PT_Ptr, Offset, E))
1352       return false;
1353     if (!this->emitArrayElemPop(ElemT, Index, E))
1354       return false;
1355     if (E->isLogicalOp()) {
1356       if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
1357         return false;
1358       if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), E))
1359         return false;
1360     } else if (NeedIntPromot) {
1361       if (!this->emitPrimCast(ElemT, PromotT, PromotTy, E))
1362         return false;
1363     }
1364     return true;
1365   };
1366 
1367 #define EMIT_ARITH_OP(OP)                                                      \
1368   {                                                                            \
1369     if (ElemT == PT_Float) {                                                   \
1370       if (!this->emit##OP##f(getFPOptions(E), E))                              \
1371         return false;                                                          \
1372     } else {                                                                   \
1373       if (!this->emit##OP(ElemT, E))                                           \
1374         return false;                                                          \
1375     }                                                                          \
1376     break;                                                                     \
1377   }
1378 
1379   for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
1380     if (!getElem(LHSOffset, ElemT, I))
1381       return false;
1382     if (!getElem(RHSOffset, RHSElemT, I))
1383       return false;
1384     switch (Op) {
1385     case BO_Add:
1386       EMIT_ARITH_OP(Add)
1387     case BO_Sub:
1388       EMIT_ARITH_OP(Sub)
1389     case BO_Mul:
1390       EMIT_ARITH_OP(Mul)
1391     case BO_Div:
1392       EMIT_ARITH_OP(Div)
1393     case BO_Rem:
1394       if (!this->emitRem(ElemT, E))
1395         return false;
1396       break;
1397     case BO_And:
1398       if (!this->emitBitAnd(OpT, E))
1399         return false;
1400       break;
1401     case BO_Or:
1402       if (!this->emitBitOr(OpT, E))
1403         return false;
1404       break;
1405     case BO_Xor:
1406       if (!this->emitBitXor(OpT, E))
1407         return false;
1408       break;
1409     case BO_Shl:
1410       if (!this->emitShl(OpT, RHSElemT, E))
1411         return false;
1412       break;
1413     case BO_Shr:
1414       if (!this->emitShr(OpT, RHSElemT, E))
1415         return false;
1416       break;
1417     case BO_EQ:
1418       if (!this->emitEQ(ElemT, E))
1419         return false;
1420       break;
1421     case BO_NE:
1422       if (!this->emitNE(ElemT, E))
1423         return false;
1424       break;
1425     case BO_LE:
1426       if (!this->emitLE(ElemT, E))
1427         return false;
1428       break;
1429     case BO_LT:
1430       if (!this->emitLT(ElemT, E))
1431         return false;
1432       break;
1433     case BO_GE:
1434       if (!this->emitGE(ElemT, E))
1435         return false;
1436       break;
1437     case BO_GT:
1438       if (!this->emitGT(ElemT, E))
1439         return false;
1440       break;
1441     case BO_LAnd:
1442       // a && b is equivalent to a!=0 & b!=0
1443       if (!this->emitBitAnd(ResultElemT, E))
1444         return false;
1445       break;
1446     case BO_LOr:
1447       // a || b is equivalent to a!=0 | b!=0
1448       if (!this->emitBitOr(ResultElemT, E))
1449         return false;
1450       break;
1451     default:
1452       return this->emitInvalid(E);
1453     }
1454 
1455     // The result of the comparison is a vector of the same width and number
1456     // of elements as the comparison operands with a signed integral element
1457     // type.
1458     //
1459     // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
1460     if (E->isComparisonOp()) {
1461       if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), E))
1462         return false;
1463       if (!this->emitNeg(ResultElemT, E))
1464         return false;
1465     }
1466 
1467     // If we performed an integer promotion, we need to cast the compute result
1468     // into result vector element type.
1469     if (NeedIntPromot &&
1470         !this->emitPrimCast(PromotT, ResultElemT, VecTy->getElementType(), E))
1471       return false;
1472 
1473     // Initialize array element with the value we just computed.
1474     if (!this->emitInitElem(ResultElemT, I, E))
1475       return false;
1476   }
1477 
1478   if (DiscardResult && E->isCompoundAssignmentOp() && !this->emitPopPtr(E))
1479     return false;
1480   return true;
1481 }
1482 
1483 template <class Emitter>
1484 bool Compiler<Emitter>::VisitFixedPointBinOp(const BinaryOperator *E) {
1485   const Expr *LHS = E->getLHS();
1486   const Expr *RHS = E->getRHS();
1487 
1488   assert(LHS->getType()->isFixedPointType() ||
1489          RHS->getType()->isFixedPointType());
1490 
1491   if (!this->visit(LHS))
1492     return false;
1493   if (!LHS->getType()->isFixedPointType()) {
1494     auto Sem = Ctx.getASTContext().getFixedPointSemantics(LHS->getType());
1495     uint32_t I;
1496     std::memcpy(&I, &Sem, sizeof(Sem));
1497     if (!this->emitCastIntegralFixedPoint(classifyPrim(LHS->getType()), I, E))
1498       return false;
1499   }
1500   if (!this->visit(RHS))
1501     return false;
1502   if (!RHS->getType()->isFixedPointType()) {
1503     auto Sem = Ctx.getASTContext().getFixedPointSemantics(RHS->getType());
1504     uint32_t I;
1505     std::memcpy(&I, &Sem, sizeof(Sem));
1506     if (!this->emitCastIntegralFixedPoint(classifyPrim(RHS->getType()), I, E))
1507       return false;
1508   }
1509 
1510   switch (E->getOpcode()) {
1511   case BO_EQ:
1512     return this->emitEQFixedPoint(E);
1513   case BO_NE:
1514     return this->emitNEFixedPoint(E);
1515 #if 0
1516   case BO_LT:
1517     return this->emitLTFixedPoint(E);
1518   case BO_LE:
1519     return this->emitLEFixedPoint(E);
1520   case BO_GT:
1521     return this->emitGTFixedPoint(E);
1522   case BO_GE:
1523     return this->emitGEFixedPoint(E);
1524 #endif
1525   default:
1526     return this->emitInvalid(E);
1527   }
1528 
1529   llvm_unreachable("unhandled binop opcode");
1530 }
1531 
1532 template <class Emitter>
1533 bool Compiler<Emitter>::VisitImplicitValueInitExpr(
1534     const ImplicitValueInitExpr *E) {
1535   QualType QT = E->getType();
1536 
1537   if (std::optional<PrimType> T = classify(QT))
1538     return this->visitZeroInitializer(*T, QT, E);
1539 
1540   if (QT->isRecordType()) {
1541     const RecordDecl *RD = QT->getAsRecordDecl();
1542     assert(RD);
1543     if (RD->isInvalidDecl())
1544       return false;
1545 
1546     if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1547         CXXRD && CXXRD->getNumVBases() > 0) {
1548       // TODO: Diagnose.
1549       return false;
1550     }
1551 
1552     const Record *R = getRecord(QT);
1553     if (!R)
1554       return false;
1555 
1556     assert(Initializing);
1557     return this->visitZeroRecordInitializer(R, E);
1558   }
1559 
1560   if (QT->isIncompleteArrayType())
1561     return true;
1562 
1563   if (QT->isArrayType()) {
1564     const ArrayType *AT = QT->getAsArrayTypeUnsafe();
1565     assert(AT);
1566     const auto *CAT = cast<ConstantArrayType>(AT);
1567     size_t NumElems = CAT->getZExtSize();
1568     PrimType ElemT = classifyPrim(CAT->getElementType());
1569 
1570     for (size_t I = 0; I != NumElems; ++I) {
1571       if (!this->visitZeroInitializer(ElemT, CAT->getElementType(), E))
1572         return false;
1573       if (!this->emitInitElem(ElemT, I, E))
1574         return false;
1575     }
1576 
1577     return true;
1578   }
1579 
1580   if (const auto *ComplexTy = E->getType()->getAs<ComplexType>()) {
1581     assert(Initializing);
1582     QualType ElemQT = ComplexTy->getElementType();
1583     PrimType ElemT = classifyPrim(ElemQT);
1584     for (unsigned I = 0; I < 2; ++I) {
1585       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1586         return false;
1587       if (!this->emitInitElem(ElemT, I, E))
1588         return false;
1589     }
1590     return true;
1591   }
1592 
1593   if (const auto *VecT = E->getType()->getAs<VectorType>()) {
1594     unsigned NumVecElements = VecT->getNumElements();
1595     QualType ElemQT = VecT->getElementType();
1596     PrimType ElemT = classifyPrim(ElemQT);
1597 
1598     for (unsigned I = 0; I < NumVecElements; ++I) {
1599       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1600         return false;
1601       if (!this->emitInitElem(ElemT, I, E))
1602         return false;
1603     }
1604     return true;
1605   }
1606 
1607   return false;
1608 }
1609 
1610 template <class Emitter>
1611 bool Compiler<Emitter>::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) {
1612   const Expr *LHS = E->getLHS();
1613   const Expr *RHS = E->getRHS();
1614   const Expr *Index = E->getIdx();
1615 
1616   if (DiscardResult)
1617     return this->discard(LHS) && this->discard(RHS);
1618 
1619   // C++17's rules require us to evaluate the LHS first, regardless of which
1620   // side is the base.
1621   bool Success = true;
1622   for (const Expr *SubExpr : {LHS, RHS}) {
1623     if (!this->visit(SubExpr))
1624       Success = false;
1625   }
1626 
1627   if (!Success)
1628     return false;
1629 
1630   PrimType IndexT = classifyPrim(Index->getType());
1631   // If the index is first, we need to change that.
1632   if (LHS == Index) {
1633     if (!this->emitFlip(PT_Ptr, IndexT, E))
1634       return false;
1635   }
1636 
1637   return this->emitArrayElemPtrPop(IndexT, E);
1638 }
1639 
1640 template <class Emitter>
1641 bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits,
1642                                       const Expr *ArrayFiller, const Expr *E) {
1643   QualType QT = E->getType();
1644   if (const auto *AT = QT->getAs<AtomicType>())
1645     QT = AT->getValueType();
1646 
1647   if (QT->isVoidType()) {
1648     if (Inits.size() == 0)
1649       return true;
1650     return this->emitInvalid(E);
1651   }
1652 
1653   // Handle discarding first.
1654   if (DiscardResult) {
1655     for (const Expr *Init : Inits) {
1656       if (!this->discard(Init))
1657         return false;
1658     }
1659     return true;
1660   }
1661 
1662   // Primitive values.
1663   if (std::optional<PrimType> T = classify(QT)) {
1664     assert(!DiscardResult);
1665     if (Inits.size() == 0)
1666       return this->visitZeroInitializer(*T, QT, E);
1667     assert(Inits.size() == 1);
1668     return this->delegate(Inits[0]);
1669   }
1670 
1671   if (QT->isRecordType()) {
1672     const Record *R = getRecord(QT);
1673 
1674     if (Inits.size() == 1 && E->getType() == Inits[0]->getType())
1675       return this->delegate(Inits[0]);
1676 
1677     auto initPrimitiveField = [=](const Record::Field *FieldToInit,
1678                                   const Expr *Init, PrimType T) -> bool {
1679       InitStackScope<Emitter> ISS(this, isa<CXXDefaultInitExpr>(Init));
1680       if (!this->visit(Init))
1681         return false;
1682 
1683       if (FieldToInit->isBitField())
1684         return this->emitInitBitField(T, FieldToInit, E);
1685       return this->emitInitField(T, FieldToInit->Offset, E);
1686     };
1687 
1688     auto initCompositeField = [=](const Record::Field *FieldToInit,
1689                                   const Expr *Init) -> bool {
1690       InitStackScope<Emitter> ISS(this, isa<CXXDefaultInitExpr>(Init));
1691       InitLinkScope<Emitter> ILS(this, InitLink::Field(FieldToInit->Offset));
1692       // Non-primitive case. Get a pointer to the field-to-initialize
1693       // on the stack and recurse into visitInitializer().
1694       if (!this->emitGetPtrField(FieldToInit->Offset, Init))
1695         return false;
1696       if (!this->visitInitializer(Init))
1697         return false;
1698       return this->emitPopPtr(E);
1699     };
1700 
1701     if (R->isUnion()) {
1702       if (Inits.size() == 0) {
1703         if (!this->visitZeroRecordInitializer(R, E))
1704           return false;
1705       } else {
1706         const Expr *Init = Inits[0];
1707         const FieldDecl *FToInit = nullptr;
1708         if (const auto *ILE = dyn_cast<InitListExpr>(E))
1709           FToInit = ILE->getInitializedFieldInUnion();
1710         else
1711           FToInit = cast<CXXParenListInitExpr>(E)->getInitializedFieldInUnion();
1712 
1713         const Record::Field *FieldToInit = R->getField(FToInit);
1714         if (std::optional<PrimType> T = classify(Init)) {
1715           if (!initPrimitiveField(FieldToInit, Init, *T))
1716             return false;
1717         } else {
1718           if (!initCompositeField(FieldToInit, Init))
1719             return false;
1720         }
1721       }
1722       return this->emitFinishInit(E);
1723     }
1724 
1725     assert(!R->isUnion());
1726     unsigned InitIndex = 0;
1727     for (const Expr *Init : Inits) {
1728       // Skip unnamed bitfields.
1729       while (InitIndex < R->getNumFields() &&
1730              R->getField(InitIndex)->Decl->isUnnamedBitField())
1731         ++InitIndex;
1732 
1733       if (std::optional<PrimType> T = classify(Init)) {
1734         const Record::Field *FieldToInit = R->getField(InitIndex);
1735         if (!initPrimitiveField(FieldToInit, Init, *T))
1736           return false;
1737         ++InitIndex;
1738       } else {
1739         // Initializer for a direct base class.
1740         if (const Record::Base *B = R->getBase(Init->getType())) {
1741           if (!this->emitGetPtrBase(B->Offset, Init))
1742             return false;
1743 
1744           if (!this->visitInitializer(Init))
1745             return false;
1746 
1747           if (!this->emitFinishInitPop(E))
1748             return false;
1749           // Base initializers don't increase InitIndex, since they don't count
1750           // into the Record's fields.
1751         } else {
1752           const Record::Field *FieldToInit = R->getField(InitIndex);
1753           if (!initCompositeField(FieldToInit, Init))
1754             return false;
1755           ++InitIndex;
1756         }
1757       }
1758     }
1759     return this->emitFinishInit(E);
1760   }
1761 
1762   if (QT->isArrayType()) {
1763     if (Inits.size() == 1 && QT == Inits[0]->getType())
1764       return this->delegate(Inits[0]);
1765 
1766     unsigned ElementIndex = 0;
1767     for (const Expr *Init : Inits) {
1768       if (const auto *EmbedS =
1769               dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
1770         PrimType TargetT = classifyPrim(Init->getType());
1771 
1772         auto Eval = [&](const Expr *Init, unsigned ElemIndex) {
1773           PrimType InitT = classifyPrim(Init->getType());
1774           if (!this->visit(Init))
1775             return false;
1776           if (InitT != TargetT) {
1777             if (!this->emitCast(InitT, TargetT, E))
1778               return false;
1779           }
1780           return this->emitInitElem(TargetT, ElemIndex, Init);
1781         };
1782         if (!EmbedS->doForEachDataElement(Eval, ElementIndex))
1783           return false;
1784       } else {
1785         if (!this->visitArrayElemInit(ElementIndex, Init))
1786           return false;
1787         ++ElementIndex;
1788       }
1789     }
1790 
1791     // Expand the filler expression.
1792     // FIXME: This should go away.
1793     if (ArrayFiller) {
1794       const ConstantArrayType *CAT =
1795           Ctx.getASTContext().getAsConstantArrayType(QT);
1796       uint64_t NumElems = CAT->getZExtSize();
1797 
1798       for (; ElementIndex != NumElems; ++ElementIndex) {
1799         if (!this->visitArrayElemInit(ElementIndex, ArrayFiller))
1800           return false;
1801       }
1802     }
1803 
1804     return this->emitFinishInit(E);
1805   }
1806 
1807   if (const auto *ComplexTy = QT->getAs<ComplexType>()) {
1808     unsigned NumInits = Inits.size();
1809 
1810     if (NumInits == 1)
1811       return this->delegate(Inits[0]);
1812 
1813     QualType ElemQT = ComplexTy->getElementType();
1814     PrimType ElemT = classifyPrim(ElemQT);
1815     if (NumInits == 0) {
1816       // Zero-initialize both elements.
1817       for (unsigned I = 0; I < 2; ++I) {
1818         if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1819           return false;
1820         if (!this->emitInitElem(ElemT, I, E))
1821           return false;
1822       }
1823     } else if (NumInits == 2) {
1824       unsigned InitIndex = 0;
1825       for (const Expr *Init : Inits) {
1826         if (!this->visit(Init))
1827           return false;
1828 
1829         if (!this->emitInitElem(ElemT, InitIndex, E))
1830           return false;
1831         ++InitIndex;
1832       }
1833     }
1834     return true;
1835   }
1836 
1837   if (const auto *VecT = QT->getAs<VectorType>()) {
1838     unsigned NumVecElements = VecT->getNumElements();
1839     assert(NumVecElements >= Inits.size());
1840 
1841     QualType ElemQT = VecT->getElementType();
1842     PrimType ElemT = classifyPrim(ElemQT);
1843 
1844     // All initializer elements.
1845     unsigned InitIndex = 0;
1846     for (const Expr *Init : Inits) {
1847       if (!this->visit(Init))
1848         return false;
1849 
1850       // If the initializer is of vector type itself, we have to deconstruct
1851       // that and initialize all the target fields from the initializer fields.
1852       if (const auto *InitVecT = Init->getType()->getAs<VectorType>()) {
1853         if (!this->emitCopyArray(ElemT, 0, InitIndex,
1854                                  InitVecT->getNumElements(), E))
1855           return false;
1856         InitIndex += InitVecT->getNumElements();
1857       } else {
1858         if (!this->emitInitElem(ElemT, InitIndex, E))
1859           return false;
1860         ++InitIndex;
1861       }
1862     }
1863 
1864     assert(InitIndex <= NumVecElements);
1865 
1866     // Fill the rest with zeroes.
1867     for (; InitIndex != NumVecElements; ++InitIndex) {
1868       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1869         return false;
1870       if (!this->emitInitElem(ElemT, InitIndex, E))
1871         return false;
1872     }
1873     return true;
1874   }
1875 
1876   return false;
1877 }
1878 
1879 /// Pointer to the array(not the element!) must be on the stack when calling
1880 /// this.
1881 template <class Emitter>
1882 bool Compiler<Emitter>::visitArrayElemInit(unsigned ElemIndex,
1883                                            const Expr *Init) {
1884   if (std::optional<PrimType> T = classify(Init->getType())) {
1885     // Visit the primitive element like normal.
1886     if (!this->visit(Init))
1887       return false;
1888     return this->emitInitElem(*T, ElemIndex, Init);
1889   }
1890 
1891   InitLinkScope<Emitter> ILS(this, InitLink::Elem(ElemIndex));
1892   // Advance the pointer currently on the stack to the given
1893   // dimension.
1894   if (!this->emitConstUint32(ElemIndex, Init))
1895     return false;
1896   if (!this->emitArrayElemPtrUint32(Init))
1897     return false;
1898   if (!this->visitInitializer(Init))
1899     return false;
1900   return this->emitFinishInitPop(Init);
1901 }
1902 
1903 template <class Emitter>
1904 bool Compiler<Emitter>::VisitInitListExpr(const InitListExpr *E) {
1905   return this->visitInitList(E->inits(), E->getArrayFiller(), E);
1906 }
1907 
1908 template <class Emitter>
1909 bool Compiler<Emitter>::VisitCXXParenListInitExpr(
1910     const CXXParenListInitExpr *E) {
1911   return this->visitInitList(E->getInitExprs(), E->getArrayFiller(), E);
1912 }
1913 
1914 template <class Emitter>
1915 bool Compiler<Emitter>::VisitSubstNonTypeTemplateParmExpr(
1916     const SubstNonTypeTemplateParmExpr *E) {
1917   return this->delegate(E->getReplacement());
1918 }
1919 
1920 template <class Emitter>
1921 bool Compiler<Emitter>::VisitConstantExpr(const ConstantExpr *E) {
1922   std::optional<PrimType> T = classify(E->getType());
1923   if (T && E->hasAPValueResult()) {
1924     // Try to emit the APValue directly, without visiting the subexpr.
1925     // This will only fail if we can't emit the APValue, so won't emit any
1926     // diagnostics or any double values.
1927     if (DiscardResult)
1928       return true;
1929 
1930     if (this->visitAPValue(E->getAPValueResult(), *T, E))
1931       return true;
1932   }
1933   return this->delegate(E->getSubExpr());
1934 }
1935 
1936 template <class Emitter>
1937 bool Compiler<Emitter>::VisitEmbedExpr(const EmbedExpr *E) {
1938   auto It = E->begin();
1939   return this->visit(*It);
1940 }
1941 
1942 static CharUnits AlignOfType(QualType T, const ASTContext &ASTCtx,
1943                              UnaryExprOrTypeTrait Kind) {
1944   bool AlignOfReturnsPreferred =
1945       ASTCtx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7;
1946 
1947   // C++ [expr.alignof]p3:
1948   //     When alignof is applied to a reference type, the result is the
1949   //     alignment of the referenced type.
1950   if (const auto *Ref = T->getAs<ReferenceType>())
1951     T = Ref->getPointeeType();
1952 
1953   if (T.getQualifiers().hasUnaligned())
1954     return CharUnits::One();
1955 
1956   // __alignof is defined to return the preferred alignment.
1957   // Before 8, clang returned the preferred alignment for alignof and
1958   // _Alignof as well.
1959   if (Kind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
1960     return ASTCtx.toCharUnitsFromBits(ASTCtx.getPreferredTypeAlign(T));
1961 
1962   return ASTCtx.getTypeAlignInChars(T);
1963 }
1964 
1965 template <class Emitter>
1966 bool Compiler<Emitter>::VisitUnaryExprOrTypeTraitExpr(
1967     const UnaryExprOrTypeTraitExpr *E) {
1968   UnaryExprOrTypeTrait Kind = E->getKind();
1969   const ASTContext &ASTCtx = Ctx.getASTContext();
1970 
1971   if (Kind == UETT_SizeOf || Kind == UETT_DataSizeOf) {
1972     QualType ArgType = E->getTypeOfArgument();
1973 
1974     // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
1975     //   the result is the size of the referenced type."
1976     if (const auto *Ref = ArgType->getAs<ReferenceType>())
1977       ArgType = Ref->getPointeeType();
1978 
1979     CharUnits Size;
1980     if (ArgType->isVoidType() || ArgType->isFunctionType())
1981       Size = CharUnits::One();
1982     else {
1983       if (ArgType->isDependentType() || !ArgType->isConstantSizeType())
1984         return false;
1985 
1986       if (Kind == UETT_SizeOf)
1987         Size = ASTCtx.getTypeSizeInChars(ArgType);
1988       else
1989         Size = ASTCtx.getTypeInfoDataSizeInChars(ArgType).Width;
1990     }
1991 
1992     if (DiscardResult)
1993       return true;
1994 
1995     return this->emitConst(Size.getQuantity(), E);
1996   }
1997 
1998   if (Kind == UETT_AlignOf || Kind == UETT_PreferredAlignOf) {
1999     CharUnits Size;
2000 
2001     if (E->isArgumentType()) {
2002       QualType ArgType = E->getTypeOfArgument();
2003 
2004       Size = AlignOfType(ArgType, ASTCtx, Kind);
2005     } else {
2006       // Argument is an expression, not a type.
2007       const Expr *Arg = E->getArgumentExpr()->IgnoreParens();
2008 
2009       // The kinds of expressions that we have special-case logic here for
2010       // should be kept up to date with the special checks for those
2011       // expressions in Sema.
2012 
2013       // alignof decl is always accepted, even if it doesn't make sense: we
2014       // default to 1 in those cases.
2015       if (const auto *DRE = dyn_cast<DeclRefExpr>(Arg))
2016         Size = ASTCtx.getDeclAlign(DRE->getDecl(),
2017                                    /*RefAsPointee*/ true);
2018       else if (const auto *ME = dyn_cast<MemberExpr>(Arg))
2019         Size = ASTCtx.getDeclAlign(ME->getMemberDecl(),
2020                                    /*RefAsPointee*/ true);
2021       else
2022         Size = AlignOfType(Arg->getType(), ASTCtx, Kind);
2023     }
2024 
2025     if (DiscardResult)
2026       return true;
2027 
2028     return this->emitConst(Size.getQuantity(), E);
2029   }
2030 
2031   if (Kind == UETT_VectorElements) {
2032     if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>())
2033       return this->emitConst(VT->getNumElements(), E);
2034     assert(E->getTypeOfArgument()->isSizelessVectorType());
2035     return this->emitSizelessVectorElementSize(E);
2036   }
2037 
2038   if (Kind == UETT_VecStep) {
2039     if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>()) {
2040       unsigned N = VT->getNumElements();
2041 
2042       // The vec_step built-in functions that take a 3-component
2043       // vector return 4. (OpenCL 1.1 spec 6.11.12)
2044       if (N == 3)
2045         N = 4;
2046 
2047       return this->emitConst(N, E);
2048     }
2049     return this->emitConst(1, E);
2050   }
2051 
2052   return false;
2053 }
2054 
2055 template <class Emitter>
2056 bool Compiler<Emitter>::VisitMemberExpr(const MemberExpr *E) {
2057   // 'Base.Member'
2058   const Expr *Base = E->getBase();
2059   const ValueDecl *Member = E->getMemberDecl();
2060 
2061   if (DiscardResult)
2062     return this->discard(Base);
2063 
2064   // MemberExprs are almost always lvalues, in which case we don't need to
2065   // do the load. But sometimes they aren't.
2066   const auto maybeLoadValue = [&]() -> bool {
2067     if (E->isGLValue())
2068       return true;
2069     if (std::optional<PrimType> T = classify(E))
2070       return this->emitLoadPop(*T, E);
2071     return false;
2072   };
2073 
2074   if (const auto *VD = dyn_cast<VarDecl>(Member)) {
2075     // I am almost confident in saying that a var decl must be static
2076     // and therefore registered as a global variable. But this will probably
2077     // turn out to be wrong some time in the future, as always.
2078     if (auto GlobalIndex = P.getGlobal(VD))
2079       return this->emitGetPtrGlobal(*GlobalIndex, E) && maybeLoadValue();
2080     return false;
2081   }
2082 
2083   if (!isa<FieldDecl>(Member)) {
2084     if (!this->discard(Base) && !this->emitSideEffect(E))
2085       return false;
2086 
2087     return this->visitDeclRef(Member, E);
2088   }
2089 
2090   if (Initializing) {
2091     if (!this->delegate(Base))
2092       return false;
2093   } else {
2094     if (!this->visit(Base))
2095       return false;
2096   }
2097 
2098   // Base above gives us a pointer on the stack.
2099   const auto *FD = cast<FieldDecl>(Member);
2100   const RecordDecl *RD = FD->getParent();
2101   const Record *R = getRecord(RD);
2102   if (!R)
2103     return false;
2104   const Record::Field *F = R->getField(FD);
2105   // Leave a pointer to the field on the stack.
2106   if (F->Decl->getType()->isReferenceType())
2107     return this->emitGetFieldPop(PT_Ptr, F->Offset, E) && maybeLoadValue();
2108   return this->emitGetPtrFieldPop(F->Offset, E) && maybeLoadValue();
2109 }
2110 
2111 template <class Emitter>
2112 bool Compiler<Emitter>::VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) {
2113   // ArrayIndex might not be set if a ArrayInitIndexExpr is being evaluated
2114   // stand-alone, e.g. via EvaluateAsInt().
2115   if (!ArrayIndex)
2116     return false;
2117   return this->emitConst(*ArrayIndex, E);
2118 }
2119 
2120 template <class Emitter>
2121 bool Compiler<Emitter>::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) {
2122   assert(Initializing);
2123   assert(!DiscardResult);
2124 
2125   // We visit the common opaque expression here once so we have its value
2126   // cached.
2127   if (!this->discard(E->getCommonExpr()))
2128     return false;
2129 
2130   // TODO: This compiles to quite a lot of bytecode if the array is larger.
2131   //   Investigate compiling this to a loop.
2132   const Expr *SubExpr = E->getSubExpr();
2133   size_t Size = E->getArraySize().getZExtValue();
2134 
2135   // So, every iteration, we execute an assignment here
2136   // where the LHS is on the stack (the target array)
2137   // and the RHS is our SubExpr.
2138   for (size_t I = 0; I != Size; ++I) {
2139     ArrayIndexScope<Emitter> IndexScope(this, I);
2140     BlockScope<Emitter> BS(this);
2141 
2142     if (!this->visitArrayElemInit(I, SubExpr))
2143       return false;
2144     if (!BS.destroyLocals())
2145       return false;
2146   }
2147   return true;
2148 }
2149 
2150 template <class Emitter>
2151 bool Compiler<Emitter>::VisitOpaqueValueExpr(const OpaqueValueExpr *E) {
2152   const Expr *SourceExpr = E->getSourceExpr();
2153   if (!SourceExpr)
2154     return false;
2155 
2156   if (Initializing)
2157     return this->visitInitializer(SourceExpr);
2158 
2159   PrimType SubExprT = classify(SourceExpr).value_or(PT_Ptr);
2160   if (auto It = OpaqueExprs.find(E); It != OpaqueExprs.end())
2161     return this->emitGetLocal(SubExprT, It->second, E);
2162 
2163   if (!this->visit(SourceExpr))
2164     return false;
2165 
2166   // At this point we either have the evaluated source expression or a pointer
2167   // to an object on the stack. We want to create a local variable that stores
2168   // this value.
2169   unsigned LocalIndex = allocateLocalPrimitive(E, SubExprT, /*IsConst=*/true);
2170   if (!this->emitSetLocal(SubExprT, LocalIndex, E))
2171     return false;
2172 
2173   // Here the local variable is created but the value is removed from the stack,
2174   // so we put it back if the caller needs it.
2175   if (!DiscardResult) {
2176     if (!this->emitGetLocal(SubExprT, LocalIndex, E))
2177       return false;
2178   }
2179 
2180   // This is cleaned up when the local variable is destroyed.
2181   OpaqueExprs.insert({E, LocalIndex});
2182 
2183   return true;
2184 }
2185 
2186 template <class Emitter>
2187 bool Compiler<Emitter>::VisitAbstractConditionalOperator(
2188     const AbstractConditionalOperator *E) {
2189   const Expr *Condition = E->getCond();
2190   const Expr *TrueExpr = E->getTrueExpr();
2191   const Expr *FalseExpr = E->getFalseExpr();
2192 
2193   LabelTy LabelEnd = this->getLabel();   // Label after the operator.
2194   LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
2195 
2196   if (!this->visitBool(Condition))
2197     return false;
2198 
2199   if (!this->jumpFalse(LabelFalse))
2200     return false;
2201 
2202   {
2203     LocalScope<Emitter> S(this);
2204     if (!this->delegate(TrueExpr))
2205       return false;
2206     if (!S.destroyLocals())
2207       return false;
2208   }
2209 
2210   if (!this->jump(LabelEnd))
2211     return false;
2212 
2213   this->emitLabel(LabelFalse);
2214 
2215   {
2216     LocalScope<Emitter> S(this);
2217     if (!this->delegate(FalseExpr))
2218       return false;
2219     if (!S.destroyLocals())
2220       return false;
2221   }
2222 
2223   this->fallthrough(LabelEnd);
2224   this->emitLabel(LabelEnd);
2225 
2226   return true;
2227 }
2228 
2229 template <class Emitter>
2230 bool Compiler<Emitter>::VisitStringLiteral(const StringLiteral *E) {
2231   if (DiscardResult)
2232     return true;
2233 
2234   if (!Initializing) {
2235     unsigned StringIndex = P.createGlobalString(E);
2236     return this->emitGetPtrGlobal(StringIndex, E);
2237   }
2238 
2239   // We are initializing an array on the stack.
2240   const ConstantArrayType *CAT =
2241       Ctx.getASTContext().getAsConstantArrayType(E->getType());
2242   assert(CAT && "a string literal that's not a constant array?");
2243 
2244   // If the initializer string is too long, a diagnostic has already been
2245   // emitted. Read only the array length from the string literal.
2246   unsigned ArraySize = CAT->getZExtSize();
2247   unsigned N = std::min(ArraySize, E->getLength());
2248   size_t CharWidth = E->getCharByteWidth();
2249 
2250   for (unsigned I = 0; I != N; ++I) {
2251     uint32_t CodeUnit = E->getCodeUnit(I);
2252 
2253     if (CharWidth == 1) {
2254       this->emitConstSint8(CodeUnit, E);
2255       this->emitInitElemSint8(I, E);
2256     } else if (CharWidth == 2) {
2257       this->emitConstUint16(CodeUnit, E);
2258       this->emitInitElemUint16(I, E);
2259     } else if (CharWidth == 4) {
2260       this->emitConstUint32(CodeUnit, E);
2261       this->emitInitElemUint32(I, E);
2262     } else {
2263       llvm_unreachable("unsupported character width");
2264     }
2265   }
2266 
2267   // Fill up the rest of the char array with NUL bytes.
2268   for (unsigned I = N; I != ArraySize; ++I) {
2269     if (CharWidth == 1) {
2270       this->emitConstSint8(0, E);
2271       this->emitInitElemSint8(I, E);
2272     } else if (CharWidth == 2) {
2273       this->emitConstUint16(0, E);
2274       this->emitInitElemUint16(I, E);
2275     } else if (CharWidth == 4) {
2276       this->emitConstUint32(0, E);
2277       this->emitInitElemUint32(I, E);
2278     } else {
2279       llvm_unreachable("unsupported character width");
2280     }
2281   }
2282 
2283   return true;
2284 }
2285 
2286 template <class Emitter>
2287 bool Compiler<Emitter>::VisitObjCStringLiteral(const ObjCStringLiteral *E) {
2288   if (std::optional<unsigned> I = P.getOrCreateDummy(E))
2289     return this->emitGetPtrGlobal(*I, E);
2290   return false;
2291 }
2292 
2293 template <class Emitter>
2294 bool Compiler<Emitter>::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) {
2295   auto &A = Ctx.getASTContext();
2296   std::string Str;
2297   A.getObjCEncodingForType(E->getEncodedType(), Str);
2298   StringLiteral *SL =
2299       StringLiteral::Create(A, Str, StringLiteralKind::Ordinary,
2300                             /*Pascal=*/false, E->getType(), E->getAtLoc());
2301   return this->delegate(SL);
2302 }
2303 
2304 template <class Emitter>
2305 bool Compiler<Emitter>::VisitSYCLUniqueStableNameExpr(
2306     const SYCLUniqueStableNameExpr *E) {
2307   if (DiscardResult)
2308     return true;
2309 
2310   assert(!Initializing);
2311 
2312   auto &A = Ctx.getASTContext();
2313   std::string ResultStr = E->ComputeName(A);
2314 
2315   QualType CharTy = A.CharTy.withConst();
2316   APInt Size(A.getTypeSize(A.getSizeType()), ResultStr.size() + 1);
2317   QualType ArrayTy = A.getConstantArrayType(CharTy, Size, nullptr,
2318                                             ArraySizeModifier::Normal, 0);
2319 
2320   StringLiteral *SL =
2321       StringLiteral::Create(A, ResultStr, StringLiteralKind::Ordinary,
2322                             /*Pascal=*/false, ArrayTy, E->getLocation());
2323 
2324   unsigned StringIndex = P.createGlobalString(SL);
2325   return this->emitGetPtrGlobal(StringIndex, E);
2326 }
2327 
2328 template <class Emitter>
2329 bool Compiler<Emitter>::VisitCharacterLiteral(const CharacterLiteral *E) {
2330   if (DiscardResult)
2331     return true;
2332   return this->emitConst(E->getValue(), E);
2333 }
2334 
2335 template <class Emitter>
2336 bool Compiler<Emitter>::VisitFloatCompoundAssignOperator(
2337     const CompoundAssignOperator *E) {
2338 
2339   const Expr *LHS = E->getLHS();
2340   const Expr *RHS = E->getRHS();
2341   QualType LHSType = LHS->getType();
2342   QualType LHSComputationType = E->getComputationLHSType();
2343   QualType ResultType = E->getComputationResultType();
2344   std::optional<PrimType> LT = classify(LHSComputationType);
2345   std::optional<PrimType> RT = classify(ResultType);
2346 
2347   assert(ResultType->isFloatingType());
2348 
2349   if (!LT || !RT)
2350     return false;
2351 
2352   PrimType LHST = classifyPrim(LHSType);
2353 
2354   // C++17 onwards require that we evaluate the RHS first.
2355   // Compute RHS and save it in a temporary variable so we can
2356   // load it again later.
2357   if (!visit(RHS))
2358     return false;
2359 
2360   unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
2361   if (!this->emitSetLocal(*RT, TempOffset, E))
2362     return false;
2363 
2364   // First, visit LHS.
2365   if (!visit(LHS))
2366     return false;
2367   if (!this->emitLoad(LHST, E))
2368     return false;
2369 
2370   // If necessary, convert LHS to its computation type.
2371   if (!this->emitPrimCast(LHST, classifyPrim(LHSComputationType),
2372                           LHSComputationType, E))
2373     return false;
2374 
2375   // Now load RHS.
2376   if (!this->emitGetLocal(*RT, TempOffset, E))
2377     return false;
2378 
2379   switch (E->getOpcode()) {
2380   case BO_AddAssign:
2381     if (!this->emitAddf(getFPOptions(E), E))
2382       return false;
2383     break;
2384   case BO_SubAssign:
2385     if (!this->emitSubf(getFPOptions(E), E))
2386       return false;
2387     break;
2388   case BO_MulAssign:
2389     if (!this->emitMulf(getFPOptions(E), E))
2390       return false;
2391     break;
2392   case BO_DivAssign:
2393     if (!this->emitDivf(getFPOptions(E), E))
2394       return false;
2395     break;
2396   default:
2397     return false;
2398   }
2399 
2400   if (!this->emitPrimCast(classifyPrim(ResultType), LHST, LHS->getType(), E))
2401     return false;
2402 
2403   if (DiscardResult)
2404     return this->emitStorePop(LHST, E);
2405   return this->emitStore(LHST, E);
2406 }
2407 
2408 template <class Emitter>
2409 bool Compiler<Emitter>::VisitPointerCompoundAssignOperator(
2410     const CompoundAssignOperator *E) {
2411   BinaryOperatorKind Op = E->getOpcode();
2412   const Expr *LHS = E->getLHS();
2413   const Expr *RHS = E->getRHS();
2414   std::optional<PrimType> LT = classify(LHS->getType());
2415   std::optional<PrimType> RT = classify(RHS->getType());
2416 
2417   if (Op != BO_AddAssign && Op != BO_SubAssign)
2418     return false;
2419 
2420   if (!LT || !RT)
2421     return false;
2422 
2423   if (!visit(LHS))
2424     return false;
2425 
2426   if (!this->emitLoad(*LT, LHS))
2427     return false;
2428 
2429   if (!visit(RHS))
2430     return false;
2431 
2432   if (Op == BO_AddAssign) {
2433     if (!this->emitAddOffset(*RT, E))
2434       return false;
2435   } else {
2436     if (!this->emitSubOffset(*RT, E))
2437       return false;
2438   }
2439 
2440   if (DiscardResult)
2441     return this->emitStorePopPtr(E);
2442   return this->emitStorePtr(E);
2443 }
2444 
2445 template <class Emitter>
2446 bool Compiler<Emitter>::VisitCompoundAssignOperator(
2447     const CompoundAssignOperator *E) {
2448   if (E->getType()->isVectorType())
2449     return VisitVectorBinOp(E);
2450 
2451   const Expr *LHS = E->getLHS();
2452   const Expr *RHS = E->getRHS();
2453   std::optional<PrimType> LHSComputationT =
2454       classify(E->getComputationLHSType());
2455   std::optional<PrimType> LT = classify(LHS->getType());
2456   std::optional<PrimType> RT = classify(RHS->getType());
2457   std::optional<PrimType> ResultT = classify(E->getType());
2458 
2459   if (!Ctx.getLangOpts().CPlusPlus14)
2460     return this->visit(RHS) && this->visit(LHS) && this->emitError(E);
2461 
2462   if (!LT || !RT || !ResultT || !LHSComputationT)
2463     return false;
2464 
2465   // Handle floating point operations separately here, since they
2466   // require special care.
2467 
2468   if (ResultT == PT_Float || RT == PT_Float)
2469     return VisitFloatCompoundAssignOperator(E);
2470 
2471   if (E->getType()->isPointerType())
2472     return VisitPointerCompoundAssignOperator(E);
2473 
2474   assert(!E->getType()->isPointerType() && "Handled above");
2475   assert(!E->getType()->isFloatingType() && "Handled above");
2476 
2477   // C++17 onwards require that we evaluate the RHS first.
2478   // Compute RHS and save it in a temporary variable so we can
2479   // load it again later.
2480   // FIXME: Compound assignments are unsequenced in C, so we might
2481   //   have to figure out how to reject them.
2482   if (!visit(RHS))
2483     return false;
2484 
2485   unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
2486 
2487   if (!this->emitSetLocal(*RT, TempOffset, E))
2488     return false;
2489 
2490   // Get LHS pointer, load its value and cast it to the
2491   // computation type if necessary.
2492   if (!visit(LHS))
2493     return false;
2494   if (!this->emitLoad(*LT, E))
2495     return false;
2496   if (LT != LHSComputationT) {
2497     if (!this->emitCast(*LT, *LHSComputationT, E))
2498       return false;
2499   }
2500 
2501   // Get the RHS value on the stack.
2502   if (!this->emitGetLocal(*RT, TempOffset, E))
2503     return false;
2504 
2505   // Perform operation.
2506   switch (E->getOpcode()) {
2507   case BO_AddAssign:
2508     if (!this->emitAdd(*LHSComputationT, E))
2509       return false;
2510     break;
2511   case BO_SubAssign:
2512     if (!this->emitSub(*LHSComputationT, E))
2513       return false;
2514     break;
2515   case BO_MulAssign:
2516     if (!this->emitMul(*LHSComputationT, E))
2517       return false;
2518     break;
2519   case BO_DivAssign:
2520     if (!this->emitDiv(*LHSComputationT, E))
2521       return false;
2522     break;
2523   case BO_RemAssign:
2524     if (!this->emitRem(*LHSComputationT, E))
2525       return false;
2526     break;
2527   case BO_ShlAssign:
2528     if (!this->emitShl(*LHSComputationT, *RT, E))
2529       return false;
2530     break;
2531   case BO_ShrAssign:
2532     if (!this->emitShr(*LHSComputationT, *RT, E))
2533       return false;
2534     break;
2535   case BO_AndAssign:
2536     if (!this->emitBitAnd(*LHSComputationT, E))
2537       return false;
2538     break;
2539   case BO_XorAssign:
2540     if (!this->emitBitXor(*LHSComputationT, E))
2541       return false;
2542     break;
2543   case BO_OrAssign:
2544     if (!this->emitBitOr(*LHSComputationT, E))
2545       return false;
2546     break;
2547   default:
2548     llvm_unreachable("Unimplemented compound assign operator");
2549   }
2550 
2551   // And now cast from LHSComputationT to ResultT.
2552   if (ResultT != LHSComputationT) {
2553     if (!this->emitCast(*LHSComputationT, *ResultT, E))
2554       return false;
2555   }
2556 
2557   // And store the result in LHS.
2558   if (DiscardResult) {
2559     if (LHS->refersToBitField())
2560       return this->emitStoreBitFieldPop(*ResultT, E);
2561     return this->emitStorePop(*ResultT, E);
2562   }
2563   if (LHS->refersToBitField())
2564     return this->emitStoreBitField(*ResultT, E);
2565   return this->emitStore(*ResultT, E);
2566 }
2567 
2568 template <class Emitter>
2569 bool Compiler<Emitter>::VisitExprWithCleanups(const ExprWithCleanups *E) {
2570   LocalScope<Emitter> ES(this);
2571   const Expr *SubExpr = E->getSubExpr();
2572 
2573   return this->delegate(SubExpr) && ES.destroyLocals(E);
2574 }
2575 
2576 template <class Emitter>
2577 bool Compiler<Emitter>::VisitMaterializeTemporaryExpr(
2578     const MaterializeTemporaryExpr *E) {
2579   const Expr *SubExpr = E->getSubExpr();
2580 
2581   if (Initializing) {
2582     // We already have a value, just initialize that.
2583     return this->delegate(SubExpr);
2584   }
2585   // If we don't end up using the materialized temporary anyway, don't
2586   // bother creating it.
2587   if (DiscardResult)
2588     return this->discard(SubExpr);
2589 
2590   // When we're initializing a global variable *or* the storage duration of
2591   // the temporary is explicitly static, create a global variable.
2592   std::optional<PrimType> SubExprT = classify(SubExpr);
2593   bool IsStatic = E->getStorageDuration() == SD_Static;
2594   if (IsStatic) {
2595     std::optional<unsigned> GlobalIndex = P.createGlobal(E);
2596     if (!GlobalIndex)
2597       return false;
2598 
2599     const LifetimeExtendedTemporaryDecl *TempDecl =
2600         E->getLifetimeExtendedTemporaryDecl();
2601     if (IsStatic)
2602       assert(TempDecl);
2603 
2604     if (SubExprT) {
2605       if (!this->visit(SubExpr))
2606         return false;
2607       if (IsStatic) {
2608         if (!this->emitInitGlobalTemp(*SubExprT, *GlobalIndex, TempDecl, E))
2609           return false;
2610       } else {
2611         if (!this->emitInitGlobal(*SubExprT, *GlobalIndex, E))
2612           return false;
2613       }
2614       return this->emitGetPtrGlobal(*GlobalIndex, E);
2615     }
2616 
2617     if (!this->checkLiteralType(SubExpr))
2618       return false;
2619     // Non-primitive values.
2620     if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2621       return false;
2622     if (!this->visitInitializer(SubExpr))
2623       return false;
2624     if (IsStatic)
2625       return this->emitInitGlobalTempComp(TempDecl, E);
2626     return true;
2627   }
2628 
2629   // For everyhing else, use local variables.
2630   if (SubExprT) {
2631     unsigned LocalIndex = allocateLocalPrimitive(E, *SubExprT, /*IsConst=*/true,
2632                                                  /*IsExtended=*/true);
2633     if (!this->visit(SubExpr))
2634       return false;
2635     if (!this->emitSetLocal(*SubExprT, LocalIndex, E))
2636       return false;
2637     return this->emitGetPtrLocal(LocalIndex, E);
2638   } else {
2639 
2640     if (!this->checkLiteralType(SubExpr))
2641       return false;
2642 
2643     const Expr *Inner = E->getSubExpr()->skipRValueSubobjectAdjustments();
2644     if (std::optional<unsigned> LocalIndex =
2645             allocateLocal(Inner, E->getExtendingDecl())) {
2646       InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
2647       if (!this->emitGetPtrLocal(*LocalIndex, E))
2648         return false;
2649       return this->visitInitializer(SubExpr);
2650     }
2651   }
2652   return false;
2653 }
2654 
2655 template <class Emitter>
2656 bool Compiler<Emitter>::VisitCXXBindTemporaryExpr(
2657     const CXXBindTemporaryExpr *E) {
2658   return this->delegate(E->getSubExpr());
2659 }
2660 
2661 template <class Emitter>
2662 bool Compiler<Emitter>::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) {
2663   const Expr *Init = E->getInitializer();
2664   if (DiscardResult)
2665     return this->discard(Init);
2666 
2667   if (Initializing) {
2668     // We already have a value, just initialize that.
2669     return this->visitInitializer(Init) && this->emitFinishInit(E);
2670   }
2671 
2672   std::optional<PrimType> T = classify(E->getType());
2673   if (E->isFileScope()) {
2674     // Avoid creating a variable if this is a primitive RValue anyway.
2675     if (T && !E->isLValue())
2676       return this->delegate(Init);
2677 
2678     if (std::optional<unsigned> GlobalIndex = P.createGlobal(E)) {
2679       if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2680         return false;
2681 
2682       if (T) {
2683         if (!this->visit(Init))
2684           return false;
2685         return this->emitInitGlobal(*T, *GlobalIndex, E);
2686       }
2687 
2688       return this->visitInitializer(Init) && this->emitFinishInit(E);
2689     }
2690 
2691     return false;
2692   }
2693 
2694   // Otherwise, use a local variable.
2695   if (T && !E->isLValue()) {
2696     // For primitive types, we just visit the initializer.
2697     return this->delegate(Init);
2698   } else {
2699     unsigned LocalIndex;
2700 
2701     if (T)
2702       LocalIndex = this->allocateLocalPrimitive(Init, *T, false, false);
2703     else if (std::optional<unsigned> MaybeIndex = this->allocateLocal(Init))
2704       LocalIndex = *MaybeIndex;
2705     else
2706       return false;
2707 
2708     if (!this->emitGetPtrLocal(LocalIndex, E))
2709       return false;
2710 
2711     if (T) {
2712       if (!this->visit(Init)) {
2713         return false;
2714       }
2715       return this->emitInit(*T, E);
2716     } else {
2717       if (!this->visitInitializer(Init) || !this->emitFinishInit(E))
2718         return false;
2719     }
2720     return true;
2721   }
2722 
2723   return false;
2724 }
2725 
2726 template <class Emitter>
2727 bool Compiler<Emitter>::VisitTypeTraitExpr(const TypeTraitExpr *E) {
2728   if (DiscardResult)
2729     return true;
2730   if (E->getType()->isBooleanType())
2731     return this->emitConstBool(E->getValue(), E);
2732   return this->emitConst(E->getValue(), E);
2733 }
2734 
2735 template <class Emitter>
2736 bool Compiler<Emitter>::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) {
2737   if (DiscardResult)
2738     return true;
2739   return this->emitConst(E->getValue(), E);
2740 }
2741 
2742 template <class Emitter>
2743 bool Compiler<Emitter>::VisitLambdaExpr(const LambdaExpr *E) {
2744   if (DiscardResult)
2745     return true;
2746 
2747   assert(Initializing);
2748   const Record *R = P.getOrCreateRecord(E->getLambdaClass());
2749 
2750   auto *CaptureInitIt = E->capture_init_begin();
2751   // Initialize all fields (which represent lambda captures) of the
2752   // record with their initializers.
2753   for (const Record::Field &F : R->fields()) {
2754     const Expr *Init = *CaptureInitIt;
2755     ++CaptureInitIt;
2756 
2757     if (!Init)
2758       continue;
2759 
2760     if (std::optional<PrimType> T = classify(Init)) {
2761       if (!this->visit(Init))
2762         return false;
2763 
2764       if (!this->emitInitField(*T, F.Offset, E))
2765         return false;
2766     } else {
2767       if (!this->emitGetPtrField(F.Offset, E))
2768         return false;
2769 
2770       if (!this->visitInitializer(Init))
2771         return false;
2772 
2773       if (!this->emitPopPtr(E))
2774         return false;
2775     }
2776   }
2777 
2778   return true;
2779 }
2780 
2781 template <class Emitter>
2782 bool Compiler<Emitter>::VisitPredefinedExpr(const PredefinedExpr *E) {
2783   if (DiscardResult)
2784     return true;
2785 
2786   return this->delegate(E->getFunctionName());
2787 }
2788 
2789 template <class Emitter>
2790 bool Compiler<Emitter>::VisitCXXThrowExpr(const CXXThrowExpr *E) {
2791   if (E->getSubExpr() && !this->discard(E->getSubExpr()))
2792     return false;
2793 
2794   return this->emitInvalid(E);
2795 }
2796 
2797 template <class Emitter>
2798 bool Compiler<Emitter>::VisitCXXReinterpretCastExpr(
2799     const CXXReinterpretCastExpr *E) {
2800   const Expr *SubExpr = E->getSubExpr();
2801 
2802   std::optional<PrimType> FromT = classify(SubExpr);
2803   std::optional<PrimType> ToT = classify(E);
2804 
2805   if (!FromT || !ToT)
2806     return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, E);
2807 
2808   if (FromT == PT_Ptr || ToT == PT_Ptr) {
2809     // Both types could be PT_Ptr because their expressions are glvalues.
2810     std::optional<PrimType> PointeeFromT;
2811     if (SubExpr->getType()->isPointerOrReferenceType())
2812       PointeeFromT = classify(SubExpr->getType()->getPointeeType());
2813     else
2814       PointeeFromT = classify(SubExpr->getType());
2815 
2816     std::optional<PrimType> PointeeToT;
2817     if (E->getType()->isPointerOrReferenceType())
2818       PointeeToT = classify(E->getType()->getPointeeType());
2819     else
2820       PointeeToT = classify(E->getType());
2821 
2822     bool Fatal = true;
2823     if (PointeeToT && PointeeFromT) {
2824       if (isIntegralType(*PointeeFromT) && isIntegralType(*PointeeToT))
2825         Fatal = false;
2826     }
2827 
2828     if (!this->emitInvalidCast(CastKind::Reinterpret, Fatal, E))
2829       return false;
2830 
2831     if (E->getCastKind() == CK_LValueBitCast)
2832       return this->delegate(SubExpr);
2833     return this->VisitCastExpr(E);
2834   }
2835 
2836   // Try to actually do the cast.
2837   bool Fatal = (ToT != FromT);
2838   if (!this->emitInvalidCast(CastKind::Reinterpret, Fatal, E))
2839     return false;
2840 
2841   return this->VisitCastExpr(E);
2842 }
2843 
2844 template <class Emitter>
2845 bool Compiler<Emitter>::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) {
2846   assert(E->getType()->isBooleanType());
2847 
2848   if (DiscardResult)
2849     return true;
2850   return this->emitConstBool(E->getValue(), E);
2851 }
2852 
2853 template <class Emitter>
2854 bool Compiler<Emitter>::VisitCXXConstructExpr(const CXXConstructExpr *E) {
2855   QualType T = E->getType();
2856   assert(!classify(T));
2857 
2858   if (T->isRecordType()) {
2859     const CXXConstructorDecl *Ctor = E->getConstructor();
2860 
2861     // Trivial copy/move constructor. Avoid copy.
2862     if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
2863         Ctor->isTrivial() &&
2864         E->getArg(0)->isTemporaryObject(Ctx.getASTContext(),
2865                                         T->getAsCXXRecordDecl()))
2866       return this->visitInitializer(E->getArg(0));
2867 
2868     // If we're discarding a construct expression, we still need
2869     // to allocate a variable and call the constructor and destructor.
2870     if (DiscardResult) {
2871       if (Ctor->isTrivial())
2872         return true;
2873       assert(!Initializing);
2874       std::optional<unsigned> LocalIndex = allocateLocal(E);
2875 
2876       if (!LocalIndex)
2877         return false;
2878 
2879       if (!this->emitGetPtrLocal(*LocalIndex, E))
2880         return false;
2881     }
2882 
2883     // Zero initialization.
2884     if (E->requiresZeroInitialization()) {
2885       const Record *R = getRecord(E->getType());
2886 
2887       if (!this->visitZeroRecordInitializer(R, E))
2888         return false;
2889 
2890       // If the constructor is trivial anyway, we're done.
2891       if (Ctor->isTrivial())
2892         return true;
2893     }
2894 
2895     const Function *Func = getFunction(Ctor);
2896 
2897     if (!Func)
2898       return false;
2899 
2900     assert(Func->hasThisPointer());
2901     assert(!Func->hasRVO());
2902 
2903     //  The This pointer is already on the stack because this is an initializer,
2904     //  but we need to dup() so the call() below has its own copy.
2905     if (!this->emitDupPtr(E))
2906       return false;
2907 
2908     // Constructor arguments.
2909     for (const auto *Arg : E->arguments()) {
2910       if (!this->visit(Arg))
2911         return false;
2912     }
2913 
2914     if (Func->isVariadic()) {
2915       uint32_t VarArgSize = 0;
2916       unsigned NumParams = Func->getNumWrittenParams();
2917       for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) {
2918         VarArgSize +=
2919             align(primSize(classify(E->getArg(I)->getType()).value_or(PT_Ptr)));
2920       }
2921       if (!this->emitCallVar(Func, VarArgSize, E))
2922         return false;
2923     } else {
2924       if (!this->emitCall(Func, 0, E)) {
2925         // When discarding, we don't need the result anyway, so clean up
2926         // the instance dup we did earlier in case surrounding code wants
2927         // to keep evaluating.
2928         if (DiscardResult)
2929           (void)this->emitPopPtr(E);
2930         return false;
2931       }
2932     }
2933 
2934     if (DiscardResult)
2935       return this->emitPopPtr(E);
2936     return this->emitFinishInit(E);
2937   }
2938 
2939   if (T->isArrayType()) {
2940     const ConstantArrayType *CAT =
2941         Ctx.getASTContext().getAsConstantArrayType(E->getType());
2942     if (!CAT)
2943       return false;
2944 
2945     size_t NumElems = CAT->getZExtSize();
2946     const Function *Func = getFunction(E->getConstructor());
2947     if (!Func || !Func->isConstexpr())
2948       return false;
2949 
2950     // FIXME(perf): We're calling the constructor once per array element here,
2951     //   in the old intepreter we had a special-case for trivial constructors.
2952     for (size_t I = 0; I != NumElems; ++I) {
2953       if (!this->emitConstUint64(I, E))
2954         return false;
2955       if (!this->emitArrayElemPtrUint64(E))
2956         return false;
2957 
2958       // Constructor arguments.
2959       for (const auto *Arg : E->arguments()) {
2960         if (!this->visit(Arg))
2961           return false;
2962       }
2963 
2964       if (!this->emitCall(Func, 0, E))
2965         return false;
2966     }
2967     return true;
2968   }
2969 
2970   return false;
2971 }
2972 
2973 template <class Emitter>
2974 bool Compiler<Emitter>::VisitSourceLocExpr(const SourceLocExpr *E) {
2975   if (DiscardResult)
2976     return true;
2977 
2978   const APValue Val =
2979       E->EvaluateInContext(Ctx.getASTContext(), SourceLocDefaultExpr);
2980 
2981   // Things like __builtin_LINE().
2982   if (E->getType()->isIntegerType()) {
2983     assert(Val.isInt());
2984     const APSInt &I = Val.getInt();
2985     return this->emitConst(I, E);
2986   }
2987   // Otherwise, the APValue is an LValue, with only one element.
2988   // Theoretically, we don't need the APValue at all of course.
2989   assert(E->getType()->isPointerType());
2990   assert(Val.isLValue());
2991   const APValue::LValueBase &Base = Val.getLValueBase();
2992   if (const Expr *LValueExpr = Base.dyn_cast<const Expr *>())
2993     return this->visit(LValueExpr);
2994 
2995   // Otherwise, we have a decl (which is the case for
2996   // __builtin_source_location).
2997   assert(Base.is<const ValueDecl *>());
2998   assert(Val.getLValuePath().size() == 0);
2999   const auto *BaseDecl = Base.dyn_cast<const ValueDecl *>();
3000   assert(BaseDecl);
3001 
3002   auto *UGCD = cast<UnnamedGlobalConstantDecl>(BaseDecl);
3003 
3004   std::optional<unsigned> GlobalIndex = P.getOrCreateGlobal(UGCD);
3005   if (!GlobalIndex)
3006     return false;
3007 
3008   if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3009     return false;
3010 
3011   const Record *R = getRecord(E->getType());
3012   const APValue &V = UGCD->getValue();
3013   for (unsigned I = 0, N = R->getNumFields(); I != N; ++I) {
3014     const Record::Field *F = R->getField(I);
3015     const APValue &FieldValue = V.getStructField(I);
3016 
3017     PrimType FieldT = classifyPrim(F->Decl->getType());
3018 
3019     if (!this->visitAPValue(FieldValue, FieldT, E))
3020       return false;
3021     if (!this->emitInitField(FieldT, F->Offset, E))
3022       return false;
3023   }
3024 
3025   // Leave the pointer to the global on the stack.
3026   return true;
3027 }
3028 
3029 template <class Emitter>
3030 bool Compiler<Emitter>::VisitOffsetOfExpr(const OffsetOfExpr *E) {
3031   unsigned N = E->getNumComponents();
3032   if (N == 0)
3033     return false;
3034 
3035   for (unsigned I = 0; I != N; ++I) {
3036     const OffsetOfNode &Node = E->getComponent(I);
3037     if (Node.getKind() == OffsetOfNode::Array) {
3038       const Expr *ArrayIndexExpr = E->getIndexExpr(Node.getArrayExprIndex());
3039       PrimType IndexT = classifyPrim(ArrayIndexExpr->getType());
3040 
3041       if (DiscardResult) {
3042         if (!this->discard(ArrayIndexExpr))
3043           return false;
3044         continue;
3045       }
3046 
3047       if (!this->visit(ArrayIndexExpr))
3048         return false;
3049       // Cast to Sint64.
3050       if (IndexT != PT_Sint64) {
3051         if (!this->emitCast(IndexT, PT_Sint64, E))
3052           return false;
3053       }
3054     }
3055   }
3056 
3057   if (DiscardResult)
3058     return true;
3059 
3060   PrimType T = classifyPrim(E->getType());
3061   return this->emitOffsetOf(T, E, E);
3062 }
3063 
3064 template <class Emitter>
3065 bool Compiler<Emitter>::VisitCXXScalarValueInitExpr(
3066     const CXXScalarValueInitExpr *E) {
3067   QualType Ty = E->getType();
3068 
3069   if (DiscardResult || Ty->isVoidType())
3070     return true;
3071 
3072   if (std::optional<PrimType> T = classify(Ty))
3073     return this->visitZeroInitializer(*T, Ty, E);
3074 
3075   if (const auto *CT = Ty->getAs<ComplexType>()) {
3076     if (!Initializing) {
3077       std::optional<unsigned> LocalIndex = allocateLocal(E);
3078       if (!LocalIndex)
3079         return false;
3080       if (!this->emitGetPtrLocal(*LocalIndex, E))
3081         return false;
3082     }
3083 
3084     // Initialize both fields to 0.
3085     QualType ElemQT = CT->getElementType();
3086     PrimType ElemT = classifyPrim(ElemQT);
3087 
3088     for (unsigned I = 0; I != 2; ++I) {
3089       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
3090         return false;
3091       if (!this->emitInitElem(ElemT, I, E))
3092         return false;
3093     }
3094     return true;
3095   }
3096 
3097   if (const auto *VT = Ty->getAs<VectorType>()) {
3098     // FIXME: Code duplication with the _Complex case above.
3099     if (!Initializing) {
3100       std::optional<unsigned> LocalIndex = allocateLocal(E);
3101       if (!LocalIndex)
3102         return false;
3103       if (!this->emitGetPtrLocal(*LocalIndex, E))
3104         return false;
3105     }
3106 
3107     // Initialize all fields to 0.
3108     QualType ElemQT = VT->getElementType();
3109     PrimType ElemT = classifyPrim(ElemQT);
3110 
3111     for (unsigned I = 0, N = VT->getNumElements(); I != N; ++I) {
3112       if (!this->visitZeroInitializer(ElemT, ElemQT, E))
3113         return false;
3114       if (!this->emitInitElem(ElemT, I, E))
3115         return false;
3116     }
3117     return true;
3118   }
3119 
3120   return false;
3121 }
3122 
3123 template <class Emitter>
3124 bool Compiler<Emitter>::VisitSizeOfPackExpr(const SizeOfPackExpr *E) {
3125   return this->emitConst(E->getPackLength(), E);
3126 }
3127 
3128 template <class Emitter>
3129 bool Compiler<Emitter>::VisitGenericSelectionExpr(
3130     const GenericSelectionExpr *E) {
3131   return this->delegate(E->getResultExpr());
3132 }
3133 
3134 template <class Emitter>
3135 bool Compiler<Emitter>::VisitChooseExpr(const ChooseExpr *E) {
3136   return this->delegate(E->getChosenSubExpr());
3137 }
3138 
3139 template <class Emitter>
3140 bool Compiler<Emitter>::VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) {
3141   if (DiscardResult)
3142     return true;
3143 
3144   return this->emitConst(E->getValue(), E);
3145 }
3146 
3147 template <class Emitter>
3148 bool Compiler<Emitter>::VisitCXXInheritedCtorInitExpr(
3149     const CXXInheritedCtorInitExpr *E) {
3150   const CXXConstructorDecl *Ctor = E->getConstructor();
3151   assert(!Ctor->isTrivial() &&
3152          "Trivial CXXInheritedCtorInitExpr, implement. (possible?)");
3153   const Function *F = this->getFunction(Ctor);
3154   assert(F);
3155   assert(!F->hasRVO());
3156   assert(F->hasThisPointer());
3157 
3158   if (!this->emitDupPtr(SourceInfo{}))
3159     return false;
3160 
3161   // Forward all arguments of the current function (which should be a
3162   // constructor itself) to the inherited ctor.
3163   // This is necessary because the calling code has pushed the pointer
3164   // of the correct base for  us already, but the arguments need
3165   // to come after.
3166   unsigned Offset = align(primSize(PT_Ptr)); // instance pointer.
3167   for (const ParmVarDecl *PD : Ctor->parameters()) {
3168     PrimType PT = this->classify(PD->getType()).value_or(PT_Ptr);
3169 
3170     if (!this->emitGetParam(PT, Offset, E))
3171       return false;
3172     Offset += align(primSize(PT));
3173   }
3174 
3175   return this->emitCall(F, 0, E);
3176 }
3177 
3178 template <class Emitter>
3179 bool Compiler<Emitter>::VisitCXXNewExpr(const CXXNewExpr *E) {
3180   assert(classifyPrim(E->getType()) == PT_Ptr);
3181   const Expr *Init = E->getInitializer();
3182   QualType ElementType = E->getAllocatedType();
3183   std::optional<PrimType> ElemT = classify(ElementType);
3184   unsigned PlacementArgs = E->getNumPlacementArgs();
3185   const FunctionDecl *OperatorNew = E->getOperatorNew();
3186   const Expr *PlacementDest = nullptr;
3187   bool IsNoThrow = false;
3188 
3189   if (PlacementArgs != 0) {
3190     // FIXME: There is no restriction on this, but it's not clear that any
3191     // other form makes any sense. We get here for cases such as:
3192     //
3193     //   new (std::align_val_t{N}) X(int)
3194     //
3195     // (which should presumably be valid only if N is a multiple of
3196     // alignof(int), and in any case can't be deallocated unless N is
3197     // alignof(X) and X has new-extended alignment).
3198     if (PlacementArgs == 1) {
3199       const Expr *Arg1 = E->getPlacementArg(0);
3200       if (Arg1->getType()->isNothrowT()) {
3201         if (!this->discard(Arg1))
3202           return false;
3203         IsNoThrow = true;
3204       } else {
3205         // Invalid unless we have C++26 or are in a std:: function.
3206         if (!this->emitInvalidNewDeleteExpr(E, E))
3207           return false;
3208 
3209         // If we have a placement-new destination, we'll later use that instead
3210         // of allocating.
3211         if (OperatorNew->isReservedGlobalPlacementOperator())
3212           PlacementDest = Arg1;
3213       }
3214     } else {
3215       // Always invalid.
3216       return this->emitInvalid(E);
3217     }
3218   } else if (!OperatorNew->isReplaceableGlobalAllocationFunction())
3219     return this->emitInvalidNewDeleteExpr(E, E);
3220 
3221   const Descriptor *Desc;
3222   if (!PlacementDest) {
3223     if (ElemT) {
3224       if (E->isArray())
3225         Desc = nullptr; // We're not going to use it in this case.
3226       else
3227         Desc = P.createDescriptor(E, *ElemT, Descriptor::InlineDescMD,
3228                                   /*IsConst=*/false, /*IsTemporary=*/false,
3229                                   /*IsMutable=*/false);
3230     } else {
3231       Desc = P.createDescriptor(
3232           E, ElementType.getTypePtr(),
3233           E->isArray() ? std::nullopt : Descriptor::InlineDescMD,
3234           /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false, Init);
3235     }
3236   }
3237 
3238   if (E->isArray()) {
3239     std::optional<const Expr *> ArraySizeExpr = E->getArraySize();
3240     if (!ArraySizeExpr)
3241       return false;
3242 
3243     const Expr *Stripped = *ArraySizeExpr;
3244     for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
3245          Stripped = ICE->getSubExpr())
3246       if (ICE->getCastKind() != CK_NoOp &&
3247           ICE->getCastKind() != CK_IntegralCast)
3248         break;
3249 
3250     PrimType SizeT = classifyPrim(Stripped->getType());
3251 
3252     if (PlacementDest) {
3253       if (!this->visit(PlacementDest))
3254         return false;
3255       if (!this->visit(Stripped))
3256         return false;
3257       if (!this->emitCheckNewTypeMismatchArray(SizeT, E, E))
3258         return false;
3259     } else {
3260       if (!this->visit(Stripped))
3261         return false;
3262 
3263       if (ElemT) {
3264         // N primitive elements.
3265         if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E))
3266           return false;
3267       } else {
3268         // N Composite elements.
3269         if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E))
3270           return false;
3271       }
3272     }
3273 
3274     if (Init && !this->visitInitializer(Init))
3275       return false;
3276 
3277   } else {
3278     if (PlacementDest) {
3279       if (!this->visit(PlacementDest))
3280         return false;
3281       if (!this->emitCheckNewTypeMismatch(E, E))
3282         return false;
3283     } else {
3284       // Allocate just one element.
3285       if (!this->emitAlloc(Desc, E))
3286         return false;
3287     }
3288 
3289     if (Init) {
3290       if (ElemT) {
3291         if (!this->visit(Init))
3292           return false;
3293 
3294         if (!this->emitInit(*ElemT, E))
3295           return false;
3296       } else {
3297         // Composite.
3298         if (!this->visitInitializer(Init))
3299           return false;
3300       }
3301     }
3302   }
3303 
3304   if (DiscardResult)
3305     return this->emitPopPtr(E);
3306 
3307   return true;
3308 }
3309 
3310 template <class Emitter>
3311 bool Compiler<Emitter>::VisitCXXDeleteExpr(const CXXDeleteExpr *E) {
3312   const Expr *Arg = E->getArgument();
3313 
3314   const FunctionDecl *OperatorDelete = E->getOperatorDelete();
3315 
3316   if (!OperatorDelete->isReplaceableGlobalAllocationFunction())
3317     return this->emitInvalidNewDeleteExpr(E, E);
3318 
3319   // Arg must be an lvalue.
3320   if (!this->visit(Arg))
3321     return false;
3322 
3323   return this->emitFree(E->isArrayForm(), E);
3324 }
3325 
3326 template <class Emitter>
3327 bool Compiler<Emitter>::VisitBlockExpr(const BlockExpr *E) {
3328   const Function *Func = nullptr;
3329   if (auto F = Compiler<ByteCodeEmitter>(Ctx, P).compileObjCBlock(E))
3330     Func = F;
3331 
3332   if (!Func)
3333     return false;
3334   return this->emitGetFnPtr(Func, E);
3335 }
3336 
3337 template <class Emitter>
3338 bool Compiler<Emitter>::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) {
3339   assert(Ctx.getLangOpts().CPlusPlus);
3340   return this->emitConstBool(E->getValue(), E);
3341 }
3342 
3343 template <class Emitter>
3344 bool Compiler<Emitter>::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
3345   if (DiscardResult)
3346     return true;
3347   assert(!Initializing);
3348 
3349   const MSGuidDecl *GuidDecl = E->getGuidDecl();
3350   const RecordDecl *RD = GuidDecl->getType()->getAsRecordDecl();
3351   assert(RD);
3352   // If the definiton of the result type is incomplete, just return a dummy.
3353   // If (and when) that is read from, we will fail, but not now.
3354   if (!RD->isCompleteDefinition()) {
3355     if (std::optional<unsigned> I = P.getOrCreateDummy(GuidDecl))
3356       return this->emitGetPtrGlobal(*I, E);
3357     return false;
3358   }
3359 
3360   std::optional<unsigned> GlobalIndex = P.getOrCreateGlobal(GuidDecl);
3361   if (!GlobalIndex)
3362     return false;
3363   if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3364     return false;
3365 
3366   assert(this->getRecord(E->getType()));
3367 
3368   const APValue &V = GuidDecl->getAsAPValue();
3369   if (V.getKind() == APValue::None)
3370     return true;
3371 
3372   assert(V.isStruct());
3373   assert(V.getStructNumBases() == 0);
3374   if (!this->visitAPValueInitializer(V, E))
3375     return false;
3376 
3377   return this->emitFinishInit(E);
3378 }
3379 
3380 template <class Emitter>
3381 bool Compiler<Emitter>::VisitRequiresExpr(const RequiresExpr *E) {
3382   assert(classifyPrim(E->getType()) == PT_Bool);
3383   if (DiscardResult)
3384     return true;
3385   return this->emitConstBool(E->isSatisfied(), E);
3386 }
3387 
3388 template <class Emitter>
3389 bool Compiler<Emitter>::VisitConceptSpecializationExpr(
3390     const ConceptSpecializationExpr *E) {
3391   assert(classifyPrim(E->getType()) == PT_Bool);
3392   if (DiscardResult)
3393     return true;
3394   return this->emitConstBool(E->isSatisfied(), E);
3395 }
3396 
3397 template <class Emitter>
3398 bool Compiler<Emitter>::VisitCXXRewrittenBinaryOperator(
3399     const CXXRewrittenBinaryOperator *E) {
3400   return this->delegate(E->getSemanticForm());
3401 }
3402 
3403 template <class Emitter>
3404 bool Compiler<Emitter>::VisitPseudoObjectExpr(const PseudoObjectExpr *E) {
3405 
3406   for (const Expr *SemE : E->semantics()) {
3407     if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
3408       if (SemE == E->getResultExpr())
3409         return false;
3410 
3411       if (OVE->isUnique())
3412         continue;
3413 
3414       if (!this->discard(OVE))
3415         return false;
3416     } else if (SemE == E->getResultExpr()) {
3417       if (!this->delegate(SemE))
3418         return false;
3419     } else {
3420       if (!this->discard(SemE))
3421         return false;
3422     }
3423   }
3424   return true;
3425 }
3426 
3427 template <class Emitter>
3428 bool Compiler<Emitter>::VisitPackIndexingExpr(const PackIndexingExpr *E) {
3429   return this->delegate(E->getSelectedExpr());
3430 }
3431 
3432 template <class Emitter>
3433 bool Compiler<Emitter>::VisitRecoveryExpr(const RecoveryExpr *E) {
3434   return this->emitError(E);
3435 }
3436 
3437 template <class Emitter>
3438 bool Compiler<Emitter>::VisitAddrLabelExpr(const AddrLabelExpr *E) {
3439   assert(E->getType()->isVoidPointerType());
3440 
3441   unsigned Offset = allocateLocalPrimitive(
3442       E->getLabel(), PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false);
3443 
3444   return this->emitGetLocal(PT_Ptr, Offset, E);
3445 }
3446 
3447 template <class Emitter>
3448 bool Compiler<Emitter>::VisitConvertVectorExpr(const ConvertVectorExpr *E) {
3449   assert(Initializing);
3450   const auto *VT = E->getType()->castAs<VectorType>();
3451   QualType ElemType = VT->getElementType();
3452   PrimType ElemT = classifyPrim(ElemType);
3453   const Expr *Src = E->getSrcExpr();
3454   PrimType SrcElemT =
3455       classifyPrim(Src->getType()->castAs<VectorType>()->getElementType());
3456 
3457   unsigned SrcOffset = this->allocateLocalPrimitive(Src, PT_Ptr, true, false);
3458   if (!this->visit(Src))
3459     return false;
3460   if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
3461     return false;
3462 
3463   for (unsigned I = 0; I != VT->getNumElements(); ++I) {
3464     if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
3465       return false;
3466     if (!this->emitArrayElemPop(SrcElemT, I, E))
3467       return false;
3468     if (SrcElemT != ElemT) {
3469       if (!this->emitPrimCast(SrcElemT, ElemT, ElemType, E))
3470         return false;
3471     }
3472     if (!this->emitInitElem(ElemT, I, E))
3473       return false;
3474   }
3475 
3476   return true;
3477 }
3478 
3479 template <class Emitter>
3480 bool Compiler<Emitter>::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) {
3481   assert(Initializing);
3482   assert(E->getNumSubExprs() > 2);
3483 
3484   const Expr *Vecs[] = {E->getExpr(0), E->getExpr(1)};
3485   const VectorType *VT = Vecs[0]->getType()->castAs<VectorType>();
3486   PrimType ElemT = classifyPrim(VT->getElementType());
3487   unsigned NumInputElems = VT->getNumElements();
3488   unsigned NumOutputElems = E->getNumSubExprs() - 2;
3489   assert(NumOutputElems > 0);
3490 
3491   // Save both input vectors to a local variable.
3492   unsigned VectorOffsets[2];
3493   for (unsigned I = 0; I != 2; ++I) {
3494     VectorOffsets[I] = this->allocateLocalPrimitive(
3495         Vecs[I], PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false);
3496     if (!this->visit(Vecs[I]))
3497       return false;
3498     if (!this->emitSetLocal(PT_Ptr, VectorOffsets[I], E))
3499       return false;
3500   }
3501   for (unsigned I = 0; I != NumOutputElems; ++I) {
3502     APSInt ShuffleIndex = E->getShuffleMaskIdx(Ctx.getASTContext(), I);
3503     if (ShuffleIndex == -1)
3504       return this->emitInvalid(E); // FIXME: Better diagnostic.
3505 
3506     assert(ShuffleIndex < (NumInputElems * 2));
3507     if (!this->emitGetLocal(PT_Ptr,
3508                             VectorOffsets[ShuffleIndex >= NumInputElems], E))
3509       return false;
3510     unsigned InputVectorIndex = ShuffleIndex.getZExtValue() % NumInputElems;
3511     if (!this->emitArrayElemPop(ElemT, InputVectorIndex, E))
3512       return false;
3513 
3514     if (!this->emitInitElem(ElemT, I, E))
3515       return false;
3516   }
3517 
3518   return true;
3519 }
3520 
3521 template <class Emitter>
3522 bool Compiler<Emitter>::VisitExtVectorElementExpr(
3523     const ExtVectorElementExpr *E) {
3524   const Expr *Base = E->getBase();
3525   assert(
3526       Base->getType()->isVectorType() ||
3527       Base->getType()->getAs<PointerType>()->getPointeeType()->isVectorType());
3528 
3529   SmallVector<uint32_t, 4> Indices;
3530   E->getEncodedElementAccess(Indices);
3531 
3532   if (Indices.size() == 1) {
3533     if (!this->visit(Base))
3534       return false;
3535 
3536     if (E->isGLValue()) {
3537       if (!this->emitConstUint32(Indices[0], E))
3538         return false;
3539       return this->emitArrayElemPtrPop(PT_Uint32, E);
3540     }
3541     // Else, also load the value.
3542     return this->emitArrayElemPop(classifyPrim(E->getType()), Indices[0], E);
3543   }
3544 
3545   // Create a local variable for the base.
3546   unsigned BaseOffset = allocateLocalPrimitive(Base, PT_Ptr, /*IsConst=*/true,
3547                                                /*IsExtended=*/false);
3548   if (!this->visit(Base))
3549     return false;
3550   if (!this->emitSetLocal(PT_Ptr, BaseOffset, E))
3551     return false;
3552 
3553   // Now the vector variable for the return value.
3554   if (!Initializing) {
3555     std::optional<unsigned> ResultIndex;
3556     ResultIndex = allocateLocal(E);
3557     if (!ResultIndex)
3558       return false;
3559     if (!this->emitGetPtrLocal(*ResultIndex, E))
3560       return false;
3561   }
3562 
3563   assert(Indices.size() == E->getType()->getAs<VectorType>()->getNumElements());
3564 
3565   PrimType ElemT =
3566       classifyPrim(E->getType()->getAs<VectorType>()->getElementType());
3567   uint32_t DstIndex = 0;
3568   for (uint32_t I : Indices) {
3569     if (!this->emitGetLocal(PT_Ptr, BaseOffset, E))
3570       return false;
3571     if (!this->emitArrayElemPop(ElemT, I, E))
3572       return false;
3573     if (!this->emitInitElem(ElemT, DstIndex, E))
3574       return false;
3575     ++DstIndex;
3576   }
3577 
3578   // Leave the result pointer on the stack.
3579   assert(!DiscardResult);
3580   return true;
3581 }
3582 
3583 template <class Emitter>
3584 bool Compiler<Emitter>::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) {
3585   const Expr *SubExpr = E->getSubExpr();
3586   if (!E->isExpressibleAsConstantInitializer())
3587     return this->discard(SubExpr) && this->emitInvalid(E);
3588 
3589   assert(classifyPrim(E) == PT_Ptr);
3590   if (std::optional<unsigned> I = P.getOrCreateDummy(E))
3591     return this->emitGetPtrGlobal(*I, E);
3592 
3593   return false;
3594 }
3595 
3596 template <class Emitter>
3597 bool Compiler<Emitter>::VisitCXXStdInitializerListExpr(
3598     const CXXStdInitializerListExpr *E) {
3599   const Expr *SubExpr = E->getSubExpr();
3600   const ConstantArrayType *ArrayType =
3601       Ctx.getASTContext().getAsConstantArrayType(SubExpr->getType());
3602   const Record *R = getRecord(E->getType());
3603   assert(Initializing);
3604   assert(SubExpr->isGLValue());
3605 
3606   if (!this->visit(SubExpr))
3607     return false;
3608   if (!this->emitConstUint8(0, E))
3609     return false;
3610   if (!this->emitArrayElemPtrPopUint8(E))
3611     return false;
3612   if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E))
3613     return false;
3614 
3615   PrimType SecondFieldT = classifyPrim(R->getField(1u)->Decl->getType());
3616   if (isIntegralType(SecondFieldT)) {
3617     if (!this->emitConst(static_cast<APSInt>(ArrayType->getSize()),
3618                          SecondFieldT, E))
3619       return false;
3620     return this->emitInitField(SecondFieldT, R->getField(1u)->Offset, E);
3621   }
3622   assert(SecondFieldT == PT_Ptr);
3623 
3624   if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E))
3625     return false;
3626   if (!this->emitExpandPtr(E))
3627     return false;
3628   if (!this->emitConst(static_cast<APSInt>(ArrayType->getSize()), PT_Uint64, E))
3629     return false;
3630   if (!this->emitArrayElemPtrPop(PT_Uint64, E))
3631     return false;
3632   return this->emitInitFieldPtr(R->getField(1u)->Offset, E);
3633 }
3634 
3635 template <class Emitter>
3636 bool Compiler<Emitter>::VisitStmtExpr(const StmtExpr *E) {
3637   BlockScope<Emitter> BS(this);
3638   StmtExprScope<Emitter> SS(this);
3639 
3640   const CompoundStmt *CS = E->getSubStmt();
3641   const Stmt *Result = CS->getStmtExprResult();
3642   for (const Stmt *S : CS->body()) {
3643     if (S != Result) {
3644       if (!this->visitStmt(S))
3645         return false;
3646       continue;
3647     }
3648 
3649     assert(S == Result);
3650     if (const Expr *ResultExpr = dyn_cast<Expr>(S))
3651       return this->delegate(ResultExpr);
3652     return this->emitUnsupported(E);
3653   }
3654 
3655   return BS.destroyLocals();
3656 }
3657 
3658 template <class Emitter> bool Compiler<Emitter>::discard(const Expr *E) {
3659   OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true,
3660                              /*NewInitializing=*/false);
3661   return this->Visit(E);
3662 }
3663 
3664 template <class Emitter> bool Compiler<Emitter>::delegate(const Expr *E) {
3665   // We're basically doing:
3666   // OptionScope<Emitter> Scope(this, DicardResult, Initializing);
3667   // but that's unnecessary of course.
3668   return this->Visit(E);
3669 }
3670 
3671 template <class Emitter> bool Compiler<Emitter>::visit(const Expr *E) {
3672   if (E->getType().isNull())
3673     return false;
3674 
3675   if (E->getType()->isVoidType())
3676     return this->discard(E);
3677 
3678   // Create local variable to hold the return value.
3679   if (!E->isGLValue() && !E->getType()->isAnyComplexType() &&
3680       !classify(E->getType())) {
3681     std::optional<unsigned> LocalIndex = allocateLocal(E);
3682     if (!LocalIndex)
3683       return false;
3684 
3685     if (!this->emitGetPtrLocal(*LocalIndex, E))
3686       return false;
3687     return this->visitInitializer(E);
3688   }
3689 
3690   //  Otherwise,we have a primitive return value, produce the value directly
3691   //  and push it on the stack.
3692   OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
3693                              /*NewInitializing=*/false);
3694   return this->Visit(E);
3695 }
3696 
3697 template <class Emitter>
3698 bool Compiler<Emitter>::visitInitializer(const Expr *E) {
3699   assert(!classify(E->getType()));
3700 
3701   OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
3702                              /*NewInitializing=*/true);
3703   return this->Visit(E);
3704 }
3705 
3706 template <class Emitter> bool Compiler<Emitter>::visitBool(const Expr *E) {
3707   std::optional<PrimType> T = classify(E->getType());
3708   if (!T) {
3709     // Convert complex values to bool.
3710     if (E->getType()->isAnyComplexType()) {
3711       if (!this->visit(E))
3712         return false;
3713       return this->emitComplexBoolCast(E);
3714     }
3715     return false;
3716   }
3717 
3718   if (!this->visit(E))
3719     return false;
3720 
3721   if (T == PT_Bool)
3722     return true;
3723 
3724   // Convert pointers to bool.
3725   if (T == PT_Ptr || T == PT_FnPtr) {
3726     if (!this->emitNull(*T, nullptr, E))
3727       return false;
3728     return this->emitNE(*T, E);
3729   }
3730 
3731   // Or Floats.
3732   if (T == PT_Float)
3733     return this->emitCastFloatingIntegralBool(getFPOptions(E), E);
3734 
3735   // Or anything else we can.
3736   return this->emitCast(*T, PT_Bool, E);
3737 }
3738 
3739 template <class Emitter>
3740 bool Compiler<Emitter>::visitZeroInitializer(PrimType T, QualType QT,
3741                                              const Expr *E) {
3742   switch (T) {
3743   case PT_Bool:
3744     return this->emitZeroBool(E);
3745   case PT_Sint8:
3746     return this->emitZeroSint8(E);
3747   case PT_Uint8:
3748     return this->emitZeroUint8(E);
3749   case PT_Sint16:
3750     return this->emitZeroSint16(E);
3751   case PT_Uint16:
3752     return this->emitZeroUint16(E);
3753   case PT_Sint32:
3754     return this->emitZeroSint32(E);
3755   case PT_Uint32:
3756     return this->emitZeroUint32(E);
3757   case PT_Sint64:
3758     return this->emitZeroSint64(E);
3759   case PT_Uint64:
3760     return this->emitZeroUint64(E);
3761   case PT_IntAP:
3762     return this->emitZeroIntAP(Ctx.getBitWidth(QT), E);
3763   case PT_IntAPS:
3764     return this->emitZeroIntAPS(Ctx.getBitWidth(QT), E);
3765   case PT_Ptr:
3766     return this->emitNullPtr(nullptr, E);
3767   case PT_FnPtr:
3768     return this->emitNullFnPtr(nullptr, E);
3769   case PT_MemberPtr:
3770     return this->emitNullMemberPtr(nullptr, E);
3771   case PT_Float:
3772     return this->emitConstFloat(APFloat::getZero(Ctx.getFloatSemantics(QT)), E);
3773   case PT_FixedPoint: {
3774     auto Sem = Ctx.getASTContext().getFixedPointSemantics(E->getType());
3775     return this->emitConstFixedPoint(FixedPoint::Zero(Sem), E);
3776   }
3777     llvm_unreachable("Implement");
3778   }
3779   llvm_unreachable("unknown primitive type");
3780 }
3781 
3782 template <class Emitter>
3783 bool Compiler<Emitter>::visitZeroRecordInitializer(const Record *R,
3784                                                    const Expr *E) {
3785   assert(E);
3786   assert(R);
3787   // Fields
3788   for (const Record::Field &Field : R->fields()) {
3789     if (Field.Decl->isUnnamedBitField())
3790       continue;
3791 
3792     const Descriptor *D = Field.Desc;
3793     if (D->isPrimitive()) {
3794       QualType QT = D->getType();
3795       PrimType T = classifyPrim(D->getType());
3796       if (!this->visitZeroInitializer(T, QT, E))
3797         return false;
3798       if (!this->emitInitField(T, Field.Offset, E))
3799         return false;
3800       if (R->isUnion())
3801         break;
3802       continue;
3803     }
3804 
3805     if (!this->emitGetPtrField(Field.Offset, E))
3806       return false;
3807 
3808     if (D->isPrimitiveArray()) {
3809       QualType ET = D->getElemQualType();
3810       PrimType T = classifyPrim(ET);
3811       for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
3812         if (!this->visitZeroInitializer(T, ET, E))
3813           return false;
3814         if (!this->emitInitElem(T, I, E))
3815           return false;
3816       }
3817     } else if (D->isCompositeArray()) {
3818       const Record *ElemRecord = D->ElemDesc->ElemRecord;
3819       assert(D->ElemDesc->ElemRecord);
3820       for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
3821         if (!this->emitConstUint32(I, E))
3822           return false;
3823         if (!this->emitArrayElemPtr(PT_Uint32, E))
3824           return false;
3825         if (!this->visitZeroRecordInitializer(ElemRecord, E))
3826           return false;
3827         if (!this->emitPopPtr(E))
3828           return false;
3829       }
3830     } else if (D->isRecord()) {
3831       if (!this->visitZeroRecordInitializer(D->ElemRecord, E))
3832         return false;
3833     } else {
3834       assert(false);
3835     }
3836 
3837     if (!this->emitFinishInitPop(E))
3838       return false;
3839 
3840     // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
3841     // object's first non-static named data member is zero-initialized
3842     if (R->isUnion())
3843       break;
3844   }
3845 
3846   for (const Record::Base &B : R->bases()) {
3847     if (!this->emitGetPtrBase(B.Offset, E))
3848       return false;
3849     if (!this->visitZeroRecordInitializer(B.R, E))
3850       return false;
3851     if (!this->emitFinishInitPop(E))
3852       return false;
3853   }
3854 
3855   // FIXME: Virtual bases.
3856 
3857   return true;
3858 }
3859 
3860 template <class Emitter>
3861 template <typename T>
3862 bool Compiler<Emitter>::emitConst(T Value, PrimType Ty, const Expr *E) {
3863   switch (Ty) {
3864   case PT_Sint8:
3865     return this->emitConstSint8(Value, E);
3866   case PT_Uint8:
3867     return this->emitConstUint8(Value, E);
3868   case PT_Sint16:
3869     return this->emitConstSint16(Value, E);
3870   case PT_Uint16:
3871     return this->emitConstUint16(Value, E);
3872   case PT_Sint32:
3873     return this->emitConstSint32(Value, E);
3874   case PT_Uint32:
3875     return this->emitConstUint32(Value, E);
3876   case PT_Sint64:
3877     return this->emitConstSint64(Value, E);
3878   case PT_Uint64:
3879     return this->emitConstUint64(Value, E);
3880   case PT_Bool:
3881     return this->emitConstBool(Value, E);
3882   case PT_Ptr:
3883   case PT_FnPtr:
3884   case PT_MemberPtr:
3885   case PT_Float:
3886   case PT_IntAP:
3887   case PT_IntAPS:
3888   case PT_FixedPoint:
3889     llvm_unreachable("Invalid integral type");
3890     break;
3891   }
3892   llvm_unreachable("unknown primitive type");
3893 }
3894 
3895 template <class Emitter>
3896 template <typename T>
3897 bool Compiler<Emitter>::emitConst(T Value, const Expr *E) {
3898   return this->emitConst(Value, classifyPrim(E->getType()), E);
3899 }
3900 
3901 template <class Emitter>
3902 bool Compiler<Emitter>::emitConst(const APSInt &Value, PrimType Ty,
3903                                   const Expr *E) {
3904   if (Ty == PT_IntAPS)
3905     return this->emitConstIntAPS(Value, E);
3906   if (Ty == PT_IntAP)
3907     return this->emitConstIntAP(Value, E);
3908 
3909   if (Value.isSigned())
3910     return this->emitConst(Value.getSExtValue(), Ty, E);
3911   return this->emitConst(Value.getZExtValue(), Ty, E);
3912 }
3913 
3914 template <class Emitter>
3915 bool Compiler<Emitter>::emitConst(const APSInt &Value, const Expr *E) {
3916   return this->emitConst(Value, classifyPrim(E->getType()), E);
3917 }
3918 
3919 template <class Emitter>
3920 unsigned Compiler<Emitter>::allocateLocalPrimitive(DeclTy &&Src, PrimType Ty,
3921                                                    bool IsConst,
3922                                                    bool IsExtended) {
3923   // Make sure we don't accidentally register the same decl twice.
3924   if (const auto *VD =
3925           dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
3926     assert(!P.getGlobal(VD));
3927     assert(!Locals.contains(VD));
3928     (void)VD;
3929   }
3930 
3931   // FIXME: There are cases where Src.is<Expr*>() is wrong, e.g.
3932   //   (int){12} in C. Consider using Expr::isTemporaryObject() instead
3933   //   or isa<MaterializeTemporaryExpr>().
3934   Descriptor *D = P.createDescriptor(Src, Ty, Descriptor::InlineDescMD, IsConst,
3935                                      Src.is<const Expr *>());
3936   Scope::Local Local = this->createLocal(D);
3937   if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>()))
3938     Locals.insert({VD, Local});
3939   VarScope->add(Local, IsExtended);
3940   return Local.Offset;
3941 }
3942 
3943 template <class Emitter>
3944 std::optional<unsigned>
3945 Compiler<Emitter>::allocateLocal(DeclTy &&Src, const ValueDecl *ExtendingDecl) {
3946   // Make sure we don't accidentally register the same decl twice.
3947   if ([[maybe_unused]] const auto *VD =
3948           dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
3949     assert(!P.getGlobal(VD));
3950     assert(!Locals.contains(VD));
3951   }
3952 
3953   QualType Ty;
3954   const ValueDecl *Key = nullptr;
3955   const Expr *Init = nullptr;
3956   bool IsTemporary = false;
3957   if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
3958     Key = VD;
3959     Ty = VD->getType();
3960 
3961     if (const auto *VarD = dyn_cast<VarDecl>(VD))
3962       Init = VarD->getInit();
3963   }
3964   if (auto *E = Src.dyn_cast<const Expr *>()) {
3965     IsTemporary = true;
3966     Ty = E->getType();
3967   }
3968 
3969   Descriptor *D = P.createDescriptor(
3970       Src, Ty.getTypePtr(), Descriptor::InlineDescMD, Ty.isConstQualified(),
3971       IsTemporary, /*IsMutable=*/false, Init);
3972   if (!D)
3973     return std::nullopt;
3974 
3975   Scope::Local Local = this->createLocal(D);
3976   if (Key)
3977     Locals.insert({Key, Local});
3978   if (ExtendingDecl)
3979     VarScope->addExtended(Local, ExtendingDecl);
3980   else
3981     VarScope->add(Local, false);
3982   return Local.Offset;
3983 }
3984 
3985 template <class Emitter>
3986 unsigned Compiler<Emitter>::allocateTemporary(const Expr *E) {
3987   QualType Ty = E->getType();
3988   assert(!Ty->isRecordType());
3989 
3990   Descriptor *D = P.createDescriptor(
3991       E, Ty.getTypePtr(), Descriptor::InlineDescMD, Ty.isConstQualified(),
3992       /*IsTemporary=*/true, /*IsMutable=*/false, /*Init=*/nullptr);
3993   assert(D);
3994 
3995   Scope::Local Local = this->createLocal(D);
3996   VariableScope<Emitter> *S = VarScope;
3997   assert(S);
3998   // Attach to topmost scope.
3999   while (S->getParent())
4000     S = S->getParent();
4001   assert(S && !S->getParent());
4002   S->addLocal(Local);
4003   return Local.Offset;
4004 }
4005 
4006 template <class Emitter>
4007 const RecordType *Compiler<Emitter>::getRecordTy(QualType Ty) {
4008   if (const PointerType *PT = dyn_cast<PointerType>(Ty))
4009     return PT->getPointeeType()->getAs<RecordType>();
4010   return Ty->getAs<RecordType>();
4011 }
4012 
4013 template <class Emitter> Record *Compiler<Emitter>::getRecord(QualType Ty) {
4014   if (const auto *RecordTy = getRecordTy(Ty))
4015     return getRecord(RecordTy->getDecl());
4016   return nullptr;
4017 }
4018 
4019 template <class Emitter>
4020 Record *Compiler<Emitter>::getRecord(const RecordDecl *RD) {
4021   return P.getOrCreateRecord(RD);
4022 }
4023 
4024 template <class Emitter>
4025 const Function *Compiler<Emitter>::getFunction(const FunctionDecl *FD) {
4026   return Ctx.getOrCreateFunction(FD);
4027 }
4028 
4029 template <class Emitter>
4030 bool Compiler<Emitter>::visitExpr(const Expr *E, bool DestroyToplevelScope) {
4031   LocalScope<Emitter> RootScope(this);
4032 
4033   auto maybeDestroyLocals = [&]() -> bool {
4034     if (DestroyToplevelScope)
4035       return RootScope.destroyLocals();
4036     return true;
4037   };
4038 
4039   // Void expressions.
4040   if (E->getType()->isVoidType()) {
4041     if (!visit(E))
4042       return false;
4043     return this->emitRetVoid(E) && maybeDestroyLocals();
4044   }
4045 
4046   // Expressions with a primitive return type.
4047   if (std::optional<PrimType> T = classify(E)) {
4048     if (!visit(E))
4049       return false;
4050 
4051     return this->emitRet(*T, E) && maybeDestroyLocals();
4052   }
4053 
4054   // Expressions with a composite return type.
4055   // For us, that means everything we don't
4056   // have a PrimType for.
4057   if (std::optional<unsigned> LocalOffset = this->allocateLocal(E)) {
4058     if (!this->emitGetPtrLocal(*LocalOffset, E))
4059       return false;
4060 
4061     if (!visitInitializer(E))
4062       return false;
4063 
4064     if (!this->emitFinishInit(E))
4065       return false;
4066     // We are destroying the locals AFTER the Ret op.
4067     // The Ret op needs to copy the (alive) values, but the
4068     // destructors may still turn the entire expression invalid.
4069     return this->emitRetValue(E) && maybeDestroyLocals();
4070   }
4071 
4072   (void)maybeDestroyLocals();
4073   return false;
4074 }
4075 
4076 template <class Emitter>
4077 VarCreationState Compiler<Emitter>::visitDecl(const VarDecl *VD) {
4078 
4079   auto R = this->visitVarDecl(VD, /*Toplevel=*/true);
4080 
4081   if (R.notCreated())
4082     return R;
4083 
4084   if (R)
4085     return true;
4086 
4087   if (!R && Context::shouldBeGloballyIndexed(VD)) {
4088     if (auto GlobalIndex = P.getGlobal(VD)) {
4089       Block *GlobalBlock = P.getGlobal(*GlobalIndex);
4090       GlobalInlineDescriptor &GD =
4091           *reinterpret_cast<GlobalInlineDescriptor *>(GlobalBlock->rawData());
4092 
4093       GD.InitState = GlobalInitState::InitializerFailed;
4094       GlobalBlock->invokeDtor();
4095     }
4096   }
4097 
4098   return R;
4099 }
4100 
4101 /// Toplevel visitDeclAndReturn().
4102 /// We get here from evaluateAsInitializer().
4103 /// We need to evaluate the initializer and return its value.
4104 template <class Emitter>
4105 bool Compiler<Emitter>::visitDeclAndReturn(const VarDecl *VD,
4106                                            bool ConstantContext) {
4107   std::optional<PrimType> VarT = classify(VD->getType());
4108 
4109   // We only create variables if we're evaluating in a constant context.
4110   // Otherwise, just evaluate the initializer and return it.
4111   if (!ConstantContext) {
4112     DeclScope<Emitter> LS(this, VD);
4113     if (!this->visit(VD->getAnyInitializer()))
4114       return false;
4115     return this->emitRet(VarT.value_or(PT_Ptr), VD) && LS.destroyLocals();
4116   }
4117 
4118   LocalScope<Emitter> VDScope(this, VD);
4119   if (!this->visitVarDecl(VD, /*Toplevel=*/true))
4120     return false;
4121 
4122   if (Context::shouldBeGloballyIndexed(VD)) {
4123     auto GlobalIndex = P.getGlobal(VD);
4124     assert(GlobalIndex); // visitVarDecl() didn't return false.
4125     if (VarT) {
4126       if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
4127         return false;
4128     } else {
4129       if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
4130         return false;
4131     }
4132   } else {
4133     auto Local = Locals.find(VD);
4134     assert(Local != Locals.end()); // Same here.
4135     if (VarT) {
4136       if (!this->emitGetLocal(*VarT, Local->second.Offset, VD))
4137         return false;
4138     } else {
4139       if (!this->emitGetPtrLocal(Local->second.Offset, VD))
4140         return false;
4141     }
4142   }
4143 
4144   // Return the value.
4145   if (!this->emitRet(VarT.value_or(PT_Ptr), VD)) {
4146     // If the Ret above failed and this is a global variable, mark it as
4147     // uninitialized, even everything else succeeded.
4148     if (Context::shouldBeGloballyIndexed(VD)) {
4149       auto GlobalIndex = P.getGlobal(VD);
4150       assert(GlobalIndex);
4151       Block *GlobalBlock = P.getGlobal(*GlobalIndex);
4152       GlobalInlineDescriptor &GD =
4153           *reinterpret_cast<GlobalInlineDescriptor *>(GlobalBlock->rawData());
4154 
4155       GD.InitState = GlobalInitState::InitializerFailed;
4156       GlobalBlock->invokeDtor();
4157     }
4158     return false;
4159   }
4160 
4161   return VDScope.destroyLocals();
4162 }
4163 
4164 template <class Emitter>
4165 VarCreationState Compiler<Emitter>::visitVarDecl(const VarDecl *VD,
4166                                                  bool Toplevel) {
4167   // We don't know what to do with these, so just return false.
4168   if (VD->getType().isNull())
4169     return false;
4170 
4171   // This case is EvalEmitter-only. If we won't create any instructions for the
4172   // initializer anyway, don't bother creating the variable in the first place.
4173   if (!this->isActive())
4174     return VarCreationState::NotCreated();
4175 
4176   const Expr *Init = VD->getInit();
4177   std::optional<PrimType> VarT = classify(VD->getType());
4178 
4179   if (Init && Init->isValueDependent())
4180     return false;
4181 
4182   if (Context::shouldBeGloballyIndexed(VD)) {
4183     auto checkDecl = [&]() -> bool {
4184       bool NeedsOp = !Toplevel && VD->isLocalVarDecl() && VD->isStaticLocal();
4185       return !NeedsOp || this->emitCheckDecl(VD, VD);
4186     };
4187 
4188     auto initGlobal = [&](unsigned GlobalIndex) -> bool {
4189       assert(Init);
4190 
4191       if (VarT) {
4192         if (!this->visit(Init))
4193           return checkDecl() && false;
4194 
4195         return checkDecl() && this->emitInitGlobal(*VarT, GlobalIndex, VD);
4196       }
4197 
4198       if (!checkDecl())
4199         return false;
4200 
4201       if (!this->emitGetPtrGlobal(GlobalIndex, Init))
4202         return false;
4203 
4204       if (!visitInitializer(Init))
4205         return false;
4206 
4207       if (!this->emitFinishInit(Init))
4208         return false;
4209 
4210       return this->emitPopPtr(Init);
4211     };
4212 
4213     DeclScope<Emitter> LocalScope(this, VD);
4214 
4215     // We've already seen and initialized this global.
4216     if (std::optional<unsigned> GlobalIndex = P.getGlobal(VD)) {
4217       if (P.getPtrGlobal(*GlobalIndex).isInitialized())
4218         return checkDecl();
4219 
4220       // The previous attempt at initialization might've been unsuccessful,
4221       // so let's try this one.
4222       return Init && checkDecl() && initGlobal(*GlobalIndex);
4223     }
4224 
4225     std::optional<unsigned> GlobalIndex = P.createGlobal(VD, Init);
4226 
4227     if (!GlobalIndex)
4228       return false;
4229 
4230     return !Init || (checkDecl() && initGlobal(*GlobalIndex));
4231   } else {
4232     InitLinkScope<Emitter> ILS(this, InitLink::Decl(VD));
4233 
4234     if (VarT) {
4235       unsigned Offset = this->allocateLocalPrimitive(
4236           VD, *VarT, VD->getType().isConstQualified());
4237       if (Init) {
4238         // If this is a toplevel declaration, create a scope for the
4239         // initializer.
4240         if (Toplevel) {
4241           LocalScope<Emitter> Scope(this);
4242           if (!this->visit(Init))
4243             return false;
4244           return this->emitSetLocal(*VarT, Offset, VD) && Scope.destroyLocals();
4245         } else {
4246           if (!this->visit(Init))
4247             return false;
4248           return this->emitSetLocal(*VarT, Offset, VD);
4249         }
4250       }
4251     } else {
4252       if (std::optional<unsigned> Offset = this->allocateLocal(VD)) {
4253         if (!Init)
4254           return true;
4255 
4256         if (!this->emitGetPtrLocal(*Offset, Init))
4257           return false;
4258 
4259         if (!visitInitializer(Init))
4260           return false;
4261 
4262         if (!this->emitFinishInit(Init))
4263           return false;
4264 
4265         return this->emitPopPtr(Init);
4266       }
4267       return false;
4268     }
4269     return true;
4270   }
4271 
4272   return false;
4273 }
4274 
4275 template <class Emitter>
4276 bool Compiler<Emitter>::visitAPValue(const APValue &Val, PrimType ValType,
4277                                      const Expr *E) {
4278   assert(!DiscardResult);
4279   if (Val.isInt())
4280     return this->emitConst(Val.getInt(), ValType, E);
4281   else if (Val.isFloat())
4282     return this->emitConstFloat(Val.getFloat(), E);
4283 
4284   if (Val.isLValue()) {
4285     if (Val.isNullPointer())
4286       return this->emitNull(ValType, nullptr, E);
4287     APValue::LValueBase Base = Val.getLValueBase();
4288     if (const Expr *BaseExpr = Base.dyn_cast<const Expr *>())
4289       return this->visit(BaseExpr);
4290     else if (const auto *VD = Base.dyn_cast<const ValueDecl *>()) {
4291       return this->visitDeclRef(VD, E);
4292     }
4293   } else if (Val.isMemberPointer()) {
4294     if (const ValueDecl *MemberDecl = Val.getMemberPointerDecl())
4295       return this->emitGetMemberPtr(MemberDecl, E);
4296     return this->emitNullMemberPtr(nullptr, E);
4297   }
4298 
4299   return false;
4300 }
4301 
4302 template <class Emitter>
4303 bool Compiler<Emitter>::visitAPValueInitializer(const APValue &Val,
4304                                                 const Expr *E) {
4305 
4306   if (Val.isStruct()) {
4307     const Record *R = this->getRecord(E->getType());
4308     assert(R);
4309     for (unsigned I = 0, N = Val.getStructNumFields(); I != N; ++I) {
4310       const APValue &F = Val.getStructField(I);
4311       const Record::Field *RF = R->getField(I);
4312 
4313       if (F.isInt() || F.isFloat() || F.isLValue() || F.isMemberPointer()) {
4314         PrimType T = classifyPrim(RF->Decl->getType());
4315         if (!this->visitAPValue(F, T, E))
4316           return false;
4317         if (!this->emitInitField(T, RF->Offset, E))
4318           return false;
4319       } else if (F.isArray()) {
4320         assert(RF->Desc->isPrimitiveArray());
4321         const auto *ArrType = RF->Decl->getType()->getAsArrayTypeUnsafe();
4322         PrimType ElemT = classifyPrim(ArrType->getElementType());
4323         assert(ArrType);
4324 
4325         if (!this->emitGetPtrField(RF->Offset, E))
4326           return false;
4327 
4328         for (unsigned A = 0, AN = F.getArraySize(); A != AN; ++A) {
4329           if (!this->visitAPValue(F.getArrayInitializedElt(A), ElemT, E))
4330             return false;
4331           if (!this->emitInitElem(ElemT, A, E))
4332             return false;
4333         }
4334 
4335         if (!this->emitPopPtr(E))
4336           return false;
4337       } else if (F.isStruct() || F.isUnion()) {
4338         if (!this->emitGetPtrField(RF->Offset, E))
4339           return false;
4340         if (!this->visitAPValueInitializer(F, E))
4341           return false;
4342         if (!this->emitPopPtr(E))
4343           return false;
4344       } else {
4345         assert(false && "I don't think this should be possible");
4346       }
4347     }
4348     return true;
4349   } else if (Val.isUnion()) {
4350     const FieldDecl *UnionField = Val.getUnionField();
4351     const Record *R = this->getRecord(UnionField->getParent());
4352     assert(R);
4353     const APValue &F = Val.getUnionValue();
4354     const Record::Field *RF = R->getField(UnionField);
4355     PrimType T = classifyPrim(RF->Decl->getType());
4356     if (!this->visitAPValue(F, T, E))
4357       return false;
4358     return this->emitInitField(T, RF->Offset, E);
4359   }
4360   // TODO: Other types.
4361 
4362   return false;
4363 }
4364 
4365 template <class Emitter>
4366 bool Compiler<Emitter>::VisitBuiltinCallExpr(const CallExpr *E,
4367                                              unsigned BuiltinID) {
4368   const Function *Func = getFunction(E->getDirectCallee());
4369   if (!Func)
4370     return false;
4371 
4372   // For these, we're expected to ultimately return an APValue pointing
4373   // to the CallExpr. This is needed to get the correct codegen.
4374   if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
4375       BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString ||
4376       BuiltinID == Builtin::BI__builtin_ptrauth_sign_constant ||
4377       BuiltinID == Builtin::BI__builtin_function_start) {
4378     if (std::optional<unsigned> GlobalOffset = P.getOrCreateDummy(E)) {
4379       if (!this->emitGetPtrGlobal(*GlobalOffset, E))
4380         return false;
4381 
4382       if (PrimType PT = classifyPrim(E); PT != PT_Ptr && isPtrType(PT))
4383         return this->emitDecayPtr(PT_Ptr, PT, E);
4384       return true;
4385     }
4386     return false;
4387   }
4388 
4389   QualType ReturnType = E->getType();
4390   std::optional<PrimType> ReturnT = classify(E);
4391 
4392   // Non-primitive return type. Prepare storage.
4393   if (!Initializing && !ReturnT && !ReturnType->isVoidType()) {
4394     std::optional<unsigned> LocalIndex = allocateLocal(E);
4395     if (!LocalIndex)
4396       return false;
4397     if (!this->emitGetPtrLocal(*LocalIndex, E))
4398       return false;
4399   }
4400 
4401   if (!Func->isUnevaluatedBuiltin()) {
4402     // Put arguments on the stack.
4403     for (const auto *Arg : E->arguments()) {
4404       if (!this->visit(Arg))
4405         return false;
4406     }
4407   }
4408 
4409   if (!this->emitCallBI(Func, E, BuiltinID, E))
4410     return false;
4411 
4412   if (DiscardResult && !ReturnType->isVoidType()) {
4413     assert(ReturnT);
4414     return this->emitPop(*ReturnT, E);
4415   }
4416 
4417   return true;
4418 }
4419 
4420 template <class Emitter>
4421 bool Compiler<Emitter>::VisitCallExpr(const CallExpr *E) {
4422   if (unsigned BuiltinID = E->getBuiltinCallee())
4423     return VisitBuiltinCallExpr(E, BuiltinID);
4424 
4425   const FunctionDecl *FuncDecl = E->getDirectCallee();
4426   // Calls to replaceable operator new/operator delete.
4427   if (FuncDecl && FuncDecl->isReplaceableGlobalAllocationFunction()) {
4428     if (FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_New ||
4429         FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Array_New) {
4430       return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_new);
4431     } else {
4432       assert(FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Delete);
4433       return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_delete);
4434     }
4435   }
4436 
4437   QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
4438   std::optional<PrimType> T = classify(ReturnType);
4439   bool HasRVO = !ReturnType->isVoidType() && !T;
4440 
4441   if (HasRVO) {
4442     if (DiscardResult) {
4443       // If we need to discard the return value but the function returns its
4444       // value via an RVO pointer, we need to create one such pointer just
4445       // for this call.
4446       if (std::optional<unsigned> LocalIndex = allocateLocal(E)) {
4447         if (!this->emitGetPtrLocal(*LocalIndex, E))
4448           return false;
4449       }
4450     } else {
4451       // We need the result. Prepare a pointer to return or
4452       // dup the current one.
4453       if (!Initializing) {
4454         if (std::optional<unsigned> LocalIndex = allocateLocal(E)) {
4455           if (!this->emitGetPtrLocal(*LocalIndex, E))
4456             return false;
4457         }
4458       }
4459       if (!this->emitDupPtr(E))
4460         return false;
4461     }
4462   }
4463 
4464   SmallVector<const Expr *, 8> Args(
4465       llvm::ArrayRef(E->getArgs(), E->getNumArgs()));
4466 
4467   bool IsAssignmentOperatorCall = false;
4468   if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
4469       OCE && OCE->isAssignmentOp()) {
4470     // Just like with regular assignments, we need to special-case assignment
4471     // operators here and evaluate the RHS (the second arg) before the LHS (the
4472     // first arg. We fix this by using a Flip op later.
4473     assert(Args.size() == 2);
4474     IsAssignmentOperatorCall = true;
4475     std::reverse(Args.begin(), Args.end());
4476   }
4477   // Calling a static operator will still
4478   // pass the instance, but we don't need it.
4479   // Discard it here.
4480   if (isa<CXXOperatorCallExpr>(E)) {
4481     if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl);
4482         MD && MD->isStatic()) {
4483       if (!this->discard(E->getArg(0)))
4484         return false;
4485       // Drop first arg.
4486       Args.erase(Args.begin());
4487     }
4488   }
4489 
4490   std::optional<unsigned> CalleeOffset;
4491   // Add the (optional, implicit) This pointer.
4492   if (const auto *MC = dyn_cast<CXXMemberCallExpr>(E)) {
4493     if (!FuncDecl && classifyPrim(E->getCallee()) == PT_MemberPtr) {
4494       // If we end up creating a CallPtr op for this, we need the base of the
4495       // member pointer as the instance pointer, and later extract the function
4496       // decl as the function pointer.
4497       const Expr *Callee = E->getCallee();
4498       CalleeOffset =
4499           this->allocateLocalPrimitive(Callee, PT_MemberPtr, true, false);
4500       if (!this->visit(Callee))
4501         return false;
4502       if (!this->emitSetLocal(PT_MemberPtr, *CalleeOffset, E))
4503         return false;
4504       if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
4505         return false;
4506       if (!this->emitGetMemberPtrBase(E))
4507         return false;
4508     } else if (!this->visit(MC->getImplicitObjectArgument())) {
4509       return false;
4510     }
4511   } else if (!FuncDecl) {
4512     const Expr *Callee = E->getCallee();
4513     CalleeOffset = this->allocateLocalPrimitive(Callee, PT_FnPtr, true, false);
4514     if (!this->visit(Callee))
4515       return false;
4516     if (!this->emitSetLocal(PT_FnPtr, *CalleeOffset, E))
4517       return false;
4518   }
4519 
4520   llvm::BitVector NonNullArgs = collectNonNullArgs(FuncDecl, Args);
4521   // Put arguments on the stack.
4522   unsigned ArgIndex = 0;
4523   for (const auto *Arg : Args) {
4524     if (!this->visit(Arg))
4525       return false;
4526 
4527     // If we know the callee already, check the known parametrs for nullability.
4528     if (FuncDecl && NonNullArgs[ArgIndex]) {
4529       PrimType ArgT = classify(Arg).value_or(PT_Ptr);
4530       if (ArgT == PT_Ptr || ArgT == PT_FnPtr) {
4531         if (!this->emitCheckNonNullArg(ArgT, Arg))
4532           return false;
4533       }
4534     }
4535     ++ArgIndex;
4536   }
4537 
4538   // Undo the argument reversal we did earlier.
4539   if (IsAssignmentOperatorCall) {
4540     assert(Args.size() == 2);
4541     PrimType Arg1T = classify(Args[0]).value_or(PT_Ptr);
4542     PrimType Arg2T = classify(Args[1]).value_or(PT_Ptr);
4543     if (!this->emitFlip(Arg2T, Arg1T, E))
4544       return false;
4545   }
4546 
4547   if (FuncDecl) {
4548     const Function *Func = getFunction(FuncDecl);
4549     if (!Func)
4550       return false;
4551     assert(HasRVO == Func->hasRVO());
4552 
4553     bool HasQualifier = false;
4554     if (const auto *ME = dyn_cast<MemberExpr>(E->getCallee()))
4555       HasQualifier = ME->hasQualifier();
4556 
4557     bool IsVirtual = false;
4558     if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl))
4559       IsVirtual = MD->isVirtual();
4560 
4561     // In any case call the function. The return value will end up on the stack
4562     // and if the function has RVO, we already have the pointer on the stack to
4563     // write the result into.
4564     if (IsVirtual && !HasQualifier) {
4565       uint32_t VarArgSize = 0;
4566       unsigned NumParams =
4567           Func->getNumWrittenParams() + isa<CXXOperatorCallExpr>(E);
4568       for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
4569         VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
4570 
4571       if (!this->emitCallVirt(Func, VarArgSize, E))
4572         return false;
4573     } else if (Func->isVariadic()) {
4574       uint32_t VarArgSize = 0;
4575       unsigned NumParams =
4576           Func->getNumWrittenParams() + isa<CXXOperatorCallExpr>(E);
4577       for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
4578         VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
4579       if (!this->emitCallVar(Func, VarArgSize, E))
4580         return false;
4581     } else {
4582       if (!this->emitCall(Func, 0, E))
4583         return false;
4584     }
4585   } else {
4586     // Indirect call. Visit the callee, which will leave a FunctionPointer on
4587     // the stack. Cleanup of the returned value if necessary will be done after
4588     // the function call completed.
4589 
4590     // Sum the size of all args from the call expr.
4591     uint32_t ArgSize = 0;
4592     for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
4593       ArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
4594 
4595     // Get the callee, either from a member pointer or function pointer saved in
4596     // CalleeOffset.
4597     if (isa<CXXMemberCallExpr>(E) && CalleeOffset) {
4598       if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
4599         return false;
4600       if (!this->emitGetMemberPtrDecl(E))
4601         return false;
4602     } else {
4603       if (!this->emitGetLocal(PT_FnPtr, *CalleeOffset, E))
4604         return false;
4605     }
4606     if (!this->emitCallPtr(ArgSize, E, E))
4607       return false;
4608   }
4609 
4610   // Cleanup for discarded return values.
4611   if (DiscardResult && !ReturnType->isVoidType() && T)
4612     return this->emitPop(*T, E);
4613 
4614   return true;
4615 }
4616 
4617 template <class Emitter>
4618 bool Compiler<Emitter>::VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) {
4619   SourceLocScope<Emitter> SLS(this, E);
4620 
4621   return this->delegate(E->getExpr());
4622 }
4623 
4624 template <class Emitter>
4625 bool Compiler<Emitter>::VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) {
4626   SourceLocScope<Emitter> SLS(this, E);
4627 
4628   const Expr *SubExpr = E->getExpr();
4629   if (std::optional<PrimType> T = classify(E->getExpr()))
4630     return this->visit(SubExpr);
4631 
4632   assert(Initializing);
4633   return this->visitInitializer(SubExpr);
4634 }
4635 
4636 template <class Emitter>
4637 bool Compiler<Emitter>::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) {
4638   if (DiscardResult)
4639     return true;
4640 
4641   return this->emitConstBool(E->getValue(), E);
4642 }
4643 
4644 template <class Emitter>
4645 bool Compiler<Emitter>::VisitCXXNullPtrLiteralExpr(
4646     const CXXNullPtrLiteralExpr *E) {
4647   if (DiscardResult)
4648     return true;
4649 
4650   return this->emitNullPtr(nullptr, E);
4651 }
4652 
4653 template <class Emitter>
4654 bool Compiler<Emitter>::VisitGNUNullExpr(const GNUNullExpr *E) {
4655   if (DiscardResult)
4656     return true;
4657 
4658   assert(E->getType()->isIntegerType());
4659 
4660   PrimType T = classifyPrim(E->getType());
4661   return this->emitZero(T, E);
4662 }
4663 
4664 template <class Emitter>
4665 bool Compiler<Emitter>::VisitCXXThisExpr(const CXXThisExpr *E) {
4666   if (DiscardResult)
4667     return true;
4668 
4669   if (this->LambdaThisCapture.Offset > 0) {
4670     if (this->LambdaThisCapture.IsPtr)
4671       return this->emitGetThisFieldPtr(this->LambdaThisCapture.Offset, E);
4672     return this->emitGetPtrThisField(this->LambdaThisCapture.Offset, E);
4673   }
4674 
4675   // In some circumstances, the 'this' pointer does not actually refer to the
4676   // instance pointer of the current function frame, but e.g. to the declaration
4677   // currently being initialized. Here we emit the necessary instruction(s) for
4678   // this scenario.
4679   if (!InitStackActive || !E->isImplicit())
4680     return this->emitThis(E);
4681 
4682   if (InitStackActive && !InitStack.empty()) {
4683     unsigned StartIndex = 0;
4684     for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) {
4685       if (InitStack[StartIndex].Kind != InitLink::K_Field &&
4686           InitStack[StartIndex].Kind != InitLink::K_Elem)
4687         break;
4688     }
4689 
4690     for (unsigned I = StartIndex, N = InitStack.size(); I != N; ++I) {
4691       if (!InitStack[I].template emit<Emitter>(this, E))
4692         return false;
4693     }
4694     return true;
4695   }
4696   return this->emitThis(E);
4697 }
4698 
4699 template <class Emitter> bool Compiler<Emitter>::visitStmt(const Stmt *S) {
4700   switch (S->getStmtClass()) {
4701   case Stmt::CompoundStmtClass:
4702     return visitCompoundStmt(cast<CompoundStmt>(S));
4703   case Stmt::DeclStmtClass:
4704     return visitDeclStmt(cast<DeclStmt>(S));
4705   case Stmt::ReturnStmtClass:
4706     return visitReturnStmt(cast<ReturnStmt>(S));
4707   case Stmt::IfStmtClass:
4708     return visitIfStmt(cast<IfStmt>(S));
4709   case Stmt::WhileStmtClass:
4710     return visitWhileStmt(cast<WhileStmt>(S));
4711   case Stmt::DoStmtClass:
4712     return visitDoStmt(cast<DoStmt>(S));
4713   case Stmt::ForStmtClass:
4714     return visitForStmt(cast<ForStmt>(S));
4715   case Stmt::CXXForRangeStmtClass:
4716     return visitCXXForRangeStmt(cast<CXXForRangeStmt>(S));
4717   case Stmt::BreakStmtClass:
4718     return visitBreakStmt(cast<BreakStmt>(S));
4719   case Stmt::ContinueStmtClass:
4720     return visitContinueStmt(cast<ContinueStmt>(S));
4721   case Stmt::SwitchStmtClass:
4722     return visitSwitchStmt(cast<SwitchStmt>(S));
4723   case Stmt::CaseStmtClass:
4724     return visitCaseStmt(cast<CaseStmt>(S));
4725   case Stmt::DefaultStmtClass:
4726     return visitDefaultStmt(cast<DefaultStmt>(S));
4727   case Stmt::AttributedStmtClass:
4728     return visitAttributedStmt(cast<AttributedStmt>(S));
4729   case Stmt::CXXTryStmtClass:
4730     return visitCXXTryStmt(cast<CXXTryStmt>(S));
4731   case Stmt::NullStmtClass:
4732     return true;
4733   // Always invalid statements.
4734   case Stmt::GCCAsmStmtClass:
4735   case Stmt::MSAsmStmtClass:
4736   case Stmt::GotoStmtClass:
4737     return this->emitInvalid(S);
4738   case Stmt::LabelStmtClass:
4739     return this->visitStmt(cast<LabelStmt>(S)->getSubStmt());
4740   default: {
4741     if (const auto *E = dyn_cast<Expr>(S))
4742       return this->discard(E);
4743     return false;
4744   }
4745   }
4746 }
4747 
4748 template <class Emitter>
4749 bool Compiler<Emitter>::visitCompoundStmt(const CompoundStmt *S) {
4750   BlockScope<Emitter> Scope(this);
4751   for (const auto *InnerStmt : S->body())
4752     if (!visitStmt(InnerStmt))
4753       return false;
4754   return Scope.destroyLocals();
4755 }
4756 
4757 template <class Emitter>
4758 bool Compiler<Emitter>::visitDeclStmt(const DeclStmt *DS) {
4759   for (const auto *D : DS->decls()) {
4760     if (isa<StaticAssertDecl, TagDecl, TypedefNameDecl, UsingEnumDecl,
4761             FunctionDecl>(D))
4762       continue;
4763 
4764     const auto *VD = dyn_cast<VarDecl>(D);
4765     if (!VD)
4766       return false;
4767     if (!this->visitVarDecl(VD))
4768       return false;
4769   }
4770 
4771   return true;
4772 }
4773 
4774 template <class Emitter>
4775 bool Compiler<Emitter>::visitReturnStmt(const ReturnStmt *RS) {
4776   if (this->InStmtExpr)
4777     return this->emitUnsupported(RS);
4778 
4779   if (const Expr *RE = RS->getRetValue()) {
4780     LocalScope<Emitter> RetScope(this);
4781     if (ReturnType) {
4782       // Primitive types are simply returned.
4783       if (!this->visit(RE))
4784         return false;
4785       this->emitCleanup();
4786       return this->emitRet(*ReturnType, RS);
4787     } else if (RE->getType()->isVoidType()) {
4788       if (!this->visit(RE))
4789         return false;
4790     } else {
4791       // RVO - construct the value in the return location.
4792       if (!this->emitRVOPtr(RE))
4793         return false;
4794       if (!this->visitInitializer(RE))
4795         return false;
4796       if (!this->emitPopPtr(RE))
4797         return false;
4798 
4799       this->emitCleanup();
4800       return this->emitRetVoid(RS);
4801     }
4802   }
4803 
4804   // Void return.
4805   this->emitCleanup();
4806   return this->emitRetVoid(RS);
4807 }
4808 
4809 template <class Emitter> bool Compiler<Emitter>::visitIfStmt(const IfStmt *IS) {
4810   if (auto *CondInit = IS->getInit())
4811     if (!visitStmt(CondInit))
4812       return false;
4813 
4814   if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt())
4815     if (!visitDeclStmt(CondDecl))
4816       return false;
4817 
4818   // Compile condition.
4819   if (IS->isNonNegatedConsteval()) {
4820     if (!this->emitIsConstantContext(IS))
4821       return false;
4822   } else if (IS->isNegatedConsteval()) {
4823     if (!this->emitIsConstantContext(IS))
4824       return false;
4825     if (!this->emitInv(IS))
4826       return false;
4827   } else {
4828     if (!this->visitBool(IS->getCond()))
4829       return false;
4830   }
4831 
4832   if (const Stmt *Else = IS->getElse()) {
4833     LabelTy LabelElse = this->getLabel();
4834     LabelTy LabelEnd = this->getLabel();
4835     if (!this->jumpFalse(LabelElse))
4836       return false;
4837     if (!visitStmt(IS->getThen()))
4838       return false;
4839     if (!this->jump(LabelEnd))
4840       return false;
4841     this->emitLabel(LabelElse);
4842     if (!visitStmt(Else))
4843       return false;
4844     this->emitLabel(LabelEnd);
4845   } else {
4846     LabelTy LabelEnd = this->getLabel();
4847     if (!this->jumpFalse(LabelEnd))
4848       return false;
4849     if (!visitStmt(IS->getThen()))
4850       return false;
4851     this->emitLabel(LabelEnd);
4852   }
4853 
4854   return true;
4855 }
4856 
4857 template <class Emitter>
4858 bool Compiler<Emitter>::visitWhileStmt(const WhileStmt *S) {
4859   const Expr *Cond = S->getCond();
4860   const Stmt *Body = S->getBody();
4861 
4862   LabelTy CondLabel = this->getLabel(); // Label before the condition.
4863   LabelTy EndLabel = this->getLabel();  // Label after the loop.
4864   LoopScope<Emitter> LS(this, EndLabel, CondLabel);
4865 
4866   this->fallthrough(CondLabel);
4867   this->emitLabel(CondLabel);
4868 
4869   {
4870     LocalScope<Emitter> CondScope(this);
4871     if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
4872       if (!visitDeclStmt(CondDecl))
4873         return false;
4874 
4875     if (!this->visitBool(Cond))
4876       return false;
4877     if (!this->jumpFalse(EndLabel))
4878       return false;
4879 
4880     if (!this->visitStmt(Body))
4881       return false;
4882 
4883     if (!CondScope.destroyLocals())
4884       return false;
4885   }
4886   if (!this->jump(CondLabel))
4887     return false;
4888   this->fallthrough(EndLabel);
4889   this->emitLabel(EndLabel);
4890 
4891   return true;
4892 }
4893 
4894 template <class Emitter> bool Compiler<Emitter>::visitDoStmt(const DoStmt *S) {
4895   const Expr *Cond = S->getCond();
4896   const Stmt *Body = S->getBody();
4897 
4898   LabelTy StartLabel = this->getLabel();
4899   LabelTy EndLabel = this->getLabel();
4900   LabelTy CondLabel = this->getLabel();
4901   LoopScope<Emitter> LS(this, EndLabel, CondLabel);
4902 
4903   this->fallthrough(StartLabel);
4904   this->emitLabel(StartLabel);
4905 
4906   {
4907     LocalScope<Emitter> CondScope(this);
4908     if (!this->visitStmt(Body))
4909       return false;
4910     this->fallthrough(CondLabel);
4911     this->emitLabel(CondLabel);
4912     if (!this->visitBool(Cond))
4913       return false;
4914 
4915     if (!CondScope.destroyLocals())
4916       return false;
4917   }
4918   if (!this->jumpTrue(StartLabel))
4919     return false;
4920 
4921   this->fallthrough(EndLabel);
4922   this->emitLabel(EndLabel);
4923   return true;
4924 }
4925 
4926 template <class Emitter>
4927 bool Compiler<Emitter>::visitForStmt(const ForStmt *S) {
4928   // for (Init; Cond; Inc) { Body }
4929   const Stmt *Init = S->getInit();
4930   const Expr *Cond = S->getCond();
4931   const Expr *Inc = S->getInc();
4932   const Stmt *Body = S->getBody();
4933 
4934   LabelTy EndLabel = this->getLabel();
4935   LabelTy CondLabel = this->getLabel();
4936   LabelTy IncLabel = this->getLabel();
4937   LoopScope<Emitter> LS(this, EndLabel, IncLabel);
4938 
4939   if (Init && !this->visitStmt(Init))
4940     return false;
4941 
4942   this->fallthrough(CondLabel);
4943   this->emitLabel(CondLabel);
4944 
4945   {
4946     LocalScope<Emitter> CondScope(this);
4947     if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
4948       if (!visitDeclStmt(CondDecl))
4949         return false;
4950 
4951     if (Cond) {
4952       if (!this->visitBool(Cond))
4953         return false;
4954       if (!this->jumpFalse(EndLabel))
4955         return false;
4956     }
4957 
4958     if (Body && !this->visitStmt(Body))
4959       return false;
4960 
4961     this->fallthrough(IncLabel);
4962     this->emitLabel(IncLabel);
4963     if (Inc && !this->discard(Inc))
4964       return false;
4965 
4966     if (!CondScope.destroyLocals())
4967       return false;
4968   }
4969   if (!this->jump(CondLabel))
4970     return false;
4971 
4972   this->fallthrough(EndLabel);
4973   this->emitLabel(EndLabel);
4974   return true;
4975 }
4976 
4977 template <class Emitter>
4978 bool Compiler<Emitter>::visitCXXForRangeStmt(const CXXForRangeStmt *S) {
4979   const Stmt *Init = S->getInit();
4980   const Expr *Cond = S->getCond();
4981   const Expr *Inc = S->getInc();
4982   const Stmt *Body = S->getBody();
4983   const Stmt *BeginStmt = S->getBeginStmt();
4984   const Stmt *RangeStmt = S->getRangeStmt();
4985   const Stmt *EndStmt = S->getEndStmt();
4986   const VarDecl *LoopVar = S->getLoopVariable();
4987 
4988   LabelTy EndLabel = this->getLabel();
4989   LabelTy CondLabel = this->getLabel();
4990   LabelTy IncLabel = this->getLabel();
4991   LoopScope<Emitter> LS(this, EndLabel, IncLabel);
4992 
4993   // Emit declarations needed in the loop.
4994   if (Init && !this->visitStmt(Init))
4995     return false;
4996   if (!this->visitStmt(RangeStmt))
4997     return false;
4998   if (!this->visitStmt(BeginStmt))
4999     return false;
5000   if (!this->visitStmt(EndStmt))
5001     return false;
5002 
5003   // Now the condition as well as the loop variable assignment.
5004   this->fallthrough(CondLabel);
5005   this->emitLabel(CondLabel);
5006   if (!this->visitBool(Cond))
5007     return false;
5008   if (!this->jumpFalse(EndLabel))
5009     return false;
5010 
5011   if (!this->visitVarDecl(LoopVar))
5012     return false;
5013 
5014   // Body.
5015   {
5016     if (!this->visitStmt(Body))
5017       return false;
5018 
5019     this->fallthrough(IncLabel);
5020     this->emitLabel(IncLabel);
5021     if (!this->discard(Inc))
5022       return false;
5023   }
5024 
5025   if (!this->jump(CondLabel))
5026     return false;
5027 
5028   this->fallthrough(EndLabel);
5029   this->emitLabel(EndLabel);
5030   return true;
5031 }
5032 
5033 template <class Emitter>
5034 bool Compiler<Emitter>::visitBreakStmt(const BreakStmt *S) {
5035   if (!BreakLabel)
5036     return false;
5037 
5038   for (VariableScope<Emitter> *C = VarScope; C != BreakVarScope;
5039        C = C->getParent())
5040     C->emitDestruction();
5041   return this->jump(*BreakLabel);
5042 }
5043 
5044 template <class Emitter>
5045 bool Compiler<Emitter>::visitContinueStmt(const ContinueStmt *S) {
5046   if (!ContinueLabel)
5047     return false;
5048 
5049   for (VariableScope<Emitter> *C = VarScope;
5050        C && C->getParent() != ContinueVarScope; C = C->getParent())
5051     C->emitDestruction();
5052   return this->jump(*ContinueLabel);
5053 }
5054 
5055 template <class Emitter>
5056 bool Compiler<Emitter>::visitSwitchStmt(const SwitchStmt *S) {
5057   const Expr *Cond = S->getCond();
5058   PrimType CondT = this->classifyPrim(Cond->getType());
5059   LocalScope<Emitter> LS(this);
5060 
5061   LabelTy EndLabel = this->getLabel();
5062   OptLabelTy DefaultLabel = std::nullopt;
5063   unsigned CondVar = this->allocateLocalPrimitive(Cond, CondT, true, false);
5064 
5065   if (const auto *CondInit = S->getInit())
5066     if (!visitStmt(CondInit))
5067       return false;
5068 
5069   if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
5070     if (!visitDeclStmt(CondDecl))
5071       return false;
5072 
5073   // Initialize condition variable.
5074   if (!this->visit(Cond))
5075     return false;
5076   if (!this->emitSetLocal(CondT, CondVar, S))
5077     return false;
5078 
5079   CaseMap CaseLabels;
5080   // Create labels and comparison ops for all case statements.
5081   for (const SwitchCase *SC = S->getSwitchCaseList(); SC;
5082        SC = SC->getNextSwitchCase()) {
5083     if (const auto *CS = dyn_cast<CaseStmt>(SC)) {
5084       // FIXME: Implement ranges.
5085       if (CS->caseStmtIsGNURange())
5086         return false;
5087       CaseLabels[SC] = this->getLabel();
5088 
5089       const Expr *Value = CS->getLHS();
5090       PrimType ValueT = this->classifyPrim(Value->getType());
5091 
5092       // Compare the case statement's value to the switch condition.
5093       if (!this->emitGetLocal(CondT, CondVar, CS))
5094         return false;
5095       if (!this->visit(Value))
5096         return false;
5097 
5098       // Compare and jump to the case label.
5099       if (!this->emitEQ(ValueT, S))
5100         return false;
5101       if (!this->jumpTrue(CaseLabels[CS]))
5102         return false;
5103     } else {
5104       assert(!DefaultLabel);
5105       DefaultLabel = this->getLabel();
5106     }
5107   }
5108 
5109   // If none of the conditions above were true, fall through to the default
5110   // statement or jump after the switch statement.
5111   if (DefaultLabel) {
5112     if (!this->jump(*DefaultLabel))
5113       return false;
5114   } else {
5115     if (!this->jump(EndLabel))
5116       return false;
5117   }
5118 
5119   SwitchScope<Emitter> SS(this, std::move(CaseLabels), EndLabel, DefaultLabel);
5120   if (!this->visitStmt(S->getBody()))
5121     return false;
5122   this->emitLabel(EndLabel);
5123 
5124   return LS.destroyLocals();
5125 }
5126 
5127 template <class Emitter>
5128 bool Compiler<Emitter>::visitCaseStmt(const CaseStmt *S) {
5129   this->emitLabel(CaseLabels[S]);
5130   return this->visitStmt(S->getSubStmt());
5131 }
5132 
5133 template <class Emitter>
5134 bool Compiler<Emitter>::visitDefaultStmt(const DefaultStmt *S) {
5135   this->emitLabel(*DefaultLabel);
5136   return this->visitStmt(S->getSubStmt());
5137 }
5138 
5139 template <class Emitter>
5140 bool Compiler<Emitter>::visitAttributedStmt(const AttributedStmt *S) {
5141   if (this->Ctx.getLangOpts().CXXAssumptions &&
5142       !this->Ctx.getLangOpts().MSVCCompat) {
5143     for (const Attr *A : S->getAttrs()) {
5144       auto *AA = dyn_cast<CXXAssumeAttr>(A);
5145       if (!AA)
5146         continue;
5147 
5148       assert(isa<NullStmt>(S->getSubStmt()));
5149 
5150       const Expr *Assumption = AA->getAssumption();
5151       if (Assumption->isValueDependent())
5152         return false;
5153 
5154       if (Assumption->HasSideEffects(this->Ctx.getASTContext()))
5155         continue;
5156 
5157       // Evaluate assumption.
5158       if (!this->visitBool(Assumption))
5159         return false;
5160 
5161       if (!this->emitAssume(Assumption))
5162         return false;
5163     }
5164   }
5165 
5166   // Ignore other attributes.
5167   return this->visitStmt(S->getSubStmt());
5168 }
5169 
5170 template <class Emitter>
5171 bool Compiler<Emitter>::visitCXXTryStmt(const CXXTryStmt *S) {
5172   // Ignore all handlers.
5173   return this->visitStmt(S->getTryBlock());
5174 }
5175 
5176 template <class Emitter>
5177 bool Compiler<Emitter>::emitLambdaStaticInvokerBody(const CXXMethodDecl *MD) {
5178   assert(MD->isLambdaStaticInvoker());
5179   assert(MD->hasBody());
5180   assert(cast<CompoundStmt>(MD->getBody())->body_empty());
5181 
5182   const CXXRecordDecl *ClosureClass = MD->getParent();
5183   const CXXMethodDecl *LambdaCallOp = ClosureClass->getLambdaCallOperator();
5184   assert(ClosureClass->captures_begin() == ClosureClass->captures_end());
5185   const Function *Func = this->getFunction(LambdaCallOp);
5186   if (!Func)
5187     return false;
5188   assert(Func->hasThisPointer());
5189   assert(Func->getNumParams() == (MD->getNumParams() + 1 + Func->hasRVO()));
5190 
5191   if (Func->hasRVO()) {
5192     if (!this->emitRVOPtr(MD))
5193       return false;
5194   }
5195 
5196   // The lambda call operator needs an instance pointer, but we don't have
5197   // one here, and we don't need one either because the lambda cannot have
5198   // any captures, as verified above. Emit a null pointer. This is then
5199   // special-cased when interpreting to not emit any misleading diagnostics.
5200   if (!this->emitNullPtr(nullptr, MD))
5201     return false;
5202 
5203   // Forward all arguments from the static invoker to the lambda call operator.
5204   for (const ParmVarDecl *PVD : MD->parameters()) {
5205     auto It = this->Params.find(PVD);
5206     assert(It != this->Params.end());
5207 
5208     // We do the lvalue-to-rvalue conversion manually here, so no need
5209     // to care about references.
5210     PrimType ParamType = this->classify(PVD->getType()).value_or(PT_Ptr);
5211     if (!this->emitGetParam(ParamType, It->second.Offset, MD))
5212       return false;
5213   }
5214 
5215   if (!this->emitCall(Func, 0, LambdaCallOp))
5216     return false;
5217 
5218   this->emitCleanup();
5219   if (ReturnType)
5220     return this->emitRet(*ReturnType, MD);
5221 
5222   // Nothing to do, since we emitted the RVO pointer above.
5223   return this->emitRetVoid(MD);
5224 }
5225 
5226 template <class Emitter>
5227 bool Compiler<Emitter>::checkLiteralType(const Expr *E) {
5228   if (Ctx.getLangOpts().CPlusPlus23)
5229     return true;
5230 
5231   if (!E->isPRValue() || E->getType()->isLiteralType(Ctx.getASTContext()))
5232     return true;
5233 
5234   return this->emitCheckLiteralType(E->getType().getTypePtr(), E);
5235 }
5236 
5237 template <class Emitter>
5238 bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
5239   assert(!ReturnType);
5240 
5241   auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset,
5242                                   const Expr *InitExpr) -> bool {
5243     // We don't know what to do with these, so just return false.
5244     if (InitExpr->getType().isNull())
5245       return false;
5246 
5247     if (std::optional<PrimType> T = this->classify(InitExpr)) {
5248       if (!this->visit(InitExpr))
5249         return false;
5250 
5251       if (F->isBitField())
5252         return this->emitInitThisBitField(*T, F, FieldOffset, InitExpr);
5253       return this->emitInitThisField(*T, FieldOffset, InitExpr);
5254     }
5255     // Non-primitive case. Get a pointer to the field-to-initialize
5256     // on the stack and call visitInitialzer() for it.
5257     InitLinkScope<Emitter> FieldScope(this, InitLink::Field(F->Offset));
5258     if (!this->emitGetPtrThisField(FieldOffset, InitExpr))
5259       return false;
5260 
5261     if (!this->visitInitializer(InitExpr))
5262       return false;
5263 
5264     return this->emitFinishInitPop(InitExpr);
5265   };
5266 
5267   const RecordDecl *RD = Ctor->getParent();
5268   const Record *R = this->getRecord(RD);
5269   if (!R)
5270     return false;
5271 
5272   if (R->isUnion() && Ctor->isCopyOrMoveConstructor()) {
5273     // union copy and move ctors are special.
5274     assert(cast<CompoundStmt>(Ctor->getBody())->body_empty());
5275     if (!this->emitThis(Ctor))
5276       return false;
5277 
5278     auto PVD = Ctor->getParamDecl(0);
5279     ParamOffset PO = this->Params[PVD]; // Must exist.
5280 
5281     if (!this->emitGetParam(PT_Ptr, PO.Offset, Ctor))
5282       return false;
5283 
5284     return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) &&
5285            this->emitRetVoid(Ctor);
5286   }
5287 
5288   InitLinkScope<Emitter> InitScope(this, InitLink::This());
5289   for (const auto *Init : Ctor->inits()) {
5290     // Scope needed for the initializers.
5291     BlockScope<Emitter> Scope(this);
5292 
5293     const Expr *InitExpr = Init->getInit();
5294     if (const FieldDecl *Member = Init->getMember()) {
5295       const Record::Field *F = R->getField(Member);
5296 
5297       if (!emitFieldInitializer(F, F->Offset, InitExpr))
5298         return false;
5299     } else if (const Type *Base = Init->getBaseClass()) {
5300       const auto *BaseDecl = Base->getAsCXXRecordDecl();
5301       assert(BaseDecl);
5302 
5303       if (Init->isBaseVirtual()) {
5304         assert(R->getVirtualBase(BaseDecl));
5305         if (!this->emitGetPtrThisVirtBase(BaseDecl, InitExpr))
5306           return false;
5307 
5308       } else {
5309         // Base class initializer.
5310         // Get This Base and call initializer on it.
5311         const Record::Base *B = R->getBase(BaseDecl);
5312         assert(B);
5313         if (!this->emitGetPtrThisBase(B->Offset, InitExpr))
5314           return false;
5315       }
5316 
5317       if (!this->visitInitializer(InitExpr))
5318         return false;
5319       if (!this->emitFinishInitPop(InitExpr))
5320         return false;
5321     } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) {
5322       assert(IFD->getChainingSize() >= 2);
5323 
5324       unsigned NestedFieldOffset = 0;
5325       const Record::Field *NestedField = nullptr;
5326       for (const NamedDecl *ND : IFD->chain()) {
5327         const auto *FD = cast<FieldDecl>(ND);
5328         const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
5329         assert(FieldRecord);
5330 
5331         NestedField = FieldRecord->getField(FD);
5332         assert(NestedField);
5333 
5334         NestedFieldOffset += NestedField->Offset;
5335       }
5336       assert(NestedField);
5337 
5338       if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr))
5339         return false;
5340     } else {
5341       assert(Init->isDelegatingInitializer());
5342       if (!this->emitThis(InitExpr))
5343         return false;
5344       if (!this->visitInitializer(Init->getInit()))
5345         return false;
5346       if (!this->emitPopPtr(InitExpr))
5347         return false;
5348     }
5349 
5350     if (!Scope.destroyLocals())
5351       return false;
5352   }
5353 
5354   if (const auto *Body = Ctor->getBody())
5355     if (!visitStmt(Body))
5356       return false;
5357 
5358   return this->emitRetVoid(SourceInfo{});
5359 }
5360 
5361 template <class Emitter>
5362 bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) {
5363   const RecordDecl *RD = Dtor->getParent();
5364   const Record *R = this->getRecord(RD);
5365   if (!R)
5366     return false;
5367 
5368   if (!Dtor->isTrivial() && Dtor->getBody()) {
5369     if (!this->visitStmt(Dtor->getBody()))
5370       return false;
5371   }
5372 
5373   if (!this->emitThis(Dtor))
5374     return false;
5375 
5376   assert(R);
5377   if (!R->isUnion()) {
5378     // First, destroy all fields.
5379     for (const Record::Field &Field : llvm::reverse(R->fields())) {
5380       const Descriptor *D = Field.Desc;
5381       if (!D->isPrimitive() && !D->isPrimitiveArray()) {
5382         if (!this->emitGetPtrField(Field.Offset, SourceInfo{}))
5383           return false;
5384         if (!this->emitDestruction(D, SourceInfo{}))
5385           return false;
5386         if (!this->emitPopPtr(SourceInfo{}))
5387           return false;
5388       }
5389     }
5390   }
5391 
5392   for (const Record::Base &Base : llvm::reverse(R->bases())) {
5393     if (Base.R->isAnonymousUnion())
5394       continue;
5395 
5396     if (!this->emitGetPtrBase(Base.Offset, SourceInfo{}))
5397       return false;
5398     if (!this->emitRecordDestruction(Base.R, {}))
5399       return false;
5400     if (!this->emitPopPtr(SourceInfo{}))
5401       return false;
5402   }
5403 
5404   // FIXME: Virtual bases.
5405   return this->emitPopPtr(Dtor) && this->emitRetVoid(Dtor);
5406 }
5407 
5408 template <class Emitter>
5409 bool Compiler<Emitter>::visitFunc(const FunctionDecl *F) {
5410   // Classify the return type.
5411   ReturnType = this->classify(F->getReturnType());
5412 
5413   if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F))
5414     return this->compileConstructor(Ctor);
5415   if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F))
5416     return this->compileDestructor(Dtor);
5417 
5418   // Emit custom code if this is a lambda static invoker.
5419   if (const auto *MD = dyn_cast<CXXMethodDecl>(F);
5420       MD && MD->isLambdaStaticInvoker())
5421     return this->emitLambdaStaticInvokerBody(MD);
5422 
5423   // Regular functions.
5424   if (const auto *Body = F->getBody())
5425     if (!visitStmt(Body))
5426       return false;
5427 
5428   // Emit a guard return to protect against a code path missing one.
5429   if (F->getReturnType()->isVoidType())
5430     return this->emitRetVoid(SourceInfo{});
5431   return this->emitNoRet(SourceInfo{});
5432 }
5433 
5434 template <class Emitter>
5435 bool Compiler<Emitter>::VisitUnaryOperator(const UnaryOperator *E) {
5436   const Expr *SubExpr = E->getSubExpr();
5437   if (SubExpr->getType()->isAnyComplexType())
5438     return this->VisitComplexUnaryOperator(E);
5439   if (SubExpr->getType()->isVectorType())
5440     return this->VisitVectorUnaryOperator(E);
5441   std::optional<PrimType> T = classify(SubExpr->getType());
5442 
5443   switch (E->getOpcode()) {
5444   case UO_PostInc: { // x++
5445     if (!Ctx.getLangOpts().CPlusPlus14)
5446       return this->emitInvalid(E);
5447     if (!T)
5448       return this->emitError(E);
5449 
5450     if (!this->visit(SubExpr))
5451       return false;
5452 
5453     if (T == PT_Ptr || T == PT_FnPtr) {
5454       if (!this->emitIncPtr(E))
5455         return false;
5456 
5457       return DiscardResult ? this->emitPopPtr(E) : true;
5458     }
5459 
5460     if (T == PT_Float) {
5461       return DiscardResult ? this->emitIncfPop(getFPOptions(E), E)
5462                            : this->emitIncf(getFPOptions(E), E);
5463     }
5464 
5465     return DiscardResult ? this->emitIncPop(*T, E) : this->emitInc(*T, E);
5466   }
5467   case UO_PostDec: { // x--
5468     if (!Ctx.getLangOpts().CPlusPlus14)
5469       return this->emitInvalid(E);
5470     if (!T)
5471       return this->emitError(E);
5472 
5473     if (!this->visit(SubExpr))
5474       return false;
5475 
5476     if (T == PT_Ptr || T == PT_FnPtr) {
5477       if (!this->emitDecPtr(E))
5478         return false;
5479 
5480       return DiscardResult ? this->emitPopPtr(E) : true;
5481     }
5482 
5483     if (T == PT_Float) {
5484       return DiscardResult ? this->emitDecfPop(getFPOptions(E), E)
5485                            : this->emitDecf(getFPOptions(E), E);
5486     }
5487 
5488     return DiscardResult ? this->emitDecPop(*T, E) : this->emitDec(*T, E);
5489   }
5490   case UO_PreInc: { // ++x
5491     if (!Ctx.getLangOpts().CPlusPlus14)
5492       return this->emitInvalid(E);
5493     if (!T)
5494       return this->emitError(E);
5495 
5496     if (!this->visit(SubExpr))
5497       return false;
5498 
5499     if (T == PT_Ptr || T == PT_FnPtr) {
5500       if (!this->emitLoadPtr(E))
5501         return false;
5502       if (!this->emitConstUint8(1, E))
5503         return false;
5504       if (!this->emitAddOffsetUint8(E))
5505         return false;
5506       return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
5507     }
5508 
5509     // Post-inc and pre-inc are the same if the value is to be discarded.
5510     if (DiscardResult) {
5511       if (T == PT_Float)
5512         return this->emitIncfPop(getFPOptions(E), E);
5513       return this->emitIncPop(*T, E);
5514     }
5515 
5516     if (T == PT_Float) {
5517       const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
5518       if (!this->emitLoadFloat(E))
5519         return false;
5520       if (!this->emitConstFloat(llvm::APFloat(TargetSemantics, 1), E))
5521         return false;
5522       if (!this->emitAddf(getFPOptions(E), E))
5523         return false;
5524       if (!this->emitStoreFloat(E))
5525         return false;
5526     } else {
5527       assert(isIntegralType(*T));
5528       if (!this->emitLoad(*T, E))
5529         return false;
5530       if (!this->emitConst(1, E))
5531         return false;
5532       if (!this->emitAdd(*T, E))
5533         return false;
5534       if (!this->emitStore(*T, E))
5535         return false;
5536     }
5537     return E->isGLValue() || this->emitLoadPop(*T, E);
5538   }
5539   case UO_PreDec: { // --x
5540     if (!Ctx.getLangOpts().CPlusPlus14)
5541       return this->emitInvalid(E);
5542     if (!T)
5543       return this->emitError(E);
5544 
5545     if (!this->visit(SubExpr))
5546       return false;
5547 
5548     if (T == PT_Ptr || T == PT_FnPtr) {
5549       if (!this->emitLoadPtr(E))
5550         return false;
5551       if (!this->emitConstUint8(1, E))
5552         return false;
5553       if (!this->emitSubOffsetUint8(E))
5554         return false;
5555       return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
5556     }
5557 
5558     // Post-dec and pre-dec are the same if the value is to be discarded.
5559     if (DiscardResult) {
5560       if (T == PT_Float)
5561         return this->emitDecfPop(getFPOptions(E), E);
5562       return this->emitDecPop(*T, E);
5563     }
5564 
5565     if (T == PT_Float) {
5566       const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
5567       if (!this->emitLoadFloat(E))
5568         return false;
5569       if (!this->emitConstFloat(llvm::APFloat(TargetSemantics, 1), E))
5570         return false;
5571       if (!this->emitSubf(getFPOptions(E), E))
5572         return false;
5573       if (!this->emitStoreFloat(E))
5574         return false;
5575     } else {
5576       assert(isIntegralType(*T));
5577       if (!this->emitLoad(*T, E))
5578         return false;
5579       if (!this->emitConst(1, E))
5580         return false;
5581       if (!this->emitSub(*T, E))
5582         return false;
5583       if (!this->emitStore(*T, E))
5584         return false;
5585     }
5586     return E->isGLValue() || this->emitLoadPop(*T, E);
5587   }
5588   case UO_LNot: // !x
5589     if (!T)
5590       return this->emitError(E);
5591 
5592     if (DiscardResult)
5593       return this->discard(SubExpr);
5594 
5595     if (!this->visitBool(SubExpr))
5596       return false;
5597 
5598     if (!this->emitInv(E))
5599       return false;
5600 
5601     if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
5602       return this->emitCast(PT_Bool, ET, E);
5603     return true;
5604   case UO_Minus: // -x
5605     if (!T)
5606       return this->emitError(E);
5607 
5608     if (!this->visit(SubExpr))
5609       return false;
5610     return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E);
5611   case UO_Plus: // +x
5612     if (!T)
5613       return this->emitError(E);
5614 
5615     if (!this->visit(SubExpr)) // noop
5616       return false;
5617     return DiscardResult ? this->emitPop(*T, E) : true;
5618   case UO_AddrOf: // &x
5619     if (E->getType()->isMemberPointerType()) {
5620       // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
5621       // member can be formed.
5622       return this->emitGetMemberPtr(cast<DeclRefExpr>(SubExpr)->getDecl(), E);
5623     }
5624     // We should already have a pointer when we get here.
5625     return this->delegate(SubExpr);
5626   case UO_Deref: // *x
5627     if (DiscardResult)
5628       return this->discard(SubExpr);
5629     return this->visit(SubExpr);
5630   case UO_Not: // ~x
5631     if (!T)
5632       return this->emitError(E);
5633 
5634     if (!this->visit(SubExpr))
5635       return false;
5636     return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
5637   case UO_Real: // __real x
5638     assert(T);
5639     return this->delegate(SubExpr);
5640   case UO_Imag: { // __imag x
5641     assert(T);
5642     if (!this->discard(SubExpr))
5643       return false;
5644     return this->visitZeroInitializer(*T, SubExpr->getType(), SubExpr);
5645   }
5646   case UO_Extension:
5647     return this->delegate(SubExpr);
5648   case UO_Coawait:
5649     assert(false && "Unhandled opcode");
5650   }
5651 
5652   return false;
5653 }
5654 
5655 template <class Emitter>
5656 bool Compiler<Emitter>::VisitComplexUnaryOperator(const UnaryOperator *E) {
5657   const Expr *SubExpr = E->getSubExpr();
5658   assert(SubExpr->getType()->isAnyComplexType());
5659 
5660   if (DiscardResult)
5661     return this->discard(SubExpr);
5662 
5663   std::optional<PrimType> ResT = classify(E);
5664   auto prepareResult = [=]() -> bool {
5665     if (!ResT && !Initializing) {
5666       std::optional<unsigned> LocalIndex = allocateLocal(SubExpr);
5667       if (!LocalIndex)
5668         return false;
5669       return this->emitGetPtrLocal(*LocalIndex, E);
5670     }
5671 
5672     return true;
5673   };
5674 
5675   // The offset of the temporary, if we created one.
5676   unsigned SubExprOffset = ~0u;
5677   auto createTemp = [=, &SubExprOffset]() -> bool {
5678     SubExprOffset = this->allocateLocalPrimitive(SubExpr, PT_Ptr, true, false);
5679     if (!this->visit(SubExpr))
5680       return false;
5681     return this->emitSetLocal(PT_Ptr, SubExprOffset, E);
5682   };
5683 
5684   PrimType ElemT = classifyComplexElementType(SubExpr->getType());
5685   auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
5686     if (!this->emitGetLocal(PT_Ptr, Offset, E))
5687       return false;
5688     return this->emitArrayElemPop(ElemT, Index, E);
5689   };
5690 
5691   switch (E->getOpcode()) {
5692   case UO_Minus:
5693     if (!prepareResult())
5694       return false;
5695     if (!createTemp())
5696       return false;
5697     for (unsigned I = 0; I != 2; ++I) {
5698       if (!getElem(SubExprOffset, I))
5699         return false;
5700       if (!this->emitNeg(ElemT, E))
5701         return false;
5702       if (!this->emitInitElem(ElemT, I, E))
5703         return false;
5704     }
5705     break;
5706 
5707   case UO_Plus:   // +x
5708   case UO_AddrOf: // &x
5709   case UO_Deref:  // *x
5710     return this->delegate(SubExpr);
5711 
5712   case UO_LNot:
5713     if (!this->visit(SubExpr))
5714       return false;
5715     if (!this->emitComplexBoolCast(SubExpr))
5716       return false;
5717     if (!this->emitInv(E))
5718       return false;
5719     if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
5720       return this->emitCast(PT_Bool, ET, E);
5721     return true;
5722 
5723   case UO_Real:
5724     return this->emitComplexReal(SubExpr);
5725 
5726   case UO_Imag:
5727     if (!this->visit(SubExpr))
5728       return false;
5729 
5730     if (SubExpr->isLValue()) {
5731       if (!this->emitConstUint8(1, E))
5732         return false;
5733       return this->emitArrayElemPtrPopUint8(E);
5734     }
5735 
5736     // Since our _Complex implementation does not map to a primitive type,
5737     // we sometimes have to do the lvalue-to-rvalue conversion here manually.
5738     return this->emitArrayElemPop(classifyPrim(E->getType()), 1, E);
5739 
5740   case UO_Not: // ~x
5741     if (!this->visit(SubExpr))
5742       return false;
5743     // Negate the imaginary component.
5744     if (!this->emitArrayElem(ElemT, 1, E))
5745       return false;
5746     if (!this->emitNeg(ElemT, E))
5747       return false;
5748     if (!this->emitInitElem(ElemT, 1, E))
5749       return false;
5750     return DiscardResult ? this->emitPopPtr(E) : true;
5751 
5752   case UO_Extension:
5753     return this->delegate(SubExpr);
5754 
5755   default:
5756     return this->emitInvalid(E);
5757   }
5758 
5759   return true;
5760 }
5761 
5762 template <class Emitter>
5763 bool Compiler<Emitter>::VisitVectorUnaryOperator(const UnaryOperator *E) {
5764   const Expr *SubExpr = E->getSubExpr();
5765   assert(SubExpr->getType()->isVectorType());
5766 
5767   if (DiscardResult)
5768     return this->discard(SubExpr);
5769 
5770   auto UnaryOp = E->getOpcode();
5771   if (UnaryOp != UO_Plus && UnaryOp != UO_Minus && UnaryOp != UO_LNot &&
5772       UnaryOp != UO_Not && UnaryOp != UO_AddrOf)
5773     return this->emitInvalid(E);
5774 
5775   // Nothing to do here.
5776   if (UnaryOp == UO_Plus || UnaryOp == UO_AddrOf)
5777     return this->delegate(SubExpr);
5778 
5779   if (!Initializing) {
5780     std::optional<unsigned> LocalIndex = allocateLocal(SubExpr);
5781     if (!LocalIndex)
5782       return false;
5783     if (!this->emitGetPtrLocal(*LocalIndex, E))
5784       return false;
5785   }
5786 
5787   // The offset of the temporary, if we created one.
5788   unsigned SubExprOffset =
5789       this->allocateLocalPrimitive(SubExpr, PT_Ptr, true, false);
5790   if (!this->visit(SubExpr))
5791     return false;
5792   if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E))
5793     return false;
5794 
5795   const auto *VecTy = SubExpr->getType()->getAs<VectorType>();
5796   PrimType ElemT = classifyVectorElementType(SubExpr->getType());
5797   auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
5798     if (!this->emitGetLocal(PT_Ptr, Offset, E))
5799       return false;
5800     return this->emitArrayElemPop(ElemT, Index, E);
5801   };
5802 
5803   switch (UnaryOp) {
5804   case UO_Minus:
5805     for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
5806       if (!getElem(SubExprOffset, I))
5807         return false;
5808       if (!this->emitNeg(ElemT, E))
5809         return false;
5810       if (!this->emitInitElem(ElemT, I, E))
5811         return false;
5812     }
5813     break;
5814   case UO_LNot: { // !x
5815     // In C++, the logic operators !, &&, || are available for vectors. !v is
5816     // equivalent to v == 0.
5817     //
5818     // The result of the comparison is a vector of the same width and number of
5819     // elements as the comparison operands with a signed integral element type.
5820     //
5821     // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
5822     QualType ResultVecTy = E->getType();
5823     PrimType ResultVecElemT =
5824         classifyPrim(ResultVecTy->getAs<VectorType>()->getElementType());
5825     for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
5826       if (!getElem(SubExprOffset, I))
5827         return false;
5828       // operator ! on vectors returns -1 for 'truth', so negate it.
5829       if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
5830         return false;
5831       if (!this->emitInv(E))
5832         return false;
5833       if (!this->emitPrimCast(PT_Bool, ElemT, VecTy->getElementType(), E))
5834         return false;
5835       if (!this->emitNeg(ElemT, E))
5836         return false;
5837       if (ElemT != ResultVecElemT &&
5838           !this->emitPrimCast(ElemT, ResultVecElemT, ResultVecTy, E))
5839         return false;
5840       if (!this->emitInitElem(ResultVecElemT, I, E))
5841         return false;
5842     }
5843     break;
5844   }
5845   case UO_Not: // ~x
5846     for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
5847       if (!getElem(SubExprOffset, I))
5848         return false;
5849       if (ElemT == PT_Bool) {
5850         if (!this->emitInv(E))
5851           return false;
5852       } else {
5853         if (!this->emitComp(ElemT, E))
5854           return false;
5855       }
5856       if (!this->emitInitElem(ElemT, I, E))
5857         return false;
5858     }
5859     break;
5860   default:
5861     llvm_unreachable("Unsupported unary operators should be handled up front");
5862   }
5863   return true;
5864 }
5865 
5866 template <class Emitter>
5867 bool Compiler<Emitter>::visitDeclRef(const ValueDecl *D, const Expr *E) {
5868   if (DiscardResult)
5869     return true;
5870 
5871   if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
5872     return this->emitConst(ECD->getInitVal(), E);
5873   } else if (const auto *BD = dyn_cast<BindingDecl>(D)) {
5874     return this->visit(BD->getBinding());
5875   } else if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) {
5876     const Function *F = getFunction(FuncDecl);
5877     return F && this->emitGetFnPtr(F, E);
5878   } else if (const auto *TPOD = dyn_cast<TemplateParamObjectDecl>(D)) {
5879     if (std::optional<unsigned> Index = P.getOrCreateGlobal(D)) {
5880       if (!this->emitGetPtrGlobal(*Index, E))
5881         return false;
5882       if (std::optional<PrimType> T = classify(E->getType())) {
5883         if (!this->visitAPValue(TPOD->getValue(), *T, E))
5884           return false;
5885         return this->emitInitGlobal(*T, *Index, E);
5886       }
5887       return this->visitAPValueInitializer(TPOD->getValue(), E);
5888     }
5889     return false;
5890   }
5891 
5892   // References are implemented via pointers, so when we see a DeclRefExpr
5893   // pointing to a reference, we need to get its value directly (i.e. the
5894   // pointer to the actual value) instead of a pointer to the pointer to the
5895   // value.
5896   bool IsReference = D->getType()->isReferenceType();
5897 
5898   // Check for local/global variables and parameters.
5899   if (auto It = Locals.find(D); It != Locals.end()) {
5900     const unsigned Offset = It->second.Offset;
5901     if (IsReference)
5902       return this->emitGetLocal(PT_Ptr, Offset, E);
5903     return this->emitGetPtrLocal(Offset, E);
5904   } else if (auto GlobalIndex = P.getGlobal(D)) {
5905     if (IsReference) {
5906       if (!Ctx.getLangOpts().CPlusPlus11)
5907         return this->emitGetGlobal(classifyPrim(E), *GlobalIndex, E);
5908       return this->emitGetGlobalUnchecked(classifyPrim(E), *GlobalIndex, E);
5909     }
5910 
5911     return this->emitGetPtrGlobal(*GlobalIndex, E);
5912   } else if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
5913     if (auto It = this->Params.find(PVD); It != this->Params.end()) {
5914       if (IsReference || !It->second.IsPtr)
5915         return this->emitGetParam(classifyPrim(E), It->second.Offset, E);
5916 
5917       return this->emitGetPtrParam(It->second.Offset, E);
5918     }
5919   }
5920 
5921   // In case we need to re-visit a declaration.
5922   auto revisit = [&](const VarDecl *VD) -> bool {
5923     auto VarState = this->visitDecl(VD);
5924 
5925     if (VarState.notCreated())
5926       return true;
5927     if (!VarState)
5928       return false;
5929     // Retry.
5930     return this->visitDeclRef(D, E);
5931   };
5932 
5933   // Handle lambda captures.
5934   if (auto It = this->LambdaCaptures.find(D);
5935       It != this->LambdaCaptures.end()) {
5936     auto [Offset, IsPtr] = It->second;
5937 
5938     if (IsPtr)
5939       return this->emitGetThisFieldPtr(Offset, E);
5940     return this->emitGetPtrThisField(Offset, E);
5941   } else if (const auto *DRE = dyn_cast<DeclRefExpr>(E);
5942              DRE && DRE->refersToEnclosingVariableOrCapture()) {
5943     if (const auto *VD = dyn_cast<VarDecl>(D); VD && VD->isInitCapture())
5944       return revisit(VD);
5945   }
5946 
5947   if (D != InitializingDecl) {
5948     // Try to lazily visit (or emit dummy pointers for) declarations
5949     // we haven't seen yet.
5950     if (Ctx.getLangOpts().CPlusPlus) {
5951       if (const auto *VD = dyn_cast<VarDecl>(D)) {
5952         const auto typeShouldBeVisited = [&](QualType T) -> bool {
5953           if (T.isConstant(Ctx.getASTContext()))
5954             return true;
5955           if (const auto *RT = T->getAs<ReferenceType>())
5956             return RT->getPointeeType().isConstQualified();
5957           return false;
5958         };
5959 
5960         // DecompositionDecls are just proxies for us.
5961         if (isa<DecompositionDecl>(VD))
5962           return revisit(VD);
5963 
5964         if ((VD->hasGlobalStorage() || VD->isStaticDataMember()) &&
5965             typeShouldBeVisited(VD->getType()))
5966           return revisit(VD);
5967 
5968         // FIXME: The evaluateValue() check here is a little ridiculous, since
5969         // it will ultimately call into Context::evaluateAsInitializer(). In
5970         // other words, we're evaluating the initializer, just to know if we can
5971         // evaluate the initializer.
5972         if (VD->isLocalVarDecl() && typeShouldBeVisited(VD->getType()) &&
5973             VD->getInit() && !VD->getInit()->isValueDependent() &&
5974             VD->evaluateValue())
5975           return revisit(VD);
5976       }
5977     } else {
5978       if (const auto *VD = dyn_cast<VarDecl>(D);
5979           VD && VD->getAnyInitializer() &&
5980           VD->getType().isConstant(Ctx.getASTContext()) && !VD->isWeak())
5981         return revisit(VD);
5982     }
5983   }
5984 
5985   if (std::optional<unsigned> I = P.getOrCreateDummy(D)) {
5986     if (!this->emitGetPtrGlobal(*I, E))
5987       return false;
5988     if (E->getType()->isVoidType())
5989       return true;
5990     // Convert the dummy pointer to another pointer type if we have to.
5991     if (PrimType PT = classifyPrim(E); PT != PT_Ptr) {
5992       if (isPtrType(PT))
5993         return this->emitDecayPtr(PT_Ptr, PT, E);
5994       return false;
5995     }
5996     return true;
5997   }
5998 
5999   if (const auto *DRE = dyn_cast<DeclRefExpr>(E))
6000     return this->emitInvalidDeclRef(DRE, E);
6001   return false;
6002 }
6003 
6004 template <class Emitter>
6005 bool Compiler<Emitter>::VisitDeclRefExpr(const DeclRefExpr *E) {
6006   const auto *D = E->getDecl();
6007   return this->visitDeclRef(D, E);
6008 }
6009 
6010 template <class Emitter> void Compiler<Emitter>::emitCleanup() {
6011   for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent())
6012     C->emitDestruction();
6013 }
6014 
6015 template <class Emitter>
6016 unsigned Compiler<Emitter>::collectBaseOffset(const QualType BaseType,
6017                                               const QualType DerivedType) {
6018   const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
6019     if (const auto *R = Ty->getPointeeCXXRecordDecl())
6020       return R;
6021     return Ty->getAsCXXRecordDecl();
6022   };
6023   const CXXRecordDecl *BaseDecl = extractRecordDecl(BaseType);
6024   const CXXRecordDecl *DerivedDecl = extractRecordDecl(DerivedType);
6025 
6026   return Ctx.collectBaseOffset(BaseDecl, DerivedDecl);
6027 }
6028 
6029 /// Emit casts from a PrimType to another PrimType.
6030 template <class Emitter>
6031 bool Compiler<Emitter>::emitPrimCast(PrimType FromT, PrimType ToT,
6032                                      QualType ToQT, const Expr *E) {
6033 
6034   if (FromT == PT_Float) {
6035     // Floating to floating.
6036     if (ToT == PT_Float) {
6037       const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
6038       return this->emitCastFP(ToSem, getRoundingMode(E), E);
6039     }
6040 
6041     if (ToT == PT_IntAP)
6042       return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(ToQT),
6043                                               getFPOptions(E), E);
6044     if (ToT == PT_IntAPS)
6045       return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(ToQT),
6046                                                getFPOptions(E), E);
6047 
6048     // Float to integral.
6049     if (isIntegralType(ToT) || ToT == PT_Bool)
6050       return this->emitCastFloatingIntegral(ToT, getFPOptions(E), E);
6051   }
6052 
6053   if (isIntegralType(FromT) || FromT == PT_Bool) {
6054     if (ToT == PT_IntAP)
6055       return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
6056     if (ToT == PT_IntAPS)
6057       return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
6058 
6059     // Integral to integral.
6060     if (isIntegralType(ToT) || ToT == PT_Bool)
6061       return FromT != ToT ? this->emitCast(FromT, ToT, E) : true;
6062 
6063     if (ToT == PT_Float) {
6064       // Integral to floating.
6065       const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
6066       return this->emitCastIntegralFloating(FromT, ToSem, getFPOptions(E), E);
6067     }
6068   }
6069 
6070   return false;
6071 }
6072 
6073 /// Emits __real(SubExpr)
6074 template <class Emitter>
6075 bool Compiler<Emitter>::emitComplexReal(const Expr *SubExpr) {
6076   assert(SubExpr->getType()->isAnyComplexType());
6077 
6078   if (DiscardResult)
6079     return this->discard(SubExpr);
6080 
6081   if (!this->visit(SubExpr))
6082     return false;
6083   if (SubExpr->isLValue()) {
6084     if (!this->emitConstUint8(0, SubExpr))
6085       return false;
6086     return this->emitArrayElemPtrPopUint8(SubExpr);
6087   }
6088 
6089   // Rvalue, load the actual element.
6090   return this->emitArrayElemPop(classifyComplexElementType(SubExpr->getType()),
6091                                 0, SubExpr);
6092 }
6093 
6094 template <class Emitter>
6095 bool Compiler<Emitter>::emitComplexBoolCast(const Expr *E) {
6096   assert(!DiscardResult);
6097   PrimType ElemT = classifyComplexElementType(E->getType());
6098   // We emit the expression (__real(E) != 0 || __imag(E) != 0)
6099   // for us, that means (bool)E[0] || (bool)E[1]
6100   if (!this->emitArrayElem(ElemT, 0, E))
6101     return false;
6102   if (ElemT == PT_Float) {
6103     if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
6104       return false;
6105   } else {
6106     if (!this->emitCast(ElemT, PT_Bool, E))
6107       return false;
6108   }
6109 
6110   // We now have the bool value of E[0] on the stack.
6111   LabelTy LabelTrue = this->getLabel();
6112   if (!this->jumpTrue(LabelTrue))
6113     return false;
6114 
6115   if (!this->emitArrayElemPop(ElemT, 1, E))
6116     return false;
6117   if (ElemT == PT_Float) {
6118     if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
6119       return false;
6120   } else {
6121     if (!this->emitCast(ElemT, PT_Bool, E))
6122       return false;
6123   }
6124   // Leave the boolean value of E[1] on the stack.
6125   LabelTy EndLabel = this->getLabel();
6126   this->jump(EndLabel);
6127 
6128   this->emitLabel(LabelTrue);
6129   if (!this->emitPopPtr(E))
6130     return false;
6131   if (!this->emitConstBool(true, E))
6132     return false;
6133 
6134   this->fallthrough(EndLabel);
6135   this->emitLabel(EndLabel);
6136 
6137   return true;
6138 }
6139 
6140 template <class Emitter>
6141 bool Compiler<Emitter>::emitComplexComparison(const Expr *LHS, const Expr *RHS,
6142                                               const BinaryOperator *E) {
6143   assert(E->isComparisonOp());
6144   assert(!Initializing);
6145   assert(!DiscardResult);
6146 
6147   PrimType ElemT;
6148   bool LHSIsComplex;
6149   unsigned LHSOffset;
6150   if (LHS->getType()->isAnyComplexType()) {
6151     LHSIsComplex = true;
6152     ElemT = classifyComplexElementType(LHS->getType());
6153     LHSOffset = allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true,
6154                                        /*IsExtended=*/false);
6155     if (!this->visit(LHS))
6156       return false;
6157     if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
6158       return false;
6159   } else {
6160     LHSIsComplex = false;
6161     PrimType LHST = classifyPrim(LHS->getType());
6162     LHSOffset = this->allocateLocalPrimitive(LHS, LHST, true, false);
6163     if (!this->visit(LHS))
6164       return false;
6165     if (!this->emitSetLocal(LHST, LHSOffset, E))
6166       return false;
6167   }
6168 
6169   bool RHSIsComplex;
6170   unsigned RHSOffset;
6171   if (RHS->getType()->isAnyComplexType()) {
6172     RHSIsComplex = true;
6173     ElemT = classifyComplexElementType(RHS->getType());
6174     RHSOffset = allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true,
6175                                        /*IsExtended=*/false);
6176     if (!this->visit(RHS))
6177       return false;
6178     if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
6179       return false;
6180   } else {
6181     RHSIsComplex = false;
6182     PrimType RHST = classifyPrim(RHS->getType());
6183     RHSOffset = this->allocateLocalPrimitive(RHS, RHST, true, false);
6184     if (!this->visit(RHS))
6185       return false;
6186     if (!this->emitSetLocal(RHST, RHSOffset, E))
6187       return false;
6188   }
6189 
6190   auto getElem = [&](unsigned LocalOffset, unsigned Index,
6191                      bool IsComplex) -> bool {
6192     if (IsComplex) {
6193       if (!this->emitGetLocal(PT_Ptr, LocalOffset, E))
6194         return false;
6195       return this->emitArrayElemPop(ElemT, Index, E);
6196     }
6197     return this->emitGetLocal(ElemT, LocalOffset, E);
6198   };
6199 
6200   for (unsigned I = 0; I != 2; ++I) {
6201     // Get both values.
6202     if (!getElem(LHSOffset, I, LHSIsComplex))
6203       return false;
6204     if (!getElem(RHSOffset, I, RHSIsComplex))
6205       return false;
6206     // And compare them.
6207     if (!this->emitEQ(ElemT, E))
6208       return false;
6209 
6210     if (!this->emitCastBoolUint8(E))
6211       return false;
6212   }
6213 
6214   // We now have two bool values on the stack. Compare those.
6215   if (!this->emitAddUint8(E))
6216     return false;
6217   if (!this->emitConstUint8(2, E))
6218     return false;
6219 
6220   if (E->getOpcode() == BO_EQ) {
6221     if (!this->emitEQUint8(E))
6222       return false;
6223   } else if (E->getOpcode() == BO_NE) {
6224     if (!this->emitNEUint8(E))
6225       return false;
6226   } else
6227     return false;
6228 
6229   // In C, this returns an int.
6230   if (PrimType ResT = classifyPrim(E->getType()); ResT != PT_Bool)
6231     return this->emitCast(PT_Bool, ResT, E);
6232   return true;
6233 }
6234 
6235 /// When calling this, we have a pointer of the local-to-destroy
6236 /// on the stack.
6237 /// Emit destruction of record types (or arrays of record types).
6238 template <class Emitter>
6239 bool Compiler<Emitter>::emitRecordDestruction(const Record *R, SourceInfo Loc) {
6240   assert(R);
6241   assert(!R->isAnonymousUnion());
6242   const CXXDestructorDecl *Dtor = R->getDestructor();
6243   if (!Dtor || Dtor->isTrivial())
6244     return true;
6245 
6246   assert(Dtor);
6247   const Function *DtorFunc = getFunction(Dtor);
6248   if (!DtorFunc)
6249     return false;
6250   assert(DtorFunc->hasThisPointer());
6251   assert(DtorFunc->getNumParams() == 1);
6252   if (!this->emitDupPtr(Loc))
6253     return false;
6254   return this->emitCall(DtorFunc, 0, Loc);
6255 }
6256 /// When calling this, we have a pointer of the local-to-destroy
6257 /// on the stack.
6258 /// Emit destruction of record types (or arrays of record types).
6259 template <class Emitter>
6260 bool Compiler<Emitter>::emitDestruction(const Descriptor *Desc,
6261                                         SourceInfo Loc) {
6262   assert(Desc);
6263   assert(!Desc->isPrimitive());
6264   assert(!Desc->isPrimitiveArray());
6265 
6266   // Arrays.
6267   if (Desc->isArray()) {
6268     const Descriptor *ElemDesc = Desc->ElemDesc;
6269     assert(ElemDesc);
6270 
6271     // Don't need to do anything for these.
6272     if (ElemDesc->isPrimitiveArray())
6273       return true;
6274 
6275     // If this is an array of record types, check if we need
6276     // to call the element destructors at all. If not, try
6277     // to save the work.
6278     if (const Record *ElemRecord = ElemDesc->ElemRecord) {
6279       if (const CXXDestructorDecl *Dtor = ElemRecord->getDestructor();
6280           !Dtor || Dtor->isTrivial())
6281         return true;
6282     }
6283 
6284     for (ssize_t I = Desc->getNumElems() - 1; I >= 0; --I) {
6285       if (!this->emitConstUint64(I, Loc))
6286         return false;
6287       if (!this->emitArrayElemPtrUint64(Loc))
6288         return false;
6289       if (!this->emitDestruction(ElemDesc, Loc))
6290         return false;
6291       if (!this->emitPopPtr(Loc))
6292         return false;
6293     }
6294     return true;
6295   }
6296 
6297   assert(Desc->ElemRecord);
6298   if (Desc->ElemRecord->isAnonymousUnion())
6299     return true;
6300 
6301   return this->emitRecordDestruction(Desc->ElemRecord, Loc);
6302 }
6303 
6304 namespace clang {
6305 namespace interp {
6306 
6307 template class Compiler<ByteCodeEmitter>;
6308 template class Compiler<EvalEmitter>;
6309 
6310 } // namespace interp
6311 } // namespace clang
6312