clang 24.0.0git
InterpState.cpp
Go to the documentation of this file.
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"
18
19using namespace clang;
20using namespace clang::interp;
21
23 InterpStack &Stk, FrameAllocator &FrameAlloc,
25 : State(Ctx.getASTContext(), 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()) {
33 EvalMode = Settings.EvalMode;
34}
35
37 InterpStack &Stk, FrameAllocator &FrameAlloc,
38 Context &Ctx, const Function *Func)
39 : State(Ctx.getASTContext(), Settings.EvalStatus), M(nullptr),
40 FrameAlloc(FrameAlloc), P(P), Stk(Stk), Ctx(Ctx), BottomFrame(*this),
41 Current(&BottomFrame), StepsLeft(Ctx.getLangOpts().ConstexprStepLimit),
42 InfiniteSteps(StepsLeft == 0), EvalID(Ctx.getEvalID()) {
47 EvalMode = Settings.EvalMode;
48}
49
51 FrameAllocator &FrameAlloc, Context &Ctx,
52 SourceMapper *M)
53 : State(Ctx.getASTContext(), Status), M(M), FrameAlloc(FrameAlloc), P(P),
55 StepsLeft(Ctx.getLangOpts().ConstexprStepLimit),
56 InfiniteSteps(StepsLeft == 0), EvalID(Ctx.getEvalID()) {
57 InConstantContext = true;
61}
62
69
71 assert(Current->isBottomFrame());
72
73 while (DeadBlocks) {
74 DeadBlock *Next = DeadBlocks->Next;
75
76 // There might be a pointer in a global structure pointing to the dead
77 // block.
78 for (Pointer *P = DeadBlocks->B.Pointers; P; P = P->asBlockPointer().Next)
79 DeadBlocks->B.removePointer(P);
80
81 std::free(DeadBlocks);
82 DeadBlocks = Next;
83 }
84}
85
87 // As a last resort, make sure all pointers still pointing to a dead block
88 // don't point to it anymore.
89 if (Alloc)
90 Alloc->cleanup();
91}
92
94
96 assert(B);
97 assert(!B->isDynamic());
98 assert(!B->isStatic());
99 assert(!B->isDead());
100
101 // The block might have a pointer saved in a field in its data
102 // that points to the block itself. We call the dtor first,
103 // which will destroy all the data but leave InlineDescriptors
104 // intact. If the block THEN still has pointers, we create a
105 // DeadBlock for it.
106 if (B->IsInitialized)
107 B->invokeDtor();
108
109 assert(!B->isInitialized());
110 if (B->hasPointers()) {
111 size_t Size = B->getSize();
112 // Allocate a new block, transferring over pointers.
113 char *Memory =
114 reinterpret_cast<char *>(std::malloc(sizeof(DeadBlock) + Size));
115 auto *D = new (Memory) DeadBlock(DeadBlocks, B);
116 // Since the block doesn't hold any actual data anymore, we can just
117 // memcpy() everything over.
118 std::memcpy(D->rawData(), B->rawData(), Size);
119 D->B.IsInitialized = false;
120 }
121}
122
124 if (!Alloc)
125 return true;
126
127 bool NoAllocationsLeft = !Alloc->hasAllocations();
128
130 for (const auto &[Source, Site] : Alloc->allocation_sites()) {
131 assert(!Site.empty());
132
133 CCEDiag(Source->getExprLoc(), diag::note_constexpr_memory_leak)
134 << (Site.size() - 1) << Source->getSourceRange();
135 }
136 }
137 // Keep evaluating before C++20, since the CXXNewExpr wasn't valid there
138 // in the first place.
139 return NoAllocationsLeft || !getLangOpts().CPlusPlus20;
140}
141
143 for (const InterpFrame *F = Current; F; F = F->Caller) {
144 const Function *Func = F->getFunction();
145 if (!Func)
146 continue;
147 const auto *MD = dyn_cast_if_present<CXXMethodDecl>(Func->getDecl());
148 if (!MD)
149 continue;
150 const IdentifierInfo *FnII = MD->getIdentifier();
151 if (!FnII || !FnII->isStr(Name))
152 continue;
153
154 const auto *CTSD =
155 dyn_cast<ClassTemplateSpecializationDecl>(MD->getParent());
156 if (!CTSD)
157 continue;
158
159 const IdentifierInfo *ClassII = CTSD->getIdentifier();
160 const TemplateArgumentList &TAL = CTSD->getTemplateArgs();
161 if (CTSD->isInStdNamespace() && ClassII && ClassII->isStr("allocator") &&
162 TAL.size() >= 1 && TAL[0].getKind() == TemplateArgument::Type) {
163 QualType ElemType = TAL[0].getAsType();
164 const auto *NewCall = cast<CallExpr>(F->Caller->getExpr(F->getRetOpPC()));
165 return {NewCall, ElemType};
166 }
167 }
168
169 return {};
170}
171
172bool InterpState::diagnoseStepLimitExceeded(CodePtr OpPC) {
173 FFDiag(Current->getSource(OpPC), diag::note_constexpr_step_limit_exceeded, 1)
174 << getLangOpts().ConstexprStepLimit;
175 Note(Current->getSource(OpPC), diag::note_constexpr_steps);
176 return false;
177}
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
Defines the C++ template declaration subclasses.
FormatToken * Next
The next token in the unwrapped line.
One of these records is kept for each identifier that is lexed.
bool isStr(const char(&Str)[StrLen]) const
Return true if this is the identifier for the specified string.
A (possibly-)qualified type.
Definition TypeBase.h:938
A template argument list.
unsigned size() const
Retrieve the number of template arguments in this template argument list.
@ Type
The template argument is a type.
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:43
unsigned getSize() const
Returns the size of the block, including metadata.
Definition InterpBlock.h:91
void invokeDtor()
Invokes the Destructor.
bool isDead() const
Definition InterpBlock.h:89
bool isStatic() const
Checks if the block has static storage duration.
Definition InterpBlock.h:79
std::byte * rawData()
Returns a pointer to the raw data, including metadata.
bool isInitialized() const
Returns whether the data of this block has been initialized via invoking the Ctor func.
Definition InterpBlock.h:98
bool isDynamic() const
Definition InterpBlock.h:83
bool hasPointers() const
Checks if the block has any live pointers.
Definition InterpBlock.h:75
Pointer into the code segment.
Definition Source.h:31
Holds all information required to evaluate constexpr code in a module.
Definition Context.h:49
Descriptor for a dead block.
Allocator for function frames.
Base class for stack frames, shared between VM and walker.
Definition Frame.h:28
Bytecode function.
Definition Function.h:98
Frame storing local variables.
Definition InterpFrame.h:27
SourceInfo getSource(CodePtr PC) const
Map a location to a source.
Stack frame storing temporaries and parameters.
Definition InterpStack.h:26
InterpFrame BottomFrame
Bottom function frame.
Context & Ctx
Interpreter Context.
InterpState(const EvalSettings &Settings, Program &P, InterpStack &Stk, FrameAllocator &FrameAlloc, Context &Ctx, SourceMapper *M=nullptr)
const unsigned EvalID
ID identifying this evaluation.
InterpStack & Stk
Temporary stack.
bool maybeDiagnoseDanglingAllocations()
Diagnose any dynamic allocations that haven't been freed yet.
unsigned StepsLeft
Steps left during evaluation.
InterpFrame * Current
The current frame.
const Frame * getCurrentFrame() override
std::optional< bool > ConstantContextOverride
const bool InfiniteSteps
Whether infinite evaluation steps have been requested.
void deallocate(Block *B)
Deallocates a pointer.
StdAllocatorCaller getStdAllocatorCaller(StringRef Name) const
Program & P
Reference to the module containing all bytecode.
A pointer to a memory block, live or dead.
Definition Pointer.h:546
The program contains and links the bytecode for all functions.
Definition Program.h:38
Interface for classes which map locations to sources.
Definition Source.h:138
EvaluationMode EvalMode
Definition State.h:190
OptionalDiagnostic FFDiag(SourceLocation Loc, diag::kind DiagId=diag::note_invalid_subexpr_in_const_expr, unsigned ExtraNotes=0)
Diagnose that the evaluation could not be folded (FF => FoldFailure)
Definition State.cpp:37
State(ASTContext &ASTCtx, Expr::EvalStatus &EvalStatus)
Definition State.h:81
bool CheckingPotentialConstantExpression
Whether we're checking that an expression is a potential constant expression.
Definition State.h:180
bool CheckingForUndefinedBehavior
Whether we're checking for an expression that has undefined behavior.
Definition State.h:188
Expr::EvalStatus & EvalStatus
Definition State.h:192
ASTContext & getASTContext() const
Definition State.h:90
OptionalDiagnostic CCEDiag(SourceLocation Loc, diag::kind DiagId=diag::note_invalid_subexpr_in_const_expr, unsigned ExtraNotes=0)
Diagnose that the evaluation does not produce a C++11 core constant expression.
Definition State.cpp:60
const LangOptions & getLangOpts() const
Definition State.h:91
bool checkingPotentialConstantExpression() const
Are we checking whether the expression is a potential constant expression?
Definition State.h:122
bool InConstantContext
Whether or not we're in a context where the front end requires a constant value.
Definition State.h:175
Top level wrappers for InstallAPI frontend operations.
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ ConstantExpression
Evaluate as a constant expression.
Definition State.h:56
U cast(CodeGen::Address addr)
Definition Address.h:327
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition Expr.h:622
const EvaluationMode EvalMode