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