1//===--- InterpState.cpp - Interpreter for the constexpr 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 "InterpState.h"
10#include "InterpFrame.h"
11#include "InterpStack.h"
12#include "Program.h"
13#include "State.h"
14#include "clang/AST/DeclCXX.h"
15#include "clang/AST/DeclTemplate.h"
16
17using namespace clang;
18using namespace clang::interp;
19
20InterpState::InterpState(const State &Parent, Program &P, InterpStack &Stk,
21 FrameAllocator &FrameAlloc, Context &Ctx,
22 SourceMapper *M)
23 : State(Ctx.getASTContext(), Parent.getEvalStatus()), M(M),
24 FrameAlloc(FrameAlloc), P(P), Stk(Stk), Ctx(Ctx), BottomFrame(*this),
25 Current(&BottomFrame), StepsLeft(Ctx.getLangOpts().ConstexprStepLimit),
26 InfiniteSteps(StepsLeft == 0), EvalID(Ctx.getEvalID()) {
27 InConstantContext = Parent.InConstantContext;
28 CheckingPotentialConstantExpression =
29 Parent.CheckingPotentialConstantExpression;
30 CheckingForUndefinedBehavior = Parent.CheckingForUndefinedBehavior;
31 EvalMode = Parent.EvalMode;
32}
33
34InterpState::InterpState(const State &Parent, Program &P, InterpStack &Stk,
35 FrameAllocator &FrameAlloc,
36
37 Context &Ctx, const Function *Func)
38 : State(Ctx.getASTContext(), Parent.getEvalStatus()), M(nullptr),
39 FrameAlloc(FrameAlloc), P(P), Stk(Stk), Ctx(Ctx), BottomFrame(*this),
40 Current(&BottomFrame), StepsLeft(Ctx.getLangOpts().ConstexprStepLimit),
41 InfiniteSteps(StepsLeft == 0), EvalID(Ctx.getEvalID()) {
42 InConstantContext = Parent.InConstantContext;
43 CheckingPotentialConstantExpression =
44 Parent.CheckingPotentialConstantExpression;
45 CheckingForUndefinedBehavior = Parent.CheckingForUndefinedBehavior;
46 EvalMode = Parent.EvalMode;
47}
48
49bool InterpState::inConstantContext() const {
50 if (ConstantContextOverride)
51 return *ConstantContextOverride;
52
53 return InConstantContext;
54}
55
56InterpState::~InterpState() {
57 assert(Current->isBottomFrame());
58
59 while (DeadBlocks) {
60 DeadBlock *Next = DeadBlocks->Next;
61
62 // There might be a pointer in a global structure pointing to the dead
63 // block.
64 for (Pointer *P = DeadBlocks->B.Pointers; P; P = P->asBlockPointer().Next)
65 DeadBlocks->B.removePointer(P);
66
67 std::free(ptr: DeadBlocks);
68 DeadBlocks = Next;
69 }
70}
71
72void InterpState::cleanup() {
73 // As a last resort, make sure all pointers still pointing to a dead block
74 // don't point to it anymore.
75 if (Alloc)
76 Alloc->cleanup();
77}
78
79const Frame *InterpState::getCurrentFrame() { return Current; }
80
81void InterpState::deallocate(Block *B) {
82 assert(B);
83 assert(!B->isDynamic());
84 assert(!B->isStatic());
85 assert(!B->isDead());
86
87 // The block might have a pointer saved in a field in its data
88 // that points to the block itself. We call the dtor first,
89 // which will destroy all the data but leave InlineDescriptors
90 // intact. If the block THEN still has pointers, we create a
91 // DeadBlock for it.
92 if (B->IsInitialized)
93 B->invokeDtor();
94
95 assert(!B->isInitialized());
96 if (B->hasPointers()) {
97 size_t Size = B->getSize();
98 // Allocate a new block, transferring over pointers.
99 char *Memory =
100 reinterpret_cast<char *>(std::malloc(size: sizeof(DeadBlock) + Size));
101 auto *D = new (Memory) DeadBlock(DeadBlocks, B);
102 // Since the block doesn't hold any actual data anymore, we can just
103 // memcpy() everything over.
104 std::memcpy(dest: D->rawData(), src: B->rawData(), n: Size);
105 D->B.IsInitialized = false;
106 }
107}
108
109bool InterpState::maybeDiagnoseDanglingAllocations() {
110 if (!Alloc)
111 return true;
112
113 bool NoAllocationsLeft = !Alloc->hasAllocations();
114
115 if (!checkingPotentialConstantExpression()) {
116 for (const auto &[Source, Site] : Alloc->allocation_sites()) {
117 assert(!Site.empty());
118
119 CCEDiag(Loc: Source->getExprLoc(), DiagId: diag::note_constexpr_memory_leak)
120 << (Site.size() - 1) << Source->getSourceRange();
121 }
122 }
123 // Keep evaluating before C++20, since the CXXNewExpr wasn't valid there
124 // in the first place.
125 return NoAllocationsLeft || !getLangOpts().CPlusPlus20;
126}
127
128StdAllocatorCaller InterpState::getStdAllocatorCaller(StringRef Name) const {
129 for (const InterpFrame *F = Current; F; F = F->Caller) {
130 const Function *Func = F->getFunction();
131 if (!Func)
132 continue;
133 const auto *MD = dyn_cast_if_present<CXXMethodDecl>(Val: Func->getDecl());
134 if (!MD)
135 continue;
136 const IdentifierInfo *FnII = MD->getIdentifier();
137 if (!FnII || !FnII->isStr(Str: Name))
138 continue;
139
140 const auto *CTSD =
141 dyn_cast<ClassTemplateSpecializationDecl>(Val: MD->getParent());
142 if (!CTSD)
143 continue;
144
145 const IdentifierInfo *ClassII = CTSD->getIdentifier();
146 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
147 if (CTSD->isInStdNamespace() && ClassII && ClassII->isStr(Str: "allocator") &&
148 TAL.size() >= 1 && TAL[0].getKind() == TemplateArgument::Type) {
149 QualType ElemType = TAL[0].getAsType();
150 const auto *NewCall = cast<CallExpr>(Val: F->Caller->getExpr(PC: F->getRetOpPC()));
151 return {.Call: NewCall, .AllocType: ElemType};
152 }
153 }
154
155 return {};
156}
157
158bool InterpState::diagnoseStepLimitExceeded(CodePtr OpPC) {
159 FFDiag(SI: Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_step_limit_exceeded, ExtraNotes: 1)
160 << getLangOpts().ConstexprStepLimit;
161 Note(Loc: Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_steps);
162 return false;
163}
164