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