clang 18.0.0git
Context.cpp
Go to the documentation of this file.
1//===--- Context.cpp - 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#include "Context.h"
10#include "ByteCodeEmitter.h"
11#include "ByteCodeExprGen.h"
12#include "ByteCodeStmtGen.h"
13#include "EvalEmitter.h"
14#include "Interp.h"
15#include "InterpFrame.h"
16#include "InterpStack.h"
17#include "PrimType.h"
18#include "Program.h"
19#include "clang/AST/Expr.h"
21
22using namespace clang;
23using namespace clang::interp;
24
25Context::Context(ASTContext &Ctx) : Ctx(Ctx), P(new Program(*this)) {}
26
28
30 assert(Stk.empty());
31 Function *Func = P->getFunction(FD);
32 if (!Func || !Func->hasBody()) {
33 if (auto R = ByteCodeStmtGen<ByteCodeEmitter>(*this, *P).compileFunc(FD)) {
34 Func = *R;
35 } else {
36 handleAllErrors(R.takeError(), [&Parent](ByteCodeGenError &Err) {
37 Parent.FFDiag(Err.getRange().getBegin(),
38 diag::err_experimental_clang_interp_failed)
39 << Err.getRange();
40 });
41 return false;
42 }
43 }
44
45 APValue DummyResult;
46 if (!Run(Parent, Func, DummyResult)) {
47 return false;
48 }
49
50 return Func->isConstexpr();
51}
52
54 assert(Stk.empty());
56 if (Check(Parent, C.interpretExpr(E))) {
57 assert(Stk.empty());
58#ifndef NDEBUG
59 // Make sure we don't rely on some value being still alive in
60 // InterpStack memory.
61 Stk.clear();
62#endif
63 return true;
64 }
65
66 Stk.clear();
67 return false;
68}
69
71 APValue &Result) {
72 assert(Stk.empty());
74 if (Check(Parent, C.interpretDecl(VD))) {
75 assert(Stk.empty());
76#ifndef NDEBUG
77 // Make sure we don't rely on some value being still alive in
78 // InterpStack memory.
79 Stk.clear();
80#endif
81 return true;
82 }
83
84 Stk.clear();
85 return false;
86}
87
88const LangOptions &Context::getLangOpts() const { return Ctx.getLangOpts(); }
89
90std::optional<PrimType> Context::classify(QualType T) const {
91 if (T->isBooleanType())
92 return PT_Bool;
93
95 switch (Ctx.getIntWidth(T)) {
96 case 64:
97 return PT_Sint64;
98 case 32:
99 return PT_Sint32;
100 case 16:
101 return PT_Sint16;
102 case 8:
103 return PT_Sint8;
104 default:
105 return std::nullopt;
106 }
107 }
108
110 switch (Ctx.getIntWidth(T)) {
111 case 64:
112 return PT_Uint64;
113 case 32:
114 return PT_Uint32;
115 case 16:
116 return PT_Uint16;
117 case 8:
118 return PT_Uint8;
119 default:
120 return std::nullopt;
121 }
122 }
123
124 if (T->isNullPtrType())
125 return PT_Ptr;
126
127 if (T->isFloatingType())
128 return PT_Float;
129
131 T->isFunctionType() || T->isSpecificBuiltinType(BuiltinType::BoundMember))
132 return PT_FnPtr;
133
134 if (T->isReferenceType() || T->isPointerType())
135 return PT_Ptr;
136
137 if (const auto *AT = dyn_cast<AtomicType>(T))
138 return classify(AT->getValueType());
139
140 if (const auto *DT = dyn_cast<DecltypeType>(T))
141 return classify(DT->getUnderlyingType());
142
143 if (const auto *DT = dyn_cast<MemberPointerType>(T))
144 return classify(DT->getPointeeType());
145
146 return std::nullopt;
147}
148
149unsigned Context::getCharBit() const {
150 return Ctx.getTargetInfo().getCharWidth();
151}
152
153/// Simple wrapper around getFloatTypeSemantics() to make code a
154/// little shorter.
155const llvm::fltSemantics &Context::getFloatSemantics(QualType T) const {
156 return Ctx.getFloatTypeSemantics(T);
157}
158
159bool Context::Run(State &Parent, const Function *Func, APValue &Result) {
160 InterpState State(Parent, *P, Stk, *this);
161 State.Current = new InterpFrame(State, Func, /*Caller=*/nullptr, {});
162 if (Interpret(State, Result))
163 return true;
164 Stk.clear();
165 return false;
166}
167
168bool Context::Check(State &Parent, llvm::Expected<bool> &&Flag) {
169 if (Flag)
170 return *Flag;
171 handleAllErrors(Flag.takeError(), [&Parent](ByteCodeGenError &Err) {
172 Parent.FFDiag(Err.getRange().getBegin(),
173 diag::err_experimental_clang_interp_failed)
174 << Err.getRange();
175 });
176 return false;
177}
178
179// TODO: Virtual bases?
180const CXXMethodDecl *
182 const CXXRecordDecl *StaticDecl,
183 const CXXMethodDecl *InitialFunction) const {
184
185 const CXXRecordDecl *CurRecord = DynamicDecl;
186 const CXXMethodDecl *FoundFunction = InitialFunction;
187 for (;;) {
188 const CXXMethodDecl *Overrider =
189 FoundFunction->getCorrespondingMethodDeclaredInClass(CurRecord, false);
190 if (Overrider)
191 return Overrider;
192
193 // Common case of only one base class.
194 if (CurRecord->getNumBases() == 1) {
195 CurRecord = CurRecord->bases_begin()->getType()->getAsCXXRecordDecl();
196 continue;
197 }
198
199 // Otherwise, go to the base class that will lead to the StaticDecl.
200 for (const CXXBaseSpecifier &Spec : CurRecord->bases()) {
201 const CXXRecordDecl *Base = Spec.getType()->getAsCXXRecordDecl();
202 if (Base == StaticDecl || Base->isDerivedFrom(StaticDecl)) {
203 CurRecord = Base;
204 break;
205 }
206 }
207 }
208
209 llvm_unreachable(
210 "Couldn't find an overriding function in the class hierarchy?");
211 return nullptr;
212}
213
215 assert(FD);
216 const Function *Func = P->getFunction(FD);
217 bool IsBeingCompiled = Func && !Func->isFullyCompiled();
218 bool WasNotDefined = Func && !Func->isConstexpr() && !Func->hasBody();
219
220 if (IsBeingCompiled)
221 return Func;
222
223 if (!Func || WasNotDefined) {
224 if (auto R = ByteCodeStmtGen<ByteCodeEmitter>(*this, *P).compileFunc(FD))
225 Func = *R;
226 else {
227 llvm::consumeError(R.takeError());
228 return nullptr;
229 }
230 }
231
232 return Func;
233}
NodeId Parent
Definition: ASTDiff.cpp:191
StringRef P
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition: APValue.h:122
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition: ASTContext.h:182
unsigned getIntWidth(QualType T) const
const llvm::fltSemantics & getFloatTypeSemantics(QualType T) const
Return the APFloat 'semantics' for the specified scalar floating point type.
const LangOptions & getLangOpts() const
Definition: ASTContext.h:761
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:743
Represents a base class of a C++ class.
Definition: DeclCXX.h:146
QualType getType() const
Retrieves the type of the base class.
Definition: DeclCXX.h:245
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2035
CXXMethodDecl * getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD, bool MayBeBase=false)
Find if RD declares a function that overrides this function, and if so, return it.
Definition: DeclCXX.cpp:2166
Represents a C++ struct/union/class.
Definition: DeclCXX.h:254
base_class_range bases()
Definition: DeclCXX.h:606
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:600
base_class_iterator bases_begin()
Definition: DeclCXX.h:613
This represents one expression.
Definition: Expr.h:110
Represents a function declaration or definition.
Definition: Decl.h:1919
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:83
A (possibly-)qualified type.
Definition: Type.h:736
unsigned getCharWidth() const
Definition: TargetInfo.h:474
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1823
bool isBooleanType() const
Definition: Type.h:7433
bool isFunctionReferenceType() const
Definition: Type.h:7040
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2108
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2158
bool isFunctionPointerType() const
Definition: Type.h:7033
bool isPointerType() const
Definition: Type.h:6999
bool isReferenceType() const
Definition: Type.h:7011
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7286
bool isFunctionType() const
Definition: Type.h:6995
bool isFloatingType() const
Definition: Type.cpp:2190
bool isNullPtrType() const
Definition: Type.h:7342
Represents a variable declaration or definition.
Definition: Decl.h:915
Compilation context for expressions.
Compilation context for statements.
const LangOptions & getLangOpts() const
Returns the language options.
Definition: Context.cpp:88
~Context()
Cleans up the constexpr VM.
Definition: Context.cpp:27
Context(ASTContext &Ctx)
Initialises the constexpr VM.
Definition: Context.cpp:25
unsigned getCharBit() const
Returns CHAR_BIT.
Definition: Context.cpp:149
bool evaluateAsInitializer(State &Parent, const VarDecl *VD, APValue &Result)
Evaluates a toplevel initializer.
Definition: Context.cpp:70
const llvm::fltSemantics & getFloatSemantics(QualType T) const
Return the floating-point semantics for T.
Definition: Context.cpp:155
bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FnDecl)
Checks if a function is a potential constant expression.
Definition: Context.cpp:29
bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
Definition: Context.cpp:53
const CXXMethodDecl * getOverridingFunction(const CXXRecordDecl *DynamicDecl, const CXXRecordDecl *StaticDecl, const CXXMethodDecl *InitialFunction) const
Definition: Context.cpp:181
std::optional< PrimType > classify(QualType T) const
Classifies an expression.
Definition: Context.cpp:90
const Function * getOrCreateFunction(const FunctionDecl *FD)
Definition: Context.cpp:214
Bytecode function.
Definition: Function.h:75
bool isFullyCompiled() const
Checks if the function is fully done compiling.
Definition: Function.h:165
bool hasBody() const
Checks if the function already has a body attached.
Definition: Function.h:170
bool isConstexpr() const
Checks if the function is valid to call in constexpr.
Definition: Function.h:131
Frame storing local variables.
Definition: InterpFrame.h:28
void clear()
Clears the stack without calling any destructors.
Definition: InterpStack.cpp:23
bool empty() const
Returns whether the stack is empty.
Definition: InterpStack.h:90
Interpreter context.
Definition: InterpState.h:35
The program contains and links the bytecode for all functions.
Definition: Program.h:40
Interface for the VM to interact with the AST walker's context.
Definition: State.h:55
Defines the clang::TargetInfo interface.
bool Interpret(InterpState &S, APValue &Result)
Interpreter entry point.
Definition: Interp.cpp:577
@ C
Languages that the frontend can parse and compile.
@ Result
The result type of a method or function.
Error thrown by the compiler.