clang 19.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 Func = ByteCodeStmtGen<ByteCodeEmitter>(*this, *P).compileFunc(FD);
34
35 APValue DummyResult;
36 if (!Run(Parent, Func, DummyResult))
37 return false;
38
39 return Func->isConstexpr();
40}
41
43 bool Recursing = !Stk.empty();
44 ByteCodeExprGen<EvalEmitter> C(*this, *P, Parent, Stk);
45
46 auto Res = C.interpretExpr(E, /*ConvertResultToRValue=*/E->isGLValue());
47
48 if (Res.isInvalid()) {
49 Stk.clear();
50 return false;
51 }
52
53 if (!Recursing) {
54 assert(Stk.empty());
55#ifndef NDEBUG
56 // Make sure we don't rely on some value being still alive in
57 // InterpStack memory.
58 Stk.clear();
59#endif
60 }
61
62 Result = Res.toAPValue();
63
64 return true;
65}
66
68 bool Recursing = !Stk.empty();
69 ByteCodeExprGen<EvalEmitter> C(*this, *P, Parent, Stk);
70
71 auto Res = C.interpretExpr(E);
72 if (Res.isInvalid()) {
73 Stk.clear();
74 return false;
75 }
76
77 if (!Recursing) {
78 assert(Stk.empty());
79#ifndef NDEBUG
80 // Make sure we don't rely on some value being still alive in
81 // InterpStack memory.
82 Stk.clear();
83#endif
84 }
85
86 Result = Res.toAPValue();
87 return true;
88}
89
91 APValue &Result) {
92 bool Recursing = !Stk.empty();
93 ByteCodeExprGen<EvalEmitter> C(*this, *P, Parent, Stk);
94
97 (VD->getType()->isRecordType() || VD->getType()->isArrayType());
98 auto Res = C.interpretDecl(VD, CheckGlobalInitialized);
99 if (Res.isInvalid()) {
100 Stk.clear();
101 return false;
102 }
103
104 if (!Recursing) {
105 assert(Stk.empty());
106#ifndef NDEBUG
107 // Make sure we don't rely on some value being still alive in
108 // InterpStack memory.
109 Stk.clear();
110#endif
111 }
112
113 Result = Res.toAPValue();
114 return true;
115}
116
117const LangOptions &Context::getLangOpts() const { return Ctx.getLangOpts(); }
118
119std::optional<PrimType> Context::classify(QualType T) const {
120 if (T->isBooleanType())
121 return PT_Bool;
122
123 if (T->isAnyComplexType())
124 return std::nullopt;
125
127 switch (Ctx.getIntWidth(T)) {
128 case 64:
129 return PT_Sint64;
130 case 32:
131 return PT_Sint32;
132 case 16:
133 return PT_Sint16;
134 case 8:
135 return PT_Sint8;
136 default:
137 return PT_IntAPS;
138 }
139 }
140
142 switch (Ctx.getIntWidth(T)) {
143 case 64:
144 return PT_Uint64;
145 case 32:
146 return PT_Uint32;
147 case 16:
148 return PT_Uint16;
149 case 8:
150 return PT_Uint8;
151 default:
152 return PT_IntAP;
153 }
154 }
155
156 if (T->isNullPtrType())
157 return PT_Ptr;
158
159 if (T->isFloatingType())
160 return PT_Float;
161
163 T->isFunctionType() || T->isSpecificBuiltinType(BuiltinType::BoundMember))
164 return PT_FnPtr;
165
166 if (T->isReferenceType() || T->isPointerType())
167 return PT_Ptr;
168
169 if (const auto *AT = T->getAs<AtomicType>())
170 return classify(AT->getValueType());
171
172 if (const auto *DT = dyn_cast<DecltypeType>(T))
173 return classify(DT->getUnderlyingType());
174
175 if (const auto *DT = dyn_cast<MemberPointerType>(T))
176 return classify(DT->getPointeeType());
177
178 return std::nullopt;
179}
180
181unsigned Context::getCharBit() const {
182 return Ctx.getTargetInfo().getCharWidth();
183}
184
185/// Simple wrapper around getFloatTypeSemantics() to make code a
186/// little shorter.
187const llvm::fltSemantics &Context::getFloatSemantics(QualType T) const {
188 return Ctx.getFloatTypeSemantics(T);
189}
190
191bool Context::Run(State &Parent, const Function *Func, APValue &Result) {
192
193 {
194 InterpState State(Parent, *P, Stk, *this);
195 State.Current = new InterpFrame(State, Func, /*Caller=*/nullptr, CodePtr(),
196 Func->getArgSize());
197 if (Interpret(State, Result)) {
198 assert(Stk.empty());
199 return true;
200 }
201
202 // State gets destroyed here, so the Stk.clear() below doesn't accidentally
203 // remove values the State's destructor might access.
204 }
205
206 Stk.clear();
207 return false;
208}
209
210// TODO: Virtual bases?
211const CXXMethodDecl *
213 const CXXRecordDecl *StaticDecl,
214 const CXXMethodDecl *InitialFunction) const {
215 assert(DynamicDecl);
216 assert(StaticDecl);
217 assert(InitialFunction);
218
219 const CXXRecordDecl *CurRecord = DynamicDecl;
220 const CXXMethodDecl *FoundFunction = InitialFunction;
221 for (;;) {
222 const CXXMethodDecl *Overrider =
223 FoundFunction->getCorrespondingMethodDeclaredInClass(CurRecord, false);
224 if (Overrider)
225 return Overrider;
226
227 // Common case of only one base class.
228 if (CurRecord->getNumBases() == 1) {
229 CurRecord = CurRecord->bases_begin()->getType()->getAsCXXRecordDecl();
230 continue;
231 }
232
233 // Otherwise, go to the base class that will lead to the StaticDecl.
234 for (const CXXBaseSpecifier &Spec : CurRecord->bases()) {
235 const CXXRecordDecl *Base = Spec.getType()->getAsCXXRecordDecl();
236 if (Base == StaticDecl || Base->isDerivedFrom(StaticDecl)) {
237 CurRecord = Base;
238 break;
239 }
240 }
241 }
242
243 llvm_unreachable(
244 "Couldn't find an overriding function in the class hierarchy?");
245 return nullptr;
246}
247
249 assert(FD);
250 const Function *Func = P->getFunction(FD);
251 bool IsBeingCompiled = Func && Func->isDefined() && !Func->isFullyCompiled();
252 bool WasNotDefined = Func && !Func->isConstexpr() && !Func->isDefined();
253
254 if (IsBeingCompiled)
255 return Func;
256
257 if (!Func || WasNotDefined) {
258 if (auto F = ByteCodeStmtGen<ByteCodeEmitter>(*this, *P).compileFunc(FD))
259 Func = F;
260 }
261
262 return Func;
263}
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:772
const TargetInfo & getTargetInfo() const
Definition: ASTContext.h:754
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:249
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2053
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:2207
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
base_class_range bases()
Definition: DeclCXX.h:618
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition: DeclCXX.h:612
base_class_iterator bases_begin()
Definition: DeclCXX.h:625
This represents one expression.
Definition: Expr.h:110
bool isGLValue() const
Definition: Expr.h:280
Represents a function declaration or definition.
Definition: Decl.h:1959
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Definition: LangOptions.h:449
A (possibly-)qualified type.
Definition: Type.h:738
unsigned getCharWidth() const
Definition: TargetInfo.h:488
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition: Type.cpp:1862
bool isBooleanType() const
Definition: Type.h:7788
bool isFunctionReferenceType() const
Definition: Type.h:7412
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition: Type.cpp:2147
bool isUnsignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is unsigned or an enumeration types whose underlying ...
Definition: Type.cpp:2197
bool isArrayType() const
Definition: Type.h:7437
bool isFunctionPointerType() const
Definition: Type.h:7405
bool isPointerType() const
Definition: Type.h:7371
bool isReferenceType() const
Definition: Type.h:7383
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition: Type.h:7629
bool isAnyComplexType() const
Definition: Type.h:7469
bool isFunctionType() const
Definition: Type.h:7367
bool isFloatingType() const
Definition: Type.cpp:2229
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:7878
bool isNullPtrType() const
Definition: Type.h:7693
bool isRecordType() const
Definition: Type.h:7461
QualType getType() const
Definition: Decl.h:717
Represents a variable declaration or definition.
Definition: Decl.h:918
Compilation context for expressions.
Compilation context for statements.
Pointer into the code segment.
Definition: Source.h:30
const LangOptions & getLangOpts() const
Returns the language options.
Definition: Context.cpp:117
~Context()
Cleans up the constexpr VM.
Definition: Context.cpp:27
Context(ASTContext &Ctx)
Initialises the constexpr VM.
Definition: Context.cpp:25
bool evaluate(State &Parent, const Expr *E, APValue &Result)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
Definition: Context.cpp:67
unsigned getCharBit() const
Returns CHAR_BIT.
Definition: Context.cpp:181
bool evaluateAsInitializer(State &Parent, const VarDecl *VD, APValue &Result)
Evaluates a toplevel initializer.
Definition: Context.cpp:90
const llvm::fltSemantics & getFloatSemantics(QualType T) const
Return the floating-point semantics for T.
Definition: Context.cpp:187
static bool shouldBeGloballyIndexed(const ValueDecl *VD)
Returns whether we should create a global variable for the given ValueDecl.
Definition: Context.h:97
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:42
const CXXMethodDecl * getOverridingFunction(const CXXRecordDecl *DynamicDecl, const CXXRecordDecl *StaticDecl, const CXXMethodDecl *InitialFunction) const
Definition: Context.cpp:212
std::optional< PrimType > classify(QualType T) const
Classifies a type.
Definition: Context.cpp:119
const Function * getOrCreateFunction(const FunctionDecl *FD)
Definition: Context.cpp:248
Bytecode function.
Definition: Function.h:77
Frame storing local variables.
Definition: InterpFrame.h:28
void clear()
Clears the stack without calling any destructors.
Definition: InterpStack.cpp:24
bool empty() const
Returns whether the stack is empty.
Definition: InterpStack.h:91
Interpreter context.
Definition: InterpState.h:35
The program contains and links the bytecode for all functions.
Definition: Program.h:39
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:664
bool CheckGlobalInitialized(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Check if a global variable is initialized.
Definition: Interp.cpp:377
The JSON file list parser is used to communicate input to InstallAPI.
@ Result
The result type of a method or function.