1 //===--- Context.cpp - Context for the constexpr VM -------------*- C++ -*-===//
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
7 //===----------------------------------------------------------------------===//
10 #include "ByteCodeEmitter.h"
11 #include "ByteCodeExprGen.h"
12 #include "ByteCodeStmtGen.h"
13 #include "EvalEmitter.h"
15 #include "InterpFrame.h"
16 #include "InterpStack.h"
19 #include "clang/AST/Expr.h"
20 #include "clang/Basic/TargetInfo.h"
22 using namespace clang;
23 using namespace clang::interp;
25 Context::Context(ASTContext &Ctx) : Ctx(Ctx), P(new Program(*this)) {}
27 Context::~Context() {}
29 bool Context::isPotentialConstantExpr(State &Parent, const FunctionDecl *FD) {
30 Function *Func = P->getFunction(FD);
32 if (auto R = ByteCodeStmtGen<ByteCodeEmitter>(*this, *P).compileFunc(FD)) {
35 handleAllErrors(R.takeError(), [&Parent](ByteCodeGenError &Err) {
36 Parent.FFDiag(Err.getLoc(), diag::err_experimental_clang_interp_failed);
42 if (!Func->isConstexpr())
46 return Run(Parent, Func, Dummy);
49 bool Context::evaluateAsRValue(State &Parent, const Expr *E, APValue &Result) {
50 ByteCodeExprGen<EvalEmitter> C(*this, *P, Parent, Stk, Result);
51 return Check(Parent, C.interpretExpr(E));
54 bool Context::evaluateAsInitializer(State &Parent, const VarDecl *VD,
56 ByteCodeExprGen<EvalEmitter> C(*this, *P, Parent, Stk, Result);
57 return Check(Parent, C.interpretDecl(VD));
60 const LangOptions &Context::getLangOpts() const { return Ctx.getLangOpts(); }
62 llvm::Optional<PrimType> Context::classify(QualType T) {
63 if (T->isReferenceType() || T->isPointerType()) {
67 if (T->isBooleanType())
70 if (T->isSignedIntegerOrEnumerationType()) {
71 switch (Ctx.getIntWidth(T)) {
85 if (T->isUnsignedIntegerOrEnumerationType()) {
86 switch (Ctx.getIntWidth(T)) {
100 if (T->isNullPtrType())
103 if (auto *AT = dyn_cast<AtomicType>(T))
104 return classify(AT->getValueType());
109 unsigned Context::getCharBit() const {
110 return Ctx.getTargetInfo().getCharWidth();
113 bool Context::Run(State &Parent, Function *Func, APValue &Result) {
114 InterpState State(Parent, *P, Stk, *this);
115 State.Current = new InterpFrame(State, Func, nullptr, {}, {});
116 if (Interpret(State, Result))
122 bool Context::Check(State &Parent, llvm::Expected<bool> &&Flag) {
125 handleAllErrors(Flag.takeError(), [&Parent](ByteCodeGenError &Err) {
126 Parent.FFDiag(Err.getLoc(), diag::err_experimental_clang_interp_failed);