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