Path: blob/main/contrib/llvm-project/clang/lib/AST/ByteCode/InterpFrame.cpp
213799 views
//===--- InterpFrame.cpp - Call Frame implementation 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 "InterpFrame.h"9#include "Boolean.h"10#include "Function.h"11#include "InterpStack.h"12#include "InterpState.h"13#include "MemberPointer.h"14#include "Pointer.h"15#include "PrimType.h"16#include "Program.h"17#include "clang/AST/ASTContext.h"18#include "clang/AST/DeclCXX.h"19#include "clang/AST/ExprCXX.h"2021using namespace clang;22using namespace clang::interp;2324InterpFrame::InterpFrame(InterpState &S)25: Caller(nullptr), S(S), Depth(0), Func(nullptr), RetPC(CodePtr()),26ArgSize(0), Args(nullptr), FrameOffset(0), IsBottom(true) {}2728InterpFrame::InterpFrame(InterpState &S, const Function *Func,29InterpFrame *Caller, CodePtr RetPC, unsigned ArgSize)30: Caller(Caller), S(S), Depth(Caller ? Caller->Depth + 1 : 0), Func(Func),31RetPC(RetPC), ArgSize(ArgSize), Args(static_cast<char *>(S.Stk.top())),32FrameOffset(S.Stk.size()), IsBottom(!Caller) {33if (!Func)34return;3536unsigned FrameSize = Func->getFrameSize();37if (FrameSize == 0)38return;3940Locals = std::make_unique<char[]>(FrameSize);41for (auto &Scope : Func->scopes()) {42for (auto &Local : Scope.locals()) {43new (localBlock(Local.Offset)) Block(S.Ctx.getEvalID(), Local.Desc);44// Note that we are NOT calling invokeCtor() here, since that is done45// via the InitScope op.46new (localInlineDesc(Local.Offset)) InlineDescriptor(Local.Desc);47}48}49}5051InterpFrame::InterpFrame(InterpState &S, const Function *Func, CodePtr RetPC,52unsigned VarArgSize)53: InterpFrame(S, Func, S.Current, RetPC, Func->getArgSize() + VarArgSize) {54// As per our calling convention, the this pointer is55// part of the ArgSize.56// If the function has RVO, the RVO pointer is first.57// If the fuction has a This pointer, that one is next.58// Then follow the actual arguments (but those are handled59// in getParamPointer()).60if (Func->hasRVO())61RVOPtr = stackRef<Pointer>(0);6263if (Func->hasThisPointer()) {64if (Func->hasRVO())65This = stackRef<Pointer>(sizeof(Pointer));66else67This = stackRef<Pointer>(0);68}69}7071InterpFrame::~InterpFrame() {72for (auto &Param : Params)73S.deallocate(reinterpret_cast<Block *>(Param.second.get()));7475// When destroying the InterpFrame, call the Dtor for all block76// that haven't been destroyed via a destroy() op yet.77// This happens when the execution is interruped midway-through.78destroyScopes();79}8081void InterpFrame::destroyScopes() {82if (!Func)83return;84for (auto &Scope : Func->scopes()) {85for (auto &Local : Scope.locals()) {86S.deallocate(localBlock(Local.Offset));87}88}89}9091void InterpFrame::initScope(unsigned Idx) {92if (!Func)93return;94for (auto &Local : Func->getScope(Idx).locals()) {95localBlock(Local.Offset)->invokeCtor();96}97}9899void InterpFrame::destroy(unsigned Idx) {100for (auto &Local : Func->getScope(Idx).locals_reverse()) {101S.deallocate(localBlock(Local.Offset));102}103}104105template <typename T>106static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx,107QualType Ty) {108if constexpr (std::is_same_v<Pointer, T>) {109if (Ty->isPointerOrReferenceType())110V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);111else {112if (std::optional<APValue> RValue = V.toRValue(ASTCtx, Ty))113RValue->printPretty(OS, ASTCtx, Ty);114else115OS << "...";116}117} else {118V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);119}120}121122static bool shouldSkipInBacktrace(const Function *F) {123if (F->isLambdaStaticInvoker())124return true;125126const FunctionDecl *FD = F->getDecl();127if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||128FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New)129return true;130return false;131}132133void InterpFrame::describe(llvm::raw_ostream &OS) const {134// For lambda static invokers, we would just print __invoke().135if (const auto *F = getFunction(); F && shouldSkipInBacktrace(F))136return;137138const Expr *CallExpr = Caller->getExpr(getRetPC());139const FunctionDecl *F = getCallee();140bool IsMemberCall = isa<CXXMethodDecl>(F) && !isa<CXXConstructorDecl>(F) &&141cast<CXXMethodDecl>(F)->isImplicitObjectMemberFunction();142if (Func->hasThisPointer() && IsMemberCall) {143if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {144const Expr *Object = MCE->getImplicitObjectArgument();145Object->printPretty(OS, /*Helper=*/nullptr,146S.getASTContext().getPrintingPolicy(),147/*Indentation=*/0);148if (Object->getType()->isPointerType())149OS << "->";150else151OS << ".";152} else if (const auto *OCE =153dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {154OCE->getArg(0)->printPretty(OS, /*Helper=*/nullptr,155S.getASTContext().getPrintingPolicy(),156/*Indentation=*/0);157OS << ".";158} else if (const auto *M = dyn_cast<CXXMethodDecl>(F)) {159print(OS, This, S.getASTContext(),160S.getASTContext().getLValueReferenceType(161S.getASTContext().getRecordType(M->getParent())));162OS << ".";163}164}165166F->getNameForDiagnostic(OS, S.getASTContext().getPrintingPolicy(),167/*Qualified=*/false);168OS << '(';169unsigned Off = 0;170171Off += Func->hasRVO() ? primSize(PT_Ptr) : 0;172Off += Func->hasThisPointer() ? primSize(PT_Ptr) : 0;173174for (unsigned I = 0, N = F->getNumParams(); I < N; ++I) {175QualType Ty = F->getParamDecl(I)->getType();176177PrimType PrimTy = S.Ctx.classify(Ty).value_or(PT_Ptr);178179TYPE_SWITCH(PrimTy, print(OS, stackRef<T>(Off), S.getASTContext(), Ty));180Off += align(primSize(PrimTy));181if (I + 1 != N)182OS << ", ";183}184OS << ")";185}186187Frame *InterpFrame::getCaller() const {188if (Caller->Caller)189return Caller;190return S.getSplitFrame();191}192193SourceRange InterpFrame::getCallRange() const {194if (!Caller->Func) {195if (SourceRange NullRange = S.getRange(nullptr, {}); NullRange.isValid())196return NullRange;197return S.EvalLocation;198}199return S.getRange(Caller->Func, RetPC - sizeof(uintptr_t));200}201202const FunctionDecl *InterpFrame::getCallee() const {203if (!Func)204return nullptr;205return Func->getDecl();206}207208Pointer InterpFrame::getLocalPointer(unsigned Offset) const {209assert(Offset < Func->getFrameSize() && "Invalid local offset.");210return Pointer(localBlock(Offset));211}212213Pointer InterpFrame::getParamPointer(unsigned Off) {214// Return the block if it was created previously.215if (auto Pt = Params.find(Off); Pt != Params.end())216return Pointer(reinterpret_cast<Block *>(Pt->second.get()));217218// Allocate memory to store the parameter and the block metadata.219const auto &Desc = Func->getParamDescriptor(Off);220size_t BlockSize = sizeof(Block) + Desc.second->getAllocSize();221auto Memory = std::make_unique<char[]>(BlockSize);222auto *B = new (Memory.get()) Block(S.Ctx.getEvalID(), Desc.second);223B->invokeCtor();224225// Copy the initial value.226TYPE_SWITCH(Desc.first, new (B->data()) T(stackRef<T>(Off)));227228// Record the param.229Params.insert({Off, std::move(Memory)});230return Pointer(B);231}232233static bool funcHasUsableBody(const Function *F) {234assert(F);235236if (F->isConstructor() || F->isDestructor())237return true;238239return !F->getDecl()->isImplicit();240}241242SourceInfo InterpFrame::getSource(CodePtr PC) const {243// Implicitly created functions don't have any code we could point at,244// so return the call site.245if (Func && !funcHasUsableBody(Func) && Caller)246return Caller->getSource(RetPC);247248// Similarly, if the resulting source location is invalid anyway,249// point to the caller instead.250SourceInfo Result = S.getSource(Func, PC);251if (Result.getLoc().isInvalid() && Caller)252return Caller->getSource(RetPC);253return Result;254}255256const Expr *InterpFrame::getExpr(CodePtr PC) const {257if (Func && !funcHasUsableBody(Func) && Caller)258return Caller->getExpr(RetPC);259260return S.getExpr(Func, PC);261}262263SourceLocation InterpFrame::getLocation(CodePtr PC) const {264if (Func && !funcHasUsableBody(Func) && Caller)265return Caller->getLocation(RetPC);266267return S.getLocation(Func, PC);268}269270SourceRange InterpFrame::getRange(CodePtr PC) const {271if (Func && !funcHasUsableBody(Func) && Caller)272return Caller->getRange(RetPC);273274return S.getRange(Func, PC);275}276277bool InterpFrame::isStdFunction() const {278if (!Func)279return false;280for (const DeclContext *DC = Func->getDecl(); DC; DC = DC->getParent())281if (DC->isStdNamespace())282return true;283284return false;285}286287288