clang 24.0.0git
Context.h
Go to the documentation of this file.
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 "FrameAllocator.h"
20#include "InterpStack.h"
22
23namespace clang {
24class LangOptions;
25class FunctionDecl;
26class VarDecl;
27class APValue;
28class BlockExpr;
29
30namespace interp {
31class Function;
32class Program;
33class State;
34enum PrimType : uint8_t;
35
37 unsigned Offset;
38 bool IsPtr;
39};
40
41struct FuncParam {
42 unsigned Index;
43 bool IsPtr;
44};
45
46class EvalIDScope;
47/// Holds all information required to evaluate constexpr code in a module.
48class Context final {
49public:
50 /// Initialises the constexpr VM.
51 explicit Context(ASTContext &Ctx);
52
53 /// Cleans up the constexpr VM.
55
56 /// Checks if a function is a potential constant expression.
57 bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FD);
58 void isPotentialConstantExprUnevaluated(State &Parent, const Expr *E,
59 const FunctionDecl *FD);
60
61 /// Evaluates a toplevel expression as an rvalue.
62 bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result);
63
64 /// Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
65 bool evaluate(State &Parent, const Expr *E, APValue &Result,
66 ConstantExprKind Kind);
67
68 /// Evaluates a toplevel initializer.
69 bool evaluateAsInitializer(State &Parent, const VarDecl *VD, const Expr *Init,
71 void registerRedecl(const VarDecl *VD, const APValue &V);
72
73 /// Evaluates the destruction of a variable.
74 bool evaluateDestruction(State &Parent, const VarDecl *VD, APValue Value);
75
76 bool evaluateCharRange(State &Parent, const Expr *SizeExpr,
77 const Expr *PtrExpr, APValue &Result);
78 bool evaluateCharRange(State &Parent, const Expr *SizeExpr,
79 const Expr *PtrExpr, std::string &Result);
80
81 /// Evaluate \param E and if it can be evaluated to a null-terminated string,
82 /// copy the result into \param Result.
83 bool evaluateString(State &Parent, const Expr *E, std::string &Result);
84
85 /// Evalute \param E and if it can be evaluated to a string literal,
86 /// run strlen() on it.
87 std::optional<uint64_t> evaluateStrlen(State &Parent, const Expr *E);
88
89 /// If \param E evaluates to a pointer the number of accessible bytes
90 /// past the pointer is estimated in \param Result as if evaluated by
91 /// the builtin function __builtin_object_size. This is a best effort
92 /// approximation, when Kind & 2 == 0 the object size is less
93 /// than or equal to the estimated size, when Kind & 2 == 1 the
94 /// true value is greater than or equal to the estimated size.
95 /// When Kind & 1 == 1 only bytes belonging to the same subobject
96 /// as the one referred to by E are considered, when Kind & 1 == 0
97 /// bytes belonging to the same storage (stack, heap allocation,
98 /// global variable) are considered.
99 std::optional<uint64_t> tryEvaluateObjectSize(State &Parent, const Expr *E,
100 unsigned Kind, bool IsDynamic);
101
102 std::optional<bool> evaluateWithSubstitution(State &Parent,
103 const FunctionDecl *Callee,
105 const Expr *This,
106 const Expr *Condition);
107
108 /// Returns the AST context.
109 ASTContext &getASTContext() const { return Ctx; }
110 /// Returns the language options.
111 const LangOptions &getLangOpts() const;
112 /// Returns CHAR_BIT.
113 unsigned getCharBit() const;
114 /// Return the floating-point semantics for T.
115 const llvm::fltSemantics &getFloatSemantics(QualType T) const;
116 /// Return the size of T in bits.
117 uint32_t getBitWidth(QualType T) const { return Ctx.getIntWidth(T); }
118
119 /// Classifies a type.
121
122 /// Classifies an expression.
123 OptPrimType classify(const Expr *E) const {
124 assert(E);
125 if (E->isGLValue())
126 return PT_Ptr;
127
128 return classify(E->getType());
129 }
130
131 bool canClassify(QualType T) const {
132 T = T.getCanonicalType();
133 if (const auto *BT = dyn_cast<BuiltinType>(T)) {
134 if (BT->isInteger() || BT->isFloatingPoint())
135 return true;
136 if (BT->getKind() == BuiltinType::NullPtr ||
137 BT->getKind() == BuiltinType::BoundMember)
138 return true;
139 }
140 if (T->isPointerOrReferenceType())
141 return true;
142
143 if (T->isArrayType() || T->isRecordType() || T->isAnyComplexType() ||
144 T->isVectorType())
145 return false;
146
147 if (T->isEnumeralType())
148 return true;
149
150 return classify(T) != std::nullopt;
151 }
152 bool canClassify(const Expr *E) const {
153 if (E->isGLValue())
154 return true;
155 return canClassify(E->getType());
156 }
157
158 const CXXMethodDecl *
159 getOverridingFunction(const CXXRecordDecl *DynamicDecl,
160 const CXXRecordDecl *StaticDecl,
161 const CXXMethodDecl *InitialFunction) const;
162
163 const Function *getOrCreateFunction(const FunctionDecl *FuncDecl);
164 const Function *getOrCreateObjCBlock(const BlockExpr *E);
165
166 /// Returns whether we should create a global variable for the
167 /// given ValueDecl.
168 static bool shouldBeGloballyIndexed(const ValueDecl *VD) {
169 if (const auto *V = dyn_cast<VarDecl>(VD))
170 return V->hasGlobalStorage() || V->isConstexpr();
171
172 return false;
173 }
174
175 /// Returns the program. This is only needed for unittests.
176 Program &getProgram() const { return *P; }
177
178 unsigned collectBaseOffset(const RecordDecl *BaseDecl,
179 const RecordDecl *DerivedDecl) const;
180
181 const Record *getRecord(const RecordDecl *D) const;
182
183 unsigned getEvalID() const { return EvalID; }
184
185 /// Unevaluated builtins don't get their arguments put on the stack
186 /// automatically. They instead operate on the AST of their Call
187 /// Expression.
188 /// Similar information is available via ASTContext::BuiltinInfo,
189 /// but that is not correct for our use cases.
190 static bool isUnevaluatedBuiltin(unsigned ID);
191
192private:
193 friend class EvalIDScope;
194 /// Runs a function.
195 bool Run(State &Parent, const Function *Func);
196
197 template <typename ResultT>
198 bool evaluateStringRepr(State &Parent, const Expr *SizeExpr,
199 const Expr *PtrExpr, ResultT &Result);
200
201 /// Current compilation context.
202 ASTContext &Ctx;
203 /// Interpreter stack, shared across invocations.
204 InterpStack Stk;
205 /// (Function) frame allocator, also shared.
206 FrameAllocator FrameAlloc;
207 /// Constexpr program.
208 std::unique_ptr<Program> P;
209 /// ID identifying an evaluation.
210 unsigned EvalID = 0;
211 /// Cached widths (in bits) of common types, for a faster classify().
212 unsigned ShortWidth;
213 unsigned IntWidth;
214 unsigned LongWidth;
215 unsigned LongLongWidth;
216};
217
219public:
220 EvalIDScope(Context &Ctx) : Ctx(Ctx), OldID(Ctx.EvalID) { ++Ctx.EvalID; }
221 ~EvalIDScope() { Ctx.EvalID = OldID; }
222 EvalIDScope(const EvalIDScope &) = delete;
224
225private:
226 Context &Ctx;
227 const unsigned OldID;
228};
229
230} // namespace interp
231} // namespace clang
232
233#endif
Defines the clang::ASTContext interface.
#define V(N, I)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:123
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:239
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6722
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
This represents one expression.
Definition Expr.h:113
bool isGLValue() const
Definition Expr.h:288
QualType getType() const
Definition Expr.h:145
Represents a function declaration or definition.
Definition Decl.h:2059
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
A (possibly-)qualified type.
Definition TypeBase.h:938
Represents a struct/union/class.
Definition Decl.h:4460
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:713
Represents a variable declaration or definition.
Definition Decl.h:933
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:48
const LangOptions & getLangOpts() const
Returns the language options.
Definition Context.cpp:478
void registerRedecl(const VarDecl *VD, const APValue &V)
Definition Context.cpp:181
OptPrimType classify(const Expr *E) const
Classifies an expression.
Definition Context.h:123
const Function * getOrCreateObjCBlock(const BlockExpr *E)
Definition Context.cpp:754
~Context()
Cleans up the constexpr VM.
Context(ASTContext &Ctx)
Initialises the constexpr VM.
Definition Context.cpp:29
bool evaluateCharRange(State &Parent, const Expr *SizeExpr, const Expr *PtrExpr, APValue &Result)
Definition Context.cpp:272
std::optional< uint64_t > evaluateStrlen(State &Parent, const Expr *E)
Evalute.
Definition Context.cpp:353
std::optional< bool > evaluateWithSubstitution(State &Parent, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This, const Expr *Condition)
Definition Context.cpp:452
friend class EvalIDScope
Definition Context.h:193
bool evaluateString(State &Parent, const Expr *E, std::string &Result)
Evaluate.
Definition Context.cpp:288
static bool isUnevaluatedBuiltin(unsigned ID)
Unevaluated builtins don't get their arguments put on the stack automatically.
Definition Context.cpp:827
unsigned getCharBit() const
Returns CHAR_BIT.
Definition Context.cpp:592
bool canClassify(const Expr *E) const
Definition Context.h:152
Program & getProgram() const
Returns the program. This is only needed for unittests.
Definition Context.h:176
const llvm::fltSemantics & getFloatSemantics(QualType T) const
Return the floating-point semantics for T.
Definition Context.cpp:598
static bool shouldBeGloballyIndexed(const ValueDecl *VD)
Returns whether we should create a global variable for the given ValueDecl.
Definition Context.h:168
std::optional< uint64_t > tryEvaluateObjectSize(State &Parent, const Expr *E, unsigned Kind, bool IsDynamic)
If.
Definition Context.cpp:419
void isPotentialConstantExprUnevaluated(State &Parent, const Expr *E, const FunctionDecl *FD)
Definition Context.cpp:60
unsigned collectBaseOffset(const RecordDecl *BaseDecl, const RecordDecl *DerivedDecl) const
Definition Context.cpp:792
bool evaluateDestruction(State &Parent, const VarDecl *VD, APValue Value)
Evaluates the destruction of a variable.
Definition Context.cpp:163
const Record * getRecord(const RecordDecl *D) const
Definition Context.cpp:823
bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FD)
Checks if a function is a potential constant expression.
Definition Context.cpp:40
const Function * getOrCreateFunction(const FunctionDecl *FuncDecl)
Definition Context.cpp:657
ASTContext & getASTContext() const
Returns the AST context.
Definition Context.h:109
uint32_t getBitWidth(QualType T) const
Return the size of T in bits.
Definition Context.h:117
OptPrimType classify(QualType T) const
Classifies a type.
Definition Context.cpp:512
bool canClassify(QualType T) const
Definition Context.h:131
bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
Definition Context.cpp:73
const CXXMethodDecl * getOverridingFunction(const CXXRecordDecl *DynamicDecl, const CXXRecordDecl *StaticDecl, const CXXMethodDecl *InitialFunction) const
Definition Context.cpp:621
bool evaluate(State &Parent, const Expr *E, APValue &Result, ConstantExprKind Kind)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
Definition Context.cpp:102
bool evaluateAsInitializer(State &Parent, const VarDecl *VD, const Expr *Init, APValue &Result)
Evaluates a toplevel initializer.
Definition Context.cpp:131
unsigned getEvalID() const
Definition Context.h:183
EvalIDScope & operator=(const EvalIDScope &)=delete
EvalIDScope(const EvalIDScope &)=delete
EvalIDScope(Context &Ctx)
Definition Context.h:220
Allocator for function frames.
Bytecode function.
Definition Function.h:98
Stack frame storing temporaries and parameters.
Definition InterpStack.h:25
The program contains and links the bytecode for all functions.
Definition Program.h:37
Structure/Class descriptor.
Definition Record.h:27
Interface for the VM to interact with the AST walker's context.
Definition State.h:79
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3228
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2425
Top level wrappers for InstallAPI frontend operations.
Expr::ConstantExprKind ConstantExprKind
Definition Expr.h:1062
@ Result
The result type of a method or function.
Definition TypeBase.h:906
const FunctionProtoType * T
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 uint8_t
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat uint32_t __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t