ByteCodeExprGen.h
10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
//===--- ByteCodeExprGen.h - Code generator for expressions -----*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// Defines the constexpr bytecode compiler.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_AST_INTERP_BYTECODEEXPRGEN_H
#define LLVM_CLANG_AST_INTERP_BYTECODEEXPRGEN_H
#include "ByteCodeEmitter.h"
#include "EvalEmitter.h"
#include "Pointer.h"
#include "PrimType.h"
#include "Record.h"
#include "clang/AST/Decl.h"
#include "clang/AST/Expr.h"
#include "clang/AST/StmtVisitor.h"
#include "clang/Basic/TargetInfo.h"
#include "llvm/ADT/Optional.h"
namespace clang {
class QualType;
namespace interp {
class Function;
class State;
template <class Emitter> class LocalScope;
template <class Emitter> class RecordScope;
template <class Emitter> class VariableScope;
template <class Emitter> class DeclScope;
template <class Emitter> class OptionScope;
/// Compilation context for expressions.
template <class Emitter>
class ByteCodeExprGen : public ConstStmtVisitor<ByteCodeExprGen<Emitter>, bool>,
public Emitter {
protected:
// Emitters for opcodes of various arities.
using NullaryFn = bool (ByteCodeExprGen::*)(const SourceInfo &);
using UnaryFn = bool (ByteCodeExprGen::*)(PrimType, const SourceInfo &);
using BinaryFn = bool (ByteCodeExprGen::*)(PrimType, PrimType,
const SourceInfo &);
// Aliases for types defined in the emitter.
using LabelTy = typename Emitter::LabelTy;
using AddrTy = typename Emitter::AddrTy;
// Reference to a function generating the pointer of an initialized object.s
using InitFnRef = std::function<bool()>;
/// Current compilation context.
Context &Ctx;
/// Program to link to.
Program &P;
public:
/// Initializes the compiler and the backend emitter.
template <typename... Tys>
ByteCodeExprGen(Context &Ctx, Program &P, Tys &&... Args)
: Emitter(Ctx, P, Args...), Ctx(Ctx), P(P) {}
// Expression visitors - result returned on stack.
bool VisitCastExpr(const CastExpr *E);
bool VisitIntegerLiteral(const IntegerLiteral *E);
bool VisitParenExpr(const ParenExpr *E);
bool VisitBinaryOperator(const BinaryOperator *E);
protected:
bool visitExpr(const Expr *E) override;
bool visitDecl(const VarDecl *VD) override;
protected:
/// Emits scope cleanup instructions.
void emitCleanup();
/// Returns a record type from a record or pointer type.
const RecordType *getRecordTy(QualType Ty);
/// Returns a record from a record or pointer type.
Record *getRecord(QualType Ty);
Record *getRecord(const RecordDecl *RD);
/// Returns the size int bits of an integer.
unsigned getIntWidth(QualType Ty) {
auto &ASTContext = Ctx.getASTContext();
return ASTContext.getIntWidth(Ty);
}
/// Returns the value of CHAR_BIT.
unsigned getCharBit() const {
auto &ASTContext = Ctx.getASTContext();
return ASTContext.getTargetInfo().getCharWidth();
}
/// Classifies a type.
llvm::Optional<PrimType> classify(const Expr *E) const {
return E->isGLValue() ? PT_Ptr : classify(E->getType());
}
llvm::Optional<PrimType> classify(QualType Ty) const {
return Ctx.classify(Ty);
}
/// Checks if a pointer needs adjustment.
bool needsAdjust(QualType Ty) const {
return true;
}
/// Classifies a known primitive type
PrimType classifyPrim(QualType Ty) const {
if (auto T = classify(Ty)) {
return *T;
}
llvm_unreachable("not a primitive type");
}
/// Evaluates an expression for side effects and discards the result.
bool discard(const Expr *E);
/// Evaluates an expression and places result on stack.
bool visit(const Expr *E);
/// Compiles an initializer for a local.
bool visitInitializer(const Expr *E, InitFnRef GenPtr);
/// Visits an expression and converts it to a boolean.
bool visitBool(const Expr *E);
/// Visits an initializer for a local.
bool visitLocalInitializer(const Expr *Init, unsigned I) {
return visitInitializer(Init, [this, I, Init] {
return this->emitGetPtrLocal(I, Init);
});
}
/// Visits an initializer for a global.
bool visitGlobalInitializer(const Expr *Init, unsigned I) {
return visitInitializer(Init, [this, I, Init] {
return this->emitGetPtrGlobal(I, Init);
});
}
/// Visits a delegated initializer.
bool visitThisInitializer(const Expr *I) {
return visitInitializer(I, [this, I] { return this->emitThis(I); });
}
/// Creates a local primitive value.
unsigned allocateLocalPrimitive(DeclTy &&Decl, PrimType Ty, bool IsMutable,
bool IsExtended = false);
/// Allocates a space storing a local given its type.
llvm::Optional<unsigned> allocateLocal(DeclTy &&Decl,
bool IsExtended = false);
private:
friend class VariableScope<Emitter>;
friend class LocalScope<Emitter>;
friend class RecordScope<Emitter>;
friend class DeclScope<Emitter>;
friend class OptionScope<Emitter>;
/// Emits a zero initializer.
bool visitZeroInitializer(PrimType T, const Expr *E);
enum class DerefKind {
/// Value is read and pushed to stack.
Read,
/// Direct method generates a value which is written. Returns pointer.
Write,
/// Direct method receives the value, pushes mutated value. Returns pointer.
ReadWrite,
};
/// Method to directly load a value. If the value can be fetched directly,
/// the direct handler is called. Otherwise, a pointer is left on the stack
/// and the indirect handler is expected to operate on that.
bool dereference(const Expr *LV, DerefKind AK,
llvm::function_ref<bool(PrimType)> Direct,
llvm::function_ref<bool(PrimType)> Indirect);
bool dereferenceParam(const Expr *LV, PrimType T, const ParmVarDecl *PD,
DerefKind AK,
llvm::function_ref<bool(PrimType)> Direct,
llvm::function_ref<bool(PrimType)> Indirect);
bool dereferenceVar(const Expr *LV, PrimType T, const VarDecl *PD,
DerefKind AK, llvm::function_ref<bool(PrimType)> Direct,
llvm::function_ref<bool(PrimType)> Indirect);
/// Emits an APInt constant.
bool emitConst(PrimType T, unsigned NumBits, const llvm::APInt &Value,
const Expr *E);
/// Emits an integer constant.
template <typename T> bool emitConst(const Expr *E, T Value) {
QualType Ty = E->getType();
unsigned NumBits = getIntWidth(Ty);
APInt WrappedValue(NumBits, Value, std::is_signed<T>::value);
return emitConst(*Ctx.classify(Ty), NumBits, WrappedValue, E);
}
/// Returns a pointer to a variable declaration.
bool getPtrVarDecl(const VarDecl *VD, const Expr *E);
/// Returns the index of a global.
llvm::Optional<unsigned> getGlobalIdx(const VarDecl *VD);
/// Emits the initialized pointer.
bool emitInitFn() {
assert(InitFn && "missing initializer");
return (*InitFn)();
}
protected:
/// Variable to storage mapping.
llvm::DenseMap<const ValueDecl *, Scope::Local> Locals;
/// OpaqueValueExpr to location mapping.
llvm::DenseMap<const OpaqueValueExpr *, unsigned> OpaqueExprs;
/// Current scope.
VariableScope<Emitter> *VarScope = nullptr;
/// Current argument index.
llvm::Optional<uint64_t> ArrayIndex;
/// Flag indicating if return value is to be discarded.
bool DiscardResult = false;
/// Expression being initialized.
llvm::Optional<InitFnRef> InitFn = {};
};
extern template class ByteCodeExprGen<ByteCodeEmitter>;
extern template class ByteCodeExprGen<EvalEmitter>;
/// Scope chain managing the variable lifetimes.
template <class Emitter> class VariableScope {
public:
virtual ~VariableScope() { Ctx->VarScope = this->Parent; }
void add(const Scope::Local &Local, bool IsExtended) {
if (IsExtended)
this->addExtended(Local);
else
this->addLocal(Local);
}
virtual void addLocal(const Scope::Local &Local) {
if (this->Parent)
this->Parent->addLocal(Local);
}
virtual void addExtended(const Scope::Local &Local) {
if (this->Parent)
this->Parent->addExtended(Local);
}
virtual void emitDestruction() {}
VariableScope *getParent() { return Parent; }
protected:
VariableScope(ByteCodeExprGen<Emitter> *Ctx)
: Ctx(Ctx), Parent(Ctx->VarScope) {
Ctx->VarScope = this;
}
/// ByteCodeExprGen instance.
ByteCodeExprGen<Emitter> *Ctx;
/// Link to the parent scope.
VariableScope *Parent;
};
/// Scope for local variables.
///
/// When the scope is destroyed, instructions are emitted to tear down
/// all variables declared in this scope.
template <class Emitter> class LocalScope : public VariableScope<Emitter> {
public:
LocalScope(ByteCodeExprGen<Emitter> *Ctx) : VariableScope<Emitter>(Ctx) {}
~LocalScope() override { this->emitDestruction(); }
void addLocal(const Scope::Local &Local) override {
if (!Idx.hasValue()) {
Idx = this->Ctx->Descriptors.size();
this->Ctx->Descriptors.emplace_back();
}
this->Ctx->Descriptors[*Idx].emplace_back(Local);
}
void emitDestruction() override {
if (!Idx.hasValue())
return;
this->Ctx->emitDestroy(*Idx, SourceInfo{});
}
protected:
/// Index of the scope in the chain.
Optional<unsigned> Idx;
};
/// Scope for storage declared in a compound statement.
template <class Emitter> class BlockScope final : public LocalScope<Emitter> {
public:
BlockScope(ByteCodeExprGen<Emitter> *Ctx) : LocalScope<Emitter>(Ctx) {}
void addExtended(const Scope::Local &Local) override {
llvm_unreachable("Cannot create temporaries in full scopes");
}
};
/// Expression scope which tracks potentially lifetime extended
/// temporaries which are hoisted to the parent scope on exit.
template <class Emitter> class ExprScope final : public LocalScope<Emitter> {
public:
ExprScope(ByteCodeExprGen<Emitter> *Ctx) : LocalScope<Emitter>(Ctx) {}
void addExtended(const Scope::Local &Local) override {
this->Parent->addLocal(Local);
}
};
} // namespace interp
} // namespace clang
#endif