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/ASTContext.h"
21
22namespace clang {
23class LangOptions;
24class FunctionDecl;
25class VarDecl;
26class APValue;
27class BlockExpr;
28
29namespace interp {
30class Function;
31class Program;
32class State;
33enum PrimType : uint8_t;
34
35struct ParamOffset {
36 unsigned Offset;
37 bool IsPtr;
38};
39
40class EvalIDScope;
41/// Holds all information required to evaluate constexpr code in a module.
42class Context final {
43public:
44 /// Initialises the constexpr VM.
45 Context(ASTContext &Ctx);
46
47 /// Cleans up the constexpr VM.
48 ~Context();
49
50 /// Checks if a function is a potential constant expression.
51 bool isPotentialConstantExpr(State &Parent, const FunctionDecl *FD);
52 void isPotentialConstantExprUnevaluated(State &Parent, const Expr *E,
53 const FunctionDecl *FD);
54
55 /// Evaluates a toplevel expression as an rvalue.
56 bool evaluateAsRValue(State &Parent, const Expr *E, APValue &Result);
57
58 /// Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
59 bool evaluate(State &Parent, const Expr *E, APValue &Result,
60 ConstantExprKind Kind);
61
62 /// Evaluates a toplevel initializer.
63 bool evaluateAsInitializer(State &Parent, const VarDecl *VD, const Expr *Init,
64 APValue &Result);
65
66 bool evaluateCharRange(State &Parent, const Expr *SizeExpr,
67 const Expr *PtrExpr, APValue &Result);
68 bool evaluateCharRange(State &Parent, const Expr *SizeExpr,
69 const Expr *PtrExpr, std::string &Result);
70
71 /// Evaluate \param E and if it can be evaluated to a null-terminated string,
72 /// copy the result into \param Result.
73 bool evaluateString(State &Parent, const Expr *E, std::string &Result);
74
75 /// Evalute \param E and if it can be evaluated to a string literal,
76 /// run strlen() on it.
77 std::optional<uint64_t> evaluateStrlen(State &Parent, const Expr *E);
78
79 /// If \param E evaluates to a pointer the number of accessible bytes
80 /// past the pointer is estimated in \param Result as if evaluated by
81 /// the builtin function __builtin_object_size. This is a best effort
82 /// approximation, when Kind & 2 == 0 the object size is less
83 /// than or equal to the estimated size, when Kind & 2 == 1 the
84 /// true value is greater than or equal to the estimated size.
85 /// When Kind & 1 == 1 only bytes belonging to the same subobject
86 /// as the one referred to by E are considered, when Kind & 1 == 0
87 /// bytes belonging to the same storage (stack, heap allocation,
88 /// global variable) are considered.
89 std::optional<uint64_t> tryEvaluateObjectSize(State &Parent, const Expr *E,
90 unsigned Kind);
91
92 /// Returns the AST context.
93 ASTContext &getASTContext() const { return Ctx; }
94 /// Returns the language options.
95 const LangOptions &getLangOpts() const;
96 /// Returns CHAR_BIT.
97 unsigned getCharBit() const;
98 /// Return the floating-point semantics for T.
99 const llvm::fltSemantics &getFloatSemantics(QualType T) const;
100 /// Return the size of T in bits.
101 uint32_t getBitWidth(QualType T) const { return Ctx.getIntWidth(T); }
102
103 /// Classifies a type.
104 OptPrimType classify(QualType T) const;
105
106 /// Classifies an expression.
107 OptPrimType classify(const Expr *E) const {
108 assert(E);
109 if (E->isGLValue())
110 return PT_Ptr;
111
112 return classify(T: E->getType());
113 }
114
115 bool canClassify(QualType T) const {
116 if (const auto *BT = dyn_cast<BuiltinType>(Val&: T)) {
117 if (BT->isInteger() || BT->isFloatingPoint())
118 return true;
119 if (BT->getKind() == BuiltinType::Bool)
120 return true;
121 }
122 if (T->isPointerOrReferenceType())
123 return true;
124
125 if (T->isArrayType() || T->isRecordType() || T->isAnyComplexType() ||
126 T->isVectorType())
127 return false;
128 return classify(T) != std::nullopt;
129 }
130 bool canClassify(const Expr *E) const {
131 if (E->isGLValue())
132 return true;
133 return canClassify(T: E->getType());
134 }
135
136 const CXXMethodDecl *
137 getOverridingFunction(const CXXRecordDecl *DynamicDecl,
138 const CXXRecordDecl *StaticDecl,
139 const CXXMethodDecl *InitialFunction) const;
140
141 const Function *getOrCreateFunction(const FunctionDecl *FuncDecl);
142 const Function *getOrCreateObjCBlock(const BlockExpr *E);
143
144 /// Returns whether we should create a global variable for the
145 /// given ValueDecl.
146 static bool shouldBeGloballyIndexed(const ValueDecl *VD) {
147 if (const auto *V = dyn_cast<VarDecl>(Val: VD))
148 return V->hasGlobalStorage() || V->isConstexpr();
149
150 return false;
151 }
152
153 /// Returns the program. This is only needed for unittests.
154 Program &getProgram() const { return *P; }
155
156 unsigned collectBaseOffset(const RecordDecl *BaseDecl,
157 const RecordDecl *DerivedDecl) const;
158
159 const Record *getRecord(const RecordDecl *D) const;
160
161 unsigned getEvalID() const { return EvalID; }
162
163 /// Unevaluated builtins don't get their arguments put on the stack
164 /// automatically. They instead operate on the AST of their Call
165 /// Expression.
166 /// Similar information is available via ASTContext::BuiltinInfo,
167 /// but that is not correct for our use cases.
168 static bool isUnevaluatedBuiltin(unsigned ID);
169
170private:
171 friend class EvalIDScope;
172 /// Runs a function.
173 bool Run(State &Parent, const Function *Func);
174
175 template <typename ResultT>
176 bool evaluateStringRepr(State &Parent, const Expr *SizeExpr,
177 const Expr *PtrExpr, ResultT &Result);
178
179 /// Current compilation context.
180 ASTContext &Ctx;
181 /// Interpreter stack, shared across invocations.
182 InterpStack Stk;
183 /// Constexpr program.
184 std::unique_ptr<Program> P;
185 /// ID identifying an evaluation.
186 unsigned EvalID = 0;
187 /// Cached widths (in bits) of common types, for a faster classify().
188 unsigned ShortWidth;
189 unsigned IntWidth;
190 unsigned LongWidth;
191 unsigned LongLongWidth;
192};
193
194class EvalIDScope {
195public:
196 EvalIDScope(Context &Ctx) : Ctx(Ctx), OldID(Ctx.EvalID) { ++Ctx.EvalID; }
197 ~EvalIDScope() { Ctx.EvalID = OldID; }
198
199private:
200 Context &Ctx;
201 const unsigned OldID;
202};
203
204} // namespace interp
205} // namespace clang
206
207#endif
208