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