Path: blob/main/contrib/llvm-project/clang/lib/AST/ByteCode/ByteCodeEmitter.cpp
213799 views
//===--- ByteCodeEmitter.cpp - Instruction emitter for the VM ---*- C++ -*-===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "ByteCodeEmitter.h"9#include "Context.h"10#include "Floating.h"11#include "IntegralAP.h"12#include "Opcode.h"13#include "Program.h"14#include "clang/AST/ASTLambda.h"15#include "clang/AST/Attr.h"16#include "clang/AST/DeclCXX.h"17#include <type_traits>1819using namespace clang;20using namespace clang::interp;2122void ByteCodeEmitter::compileFunc(const FunctionDecl *FuncDecl,23Function *Func) {24assert(FuncDecl);25assert(Func);2627// Manually created functions that haven't been assigned proper28// parameters yet.29if (!FuncDecl->param_empty() && !FuncDecl->param_begin())30return;3132if (!FuncDecl->isDefined())33return;3435// Set up lambda captures.36if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl);37MD && isLambdaCallOperator(MD)) {38// Set up lambda capture to closure record field mapping.39const Record *R = P.getOrCreateRecord(MD->getParent());40assert(R);41llvm::DenseMap<const ValueDecl *, FieldDecl *> LC;42FieldDecl *LTC;4344MD->getParent()->getCaptureFields(LC, LTC);4546for (auto Cap : LC) {47unsigned Offset = R->getField(Cap.second)->Offset;48this->LambdaCaptures[Cap.first] = {49Offset, Cap.second->getType()->isReferenceType()};50}51if (LTC) {52QualType CaptureType = R->getField(LTC)->Decl->getType();53this->LambdaThisCapture = {R->getField(LTC)->Offset,54CaptureType->isPointerOrReferenceType()};55}56}5758// Register parameters with their offset.59unsigned ParamIndex = 0;60unsigned Drop = Func->hasRVO() +61(Func->hasThisPointer() && !Func->isThisPointerExplicit());62for (auto ParamOffset : llvm::drop_begin(Func->ParamOffsets, Drop)) {63const ParmVarDecl *PD = FuncDecl->parameters()[ParamIndex];64std::optional<PrimType> T = Ctx.classify(PD->getType());65this->Params.insert({PD, {ParamOffset, T != std::nullopt}});66++ParamIndex;67}6869Func->setDefined(true);7071// Lambda static invokers are a special case that we emit custom code for.72bool IsEligibleForCompilation = Func->isLambdaStaticInvoker() ||73FuncDecl->isConstexpr() ||74FuncDecl->hasAttr<MSConstexprAttr>();7576// Compile the function body.77if (!IsEligibleForCompilation || !visitFunc(FuncDecl)) {78Func->setIsFullyCompiled(true);79return;80}8182// Create scopes from descriptors.83llvm::SmallVector<Scope, 2> Scopes;84for (auto &DS : Descriptors) {85Scopes.emplace_back(std::move(DS));86}8788// Set the function's code.89Func->setCode(NextLocalOffset, std::move(Code), std::move(SrcMap),90std::move(Scopes), FuncDecl->hasBody());91Func->setIsFullyCompiled(true);92}9394Scope::Local ByteCodeEmitter::createLocal(Descriptor *D) {95NextLocalOffset += sizeof(Block);96unsigned Location = NextLocalOffset;97NextLocalOffset += align(D->getAllocSize());98return {Location, D};99}100101void ByteCodeEmitter::emitLabel(LabelTy Label) {102const size_t Target = Code.size();103LabelOffsets.insert({Label, Target});104105if (auto It = LabelRelocs.find(Label); It != LabelRelocs.end()) {106for (unsigned Reloc : It->second) {107using namespace llvm::support;108109// Rewrite the operand of all jumps to this label.110void *Location = Code.data() + Reloc - align(sizeof(int32_t));111assert(aligned(Location));112const int32_t Offset = Target - static_cast<int64_t>(Reloc);113endian::write<int32_t, llvm::endianness::native>(Location, Offset);114}115LabelRelocs.erase(It);116}117}118119int32_t ByteCodeEmitter::getOffset(LabelTy Label) {120// Compute the PC offset which the jump is relative to.121const int64_t Position =122Code.size() + align(sizeof(Opcode)) + align(sizeof(int32_t));123assert(aligned(Position));124125// If target is known, compute jump offset.126if (auto It = LabelOffsets.find(Label); It != LabelOffsets.end())127return It->second - Position;128129// Otherwise, record relocation and return dummy offset.130LabelRelocs[Label].push_back(Position);131return 0ull;132}133134/// Helper to write bytecode and bail out if 32-bit offsets become invalid.135/// Pointers will be automatically marshalled as 32-bit IDs.136template <typename T>137static void emit(Program &P, std::vector<std::byte> &Code, const T &Val,138bool &Success) {139size_t Size;140141if constexpr (std::is_pointer_v<T>)142Size = sizeof(uint32_t);143else144Size = sizeof(T);145146if (Code.size() + Size > std::numeric_limits<unsigned>::max()) {147Success = false;148return;149}150151// Access must be aligned!152size_t ValPos = align(Code.size());153Size = align(Size);154assert(aligned(ValPos + Size));155Code.resize(ValPos + Size);156157if constexpr (!std::is_pointer_v<T>) {158new (Code.data() + ValPos) T(Val);159} else {160uint32_t ID = P.getOrCreateNativePointer(Val);161new (Code.data() + ValPos) uint32_t(ID);162}163}164165/// Emits a serializable value. These usually (potentially) contain166/// heap-allocated memory and aren't trivially copyable.167template <typename T>168static void emitSerialized(std::vector<std::byte> &Code, const T &Val,169bool &Success) {170size_t Size = Val.bytesToSerialize();171172if (Code.size() + Size > std::numeric_limits<unsigned>::max()) {173Success = false;174return;175}176177// Access must be aligned!178assert(aligned(Code.size()));179size_t ValPos = Code.size();180Size = align(Size);181assert(aligned(ValPos + Size));182Code.resize(ValPos + Size);183184Val.serialize(Code.data() + ValPos);185}186187template <>188void emit(Program &P, std::vector<std::byte> &Code, const Floating &Val,189bool &Success) {190emitSerialized(Code, Val, Success);191}192193template <>194void emit(Program &P, std::vector<std::byte> &Code,195const IntegralAP<false> &Val, bool &Success) {196emitSerialized(Code, Val, Success);197}198199template <>200void emit(Program &P, std::vector<std::byte> &Code, const IntegralAP<true> &Val,201bool &Success) {202emitSerialized(Code, Val, Success);203}204205template <>206void emit(Program &P, std::vector<std::byte> &Code, const FixedPoint &Val,207bool &Success) {208emitSerialized(Code, Val, Success);209}210211template <typename... Tys>212bool ByteCodeEmitter::emitOp(Opcode Op, const Tys &...Args,213const SourceInfo &SI) {214bool Success = true;215216// The opcode is followed by arguments. The source info is217// attached to the address after the opcode.218emit(P, Code, Op, Success);219if (SI)220SrcMap.emplace_back(Code.size(), SI);221222(..., emit(P, Code, Args, Success));223return Success;224}225226bool ByteCodeEmitter::jumpTrue(const LabelTy &Label) {227return emitJt(getOffset(Label), SourceInfo{});228}229230bool ByteCodeEmitter::jumpFalse(const LabelTy &Label) {231return emitJf(getOffset(Label), SourceInfo{});232}233234bool ByteCodeEmitter::jump(const LabelTy &Label) {235return emitJmp(getOffset(Label), SourceInfo{});236}237238bool ByteCodeEmitter::fallthrough(const LabelTy &Label) {239emitLabel(Label);240return true;241}242243bool ByteCodeEmitter::speculate(const CallExpr *E, const LabelTy &EndLabel) {244const Expr *Arg = E->getArg(0);245PrimType T = Ctx.classify(Arg->getType()).value_or(PT_Ptr);246if (!this->emitBCP(getOffset(EndLabel), T, E))247return false;248if (!this->visit(Arg))249return false;250return true;251}252253//===----------------------------------------------------------------------===//254// Opcode emitters255//===----------------------------------------------------------------------===//256257#define GET_LINK_IMPL258#include "Opcodes.inc"259#undef GET_LINK_IMPL260261262