clang 24.0.0git
ByteCodeEmitter.cpp
Go to the documentation of this file.
1//===--- ByteCodeEmitter.cpp - Instruction emitter for the 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 "ByteCodeEmitter.h"
10#include "Context.h"
11#include "Floating.h"
12#include "IntegralAP.h"
13#include "Opcode.h"
14#include "Program.h"
15#include "clang/AST/ASTLambda.h"
16#include "clang/AST/Attr.h"
17#include "clang/AST/DeclCXX.h"
18#include <type_traits>
19
20using namespace clang;
21using namespace clang::interp;
22
24 Function *Func) {
25 assert(FuncDecl);
26 assert(Func);
27 assert(FuncDecl->isThisDeclarationADefinition());
28
29 // Set up lambda captures.
30 if (Func->isLambdaCallOperator()) {
31 // Set up lambda capture to closure record field mapping.
32 const CXXRecordDecl *ParentDecl = Func->getParentDecl();
33 const Record *R = P.getOrCreateRecord(ParentDecl);
34 assert(R);
35 llvm::DenseMap<const ValueDecl *, FieldDecl *> LC;
36 FieldDecl *LTC;
37
38 ParentDecl->getCaptureFields(LC, LTC);
39
40 for (const auto &Cap : LC) {
41 unsigned Offset = R->getField(Cap.second)->Offset;
42 this->LambdaCaptures[Cap.first] = {
43 Offset, Cap.second->getType()->isReferenceType()};
44 }
45 if (LTC) {
46 QualType CaptureType = R->getField(LTC)->Decl->getType();
47 this->LambdaThisCapture = {R->getField(LTC)->Offset,
48 CaptureType->isPointerOrReferenceType()};
49 }
50 }
51
52 bool IsValid = !FuncDecl->isInvalidDecl();
53 // Register parameters and their index.
54 for (unsigned ParamIndex = 0, N = Func->getNumWrittenParams();
55 ParamIndex != N; ++ParamIndex) {
56 const ParmVarDecl *PD = FuncDecl->getParamDecl(ParamIndex);
57 if (PD->isInvalidDecl())
58 IsValid = false;
59 this->Params.insert({PD, {ParamIndex, Ctx.canClassify(PD->getType())}});
60 }
61
62 Func->setDefined(true);
63
64 // Lambda static invokers are a special case that we emit custom code for.
65 bool IsEligibleForCompilation = Func->isLambdaStaticInvoker() ||
66 FuncDecl->isConstexpr() ||
67 FuncDecl->hasAttr<MSConstexprAttr>();
68
69 // Compile the function body.
70 if (!IsEligibleForCompilation || !visitFunc(FuncDecl)) {
71 Func->setIsFullyCompiled(true);
72 return;
73 }
74
75 // Create scopes from descriptors.
77 for (auto &DS : Descriptors) {
78 Scopes.emplace_back(std::move(DS));
79 }
80
81 // Set the function's code.
82 Func->setCode(FuncDecl, NextLocalOffset, std::move(Code), std::move(SrcMap),
83 std::move(Scopes), FuncDecl->hasBody(), IsValid);
84 Func->setIsFullyCompiled(true);
85}
86
88 NextLocalOffset += sizeof(Block);
89 unsigned Location = NextLocalOffset;
90 NextLocalOffset += align(Block::InlineDescMD + D->getAllocSize());
91 return {D, Location};
92}
93
95 const size_t Target = Code.size();
96 LabelOffsets.insert({Label, Target});
97
98 if (auto It = LabelRelocs.find(Label); It != LabelRelocs.end()) {
99 for (unsigned Reloc : It->second) {
100 using namespace llvm::support;
101
102 // Rewrite the operand of all jumps to this label.
103 void *Location = Code.data() + Reloc - align(sizeof(int32_t));
104 assert(aligned(Location));
105 const int32_t Offset = Target - static_cast<int64_t>(Reloc);
106 endian::write<int32_t, llvm::endianness::native>(Location, Offset);
107 }
108 LabelRelocs.erase(It);
109 }
110}
111
112int32_t ByteCodeEmitter::getOffset(LabelTy Label) {
113 // Compute the PC offset which the jump is relative to.
114 const int64_t Position =
115 Code.size() + align(sizeof(Opcode)) + align(sizeof(int32_t));
116 assert(aligned(Position));
117
118 // If target is known, compute jump offset.
119 if (auto It = LabelOffsets.find(Label); It != LabelOffsets.end())
120 return It->second - Position;
121
122 // Otherwise, record relocation and return dummy offset.
123 LabelRelocs[Label].push_back(Position);
124 return 0ull;
125}
126
127/// Helper to write bytecode and bail out if 32-bit offsets become invalid.
128template <typename T>
130 const T &Val, bool &Success) {
131 size_t ValPos = Code.size();
132 size_t Size;
133
134 if constexpr (std::is_pointer_v<T>)
135 Size = align(sizeof(uintptr_t));
136 else
137 Size = align(sizeof(T));
138
139 if (ValPos + Size > std::numeric_limits<unsigned>::max()) {
140 Success = false;
141 return;
142 }
143
144 // Access must be aligned!
145 assert(aligned(ValPos));
146 assert(aligned(ValPos + Size));
147 Code.resize_for_overwrite(ValPos + Size);
148
149 if constexpr (std::is_pointer_v<T>)
150 new (Code.data() + ValPos) uintptr_t(reinterpret_cast<uintptr_t>(Val));
151 else
152 new (Code.data() + ValPos) T(Val);
153}
154
155/// Emits a serializable value. These usually (potentially) contain
156/// heap-allocated memory and aren't trivially copyable.
157template <typename T>
159 bool &Success) {
160 size_t ValPos = Code.size();
161 size_t Size = align(Val.bytesToSerialize());
162
163 if (ValPos + Size > std::numeric_limits<unsigned>::max()) {
164 Success = false;
165 return;
166 }
167
168 // Access must be aligned!
169 assert(aligned(ValPos));
170 assert(aligned(ValPos + Size));
171 Code.resize_for_overwrite(ValPos + Size);
172
173 Val.serialize(Code.data() + ValPos);
174}
175
176template <>
178 const Floating &Val, bool &Success) {
179 emitSerialized(Code, Val, Success);
180}
181
182template <>
184 const IntegralAP<false> &Val, bool &Success) {
185 emitSerialized(Code, Val, Success);
186}
187
188template <>
190 const IntegralAP<true> &Val, bool &Success) {
191 emitSerialized(Code, Val, Success);
192}
193
194template <>
196 const FixedPoint &Val, bool &Success) {
197 emitSerialized(Code, Val, Success);
198}
199
200template <typename... Tys>
201bool ByteCodeEmitter::emitOp(Opcode Op, const Tys &...Args, SourceInfo SI) {
202 bool Success = true;
203
204 // The opcode is followed by arguments. The source info is
205 // attached to the address after the opcode.
206 emit(P, Code, Op, Success);
207
208 SI = LocOverride.value_or(SI);
209 if (SrcMap.empty() || SrcMap.back() != SI)
210 SrcMap.push(Code.size(), SI);
211
212 (..., emit(P, Code, Args, Success));
213 return Success;
214}
215
217 return emitJt(getOffset(Label), SI);
218}
219
221 return emitJf(getOffset(Label), SI);
222}
223
225 return emitJmp(getOffset(Label), SI);
226}
227
229 emitLabel(Label);
230 return true;
231}
232
233bool ByteCodeEmitter::speculate(const CallExpr *E, const LabelTy &EndLabel) {
234 const Expr *Arg = E->getArg(0);
235 PrimType T = Ctx.classify(Arg->getType()).value_or(PT_Ptr);
236 if (!this->emitBCP(getOffset(EndLabel), T, E))
237 return false;
238 if (!this->visit(Arg))
239 return false;
240 return true;
241}
242
243//===----------------------------------------------------------------------===//
244// Opcode emitters
245//===----------------------------------------------------------------------===//
246
247#define GET_LINK_IMPL
248#include "Opcodes.inc"
249#undef GET_LINK_IMPL
This file provides some common utility functions for processing Lambda related AST Constructs.
static void emitSerialized(llvm::SmallVectorImpl< std::byte > &Code, const T &Val, bool &Success)
Emits a serializable value.
static void emit(Program &P, llvm::SmallVectorImpl< std::byte > &Code, const T &Val, bool &Success)
Helper to write bytecode and bail out if 32-bit offsets become invalid.
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
void getCaptureFields(llvm::DenseMap< const ValueDecl *, FieldDecl * > &Captures, FieldDecl *&ThisCapture) const
For a closure type, retrieve the mapping from captured variables and this to the non-static data memb...
Definition DeclCXX.cpp:1792
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2987
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3191
bool isInvalidDecl() const
Definition DeclBase.h:596
bool hasAttr() const
Definition DeclBase.h:585
This represents one expression.
Definition Expr.h:113
QualType getType() const
Definition Expr.h:145
Represents a member of a struct/union/class.
Definition Decl.h:3295
Represents a function declaration or definition.
Definition Decl.h:2059
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2928
bool isThisDeclarationADefinition() const
Returns whether this specific declaration of the function is also a definition that does not contain ...
Definition Decl.h:2428
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2597
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3188
Represents a parameter to a function.
Definition Decl.h:1820
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isPointerOrReferenceType() const
Definition TypeBase.h:8742
QualType getType() const
Definition Decl.h:724
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:43
static constexpr uint8_t InlineDescMD
Definition InterpBlock.h:51
bool jump(const LabelTy &Label, SourceInfo SI)
void emitLabel(LabelTy Label)
Define a label.
Local createLocal(const Descriptor *D)
Callback for local registration.
ParamOffset LambdaThisCapture
Offset of the This parameter in a lambda record.
llvm::DenseMap< const ValueDecl *, ParamOffset > LambdaCaptures
Lambda captures.
bool jumpTrue(const LabelTy &Label, SourceInfo SI)
Emits jumps.
bool speculate(const CallExpr *E, const LabelTy &EndLabel)
Speculative execution.
void compileFunc(const FunctionDecl *FuncDecl, Function *Func=nullptr)
Compiles the function into the module.
bool fallthrough(const LabelTy &Label)
bool jumpFalse(const LabelTy &Label, SourceInfo SI)
virtual bool visitFunc(const FunctionDecl *E)=0
Methods implemented by the compiler.
std::optional< SourceInfo > LocOverride
llvm::DenseMap< const ParmVarDecl *, FuncParam > Params
Parameter indices.
virtual bool visit(const Expr *E)=0
llvm::SmallVector< SmallVector< Local, 8 >, 2 > Descriptors
Local descriptors.
Wrapper around fixed point types.
Definition FixedPoint.h:23
If a Floating is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition Floating.h:35
Bytecode function.
Definition Function.h:98
If an IntegralAP is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition IntegralAP.h:36
The program contains and links the bytecode for all functions.
Definition Program.h:37
Structure/Class descriptor.
Definition Record.h:25
Describes the statement/declaration an opcode was generated from.
Definition Source.h:77
constexpr bool aligned(uintptr_t Value)
Definition PrimType.h:217
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:213
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
Top level wrappers for InstallAPI frontend operations.
@ Success
Annotation was successful.
Definition Parser.h:65
const FunctionProtoType * T
__UINTPTR_TYPE__ uintptr_t
An unsigned integer type with the property that any valid pointer to void can be converted to this ty...
Describes a memory block created by an allocation site.
Definition Descriptor.h:122
unsigned getAllocSize() const
Returns the allocated size, including metadata.
Definition Descriptor.h:237
Information about a local's storage.
Definition Function.h:38