xref: /llvm-project/clang/lib/AST/ByteCode/Compiler.h (revision a07aba5d44204a7ca0d891a3da05af9960081e4c)
1 //===--- Compiler.h - 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 // Defines the constexpr bytecode compiler.
10 //
11 //===----------------------------------------------------------------------===//
12 
13 #ifndef LLVM_CLANG_AST_INTERP_BYTECODEEXPRGEN_H
14 #define LLVM_CLANG_AST_INTERP_BYTECODEEXPRGEN_H
15 
16 #include "ByteCodeEmitter.h"
17 #include "EvalEmitter.h"
18 #include "Pointer.h"
19 #include "PrimType.h"
20 #include "Record.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/Expr.h"
23 #include "clang/AST/StmtVisitor.h"
24 #include "clang/Basic/TargetInfo.h"
25 
26 namespace clang {
27 class QualType;
28 
29 namespace interp {
30 
31 template <class Emitter> class LocalScope;
32 template <class Emitter> class DestructorScope;
33 template <class Emitter> class VariableScope;
34 template <class Emitter> class DeclScope;
35 template <class Emitter> class InitLinkScope;
36 template <class Emitter> class InitStackScope;
37 template <class Emitter> class OptionScope;
38 template <class Emitter> class ArrayIndexScope;
39 template <class Emitter> class SourceLocScope;
40 template <class Emitter> class LoopScope;
41 template <class Emitter> class LabelScope;
42 template <class Emitter> class SwitchScope;
43 template <class Emitter> class StmtExprScope;
44 
45 template <class Emitter> class Compiler;
46 struct InitLink {
47 public:
48   enum {
49     K_This = 0,
50     K_Field = 1,
51     K_Temp = 2,
52     K_Decl = 3,
53     K_Elem = 5,
54   };
55 
56   static InitLink This() { return InitLink{K_This}; }
57   static InitLink Field(unsigned Offset) {
58     InitLink IL{K_Field};
59     IL.Offset = Offset;
60     return IL;
61   }
62   static InitLink Temp(unsigned Offset) {
63     InitLink IL{K_Temp};
64     IL.Offset = Offset;
65     return IL;
66   }
67   static InitLink Decl(const ValueDecl *D) {
68     InitLink IL{K_Decl};
69     IL.D = D;
70     return IL;
71   }
72   static InitLink Elem(unsigned Index) {
73     InitLink IL{K_Elem};
74     IL.Offset = Index;
75     return IL;
76   }
77 
78   InitLink(uint8_t Kind) : Kind(Kind) {}
79   template <class Emitter>
80   bool emit(Compiler<Emitter> *Ctx, const Expr *E) const;
81 
82   uint32_t Kind;
83   union {
84     unsigned Offset;
85     const ValueDecl *D;
86   };
87 };
88 
89 /// State encapsulating if a the variable creation has been successful,
90 /// unsuccessful, or no variable has been created at all.
91 struct VarCreationState {
92   std::optional<bool> S = std::nullopt;
93   VarCreationState() = default;
94   VarCreationState(bool b) : S(b) {}
95   static VarCreationState NotCreated() { return VarCreationState(); }
96 
97   operator bool() const { return S && *S; }
98   bool notCreated() const { return !S; }
99 };
100 
101 /// Compilation context for expressions.
102 template <class Emitter>
103 class Compiler : public ConstStmtVisitor<Compiler<Emitter>, bool>,
104                  public Emitter {
105 protected:
106   // Aliases for types defined in the emitter.
107   using LabelTy = typename Emitter::LabelTy;
108   using AddrTy = typename Emitter::AddrTy;
109   using OptLabelTy = std::optional<LabelTy>;
110   using CaseMap = llvm::DenseMap<const SwitchCase *, LabelTy>;
111 
112   /// Current compilation context.
113   Context &Ctx;
114   /// Program to link to.
115   Program &P;
116 
117 public:
118   /// Initializes the compiler and the backend emitter.
119   template <typename... Tys>
120   Compiler(Context &Ctx, Program &P, Tys &&...Args)
121       : Emitter(Ctx, P, Args...), Ctx(Ctx), P(P) {}
122 
123   // Expressions.
124   bool VisitCastExpr(const CastExpr *E);
125   bool VisitIntegerLiteral(const IntegerLiteral *E);
126   bool VisitFloatingLiteral(const FloatingLiteral *E);
127   bool VisitImaginaryLiteral(const ImaginaryLiteral *E);
128   bool VisitParenExpr(const ParenExpr *E);
129   bool VisitBinaryOperator(const BinaryOperator *E);
130   bool VisitLogicalBinOp(const BinaryOperator *E);
131   bool VisitPointerArithBinOp(const BinaryOperator *E);
132   bool VisitComplexBinOp(const BinaryOperator *E);
133   bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E);
134   bool VisitCallExpr(const CallExpr *E);
135   bool VisitBuiltinCallExpr(const CallExpr *E);
136   bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E);
137   bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E);
138   bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E);
139   bool VisitGNUNullExpr(const GNUNullExpr *E);
140   bool VisitCXXThisExpr(const CXXThisExpr *E);
141   bool VisitUnaryOperator(const UnaryOperator *E);
142   bool VisitComplexUnaryOperator(const UnaryOperator *E);
143   bool VisitDeclRefExpr(const DeclRefExpr *E);
144   bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E);
145   bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E);
146   bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E);
147   bool VisitInitListExpr(const InitListExpr *E);
148   bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E);
149   bool VisitConstantExpr(const ConstantExpr *E);
150   bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E);
151   bool VisitMemberExpr(const MemberExpr *E);
152   bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E);
153   bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E);
154   bool VisitOpaqueValueExpr(const OpaqueValueExpr *E);
155   bool VisitAbstractConditionalOperator(const AbstractConditionalOperator *E);
156   bool VisitStringLiteral(const StringLiteral *E);
157   bool VisitObjCStringLiteral(const ObjCStringLiteral *E);
158   bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E);
159   bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E);
160   bool VisitCharacterLiteral(const CharacterLiteral *E);
161   bool VisitCompoundAssignOperator(const CompoundAssignOperator *E);
162   bool VisitFloatCompoundAssignOperator(const CompoundAssignOperator *E);
163   bool VisitPointerCompoundAssignOperator(const CompoundAssignOperator *E);
164   bool VisitExprWithCleanups(const ExprWithCleanups *E);
165   bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E);
166   bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E);
167   bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E);
168   bool VisitTypeTraitExpr(const TypeTraitExpr *E);
169   bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E);
170   bool VisitLambdaExpr(const LambdaExpr *E);
171   bool VisitPredefinedExpr(const PredefinedExpr *E);
172   bool VisitCXXThrowExpr(const CXXThrowExpr *E);
173   bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E);
174   bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E);
175   bool VisitCXXConstructExpr(const CXXConstructExpr *E);
176   bool VisitSourceLocExpr(const SourceLocExpr *E);
177   bool VisitOffsetOfExpr(const OffsetOfExpr *E);
178   bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E);
179   bool VisitSizeOfPackExpr(const SizeOfPackExpr *E);
180   bool VisitGenericSelectionExpr(const GenericSelectionExpr *E);
181   bool VisitChooseExpr(const ChooseExpr *E);
182   bool VisitEmbedExpr(const EmbedExpr *E);
183   bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E);
184   bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E);
185   bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E);
186   bool VisitCXXUuidofExpr(const CXXUuidofExpr *E);
187   bool VisitRequiresExpr(const RequiresExpr *E);
188   bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E);
189   bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E);
190   bool VisitPseudoObjectExpr(const PseudoObjectExpr *E);
191   bool VisitPackIndexingExpr(const PackIndexingExpr *E);
192   bool VisitRecoveryExpr(const RecoveryExpr *E);
193   bool VisitAddrLabelExpr(const AddrLabelExpr *E);
194   bool VisitConvertVectorExpr(const ConvertVectorExpr *E);
195   bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E);
196   bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E);
197   bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E);
198   bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E);
199   bool VisitStmtExpr(const StmtExpr *E);
200   bool VisitCXXNewExpr(const CXXNewExpr *E);
201   bool VisitCXXDeleteExpr(const CXXDeleteExpr *E);
202 
203   // Statements.
204   bool visitCompoundStmt(const CompoundStmt *S);
205   bool visitDeclStmt(const DeclStmt *DS);
206   bool visitReturnStmt(const ReturnStmt *RS);
207   bool visitIfStmt(const IfStmt *IS);
208   bool visitWhileStmt(const WhileStmt *S);
209   bool visitDoStmt(const DoStmt *S);
210   bool visitForStmt(const ForStmt *S);
211   bool visitCXXForRangeStmt(const CXXForRangeStmt *S);
212   bool visitBreakStmt(const BreakStmt *S);
213   bool visitContinueStmt(const ContinueStmt *S);
214   bool visitSwitchStmt(const SwitchStmt *S);
215   bool visitCaseStmt(const CaseStmt *S);
216   bool visitDefaultStmt(const DefaultStmt *S);
217   bool visitAttributedStmt(const AttributedStmt *S);
218   bool visitCXXTryStmt(const CXXTryStmt *S);
219 
220 protected:
221   bool visitStmt(const Stmt *S);
222   bool visitExpr(const Expr *E) override;
223   bool visitFunc(const FunctionDecl *F) override;
224 
225   bool visitDeclAndReturn(const VarDecl *VD, bool ConstantContext) override;
226 
227 protected:
228   /// Emits scope cleanup instructions.
229   void emitCleanup();
230 
231   /// Returns a record type from a record or pointer type.
232   const RecordType *getRecordTy(QualType Ty);
233 
234   /// Returns a record from a record or pointer type.
235   Record *getRecord(QualType Ty);
236   Record *getRecord(const RecordDecl *RD);
237 
238   /// Returns a function for the given FunctionDecl.
239   /// If the function does not exist yet, it is compiled.
240   const Function *getFunction(const FunctionDecl *FD);
241 
242   std::optional<PrimType> classify(const Expr *E) const {
243     return Ctx.classify(E);
244   }
245   std::optional<PrimType> classify(QualType Ty) const {
246     return Ctx.classify(Ty);
247   }
248 
249   /// Classifies a known primitive type.
250   PrimType classifyPrim(QualType Ty) const {
251     if (auto T = classify(Ty)) {
252       return *T;
253     }
254     llvm_unreachable("not a primitive type");
255   }
256   /// Classifies a known primitive expression.
257   PrimType classifyPrim(const Expr *E) const {
258     if (auto T = classify(E))
259       return *T;
260     llvm_unreachable("not a primitive type");
261   }
262 
263   /// Evaluates an expression and places the result on the stack. If the
264   /// expression is of composite type, a local variable will be created
265   /// and a pointer to said variable will be placed on the stack.
266   bool visit(const Expr *E);
267   /// Compiles an initializer. This is like visit() but it will never
268   /// create a variable and instead rely on a variable already having
269   /// been created. visitInitializer() then relies on a pointer to this
270   /// variable being on top of the stack.
271   bool visitInitializer(const Expr *E);
272   /// Evaluates an expression for side effects and discards the result.
273   bool discard(const Expr *E);
274   /// Just pass evaluation on to \p E. This leaves all the parsing flags
275   /// intact.
276   bool delegate(const Expr *E);
277   /// Creates and initializes a variable from the given decl.
278   VarCreationState visitVarDecl(const VarDecl *VD, bool Toplevel = false);
279   VarCreationState visitDecl(const VarDecl *VD);
280   /// Visit an APValue.
281   bool visitAPValue(const APValue &Val, PrimType ValType, const Expr *E);
282   bool visitAPValueInitializer(const APValue &Val, const Expr *E);
283   /// Visit the given decl as if we have a reference to it.
284   bool visitDeclRef(const ValueDecl *D, const Expr *E);
285 
286   /// Visits an expression and converts it to a boolean.
287   bool visitBool(const Expr *E);
288 
289   bool visitInitList(ArrayRef<const Expr *> Inits, const Expr *ArrayFiller,
290                      const Expr *E);
291   bool visitArrayElemInit(unsigned ElemIndex, const Expr *Init);
292 
293   /// Creates a local primitive value.
294   unsigned allocateLocalPrimitive(DeclTy &&Decl, PrimType Ty, bool IsConst,
295                                   bool IsExtended = false);
296 
297   /// Allocates a space storing a local given its type.
298   std::optional<unsigned>
299   allocateLocal(DeclTy &&Decl, const ValueDecl *ExtendingDecl = nullptr);
300   unsigned allocateTemporary(const Expr *E);
301 
302 private:
303   friend class VariableScope<Emitter>;
304   friend class LocalScope<Emitter>;
305   friend class DestructorScope<Emitter>;
306   friend class DeclScope<Emitter>;
307   friend class InitLinkScope<Emitter>;
308   friend class InitStackScope<Emitter>;
309   friend class OptionScope<Emitter>;
310   friend class ArrayIndexScope<Emitter>;
311   friend class SourceLocScope<Emitter>;
312   friend struct InitLink;
313   friend class LoopScope<Emitter>;
314   friend class LabelScope<Emitter>;
315   friend class SwitchScope<Emitter>;
316   friend class StmtExprScope<Emitter>;
317 
318   /// Emits a zero initializer.
319   bool visitZeroInitializer(PrimType T, QualType QT, const Expr *E);
320   bool visitZeroRecordInitializer(const Record *R, const Expr *E);
321 
322   /// Emits an APSInt constant.
323   bool emitConst(const llvm::APSInt &Value, PrimType Ty, const Expr *E);
324   bool emitConst(const llvm::APSInt &Value, const Expr *E);
325   bool emitConst(const llvm::APInt &Value, const Expr *E) {
326     return emitConst(static_cast<llvm::APSInt>(Value), E);
327   }
328 
329   /// Emits an integer constant.
330   template <typename T> bool emitConst(T Value, PrimType Ty, const Expr *E);
331   template <typename T> bool emitConst(T Value, const Expr *E);
332 
333   llvm::RoundingMode getRoundingMode(const Expr *E) const {
334     FPOptions FPO = E->getFPFeaturesInEffect(Ctx.getLangOpts());
335 
336     if (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic)
337       return llvm::RoundingMode::NearestTiesToEven;
338 
339     return FPO.getRoundingMode();
340   }
341 
342   bool emitPrimCast(PrimType FromT, PrimType ToT, QualType ToQT, const Expr *E);
343   PrimType classifyComplexElementType(QualType T) const {
344     assert(T->isAnyComplexType());
345 
346     QualType ElemType = T->getAs<ComplexType>()->getElementType();
347 
348     return *this->classify(ElemType);
349   }
350 
351   bool emitComplexReal(const Expr *SubExpr);
352   bool emitComplexBoolCast(const Expr *E);
353   bool emitComplexComparison(const Expr *LHS, const Expr *RHS,
354                              const BinaryOperator *E);
355 
356   bool emitRecordDestruction(const Record *R);
357   bool emitDestruction(const Descriptor *Desc);
358   unsigned collectBaseOffset(const QualType BaseType,
359                              const QualType DerivedType);
360   bool emitLambdaStaticInvokerBody(const CXXMethodDecl *MD);
361   bool compileConstructor(const CXXConstructorDecl *Ctor);
362   bool compileDestructor(const CXXDestructorDecl *Dtor);
363 
364   bool checkLiteralType(const Expr *E);
365 
366 protected:
367   /// Variable to storage mapping.
368   llvm::DenseMap<const ValueDecl *, Scope::Local> Locals;
369 
370   /// OpaqueValueExpr to location mapping.
371   llvm::DenseMap<const OpaqueValueExpr *, unsigned> OpaqueExprs;
372 
373   /// Current scope.
374   VariableScope<Emitter> *VarScope = nullptr;
375 
376   /// Current argument index. Needed to emit ArrayInitIndexExpr.
377   std::optional<uint64_t> ArrayIndex;
378 
379   /// DefaultInit- or DefaultArgExpr, needed for SourceLocExpr.
380   const Expr *SourceLocDefaultExpr = nullptr;
381 
382   /// Flag indicating if return value is to be discarded.
383   bool DiscardResult = false;
384 
385   bool InStmtExpr = false;
386 
387   /// Flag inidicating if we're initializing an already created
388   /// variable. This is set in visitInitializer().
389   bool Initializing = false;
390   const ValueDecl *InitializingDecl = nullptr;
391 
392   llvm::SmallVector<InitLink> InitStack;
393   bool InitStackActive = false;
394 
395   /// Type of the expression returned by the function.
396   std::optional<PrimType> ReturnType;
397 
398   /// Switch case mapping.
399   CaseMap CaseLabels;
400 
401   /// Point to break to.
402   OptLabelTy BreakLabel;
403   /// Point to continue to.
404   OptLabelTy ContinueLabel;
405   /// Default case label.
406   OptLabelTy DefaultLabel;
407 };
408 
409 extern template class Compiler<ByteCodeEmitter>;
410 extern template class Compiler<EvalEmitter>;
411 
412 /// Scope chain managing the variable lifetimes.
413 template <class Emitter> class VariableScope {
414 public:
415   VariableScope(Compiler<Emitter> *Ctx, const ValueDecl *VD)
416       : Ctx(Ctx), Parent(Ctx->VarScope), ValDecl(VD) {
417     Ctx->VarScope = this;
418   }
419 
420   virtual ~VariableScope() { Ctx->VarScope = this->Parent; }
421 
422   void add(const Scope::Local &Local, bool IsExtended) {
423     if (IsExtended)
424       this->addExtended(Local);
425     else
426       this->addLocal(Local);
427   }
428 
429   virtual void addLocal(const Scope::Local &Local) {
430     if (this->Parent)
431       this->Parent->addLocal(Local);
432   }
433 
434   virtual void addExtended(const Scope::Local &Local) {
435     if (this->Parent)
436       this->Parent->addExtended(Local);
437   }
438 
439   void addExtended(const Scope::Local &Local, const ValueDecl *ExtendingDecl) {
440     // Walk up the chain of scopes until we find the one for ExtendingDecl.
441     // If there is no such scope, attach it to the parent one.
442     VariableScope *P = this;
443     while (P) {
444       if (P->ValDecl == ExtendingDecl) {
445         P->addLocal(Local);
446         return;
447       }
448       P = P->Parent;
449       if (!P)
450         break;
451     }
452 
453     // Use the parent scope.
454     if (this->Parent)
455       this->Parent->addLocal(Local);
456     else
457       this->addLocal(Local);
458   }
459 
460   virtual void emitDestruction() {}
461   virtual bool emitDestructors(const Expr *E = nullptr) { return true; }
462   virtual bool destroyLocals(const Expr *E = nullptr) { return true; }
463   VariableScope *getParent() const { return Parent; }
464 
465 protected:
466   /// Compiler instance.
467   Compiler<Emitter> *Ctx;
468   /// Link to the parent scope.
469   VariableScope *Parent;
470   const ValueDecl *ValDecl = nullptr;
471 };
472 
473 /// Generic scope for local variables.
474 template <class Emitter> class LocalScope : public VariableScope<Emitter> {
475 public:
476   LocalScope(Compiler<Emitter> *Ctx) : VariableScope<Emitter>(Ctx, nullptr) {}
477   LocalScope(Compiler<Emitter> *Ctx, const ValueDecl *VD)
478       : VariableScope<Emitter>(Ctx, VD) {}
479 
480   /// Emit a Destroy op for this scope.
481   ~LocalScope() override {
482     if (!Idx)
483       return;
484     this->Ctx->emitDestroy(*Idx, SourceInfo{});
485     removeStoredOpaqueValues();
486   }
487 
488   /// Overriden to support explicit destruction.
489   void emitDestruction() override {
490     if (!Idx)
491       return;
492 
493     this->emitDestructors();
494     this->Ctx->emitDestroy(*Idx, SourceInfo{});
495   }
496 
497   /// Explicit destruction of local variables.
498   bool destroyLocals(const Expr *E = nullptr) override {
499     if (!Idx)
500       return true;
501 
502     bool Success = this->emitDestructors(E);
503     this->Ctx->emitDestroy(*Idx, E);
504     this->Idx = std::nullopt;
505     return Success;
506   }
507 
508   void addLocal(const Scope::Local &Local) override {
509     if (!Idx) {
510       Idx = this->Ctx->Descriptors.size();
511       this->Ctx->Descriptors.emplace_back();
512       this->Ctx->emitInitScope(*Idx, {});
513     }
514 
515     this->Ctx->Descriptors[*Idx].emplace_back(Local);
516   }
517 
518   bool emitDestructors(const Expr *E = nullptr) override {
519     if (!Idx)
520       return true;
521     // Emit destructor calls for local variables of record
522     // type with a destructor.
523     for (Scope::Local &Local : this->Ctx->Descriptors[*Idx]) {
524       if (!Local.Desc->isPrimitive() && !Local.Desc->isPrimitiveArray()) {
525         if (!this->Ctx->emitGetPtrLocal(Local.Offset, E))
526           return false;
527 
528         if (!this->Ctx->emitDestruction(Local.Desc))
529           return false;
530 
531         if (!this->Ctx->emitPopPtr(E))
532           return false;
533         removeIfStoredOpaqueValue(Local);
534       }
535     }
536     return true;
537   }
538 
539   void removeStoredOpaqueValues() {
540     if (!Idx)
541       return;
542 
543     for (const Scope::Local &Local : this->Ctx->Descriptors[*Idx]) {
544       removeIfStoredOpaqueValue(Local);
545     }
546   }
547 
548   void removeIfStoredOpaqueValue(const Scope::Local &Local) {
549     if (const auto *OVE =
550             llvm::dyn_cast_if_present<OpaqueValueExpr>(Local.Desc->asExpr())) {
551       if (auto It = this->Ctx->OpaqueExprs.find(OVE);
552           It != this->Ctx->OpaqueExprs.end())
553         this->Ctx->OpaqueExprs.erase(It);
554     };
555   }
556 
557   /// Index of the scope in the chain.
558   std::optional<unsigned> Idx;
559 };
560 
561 /// Scope for storage declared in a compound statement.
562 template <class Emitter> class BlockScope final : public LocalScope<Emitter> {
563 public:
564   BlockScope(Compiler<Emitter> *Ctx) : LocalScope<Emitter>(Ctx) {}
565 
566   void addExtended(const Scope::Local &Local) override {
567     // If we to this point, just add the variable as a normal local
568     // variable. It will be destroyed at the end of the block just
569     // like all others.
570     this->addLocal(Local);
571   }
572 };
573 
574 template <class Emitter> class ArrayIndexScope final {
575 public:
576   ArrayIndexScope(Compiler<Emitter> *Ctx, uint64_t Index) : Ctx(Ctx) {
577     OldArrayIndex = Ctx->ArrayIndex;
578     Ctx->ArrayIndex = Index;
579   }
580 
581   ~ArrayIndexScope() { Ctx->ArrayIndex = OldArrayIndex; }
582 
583 private:
584   Compiler<Emitter> *Ctx;
585   std::optional<uint64_t> OldArrayIndex;
586 };
587 
588 template <class Emitter> class SourceLocScope final {
589 public:
590   SourceLocScope(Compiler<Emitter> *Ctx, const Expr *DefaultExpr) : Ctx(Ctx) {
591     assert(DefaultExpr);
592     // We only switch if the current SourceLocDefaultExpr is null.
593     if (!Ctx->SourceLocDefaultExpr) {
594       Enabled = true;
595       Ctx->SourceLocDefaultExpr = DefaultExpr;
596     }
597   }
598 
599   ~SourceLocScope() {
600     if (Enabled)
601       Ctx->SourceLocDefaultExpr = nullptr;
602   }
603 
604 private:
605   Compiler<Emitter> *Ctx;
606   bool Enabled = false;
607 };
608 
609 template <class Emitter> class InitLinkScope final {
610 public:
611   InitLinkScope(Compiler<Emitter> *Ctx, InitLink &&Link) : Ctx(Ctx) {
612     Ctx->InitStack.push_back(std::move(Link));
613   }
614 
615   ~InitLinkScope() { this->Ctx->InitStack.pop_back(); }
616 
617 private:
618   Compiler<Emitter> *Ctx;
619 };
620 
621 template <class Emitter> class InitStackScope final {
622 public:
623   InitStackScope(Compiler<Emitter> *Ctx, bool Active)
624       : Ctx(Ctx), OldValue(Ctx->InitStackActive) {
625     Ctx->InitStackActive = Active;
626   }
627 
628   ~InitStackScope() { this->Ctx->InitStackActive = OldValue; }
629 
630 private:
631   Compiler<Emitter> *Ctx;
632   bool OldValue;
633 };
634 
635 } // namespace interp
636 } // namespace clang
637 
638 #endif
639