1 //===--- Context.h - Context for the constexpr VM ---------------*- 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 execution context. 10 // 11 // The execution context manages cached bytecode and the global context. 12 // It invokes the compiler and interpreter, propagating errors. 13 // 14 //===----------------------------------------------------------------------===// 15 16 #ifndef LLVM_CLANG_AST_INTERP_CONTEXT_H 17 #define LLVM_CLANG_AST_INTERP_CONTEXT_H 18 19 #include "InterpStack.h" 20 #include "clang/AST/APValue.h" 21 #include "llvm/ADT/PointerIntPair.h" 22 23 namespace clang { 24 class ASTContext; 25 class LangOptions; 26 class FunctionDecl; 27 class VarDecl; 28 29 namespace interp { 30 class Function; 31 class Program; 32 class State; 33 enum PrimType : unsigned; 34 35 /// Holds all information required to evaluate constexpr code in a module. 36 class Context { 37 public: 38 /// Initialises the constexpr VM. 39 Context(ASTContext &Ctx); 40 41 /// Cleans up the constexpr VM. 42 ~Context(); 43 44 /// Checks if a function is a potential constant expression. 45 bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FnDecl); 46 47 /// Evaluates a toplevel expression as an rvalue. 48 bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result); 49 50 /// Evaluates a toplevel initializer. 51 bool evaluateAsInitializer(State &Parent, const VarDecl *VD, APValue &Result); 52 53 /// Returns the AST context. 54 ASTContext &getASTContext() const { return Ctx; } 55 /// Returns the language options. 56 const LangOptions &getLangOpts() const; 57 /// Returns the interpreter stack. 58 InterpStack &getStack() { return Stk; } 59 /// Returns CHAR_BIT. 60 unsigned getCharBit() const; 61 62 /// Classifies an expression. 63 llvm::Optional<PrimType> classify(QualType T); 64 65 private: 66 /// Runs a function. 67 bool Run(State &Parent, Function *Func, APValue &Result); 68 69 /// Checks a result from the interpreter. 70 bool Check(State &Parent, llvm::Expected<bool> &&R); 71 72 private: 73 /// Current compilation context. 74 ASTContext &Ctx; 75 /// Interpreter stack, shared across invocations. 76 InterpStack Stk; 77 /// Constexpr program. 78 std::unique_ptr<Program> P; 79 }; 80 81 } // namespace interp 82 } // namespace clang 83 84 #endif 85