brintos

brintos / llvm-project-archived public Read only

0
0
Text · 9.8 KiB · 3b88376 Raw
316 lines · cpp
1//===--- InterpFrame.cpp - Call Frame implementation 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-exception6//7//===----------------------------------------------------------------------===//8 9#include "InterpFrame.h"10#include "Boolean.h"11#include "Function.h"12#include "InterpStack.h"13#include "InterpState.h"14#include "MemberPointer.h"15#include "Pointer.h"16#include "PrimType.h"17#include "Program.h"18#include "clang/AST/ASTContext.h"19#include "clang/AST/DeclCXX.h"20#include "clang/AST/ExprCXX.h"21 22using namespace clang;23using namespace clang::interp;24 25InterpFrame::InterpFrame(InterpState &S)26    : Caller(nullptr), S(S), Depth(0), Func(nullptr), RetPC(CodePtr()),27      ArgSize(0), Args(nullptr), FrameOffset(0) {}28 29InterpFrame::InterpFrame(InterpState &S, const Function *Func,30                         InterpFrame *Caller, CodePtr RetPC, unsigned ArgSize)31    : Caller(Caller), S(S), Depth(Caller ? Caller->Depth + 1 : 0), Func(Func),32      RetPC(RetPC), ArgSize(ArgSize), Args(static_cast<char *>(S.Stk.top())),33      FrameOffset(S.Stk.size()) {34  if (!Func)35    return;36 37  unsigned FrameSize = Func->getFrameSize();38  if (FrameSize == 0)39    return;40 41  Locals = std::make_unique<char[]>(FrameSize);42  for (auto &Scope : Func->scopes()) {43    for (auto &Local : Scope.locals()) {44      new (localBlock(Local.Offset)) Block(S.Ctx.getEvalID(), Local.Desc);45      // Note that we are NOT calling invokeCtor() here, since that is done46      // via the InitScope op.47      new (localInlineDesc(Local.Offset)) InlineDescriptor(Local.Desc);48    }49  }50}51 52InterpFrame::InterpFrame(InterpState &S, const Function *Func, CodePtr RetPC,53                         unsigned VarArgSize)54    : InterpFrame(S, Func, S.Current, RetPC, Func->getArgSize() + VarArgSize) {55  // As per our calling convention, the this pointer is56  // part of the ArgSize.57  // If the function has RVO, the RVO pointer is first.58  // If the fuction has a This pointer, that one is next.59  // Then follow the actual arguments (but those are handled60  // in getParamPointer()).61  if (Func->hasRVO()) {62    // RVO pointer offset is always 0.63  }64 65  if (Func->hasThisPointer())66    ThisPointerOffset = Func->hasRVO() ? sizeof(Pointer) : 0;67}68 69InterpFrame::~InterpFrame() {70  for (auto &Param : Params)71    S.deallocate(reinterpret_cast<Block *>(Param.second.get()));72 73  // When destroying the InterpFrame, call the Dtor for all block74  // that haven't been destroyed via a destroy() op yet.75  // This happens when the execution is interruped midway-through.76  destroyScopes();77}78 79void InterpFrame::destroyScopes() {80  if (!Func)81    return;82  for (auto &Scope : Func->scopes()) {83    for (auto &Local : Scope.locals()) {84      S.deallocate(localBlock(Local.Offset));85    }86  }87}88 89void InterpFrame::initScope(unsigned Idx) {90  if (!Func)91    return;92 93  for (auto &Local : Func->getScope(Idx).locals()) {94    localBlock(Local.Offset)->invokeCtor();95  }96}97 98void InterpFrame::enableLocal(unsigned Idx) {99  assert(Func);100 101  // FIXME: This is a little dirty, but to avoid adding a flag to102  // InlineDescriptor that's only ever useful on the toplevel of local103  // variables, we reuse the IsActive flag for the enabled state. We should104  // probably use a different struct than InlineDescriptor for the block-level105  // inline descriptor of local varaibles.106  localInlineDesc(Idx)->IsActive = true;107}108 109void InterpFrame::destroy(unsigned Idx) {110  for (auto &Local : Func->getScope(Idx).locals_reverse()) {111    S.deallocate(localBlock(Local.Offset));112  }113}114 115template <typename T>116static void print(llvm::raw_ostream &OS, const T &V, ASTContext &ASTCtx,117                  QualType Ty) {118  if constexpr (std::is_same_v<Pointer, T>) {119    if (Ty->isPointerOrReferenceType())120      V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);121    else {122      if (std::optional<APValue> RValue = V.toRValue(ASTCtx, Ty))123        RValue->printPretty(OS, ASTCtx, Ty);124      else125        OS << "...";126    }127  } else {128    V.toAPValue(ASTCtx).printPretty(OS, ASTCtx, Ty);129  }130}131 132static bool shouldSkipInBacktrace(const Function *F) {133  if (F->isLambdaStaticInvoker())134    return true;135 136  const FunctionDecl *FD = F->getDecl();137  if (FD->getDeclName().getCXXOverloadedOperator() == OO_New ||138      FD->getDeclName().getCXXOverloadedOperator() == OO_Array_New)139    return true;140 141  if (const auto *MD = dyn_cast<CXXMethodDecl>(FD);142      MD && MD->getParent()->isAnonymousStructOrUnion())143    return true;144 145  if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(FD);146      Ctor && Ctor->isDefaulted() && Ctor->isTrivial() &&147      Ctor->isCopyOrMoveConstructor() && Ctor->inits().empty())148    return true;149 150  return false;151}152 153void InterpFrame::describe(llvm::raw_ostream &OS) const {154  // For lambda static invokers, we would just print __invoke().155  if (const auto *F = getFunction(); F && shouldSkipInBacktrace(F))156    return;157 158  const Expr *CallExpr = Caller->getExpr(getRetPC());159  const FunctionDecl *F = getCallee();160  bool IsMemberCall = isa<CXXMethodDecl>(F) && !isa<CXXConstructorDecl>(F) &&161                      cast<CXXMethodDecl>(F)->isImplicitObjectMemberFunction();162  if (Func->hasThisPointer() && IsMemberCall) {163    if (const auto *MCE = dyn_cast_if_present<CXXMemberCallExpr>(CallExpr)) {164      const Expr *Object = MCE->getImplicitObjectArgument();165      Object->printPretty(OS, /*Helper=*/nullptr,166                          S.getASTContext().getPrintingPolicy(),167                          /*Indentation=*/0);168      if (Object->getType()->isPointerType())169        OS << "->";170      else171        OS << ".";172    } else if (const auto *OCE =173                   dyn_cast_if_present<CXXOperatorCallExpr>(CallExpr)) {174      OCE->getArg(0)->printPretty(OS, /*Helper=*/nullptr,175                                  S.getASTContext().getPrintingPolicy(),176                                  /*Indentation=*/0);177      OS << ".";178    } else if (const auto *M = dyn_cast<CXXMethodDecl>(F)) {179      print(OS, getThis(), S.getASTContext(),180            S.getASTContext().getLValueReferenceType(181                S.getASTContext().getCanonicalTagType(M->getParent())));182      OS << ".";183    }184  }185 186  F->getNameForDiagnostic(OS, S.getASTContext().getPrintingPolicy(),187                          /*Qualified=*/false);188  OS << '(';189  unsigned Off = 0;190 191  Off += Func->hasRVO() ? primSize(PT_Ptr) : 0;192  Off += Func->hasThisPointer() ? primSize(PT_Ptr) : 0;193 194  for (unsigned I = 0, N = F->getNumParams(); I < N; ++I) {195    QualType Ty = F->getParamDecl(I)->getType();196 197    PrimType PrimTy = S.Ctx.classify(Ty).value_or(PT_Ptr);198 199    TYPE_SWITCH(PrimTy, print(OS, stackRef<T>(Off), S.getASTContext(), Ty));200    Off += align(primSize(PrimTy));201    if (I + 1 != N)202      OS << ", ";203  }204  OS << ")";205}206 207SourceRange InterpFrame::getCallRange() const {208  if (!Caller->Func) {209    if (SourceRange NullRange = S.getRange(nullptr, {}); NullRange.isValid())210      return NullRange;211    return S.EvalLocation;212  }213 214  // Move up to the frame that has a valid location for the caller.215  for (const InterpFrame *C = this; C; C = C->Caller) {216    if (!C->RetPC)217      continue;218    SourceRange CallRange =219        S.getRange(C->Caller->Func, C->RetPC - sizeof(uintptr_t));220    if (CallRange.isValid())221      return CallRange;222  }223  return S.EvalLocation;224}225 226const FunctionDecl *InterpFrame::getCallee() const {227  if (!Func)228    return nullptr;229  return Func->getDecl();230}231 232Pointer InterpFrame::getLocalPointer(unsigned Offset) const {233  assert(Offset < Func->getFrameSize() && "Invalid local offset.");234  return Pointer(localBlock(Offset));235}236 237Block *InterpFrame::getLocalBlock(unsigned Offset) const {238  return localBlock(Offset);239}240 241Pointer InterpFrame::getParamPointer(unsigned Off) {242  // Return the block if it was created previously.243  if (auto Pt = Params.find(Off); Pt != Params.end())244    return Pointer(reinterpret_cast<Block *>(Pt->second.get()));245 246  assert(!isBottomFrame());247 248  // Allocate memory to store the parameter and the block metadata.249  const auto &Desc = Func->getParamDescriptor(Off);250  size_t BlockSize = sizeof(Block) + Desc.second->getAllocSize();251  auto Memory = std::make_unique<char[]>(BlockSize);252  auto *B = new (Memory.get()) Block(S.Ctx.getEvalID(), Desc.second);253  B->invokeCtor();254 255  // Copy the initial value.256  TYPE_SWITCH(Desc.first, new (B->data()) T(stackRef<T>(Off)));257 258  // Record the param.259  Params.insert({Off, std::move(Memory)});260  return Pointer(B);261}262 263static bool funcHasUsableBody(const Function *F) {264  assert(F);265 266  if (F->isConstructor() || F->isDestructor())267    return true;268 269  return !F->getDecl()->isImplicit();270}271 272SourceInfo InterpFrame::getSource(CodePtr PC) const {273  // Implicitly created functions don't have any code we could point at,274  // so return the call site.275  if (Func && !funcHasUsableBody(Func) && Caller)276    return Caller->getSource(RetPC);277 278  // Similarly, if the resulting source location is invalid anyway,279  // point to the caller instead.280  SourceInfo Result = S.getSource(Func, PC);281  if (Result.getLoc().isInvalid() && Caller)282    return Caller->getSource(RetPC);283  return Result;284}285 286const Expr *InterpFrame::getExpr(CodePtr PC) const {287  if (Func && !funcHasUsableBody(Func) && Caller)288    return Caller->getExpr(RetPC);289 290  return S.getExpr(Func, PC);291}292 293SourceLocation InterpFrame::getLocation(CodePtr PC) const {294  if (Func && !funcHasUsableBody(Func) && Caller)295    return Caller->getLocation(RetPC);296 297  return S.getLocation(Func, PC);298}299 300SourceRange InterpFrame::getRange(CodePtr PC) const {301  if (Func && !funcHasUsableBody(Func) && Caller)302    return Caller->getRange(RetPC);303 304  return S.getRange(Func, PC);305}306 307bool InterpFrame::isStdFunction() const {308  if (!Func)309    return false;310  for (const DeclContext *DC = Func->getDecl(); DC; DC = DC->getParent())311    if (DC->isStdNamespace())312      return true;313 314  return false;315}316