clang 22.0.0git
Program.h
Go to the documentation of this file.
1//===--- Program.h - Bytecode 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 a program which organises and links multiple bytecode functions.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_INTERP_PROGRAM_H
14#define LLVM_CLANG_AST_INTERP_PROGRAM_H
15
16#include "Function.h"
17#include "Pointer.h"
18#include "PrimType.h"
19#include "Record.h"
20#include "Source.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/Support/Allocator.h"
23#include <vector>
24
25namespace clang {
26class RecordDecl;
27class Expr;
28class FunctionDecl;
29class StringLiteral;
30class VarDecl;
31
32namespace interp {
33class Context;
34
35/// The program contains and links the bytecode for all functions.
36class Program final {
37public:
38 Program(Context &Ctx) : Ctx(Ctx) {}
39
41 // Manually destroy all the blocks. They are almost all harmless,
42 // but primitive arrays might have an InitMap* heap allocated and
43 // that needs to be freed.
44 for (Global *G : Globals)
45 if (Block *B = G->block(); B->isInitialized())
46 B->invokeDtor();
47
48 // Records might actually allocate memory themselves, but they
49 // are allocated using a BumpPtrAllocator. Call their desctructors
50 // here manually so they are properly freeing their resources.
51 for (auto RecordPair : Records) {
52 if (Record *R = RecordPair.second)
53 R->~Record();
54 }
55 }
56
57 /// Marshals a native pointer to an ID for embedding in bytecode.
58 unsigned getOrCreateNativePointer(const void *Ptr);
59
60 /// Returns the value of a marshalled native pointer.
61 const void *getNativePointer(unsigned Idx);
62
63 /// Emits a string literal among global data.
64 unsigned createGlobalString(const StringLiteral *S,
65 const Expr *Base = nullptr);
66
67 /// Returns a pointer to a global.
68 Pointer getPtrGlobal(unsigned Idx) const;
69
70 /// Returns the value of a global.
71 Block *getGlobal(unsigned Idx) {
72 assert(Idx < Globals.size());
73 return Globals[Idx]->block();
74 }
75
76 bool isGlobalInitialized(unsigned Index) const {
77 return getPtrGlobal(Index).isInitialized();
78 }
79
80 /// Finds a global's index.
81 std::optional<unsigned> getGlobal(const ValueDecl *VD);
82 std::optional<unsigned> getGlobal(const Expr *E);
83
84 /// Returns or creates a global an creates an index to it.
85 std::optional<unsigned> getOrCreateGlobal(const ValueDecl *VD,
86 const Expr *Init = nullptr);
87
88 /// Returns or creates a dummy value for unknown declarations.
89 unsigned getOrCreateDummy(const DeclTy &D);
90
91 /// Creates a global and returns its index.
92 std::optional<unsigned> createGlobal(const ValueDecl *VD, const Expr *Init);
93
94 /// Creates a global from a lifetime-extended temporary.
95 std::optional<unsigned> createGlobal(const Expr *E);
96
97 /// Creates a new function from a code range.
98 template <typename... Ts>
99 Function *createFunction(const FunctionDecl *Def, Ts &&...Args) {
100 Def = Def->getCanonicalDecl();
101 auto *Func = new Function(*this, Def, std::forward<Ts>(Args)...);
102 Funcs.insert({Def, std::unique_ptr<Function>(Func)});
103 return Func;
104 }
105 /// Creates an anonymous function.
106 template <typename... Ts> Function *createFunction(Ts &&...Args) {
107 auto *Func = new Function(*this, std::forward<Ts>(Args)...);
108 AnonFuncs.emplace_back(Func);
109 return Func;
110 }
111
112 /// Returns a function.
114
115 /// Returns a record or creates one if it does not exist.
117
118 /// Creates a descriptor for a primitive type.
120 const Type *SourceTy = nullptr,
121 Descriptor::MetadataSize MDSize = std::nullopt,
122 bool IsConst = false, bool IsTemporary = false,
123 bool IsMutable = false,
124 bool IsVolatile = false) {
125 return allocateDescriptor(D, SourceTy, T, MDSize, IsConst, IsTemporary,
126 IsMutable, IsVolatile);
127 }
128
129 /// Creates a descriptor for a composite type.
130 Descriptor *createDescriptor(const DeclTy &D, const Type *Ty,
131 Descriptor::MetadataSize MDSize = std::nullopt,
132 bool IsConst = false, bool IsTemporary = false,
133 bool IsMutable = false, bool IsVolatile = false,
134 const Expr *Init = nullptr);
135
136 void *Allocate(size_t Size, unsigned Align = 8) const {
137 return Allocator.Allocate(Size, Align);
138 }
139 template <typename T> T *Allocate(size_t Num = 1) const {
140 return static_cast<T *>(Allocate(Num * sizeof(T), alignof(T)));
141 }
142 void Deallocate(void *Ptr) const {}
143
144 /// Context to manage declaration lifetimes.
145 class DeclScope {
146 public:
147 DeclScope(Program &P) : P(P), PrevDecl(P.CurrentDeclaration) {
148 ++P.LastDeclaration;
149 P.CurrentDeclaration = P.LastDeclaration;
150 }
151 ~DeclScope() { P.CurrentDeclaration = PrevDecl; }
152
153 private:
154 Program &P;
155 unsigned PrevDecl;
156 };
157
158 /// Returns the current declaration ID.
160 if (CurrentDeclaration == NoDeclaration)
161 return std::nullopt;
162 return CurrentDeclaration;
163 }
164
165private:
166 friend class DeclScope;
167
168 std::optional<unsigned> createGlobal(const DeclTy &D, QualType Ty,
169 bool IsStatic, bool IsExtern,
170 bool IsWeak, const Expr *Init = nullptr);
171
172 /// Reference to the VM context.
173 Context &Ctx;
174 /// Mapping from decls to cached bytecode functions.
175 llvm::DenseMap<const FunctionDecl *, std::unique_ptr<Function>> Funcs;
176 /// List of anonymous functions.
177 std::vector<std::unique_ptr<Function>> AnonFuncs;
178
179 /// Native pointers referenced by bytecode.
180 std::vector<const void *> NativePointers;
181 /// Cached native pointer indices.
182 llvm::DenseMap<const void *, unsigned> NativePointerIndices;
183
184 /// Custom allocator for global storage.
185 using PoolAllocTy = llvm::BumpPtrAllocator;
186
187 /// Descriptor + storage for a global object.
188 ///
189 /// Global objects never go out of scope, thus they do not track pointers.
190 class Global {
191 public:
192 /// Create a global descriptor for string literals.
193 template <typename... Tys>
194 Global(Tys... Args) : B(std::forward<Tys>(Args)...) {}
195
196 /// Allocates the global in the pool, reserving storate for data.
197 void *operator new(size_t Meta, PoolAllocTy &Alloc, size_t Data) {
198 return Alloc.Allocate(Meta + Data, alignof(void *));
199 }
200
201 /// Return a pointer to the data.
202 std::byte *data() { return B.data(); }
203 /// Return a pointer to the block.
204 Block *block() { return &B; }
205 const Block *block() const { return &B; }
206
207 private:
208 /// Required metadata - does not actually track pointers.
209 Block B;
210 };
211
212 /// Allocator for globals.
213 mutable PoolAllocTy Allocator;
214
215 /// Global objects.
216 std::vector<Global *> Globals;
217 /// Cached global indices.
218 llvm::DenseMap<const void *, unsigned> GlobalIndices;
219
220 /// Mapping from decls to record metadata.
221 llvm::DenseMap<const RecordDecl *, Record *> Records;
222
223 /// Dummy parameter to generate pointers from.
224 llvm::DenseMap<const void *, unsigned> DummyVariables;
225
226 /// Creates a new descriptor.
227 template <typename... Ts> Descriptor *allocateDescriptor(Ts &&...Args) {
228 return new (Allocator) Descriptor(std::forward<Ts>(Args)...);
229 }
230
231 /// No declaration ID.
232 static constexpr unsigned NoDeclaration = ~0u;
233 /// Last declaration ID.
234 unsigned LastDeclaration = 0;
235 /// Current declaration ID.
236 unsigned CurrentDeclaration = NoDeclaration;
237
238public:
239 /// Dumps the disassembled bytecode to \c llvm::errs().
240 void dump() const;
241 void dump(llvm::raw_ostream &OS) const;
242};
243
244} // namespace interp
245} // namespace clang
246
247inline void *operator new(size_t Bytes, const clang::interp::Program &C,
248 size_t Alignment = 8) {
249 return C.Allocate(Bytes, Alignment);
250}
251
252inline void operator delete(void *Ptr, const clang::interp::Program &C,
253 size_t) {
254 C.Deallocate(Ptr);
255}
256inline void *operator new[](size_t Bytes, const clang::interp::Program &C,
257 size_t Alignment = 8) {
258 return C.Allocate(Bytes, Alignment);
259}
260
261#endif
StringRef P
const Decl * D
Expr * E
bool IsStatic
Definition: Format.cpp:3189
const CFGBlock * Block
Definition: HTMLLogger.cpp:152
llvm::MachO::Records Records
Definition: MachO.h:40
__SIZE_TYPE__ size_t
This represents one expression.
Definition: Expr.h:112
Represents a function declaration or definition.
Definition: Decl.h:1999
FunctionDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition: Decl.cpp:3688
A (possibly-)qualified type.
Definition: TypeBase.h:937
Represents a struct/union/class.
Definition: Decl.h:4309
StringLiteral - This represents a string literal expression, e.g.
Definition: Expr.h:1801
The base class of the type hierarchy.
Definition: TypeBase.h:1833
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition: Decl.h:711
A memory block, either on the stack or in the heap.
Definition: InterpBlock.h:44
bool isInitialized() const
Returns whether the data of this block has been initialized via invoking the Ctor func.
Definition: InterpBlock.h:92
Holds all information required to evaluate constexpr code in a module.
Definition: Context.h:41
Bytecode function.
Definition: Function.h:86
A pointer to a memory block, live or dead.
Definition: Pointer.h:90
bool isInitialized() const
Checks if an object was initialized.
Definition: Pointer.cpp:432
Context to manage declaration lifetimes.
Definition: Program.h:145
The program contains and links the bytecode for all functions.
Definition: Program.h:36
void * Allocate(size_t Size, unsigned Align=8) const
Definition: Program.h:136
std::optional< unsigned > getOrCreateGlobal(const ValueDecl *VD, const Expr *Init=nullptr)
Returns or creates a global an creates an index to it.
Definition: Program.cpp:140
Function * getFunction(const FunctionDecl *F)
Returns a function.
Definition: Program.cpp:288
Block * getGlobal(unsigned Idx)
Returns the value of a global.
Definition: Program.h:71
std::optional< unsigned > createGlobal(const ValueDecl *VD, const Expr *Init)
Creates a global and returns its index.
Definition: Program.cpp:198
const void * getNativePointer(unsigned Idx)
Returns the value of a marshalled native pointer.
Definition: Program.cpp:30
unsigned getOrCreateNativePointer(const void *Ptr)
Marshals a native pointer to an ID for embedding in bytecode.
Definition: Program.cpp:21
Function * createFunction(const FunctionDecl *Def, Ts &&...Args)
Creates a new function from a code range.
Definition: Program.h:99
bool isGlobalInitialized(unsigned Index) const
Definition: Program.h:76
Pointer getPtrGlobal(unsigned Idx) const
Returns a pointer to a global.
Definition: Program.cpp:109
unsigned getOrCreateDummy(const DeclTy &D)
Returns or creates a dummy value for unknown declarations.
Definition: Program.cpp:152
void dump() const
Dumps the disassembled bytecode to llvm::errs().
Definition: Disasm.cpp:251
T * Allocate(size_t Num=1) const
Definition: Program.h:139
void Deallocate(void *Ptr) const
Definition: Program.h:142
Descriptor * createDescriptor(const DeclTy &D, PrimType T, const Type *SourceTy=nullptr, Descriptor::MetadataSize MDSize=std::nullopt, bool IsConst=false, bool IsTemporary=false, bool IsMutable=false, bool IsVolatile=false)
Creates a descriptor for a primitive type.
Definition: Program.h:119
unsigned createGlobalString(const StringLiteral *S, const Expr *Base=nullptr)
Emits a string literal among global data.
Definition: Program.cpp:34
Function * createFunction(Ts &&...Args)
Creates an anonymous function.
Definition: Program.h:106
UnsignedOrNone getCurrentDecl() const
Returns the current declaration ID.
Definition: Program.h:159
Record * getOrCreateRecord(const RecordDecl *RD)
Returns a record or creates one if it does not exist.
Definition: Program.cpp:295
Program(Context &Ctx)
Definition: Program.h:38
Structure/Class descriptor.
Definition: Record.h:25
Code completion in a.
PrimType
Enumeration of the primitive types of the VM.
Definition: PrimType.h:34
bool Alloc(InterpState &S, CodePtr OpPC, const Descriptor *Desc)
Definition: Interp.h:3464
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
Definition: Descriptor.h:29
The JSON file list parser is used to communicate input to InstallAPI.
const FunctionProtoType * T
Describes a memory block created by an allocation site.
Definition: Descriptor.h:122
std::optional< unsigned > MetadataSize
Definition: Descriptor.h:143