clang 24.0.0git
Interp.cpp
Go to the documentation of this file.
1//===------- Interp.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 "Interp.h"
10#include "Compiler.h"
11#include "Function.h"
12#include "InterpFrame.h"
13#include "InterpShared.h"
14#include "InterpStack.h"
15#include "Opcode.h"
16#include "PrimType.h"
17#include "Program.h"
18#include "State.h"
21#include "clang/AST/DeclObjC.h"
22#include "clang/AST/Expr.h"
23#include "clang/AST/ExprCXX.h"
24#include "clang/AST/SemaProxy.h"
27#include "llvm/ADT/ScopeExit.h"
28#include "llvm/ADT/StringExtras.h"
29
30using namespace clang;
31using namespace clang::interp;
32
33#if __has_cpp_attribute(clang::musttail)
34#define MUSTTAIL [[clang::musttail]]
35#elif __has_cpp_attribute(msvc::musttail)
36#define MUSTTAIL [[msvc::musttail]]
37#elif __has_attribute(musttail)
38#define MUSTTAIL __attribute__((musttail))
39#endif
40
41// On MSVC, musttail does not guarantee tail calls in debug mode.
42// We disable it on MSVC generally since it doesn't seem to be able
43// to handle the way we use tailcalls.
44// MIPS and PPC can't tail-call external calls, which is a problem for
45// InterpNext.
46#if defined(_MSC_VER) || defined(__powerpc__) || !defined(MUSTTAIL) || \
47 defined(__i386__) || defined(__sparc__) || defined(__mips__)
48#undef MUSTTAIL
49#define MUSTTAIL
50#define USE_TAILCALLS 0
51#else
52#define USE_TAILCALLS 1
53#endif
54
55// FIXME: Code duplication with Pointer.cpp
56static bool validType(QualType T) {
57 if (const RecordDecl *RD = T->getAsRecordDecl())
58 return ASTContext::hasLayout(RD);
59 return !T->isDependentType() && !T->isUndeducedAutoType() &&
60 !T->isSpecificBuiltinType(BuiltinType::UnknownAny) &&
61 !T->isIncompleteType();
62}
63
65 llvm::report_fatal_error("Interpreter cannot return values");
66}
67
68//===----------------------------------------------------------------------===//
69// Jmp, Jt, Jf
70//===----------------------------------------------------------------------===//
71
72static bool Jmp(InterpState &S, CodePtr OpPC, int32_t Offset) {
73 S.PC += Offset;
74 return S.noteStep(OpPC);
75}
76
77static bool Jt(InterpState &S, CodePtr OpPC, int32_t Offset) {
78 if (S.Stk.pop<bool>()) {
79 S.PC += Offset;
80 return S.noteStep(OpPC);
81 }
82 return true;
83}
84
85static bool Jf(InterpState &S, CodePtr OpPC, int32_t Offset) {
86 if (!S.Stk.pop<bool>()) {
87 S.PC += Offset;
88 return S.noteStep(OpPC);
89 }
90 return true;
91}
92
94 const ValueDecl *VD) {
95 const SourceInfo &E = S.Current->getSource(OpPC);
96 S.FFDiag(E, diag::note_constexpr_var_init_unknown, 1) << VD;
97 S.Note(VD->getLocation(), diag::note_declared_at) << VD->getSourceRange();
98}
99
100static void diagnoseNonConstVariable(InterpState &S, CodePtr OpPC,
101 const ValueDecl *VD,
102 AccessKinds AK = AK_Read);
104 const ValueDecl *D, AccessKinds AK = AK_Read) {
105 // This function tries pretty hard to produce a good diagnostic. Just skip
106 // that if nobody will see it anyway. This should be handled in the caller.
107 assert(S.diagnosing());
108
109 if (isa<ParmVarDecl>(D)) {
110 if (D->getType()->isReferenceType()) {
111 if (S.inConstantContext() && S.getLangOpts().CPlusPlus &&
112 !S.getLangOpts().CPlusPlus11) {
113 diagnoseNonConstVariable(S, OpPC, D);
114 return false;
115 }
116 }
117
118 const SourceInfo &Loc = S.Current->getSource(OpPC);
119 if (S.getLangOpts().CPlusPlus23 && D->getType()->isReferenceType()) {
120 S.FFDiag(Loc, diag::note_constexpr_access_unknown_variable, 1)
121 << AK_Read << D;
122 S.Note(D->getLocation(), diag::note_declared_at) << D->getSourceRange();
123 } else if (S.getLangOpts().CPlusPlus11) {
124 S.FFDiag(Loc, diag::note_constexpr_function_param_value_unknown, 1) << D;
125 S.Note(D->getLocation(), diag::note_declared_at) << D->getSourceRange();
126 } else {
127 S.FFDiag(Loc);
128 }
129 return false;
130 }
131
132 if (!D->getType().isConstQualified()) {
133 diagnoseNonConstVariable(S, OpPC, D, AK);
134 } else if (const auto *VD = dyn_cast<VarDecl>(D)) {
135 if (!VD->getAnyInitializer()) {
136 diagnoseMissingInitializer(S, OpPC, VD);
137 } else {
138 const SourceInfo &Loc = S.Current->getSource(OpPC);
139 S.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << VD;
140 S.Note(VD->getLocation(), diag::note_declared_at);
141 }
142 }
143
144 return false;
145}
146
148 return AK == AK_Assign || AK == AK_Increment || AK == AK_Decrement ||
149 AK == AK_Construct || AK == AK_Destroy;
150}
151
153 const ValueDecl *VD, AccessKinds AK) {
154 if (!S.diagnosing())
155 return;
156
157 if (!S.getLangOpts().CPlusPlus) {
158 S.FFDiag(S.Current->getSource(OpPC));
159 return;
160 }
161
162 if (const auto *VarD = dyn_cast<VarDecl>(VD);
163 VarD && VarD->isCXXForRangeImplicitVar()) {
164 S.FFDiag(S.Current->getSource(OpPC),
165 diag::note_constexpr_ltor_for_range_var)
166 << VarD;
167 return;
168 }
169
170 if (const auto *VarD = dyn_cast<VarDecl>(VD);
171 VarD && VarD->getType().isConstQualified() &&
172 (VarD->isConstexpr() || !VarD->getType()->isArrayType()) &&
173 !VarD->getAnyInitializer()) {
174 diagnoseMissingInitializer(S, OpPC, VD);
175 return;
176 }
177
178 // Rather random, but this is to match the diagnostic output of the current
179 // interpreter.
180 if (isa<ObjCIvarDecl>(VD))
181 return;
182
184 SourceInfo Loc = S.Current->getSource(OpPC);
185 if (isModification(AK)) {
186 S.FFDiag(Loc, diag::note_constexpr_modify_global);
187 } else {
188 S.FFDiag(Loc, diag::note_constexpr_ltor_non_const_int, 1) << VD;
189 S.Note(VD->getLocation(), diag::note_declared_at);
190 }
191 return;
192 }
193
194 S.FFDiag(S.Current->getSource(OpPC),
195 S.getLangOpts().CPlusPlus11 ? diag::note_constexpr_ltor_non_constexpr
196 : diag::note_constexpr_ltor_non_integral,
197 1)
198 << VD << VD->getType();
199 S.Note(VD->getLocation(), diag::note_declared_at);
200}
201
202static bool CheckGlobal(InterpState &S, CodePtr OpPC, const Block *B) {
203 if (auto ID = B->getDeclID()) {
204 if (!B->isGlobal())
205 return true;
206
207 if (S.P.getCurrentDecl() == ID)
208 return true;
209
210 S.FFDiag(S.Current->getLocation(OpPC), diag::note_constexpr_modify_global);
211 return false;
212 }
213 return true;
214}
215
216namespace clang {
217namespace interp {
218
219static void noteValueLocation(InterpState &S, const Block *B) {
220 const Descriptor *Desc = B->getDescriptor();
221
222 if (B->isDynamic())
223 S.Note(Desc->getLocation(), diag::note_constexpr_dynamic_alloc_here);
224 else if (B->isTemporary())
225 S.Note(Desc->getLocation(), diag::note_constexpr_temporary_here);
226 else
227 S.Note(Desc->getLocation(), diag::note_declared_at);
228}
229
231 if (Ptr.isBlockPointer()) {
232 noteValueLocation(S, Ptr.block());
233 return;
234 }
235
236 if (Ptr.isOpaquePointer())
237 S.Note(Ptr.asOpaquePointer().Base.getLocation(), diag::note_declared_at);
238
239 if (Ptr.isStringPointer())
240 S.Note(Ptr.asStringPointer().getLiteral(),
241 diag::note_constexpr_temporary_here);
242}
243
244static bool CheckTemporary(InterpState &S, CodePtr OpPC, const Block *B,
245 AccessKinds AK) {
246 if (B->getDeclID()) {
247 if (!(B->isGlobal() && B->isTemporary()))
248 return true;
249
250 const auto *MTE = dyn_cast_if_present<MaterializeTemporaryExpr>(
251 B->getDescriptor()->asExpr());
252 if (!MTE)
253 return true;
254
255 // FIXME(perf): Since we do this check on every Load from a static
256 // temporary, it might make sense to cache the value of the
257 // isUsableInConstantExpressions call.
259 (B->getEvalID() != S.EvalID &&
260 !MTE->isUsableInConstantExpressions(S.getASTContext()))) {
261 const SourceInfo &E = S.Current->getSource(OpPC);
262 S.FFDiag(E, diag::note_constexpr_access_static_temporary, 1) << AK;
263 noteValueLocation(S, B);
264 return false;
265 }
266 }
267
268 return true;
269}
270static bool CheckTemporary(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
271 AccessKinds AK) {
272 if (!Ptr.isBlockPointer())
273 return true;
274 return CheckTemporary(S, OpPC, Ptr.block(), AK);
275}
276
277PRESERVE_NONE static bool BCP(InterpState &S, CodePtr OpPC, int32_t Offset,
278 PrimType PT);
279
281 const APSInt *Value, unsigned Bits) {
282 switch (Failure) {
284 assert(Value);
285 S.CCEDiag(S.Current->getSource(OpPC), diag::note_constexpr_negative_shift)
286 << *Value;
287 break;
289 assert(Value);
290 const Expr *E = S.Current->getExpr(OpPC);
291 S.CCEDiag(E, diag::note_constexpr_large_shift)
292 << *Value << E->getType() << Bits;
293 break;
294 }
296 assert(Value);
297 S.CCEDiag(S.Current->getExpr(OpPC), diag::note_constexpr_lshift_of_negative)
298 << *Value;
299 break;
301 S.CCEDiag(S.Current->getExpr(OpPC), diag::note_constexpr_lshift_discards);
302 break;
303 }
304 return S.noteUndefinedBehavior();
305}
306
307bool diagnoseArrayIndex(InterpState &S, CodePtr OpPC, const APSInt &Index,
308 std::optional<uint64_t> NumElems, bool IsArray) {
309 if (IsArray)
310 assert(NumElems);
311
312 S.CCEDiag(S.Current->getSource(OpPC), diag::note_constexpr_array_index)
313 << Index << /*non-array=*/!IsArray << NumElems.value_or(0u);
314 return false;
315}
316
318 assert(S.Current);
319 assert(Func);
320
321 // Pop variadic parameter values from the stack.
322 if (S.Current->Caller && Func->isVariadic()) {
323 unsigned VariadicArgSize =
325 unsigned TargetStackSize = S.Stk.size() - VariadicArgSize;
326 while (S.Stk.size() != TargetStackSize) {
327 S.Stk.discardSlow();
328 }
329 }
330
331 // And in any case, remove the fixed parameters (the non-variadic ones)
332 // at the end.
333 for (const Function::ParamDescriptor &PDesc : Func->args_reverse())
334 TYPE_SWITCH(PDesc.T, S.Stk.discard<T>());
335
336 if (Func->hasImplicitThisPointer())
337 S.Stk.discard<Pointer>();
338 if (Func->hasRVO())
339 S.Stk.discard<Pointer>();
340}
341
342bool CheckBCPResult(InterpState &S, const Pointer &Ptr) {
343 if (Ptr.isDummy())
344 return false;
345 if (Ptr.isZero())
346 return true;
347 if (Ptr.isFunctionPointer())
348 return false;
349 if (Ptr.isIntegralPointer())
350 return true;
351 if (Ptr.isTypeidPointer())
352 return true;
353
354 if (Ptr.getType()->isAnyComplexType())
355 return true;
356
357 if (const Expr *Base = Ptr.getRootExpr())
358 return isa<StringLiteral>(Base) && Ptr.getIndex() == 0;
359 return false;
360}
361
362static bool CheckActive(InterpState &S, CodePtr OpPC, PtrView Ptr,
363 AccessKinds AK, bool WillActivate = false) {
364 if (Ptr.isActive())
365 return true;
366
367 assert(Ptr.inUnion());
368
369 // Find the outermost union.
370 PtrView U = Ptr.getBase();
371 PtrView C = Ptr;
372 while (!U.isRoot() && !U.isActive()) {
373 // A little arbitrary, but this is what the current interpreter does.
374 // See the AnonymousUnion test in test/AST/ByteCode/unions.cpp.
375 // GCC's output is more similar to what we would get without
376 // this condition.
377 if (U.getRecord() && U.getRecord()->isAnonymousUnion())
378 break;
379
380 C = U;
381 U = U.getBase();
382 }
383 assert(C.isField());
384 assert(C.getBase() == U);
385
386 // Consider:
387 // union U {
388 // struct {
389 // int x;
390 // int y;
391 // } a;
392 // }
393 //
394 // When activating x, we will also activate a. If we now try to read
395 // from y, we will get to CheckActive, because y is not active. In that
396 // case, our U will be a (not a union). We return here and let later code
397 // handle this.
398 if (!U.getFieldDesc()->isUnion())
399 return true;
400
401 // When we will activate Ptr, check that none of the unions in its path have a
402 // non-trivial default constructor.
403 if (WillActivate) {
404 bool Fails = false;
405 PtrView It = Ptr;
406 while (!It.isRoot() && !It.isActive()) {
407 if (const Record *R = It.getRecord(); R && R->isUnion()) {
408 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl());
409 CXXRD && !CXXRD->hasTrivialDefaultConstructor()) {
410 Fails = true;
411 break;
412 }
413 }
414 It = It.getBase();
415 }
416 if (!Fails)
417 return true;
418 }
419
420 // Get the inactive field descriptor.
421 assert(!C.isActive());
422 const FieldDecl *InactiveField = C.getField();
423 assert(InactiveField);
424
425 // Find the active field of the union.
426 const Record *R = U.getRecord();
427 assert(R && R->isUnion() && "Not a union");
428
429 const FieldDecl *ActiveField = nullptr;
430 for (const Record::Field &F : R->fields()) {
431 PtrView Field = U.atField(F.Offset);
432 if (Field.isActive()) {
433 ActiveField = Field.getField();
434 break;
435 }
436 }
437
438 S.FFDiag(S.Current->getSource(OpPC),
439 diag::note_constexpr_access_inactive_union_member)
440 << AK << InactiveField << !ActiveField << ActiveField;
441 return false;
442}
443
444static bool CheckActive(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
445 AccessKinds AK, bool WillActivate = false) {
446 if (!Ptr.isBlockPointer())
447 return true;
448 return CheckActive(S, OpPC, Ptr.view(), AK, WillActivate);
449}
450
451static bool CheckExtern(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
452 if (!Ptr.isExtern())
453 return true;
454
455 if (!Ptr.isPastEnd() &&
456 (Ptr.isInitialized() ||
457 (Ptr.getDeclDesc()->asVarDecl() == S.EvaluatingDecl)))
458 return true;
459
460 if (S.checkingPotentialConstantExpression() && S.getLangOpts().CPlusPlus &&
461 Ptr.isConst())
462 return false;
463
464 const auto *VD = Ptr.getDeclDesc()->asValueDecl();
465 if (!Ptr.isConstexprUnknown() || !S.checkingPotentialConstantExpression())
466 diagnoseNonConstVariable(S, OpPC, VD);
467 return false;
468}
469
470static bool CheckExtern(InterpState &S, CodePtr OpPC, const Block *B) {
471 if (!B->isExtern())
472 return true;
473 return CheckExtern(S, OpPC, Pointer(const_cast<Block *>(B)));
474}
475
476bool CheckArray(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
477 if (!Ptr.isUnknownSizeArray())
478 return true;
479 const SourceInfo &E = S.Current->getSource(OpPC);
480 S.FFDiag(E, diag::note_constexpr_unsized_array_indexed);
481 return false;
482}
483
484bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
485 AccessKinds AK) {
486 if (Ptr.isZero()) {
487 const auto Loc = S.Current->getSource(OpPC);
488
489 if (Ptr.isField())
490 S.FFDiag(Loc, diag::note_constexpr_null_subobject) << CSK_Field;
491 else
492 S.FFDiag(Loc, diag::note_constexpr_access_null) << AK;
493
494 return false;
495 }
496
497 if (!Ptr.isLive()) {
498 if (Ptr.isDynamic()) {
499 S.FFDiag(S.Current->getSource(OpPC),
500 diag::note_constexpr_access_deleted_object)
501 << AK;
502 } else if (!S.checkingPotentialConstantExpression()) {
503 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_uninit)
504 << AK << /*uninitialized=*/false << S.Current->getRange(OpPC);
505 noteValueLocation(S, Ptr);
506 }
507
508 return false;
509 }
510
511 return true;
512}
513
514bool CheckConstant(InterpState &S, CodePtr OpPC, const Descriptor *Desc,
515 AccessKinds AK) {
516 assert(Desc);
517
518 const auto *D = Desc->asVarDecl();
520 // If we're checking for a constant destructor for this variable, we can
521 // only read from it if it is constant.
522 if (D->getType().isConstQualified())
523 return true;
524 } else if (!D || D == S.EvaluatingDecl || D->isConstexpr())
525 return true;
526
527 // If we're evaluating the initializer for a constexpr variable in C23, we may
528 // only read other contexpr variables. Abort here since this one isn't
529 // constexpr.
530 if (const auto *VD = S.EvaluatingDecl;
531 VD && VD->isConstexpr() && S.getLangOpts().C23)
532 return Invalid(S, OpPC);
533
534 QualType T = D->getType();
535 bool IsConstant = T.isConstant(S.getASTContext());
536 if (T->isIntegralOrEnumerationType()) {
537 if (!IsConstant) {
538 diagnoseNonConstVariable(S, OpPC, D, AK);
539 return false;
540 }
541 return true;
542 }
543
544 if (IsConstant) {
545 if (S.getLangOpts().CPlusPlus) {
546 S.CCEDiag(S.Current->getLocation(OpPC),
547 S.getLangOpts().CPlusPlus11
548 ? diag::note_constexpr_ltor_non_constexpr
549 : diag::note_constexpr_ltor_non_integral,
550 1)
551 << D << T;
552 S.Note(D->getLocation(), diag::note_declared_at);
553 } else {
554 S.CCEDiag(S.Current->getLocation(OpPC));
555 }
556 return true;
557 }
558
559 if (T->isPointerOrReferenceType()) {
560 if (!T->getPointeeType().isConstant(S.getASTContext()) ||
561 !S.getLangOpts().CPlusPlus11) {
562 diagnoseNonConstVariable(S, OpPC, D, AK);
563 return false;
564 }
565 return true;
566 }
567
568 diagnoseNonConstVariable(S, OpPC, D, AK);
569 return false;
570}
571
572static bool CheckConstant(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
573 AccessKinds AK = AK_Read) {
575 return CheckConstant(S, OpPC, Ptr.getDeclDesc(), AK);
576
577 if (!Ptr.isStatic() || !Ptr.isBlockPointer())
578 return true;
579 if (!Ptr.getDeclID())
580 return true;
581 return CheckConstant(S, OpPC, Ptr.getDeclDesc(), AK);
582}
583
584static bool CheckConstant(InterpState &S, CodePtr OpPC, PtrView Ptr,
585 AccessKinds AK = AK_Read) {
586 if (S.checkingConstantDestruction(Ptr.getDeclDesc()->asVarDecl()))
587 return CheckConstant(S, OpPC, Ptr.getDeclDesc(), AK);
588
589 if (!Ptr.block()->isGlobal())
590 return true;
591 if (!Ptr.block()->getDeclID())
592 return true;
593 return CheckConstant(S, OpPC, Ptr.getDeclDesc(), AK);
594}
595
596bool CheckNull(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
597 CheckSubobjectKind CSK) {
598 if (!Ptr.isZero())
599 return true;
600 const SourceInfo &Loc = S.Current->getSource(OpPC);
601 S.FFDiag(Loc, diag::note_constexpr_null_subobject)
602 << CSK << S.Current->getRange(OpPC);
603
604 return false;
605}
606
607bool CheckRange(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
608 CheckSubobjectKind CSK) {
609 if (!Ptr.isElementPastEnd() && !Ptr.isZeroSizeArray())
610 return true;
611 const SourceInfo &Loc = S.Current->getSource(OpPC);
612 S.FFDiag(Loc, diag::note_constexpr_past_end_subobject)
613 << CSK << S.Current->getRange(OpPC);
614 return false;
615}
616
617bool CheckSubobject(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
618 CheckSubobjectKind CSK) {
619 if (!Ptr.isOnePastEnd())
620 return true;
621
622 const SourceInfo &Loc = S.Current->getSource(OpPC);
623 S.FFDiag(Loc, diag::note_constexpr_past_end_subobject)
624 << CSK << S.Current->getRange(OpPC);
625 return false;
626}
627
628static bool CheckConst(InterpState &S, CodePtr OpPC, PtrView Ptr) {
629 assert(Ptr.isLive() && "Pointer is not live");
630 if (!Ptr.isConst())
631 return true;
632
633 if (Ptr.isMutable() && !Ptr.isConstInMutable())
634 return true;
635
636 // The This pointer is writable in constructors and destructors,
637 // even if isConst() returns true.
638 for (PtrView V : llvm::reverse(S.InitializingPtrs)) {
639 if (V.block() != Ptr.block())
640 continue;
641 if (!V.getFieldDesc()->IsConst) {
642 // If the pointer being initialized is not declared as const,
643 // Ptr is const because of a parent of V, but that is irrelevant
644 // since V is being initialized and NOT const.
645 // This is fine, so return true.
646 return true;
647 }
648
649 // We know that Ptr is const because of a parent field and we also
650 // know that V is explicitly marked const.
651 // But since V is in InitializingPtrs, the fact that it is const doesn't
652 // matter and it is writable.
653 // What we now need to check is whether there is a pointer between Ptr and V
654 // that is marked const but NOT in InitializingPtrs. If that is the case,
655 // Ptr is currently not writable.
656 bool FoundProblem = false;
657 for (PtrView P = Ptr; P != V; P = P.getBase()) {
658 if (P.getFieldDesc()->IsConst) {
659 FoundProblem = true;
660 break;
661 }
662 }
663
664 // We couldn't find any pointer that's explicitly marked const, so
665 // Ptr is writable right now.
666 if (!FoundProblem)
667 return true;
668 // We only need to find the right block once.
669 break;
670 }
671
673 QualType Ty = Ptr.getType();
674 if (!Ptr.getFieldDesc()->IsConst)
675 Ty.addConst();
676 const SourceInfo &Loc = S.Current->getSource(OpPC);
677 S.FFDiag(Loc, diag::note_constexpr_modify_const_type) << Ty;
678 }
679 return false;
680}
681
682bool CheckConst(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
683 assert(Ptr.isLive() && "Pointer is not live");
684
685 if (!Ptr.isConst())
686 return true;
687
688 if (!Ptr.isBlockPointer())
689 return false;
690 return CheckConst(S, OpPC, Ptr.view());
691}
692
694 assert(Ptr.isLive() && "Pointer is not live");
695 if (!Ptr.isMutable())
696 return true;
697
699 // Never allowed when checking for constant destruction.
700 // Diagnose below.
701 } else if (S.getLangOpts().CPlusPlus14 &&
702 S.lifetimeStartedInEvaluation(Ptr.block())) {
703 // In C++14 onwards, it is permitted to read a mutable member whose
704 // lifetime began within the evaluation.
705 return true;
706 }
707
708 // Find the reason this pointer is mutable.
709 PtrView MutablePtr = Ptr;
710 while (!MutablePtr.isRoot() && MutablePtr.getBase().isMutable())
711 MutablePtr = MutablePtr.getBase();
712
713 const SourceInfo &Loc = S.Current->getSource(OpPC);
714 const FieldDecl *Field = MutablePtr.getField();
715 S.FFDiag(Loc, diag::note_constexpr_access_mutable, 1) << AK << Field;
716 S.Note(Field->getLocation(), diag::note_declared_at);
717 return false;
718}
719
720static bool CheckVolatile(InterpState &S, CodePtr OpPC, PtrView Ptr,
721 AccessKinds AK) {
722 assert(Ptr.isLive());
723
724 if (!Ptr.isVolatile())
725 return true;
726
727 if (!S.getLangOpts().CPlusPlus)
728 return Invalid(S, OpPC);
729
730 // Volatile object can be written-to and read if they are being constructed.
731 if (S.initializingBlock(Ptr.block()))
732 return true;
733
734 // The reason why Ptr is volatile might be further up the hierarchy.
735 // Find that pointer.
736 PtrView P = Ptr;
737 while (!P.isRoot()) {
739 break;
740 P = P.getBase();
741 }
742
743 const NamedDecl *ND = nullptr;
744 int DiagKind;
745 SourceLocation Loc;
746 if (const auto *F = P.getField()) {
747 DiagKind = 2;
748 Loc = F->getLocation();
749 ND = F;
750 } else if (auto *VD = P.getFieldDesc()->asValueDecl()) {
751 DiagKind = 1;
752 Loc = VD->getLocation();
753 ND = VD;
754 } else {
755 DiagKind = 0;
756 if (const auto *E = P.getFieldDesc()->asExpr())
757 Loc = E->getExprLoc();
758 }
759
760 S.FFDiag(S.Current->getLocation(OpPC),
761 diag::note_constexpr_access_volatile_obj, 1)
762 << AK << DiagKind << ND;
763 S.Note(Loc, diag::note_constexpr_volatile_here) << DiagKind;
764 return false;
765}
766
768 AccessKinds AK) {
769 assert(Ptr.isLive());
770 assert(!Ptr.isInitialized());
771 return diagnoseUninitialized(S, OpPC, Ptr.isExtern(), Ptr.block(),
772 Ptr.getLifetime(), AK);
773}
774
775bool diagnoseUninitialized(InterpState &S, CodePtr OpPC, bool Extern,
776 const Block *B, Lifetime LT, AccessKinds AK) {
778 // Extern and static member declarations might be initialized later.
779 if (Extern)
780 return false;
781
782 if (const VarDecl *VD = B->getDescriptor()->asVarDecl();
783 VD && VD->isStaticDataMember())
784 return false;
785 }
786
787 const Descriptor *Desc = B->getDescriptor();
788
789 if (const auto *VD = Desc->asVarDecl();
790 VD && (VD->isConstexpr() || VD->hasGlobalStorage())) {
791
792 if (VD == S.EvaluatingDecl &&
793 !(S.getLangOpts().CPlusPlus23 && VD->getType()->isReferenceType())) {
794 if (!S.getLangOpts().CPlusPlus14 &&
795 !VD->getType().isConstant(S.getASTContext())) {
796 // Diagnose as non-const read.
797 diagnoseNonConstVariable(S, OpPC, VD);
798 } else {
799 // Diagnose as "read of object outside its lifetime".
800 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_uninit)
801 << AK << /*IsIndeterminate=*/false;
802 S.Note(VD->getFirstDecl()->getLocation(), diag::note_declared_at);
803 }
804 return false;
805 }
806
807 if (VD->getAnyInitializer()) {
808 const SourceInfo &Loc = S.Current->getSource(OpPC);
809 S.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << VD;
810 S.Note(VD->getLocation(), diag::note_declared_at);
811 } else {
812 diagnoseMissingInitializer(S, OpPC, VD);
813 }
814 return false;
815 }
816
818 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_uninit)
819 << AK << /*uninitialized=*/(LT == Lifetime::Started)
820 << S.Current->getRange(OpPC);
821 noteValueLocation(S, B);
822 }
823 return false;
824}
825
827 AccessKinds AK) {
828 assert(Ptr.isLive());
829 assert(!Ptr.isInitialized());
830 return diagnoseUninitialized(S, OpPC, Ptr.isExtern(), Ptr.block(),
831 Ptr.getLifetime(), AK);
832}
833
835 const Block *B, AccessKinds AK) {
836 if (LT == Lifetime::Started)
837 return true;
838
840 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_uninit)
841 << AK << /*uninitialized=*/false << S.Current->getRange(OpPC);
842 noteValueLocation(S, B);
843 }
844 return false;
845}
846static bool CheckLifetime(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
847 AccessKinds AK) {
848 if (!Ptr.isBlockPointer())
849 return true;
850 return CheckLifetime(S, OpPC, Ptr.getLifetime(), Ptr.block(), AK);
851}
852
853static bool CheckWeak(InterpState &S, CodePtr OpPC, const Block *B) {
854 if (!B->isWeak())
855 return true;
856
857 const auto *VD = B->getDescriptor()->asVarDecl();
858 assert(VD);
859 S.FFDiag(S.Current->getLocation(OpPC), diag::note_constexpr_var_init_weak)
860 << VD;
861 S.Note(VD->getLocation(), diag::note_declared_at);
862
863 return false;
864}
865
866// The list of checks here is just the one from CheckLoad, but with the
867// ones removed that are impossible on primitive global values.
868// For example, since those can't be members of structs, they also can't
869// be mutable.
870bool CheckGlobalLoad(InterpState &S, CodePtr OpPC, const Block *B) {
871 const auto &Desc = B->getBlockDesc<GlobalInlineDescriptor>();
872 if (!B->isAccessible()) {
873 if (!CheckExtern(S, OpPC, B))
874 return false;
875 if (!CheckWeak(S, OpPC, B))
876 return false;
877 return false;
878 }
879
880 if (!CheckConstant(S, OpPC, B->getDescriptor()))
881 return false;
882 if (Desc.InitState != GlobalInitState::Initialized)
883 return diagnoseUninitialized(S, OpPC, B->isExtern(), B);
884 if (!CheckTemporary(S, OpPC, B, AK_Read))
885 return false;
886 if (B->getDescriptor()->IsVolatile) {
887 if (!S.getLangOpts().CPlusPlus)
888 return Invalid(S, OpPC);
889
890 const ValueDecl *D = B->getDescriptor()->asValueDecl();
891 S.FFDiag(S.Current->getLocation(OpPC),
892 diag::note_constexpr_access_volatile_obj, 1)
893 << AK_Read << 1 << D;
894 S.Note(D->getLocation(), diag::note_constexpr_volatile_here) << 1;
895 return false;
896 }
897 return true;
898}
899
900// Similarly, for local loads.
901bool CheckLocalLoad(InterpState &S, CodePtr OpPC, const Block *B) {
902 assert(!B->isExtern());
903 const auto &Desc = B->getBlockDesc<LocalInlineDescriptor>();
904 const Descriptor *BlockDesc = B->getDescriptor();
905 if (!Desc.IsInitialized)
906 return diagnoseUninitialized(S, OpPC, /*Extern=*/false, B,
907 Desc.getLifetime());
908 if (!CheckLifetime(S, OpPC, Desc.getLifetime(), B, AK_Read))
909 return false;
910 if (BlockDesc->IsVolatile) {
911 if (!S.getLangOpts().CPlusPlus)
912 return Invalid(S, OpPC);
913
914 const ValueDecl *D = BlockDesc->asValueDecl();
915 S.FFDiag(S.Current->getLocation(OpPC),
916 diag::note_constexpr_access_volatile_obj, 1)
917 << AK_Read << 1 << D;
918 S.Note(D->getLocation(), diag::note_constexpr_volatile_here) << 1;
919 return false;
920 }
921
922 // A non-const local variable while we don't have a parent frame. This must be
923 // a local variable in a statement expression.
924 if (S.Current->isBottomFrame() && !BlockDesc->IsConst &&
925 !BlockDesc->IsTemporary && !S.checkingPotentialConstantExpression()) {
926 if (const ValueDecl *VD = BlockDesc->asValueDecl())
927 diagnoseNonConstVariable(S, OpPC, VD);
928 return false;
929 }
930 return true;
931}
932
934 if (Ptr.isZero()) {
935 SourceInfo Loc = S.Current->getSource(OpPC);
936
937 if (Ptr.isField())
938 S.FFDiag(Loc, diag::note_constexpr_null_subobject) << CSK_Field;
939 else
940 S.FFDiag(Loc, diag::note_constexpr_access_null) << AK;
941 return false;
942 }
943
944 if (!Ptr.block()->isAccessible()) {
945 if (!Ptr.isLive()) {
946 if (Ptr.block()->isDynamic()) {
947 S.FFDiag(S.Current->getSource(OpPC),
948 diag::note_constexpr_access_deleted_object)
949 << AK;
950 } else if (!S.checkingPotentialConstantExpression()) {
951 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_uninit)
952 << AK << /*uninitialized=*/false << S.Current->getRange(OpPC);
953 noteValueLocation(S, Ptr.block());
954 }
955
956 return false;
957 }
958 if (!CheckExtern(S, OpPC, Ptr.block()))
959 return false;
960 if (!CheckWeak(S, OpPC, Ptr.block()))
961 return false;
962 return false;
963 }
964
965 if (!CheckConstant(S, OpPC, Ptr, AK))
966 return false;
967 if (!CheckRange(S, OpPC, Ptr, AK))
968 return false;
969 if (!CheckActive(S, OpPC, Ptr, AK))
970 return false;
971 if (!Ptr.isInitialized())
972 return diagnoseUninitialized(S, OpPC, Ptr, AK);
973
974 if (!CheckLifetime(S, OpPC, Ptr.getLifetime(), Ptr.block(), AK))
975 return false;
976 if (!CheckTemporary(S, OpPC, Ptr.block(), AK))
977 return false;
978
979 if (!CheckMutable(S, OpPC, Ptr, AK))
980 return false;
981 if (!CheckVolatile(S, OpPC, Ptr, AK))
982 return false;
983
984 if (!Ptr.isArrayRoot()) {
985 // According to GCC info page:
986 //
987 // 6.28 Compound Literals
988 //
989 // As an optimization, G++ sometimes gives array compound literals
990 // longer lifetimes: when the array either appears outside a function or
991 // has a const-qualified type. If foo and its initializer had elements
992 // of type char *const rather than char *, or if foo were a global
993 // variable, the array would have static storage duration. But it is
994 // probably safest just to avoid the use of array compound literals in
995 // C++ code.
996 //
997 // Obey that rule by checking constness for converted array types.
998 const Descriptor *Desc = Ptr.getFieldDesc();
999 if (const auto *CLE =
1000 dyn_cast_if_present<CompoundLiteralExpr>(Desc->asExpr())) {
1001 if (QualType CLETy = CLE->getType();
1002 CLETy->isArrayType() && !CLETy.isConstant(S.getASTContext())) {
1003 S.FFDiag(S.Current->getLocation(OpPC),
1004 diag::note_invalid_subexpr_in_const_expr)
1005 << S.Current->getRange(OpPC);
1006 S.Note(CLE->getExprLoc(), diag::note_declared_at);
1007 return false;
1008 }
1009 }
1010 }
1011 return true;
1012}
1013
1014bool CheckLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1015 AccessKinds AK) {
1016 if (Ptr.isBlockPointer())
1017 return CheckLoad(S, OpPC, Ptr.view(), AK);
1018
1019 if (Ptr.isZero()) {
1020 SourceInfo Loc = S.Current->getSource(OpPC);
1021 if (Ptr.isField())
1022 S.FFDiag(Loc, diag::note_constexpr_null_subobject) << CSK_Field;
1023 else
1024 S.FFDiag(Loc, diag::note_constexpr_access_null) << AK;
1025 return false;
1026 }
1027
1028 // Block and string pointers are the only ones we can actually read from.
1029 if (!Ptr.isStringPointer())
1030 return diagnoseDummy(S, OpPC, Ptr, AK);
1031
1032 assert(Ptr.isStringPointer());
1033
1034 if (!CheckConstant(S, OpPC, Ptr, AK))
1035 return false;
1036 if (!CheckRange(S, OpPC, Ptr, AK))
1037 return false;
1038 if (!Ptr.isInitialized())
1039 return diagnoseUninitialized(S, OpPC, Ptr, AK);
1040 return true;
1041}
1042
1043/// This is not used by any of the opcodes directly. It's used by
1044/// EvalEmitter to do the final lvalue-to-rvalue conversion.
1045bool CheckFinalLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
1046 assert(!Ptr.isZero());
1047 if (!Ptr.isReadablePointerType())
1048 return diagnoseDummy(S, OpPC, Ptr, AK_Read);
1049
1050 if (Ptr.isBlockPointer() && !Ptr.block()->isAccessible()) {
1051 if (!CheckLive(S, OpPC, Ptr, AK_Read))
1052 return false;
1053 if (!CheckExtern(S, OpPC, Ptr))
1054 return false;
1055 if (!CheckWeak(S, OpPC, Ptr.block()))
1056 return false;
1057 return false;
1058 }
1059
1060 if (Ptr.isPastEnd())
1061 return false;
1062
1063 if (!CheckConstant(S, OpPC, Ptr))
1064 return false;
1065
1066 if (!CheckActive(S, OpPC, Ptr, AK_Read))
1067 return false;
1068 if (!Ptr.isInitialized())
1069 return diagnoseUninitialized(S, OpPC, Ptr, AK_Read);
1070
1071 if (Ptr.isBlockPointer()) {
1072 if (!CheckLifetime(S, OpPC, Ptr.getLifetime(), Ptr.block(), AK_Read))
1073 return false;
1074 if (!CheckTemporary(S, OpPC, Ptr.block(), AK_Read))
1075 return false;
1076 if (!CheckMutable(S, OpPC, Ptr.view()))
1077 return false;
1078 }
1079 return true;
1080}
1081
1082bool CheckStore(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1083 AccessKinds AK, bool WillBeActivated) {
1084 if (Ptr.isZero())
1085 return false;
1086
1087 if (Ptr.isOpaquePointer())
1088 return diagnoseDummy(S, OpPC, Ptr, AK);
1089
1090 if (!Ptr.isBlockPointer())
1091 return false;
1092
1093 PtrView P = Ptr.view();
1094 const Block *B = Ptr.block();
1095
1096 if (!B->isAccessible()) {
1097 if (!CheckLive(S, OpPC, Ptr, AK))
1098 return false;
1099 if (!CheckExtern(S, OpPC, Ptr))
1100 return false;
1101 return false;
1102 }
1103 if (!WillBeActivated && !CheckLifetime(S, OpPC, P.getLifetime(), B, AK))
1104 return false;
1105 if (!CheckRange(S, OpPC, Ptr, AK))
1106 return false;
1107 if (!CheckActive(S, OpPC, P, AK, WillBeActivated))
1108 return false;
1109 if (!CheckGlobal(S, OpPC, B))
1110 return false;
1111 if (!CheckConst(S, OpPC, P))
1112 return false;
1113 if (!CheckVolatile(S, OpPC, P, AK))
1114 return false;
1115 if (!CheckMutable(S, OpPC, P, AK))
1116 return false;
1117 return true;
1118}
1119
1120static bool CheckInvoke(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1121 bool IsCtor, bool IsDtor) {
1122 if (!Ptr.isDummy() && !Ptr.isConstexprUnknown()) {
1123 if (!CheckLive(S, OpPC, Ptr, AK_MemberCall))
1124 return false;
1125 if (!CheckRange(S, OpPC, Ptr, AK_MemberCall))
1126 return false;
1127 if (!(IsCtor || IsDtor) && !CheckLifetime(S, OpPC, Ptr, AK_MemberCall))
1128 return false;
1129 }
1130 return true;
1131}
1132
1133bool CheckInit(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
1134 if (!CheckLive(S, OpPC, Ptr, AK_Assign))
1135 return false;
1136 if (!CheckRange(S, OpPC, Ptr, AK_Assign))
1137 return false;
1138 if (!Ptr.isBlockPointer())
1139 return false;
1140 return true;
1141}
1142
1144 const FunctionDecl *DiagDecl) {
1145 if (!S.diagnosing())
1146 return false;
1147 // Bail out if the function declaration itself is invalid. We will
1148 // have produced a relevant diagnostic while parsing it, so just
1149 // note the problematic sub-expression.
1150 if (DiagDecl->isInvalidDecl())
1151 return Invalid(S, OpPC);
1152
1153 // Diagnose failed assertions specially.
1154 if (S.Current->getLocation(OpPC).isMacroID() && DiagDecl->getIdentifier()) {
1155 // FIXME: Instead of checking for an implementation-defined function,
1156 // check and evaluate the assert() macro.
1157 StringRef Name = DiagDecl->getName();
1158 bool AssertFailed =
1159 Name == "__assert_rtn" || Name == "__assert_fail" || Name == "_wassert";
1160 if (AssertFailed) {
1161 S.FFDiag(S.Current->getLocation(OpPC),
1162 diag::note_constexpr_assert_failed);
1163 return false;
1164 }
1165 }
1166
1167 if (!S.getLangOpts().CPlusPlus11) {
1168 S.FFDiag(S.Current->getLocation(OpPC),
1169 diag::note_invalid_subexpr_in_const_expr);
1170 return false;
1171 }
1172
1173 // If this function is not constexpr because it is an inherited
1174 // non-constexpr constructor, diagnose that directly.
1175 const auto *CD = dyn_cast<CXXConstructorDecl>(DiagDecl);
1176 if (CD && CD->isInheritingConstructor()) {
1177 const auto *Inherited = CD->getInheritedConstructor().getConstructor();
1178 if (!Inherited->isConstexpr())
1179 DiagDecl = CD = Inherited;
1180 }
1181
1182 // Silently reject constructors of invalid classes. The invalid class
1183 // has been rejected elsewhere before.
1184 if (CD && CD->getParent()->isInvalidDecl())
1185 return false;
1186
1187 // FIXME: If DiagDecl is an implicitly-declared special member function
1188 // or an inheriting constructor, we should be much more explicit about why
1189 // it's not constexpr.
1190 if (CD && CD->isInheritingConstructor()) {
1191 S.FFDiag(S.Current->getLocation(OpPC), diag::note_constexpr_invalid_inhctor,
1192 1)
1193 << CD->getInheritedConstructor().getConstructor()->getParent();
1194 S.Note(DiagDecl->getLocation(), diag::note_declared_at);
1195 } else {
1196 // Don't emit anything if the function isn't defined and we're checking
1197 // for a constant expression. It might be defined at the point we're
1198 // actually calling it.
1199 bool IsExtern = DiagDecl->getStorageClass() == SC_Extern;
1200 bool IsDefined = DiagDecl->isDefined();
1201 if (!IsDefined && !IsExtern && DiagDecl->isConstexpr() &&
1203 return false;
1204
1205 // If the declaration is defined, declared 'constexpr' _and_ has a body,
1206 // the below diagnostic doesn't add anything useful.
1207 if (DiagDecl->isDefined() && DiagDecl->isConstexpr() && DiagDecl->hasBody())
1208 return false;
1209
1210 S.FFDiag(S.Current->getLocation(OpPC),
1211 diag::note_constexpr_invalid_function, 1)
1212 << DiagDecl->isConstexpr() << (bool)CD << DiagDecl;
1213
1214 const FunctionDecl *Definition;
1215 bool HasBody = DiagDecl->hasBody(Definition);
1216 if (HasBody && Definition)
1217 S.Note(Definition->getLocation(), diag::note_declared_at);
1218 else
1219 S.Note(DiagDecl->getLocation(), diag::note_declared_at);
1220 }
1221
1222 return false;
1223}
1224
1225static bool CheckCallable(InterpState &S, CodePtr OpPC, const Function *F) {
1226 if (F->isVirtual() && !S.getLangOpts().CPlusPlus20) {
1227 const SourceLocation &Loc = S.Current->getLocation(OpPC);
1228 S.CCEDiag(Loc, diag::note_constexpr_virtual_call);
1229 return false;
1230 }
1231
1232 if (F->isValid() && F->hasBody() &&
1234 F->getDecl()->hasAttr<MSConstexprAttr>())))
1235 return true;
1236
1237 const FunctionDecl *DiagDecl = F->getDecl();
1238 const FunctionDecl *Definition = nullptr;
1239 DiagDecl->hasBody(Definition);
1240
1242 DiagDecl->isConstexpr()) {
1243 return false;
1244 }
1245
1246 return diagnoseCallableDecl(S, OpPC, DiagDecl);
1247}
1248
1249static bool CheckCallDepth(InterpState &S, CodePtr OpPC) {
1250 if ((S.FrameDepth + 1) > S.getLangOpts().ConstexprCallDepth) {
1251 S.FFDiag(S.Current->getSource(OpPC),
1252 diag::note_constexpr_depth_limit_exceeded)
1253 << S.getLangOpts().ConstexprCallDepth;
1254 return false;
1255 }
1256
1257 return true;
1258}
1259
1261 if (S.Current->hasThisPointer())
1262 return true;
1263
1264 if (!S.diagnosing())
1265 return false;
1266
1267 const Expr *E = S.Current->getExpr(OpPC);
1268 if (S.getLangOpts().CPlusPlus11) {
1269 bool IsImplicit = false;
1270 if (const auto *TE = dyn_cast<CXXThisExpr>(E))
1271 IsImplicit = TE->isImplicit();
1272 S.FFDiag(E, diag::note_constexpr_this) << IsImplicit;
1273 } else {
1274 S.FFDiag(E);
1275 }
1276
1277 return false;
1278}
1279
1280bool CheckFloatStatus(InterpState &S, CodePtr OpPC, APFloat::opStatus Status,
1281 FPOptions FPO) {
1282 // In a constant context, assume that any dynamic rounding mode or FP
1283 // exception state matches the default floating-point environment.
1284 if (S.inConstantContext())
1285 return true;
1286
1287 if ((Status & APFloat::opInexact) &&
1288 FPO.getRoundingMode() == llvm::RoundingMode::Dynamic) {
1289 // Inexact result means that it depends on rounding mode. If the requested
1290 // mode is dynamic, the evaluation cannot be made in compile time.
1291 const SourceInfo &E = S.Current->getSource(OpPC);
1292 S.FFDiag(E, diag::note_constexpr_dynamic_rounding);
1293 return false;
1294 }
1295
1296 if ((Status != APFloat::opOK) &&
1297 (FPO.getRoundingMode() == llvm::RoundingMode::Dynamic ||
1299 FPO.getAllowFEnvAccess())) {
1300 const SourceInfo &E = S.Current->getSource(OpPC);
1301 S.FFDiag(E, diag::note_constexpr_float_arithmetic_strict);
1302 return false;
1303 }
1304
1305 if ((Status & APFloat::opStatus::opInvalidOp) &&
1307 const SourceInfo &E = S.Current->getSource(OpPC);
1308 // There is no usefully definable result.
1309 S.FFDiag(E);
1310 return false;
1311 }
1312
1313 return true;
1314}
1315
1317 APFloat::opStatus Status, FPOptions FPO) {
1318 // FIXME: The standard quote below is deleted by P3899R3.
1319 // [expr.pre]p4:
1320 // If during the evaluation of an expression, the result is not
1321 // mathematically defined [...], the behavior is undefined.
1322 // FIXME: C++ rules require us to not conform to IEEE 754 here.
1323 // FIXME: The NaN check should not be applied outside of "constant contexts"
1324 // because it prevents NaN propagation and the "invalid" status is the
1325 // responsibility of CheckFloatStatus.
1326 if (Result.isNan()) {
1327 const SourceInfo &E = S.Current->getSource(OpPC);
1328 S.CCEDiag(E, diag::note_constexpr_float_arithmetic)
1329 << /*NaN=*/true << S.Current->getRange(OpPC);
1330 return S.noteUndefinedBehavior();
1331 }
1332
1333 return CheckFloatStatus(S, OpPC, Status, FPO);
1334}
1335
1337 if (S.getLangOpts().CPlusPlus20)
1338 return true;
1339
1340 const SourceInfo &E = S.Current->getSource(OpPC);
1341 S.CCEDiag(E, diag::note_constexpr_new);
1342 return true;
1343}
1344
1346 DynamicAllocator::Form AllocForm,
1347 DynamicAllocator::Form DeleteForm, const Descriptor *D,
1348 const Expr *NewExpr) {
1349 if (AllocForm == DeleteForm)
1350 return true;
1351
1352 QualType TypeToDiagnose = D->getDataType(S.getASTContext());
1353
1354 const SourceInfo &E = S.Current->getSource(OpPC);
1355 S.FFDiag(E, diag::note_constexpr_new_delete_mismatch)
1356 << static_cast<int>(DeleteForm) << static_cast<int>(AllocForm)
1357 << TypeToDiagnose;
1358 S.Note(NewExpr->getExprLoc(), diag::note_constexpr_dynamic_alloc_here)
1359 << NewExpr->getSourceRange();
1360 return false;
1361}
1362
1363bool CheckDeleteSource(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
1364 if (Ptr.isBlockPointer() && Ptr.block()->isDynamic())
1365 return true;
1366
1367 // Whatever this is, we didn't heap allocate it.
1368 const SourceInfo &Loc = S.Current->getSource(OpPC);
1369 S.FFDiag(Loc, diag::note_constexpr_delete_not_heap_alloc)
1370 << Ptr.toDiagnosticString(S.getASTContext());
1371 noteValueLocation(S, Ptr);
1372 return false;
1373}
1374
1375/// We aleady know the given DeclRefExpr is invalid for some reason,
1376/// now figure out why and print appropriate diagnostics.
1377bool CheckDeclRef(InterpState &S, CodePtr OpPC, const DeclRefExpr *DR) {
1378 if (!S.diagnosing())
1379 return false;
1380
1381 const ValueDecl *D = DR->getDecl();
1382 return diagnoseUnknownDecl(S, OpPC, D);
1383}
1384
1386 bool InitializerFailed) {
1387 assert(DR);
1388
1389 if (InitializerFailed) {
1390 const SourceInfo &Loc = S.Current->getSource(OpPC);
1391 const auto *VD = cast<VarDecl>(DR->getDecl());
1392 S.FFDiag(Loc, diag::note_constexpr_var_init_non_constant, 1) << VD;
1393 S.Note(VD->getLocation(), diag::note_declared_at);
1394 return false;
1395 }
1396
1397 return CheckDeclRef(S, OpPC, DR);
1398}
1399
1400bool diagnoseDummy(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1401 AccessKinds AK) {
1402 if (!S.diagnosing())
1403 return false;
1404
1405 if (AK == AK_Read || AK == AK_Increment || AK == AK_Decrement) {
1406 const VarDecl *D = Ptr.getRootVarDecl();
1407 if (!D)
1408 return false;
1409 return diagnoseUnknownDecl(S, OpPC, D, AK);
1410 }
1411
1412 if (AK == AK_Destroy || S.getLangOpts().CPlusPlus14)
1413 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_modify_global);
1414 return false;
1415}
1416
1417bool CheckDummy(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1418 AccessKinds AK) {
1419 if (!Ptr.isDummy())
1420 return true;
1421 return diagnoseDummy(S, OpPC, Ptr, AK);
1422}
1423
1424static bool CheckNonNullArgs(InterpState &S, CodePtr OpPC, const Function *F,
1425 const CallExpr *CE, unsigned ArgSize) {
1426 auto Args = ArrayRef(CE->getArgs(), CE->getNumArgs());
1427 auto NonNullArgs = collectNonNullArgs(F->getDecl(), Args);
1428 unsigned Offset = 0;
1429 unsigned Index = 0;
1430 for (const Expr *Arg : Args) {
1431 if (NonNullArgs[Index] && Arg->getType()->isPointerType()) {
1432 const Pointer &ArgPtr = S.Stk.peek<Pointer>(ArgSize - Offset);
1433 if (ArgPtr.isZero()) {
1434 const SourceLocation &Loc = S.Current->getLocation(OpPC);
1435 S.CCEDiag(Loc, diag::note_non_null_attribute_failed);
1436 return false;
1437 }
1438 }
1439
1440 Offset += align(primSize(S.Ctx.classify(Arg).value_or(PT_Ptr)));
1441 ++Index;
1442 }
1443 return true;
1444}
1445
1447 const Pointer &BasePtr,
1448 const Descriptor *Desc) {
1449 assert(Desc->isRecord());
1450 const Record *R = Desc->ElemRecord;
1451 assert(R);
1452
1453 if (!S.Current->isBottomFrame() && S.Current->hasThisPointer() &&
1455 Pointer::pointToSameBlock(BasePtr, S.Current->getThis())) {
1456 const SourceInfo &Loc = S.Current->getSource(OpPC);
1457 S.FFDiag(Loc, diag::note_constexpr_double_destroy);
1458 return false;
1459 }
1460
1461 // Destructor of this record.
1462 const CXXDestructorDecl *Dtor = R->getDestructor();
1463 assert(Dtor);
1464 assert(!Dtor->isTrivial());
1465 const Function *DtorFunc = S.getContext().getOrCreateFunction(Dtor);
1466 if (!DtorFunc)
1467 return false;
1468
1469 S.Stk.push<Pointer>(BasePtr);
1470 return Call(S, OpPC, DtorFunc, 0);
1471}
1472
1473static bool RunDestructors(InterpState &S, CodePtr OpPC, const Block *B) {
1474 assert(B);
1475 const Descriptor *Desc = B->getDescriptor();
1476
1477 if (Desc->isPrimitive() || Desc->isPrimitiveArray())
1478 return true;
1479
1480 assert(Desc->isRecord() || Desc->isCompositeArray());
1481
1482 if (Desc->hasTrivialDtor())
1483 return true;
1484
1485 if (Desc->isCompositeArray()) {
1486 unsigned N = Desc->getNumElems();
1487 if (N == 0)
1488 return true;
1489 const Descriptor *ElemDesc = Desc->ElemDesc;
1490 assert(ElemDesc->isRecord());
1491
1492 Pointer RP(const_cast<Block *>(B));
1493 for (int I = static_cast<int>(N) - 1; I >= 0; --I) {
1494 if (!runRecordDestructor(S, OpPC, RP.atIndex(I).narrow(), ElemDesc))
1495 return false;
1496 }
1497 return true;
1498 }
1499
1500 assert(Desc->isRecord());
1501 return runRecordDestructor(S, OpPC, Pointer(const_cast<Block *>(B)), Desc);
1502}
1503
1505 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1506 if (const CXXDestructorDecl *DD = RD->getDestructor())
1507 return DD->isVirtual();
1508 return false;
1509}
1510
1511bool Free(InterpState &S, CodePtr OpPC, bool DeleteIsArrayForm,
1512 bool IsGlobalDelete) {
1513 if (!CheckDynamicMemoryAllocation(S, OpPC))
1514 return false;
1515
1516 DynamicAllocator &Allocator = S.getAllocator();
1517
1518 const Expr *Source = nullptr;
1519 const Block *BlockToDelete = nullptr;
1520 {
1521 // Extra scope for this so the block doesn't have this pointer
1522 // pointing to it when we destroy it.
1523 Pointer Ptr = S.Stk.pop<Pointer>();
1524
1525 // Deleteing nullptr is always fine.
1526 if (Ptr.isZero())
1527 return true;
1528
1529 if (!Ptr.isBlockPointer())
1530 return CheckDeleteSource(S, OpPC, Ptr);
1531
1532 // Remove base casts.
1533 QualType InitialType = Ptr.getType();
1534 Ptr = Ptr.expand().stripBaseCasts();
1535
1536 Source = Ptr.getRootExpr();
1537 BlockToDelete = Ptr.block();
1538
1539 // Check that new[]/delete[] or new/delete were used, not a mixture.
1540 const Descriptor *BlockDesc = BlockToDelete->getDescriptor();
1541 if (std::optional<DynamicAllocator::Form> AllocForm =
1542 Allocator.getAllocationForm(Source)) {
1543 DynamicAllocator::Form DeleteForm =
1544 DeleteIsArrayForm ? DynamicAllocator::Form::Array
1546 if (!CheckNewDeleteForms(S, OpPC, *AllocForm, DeleteForm, BlockDesc,
1547 Source))
1548 return false;
1549 }
1550
1551 // For the non-array case, the types must match if the static type
1552 // does not have a virtual destructor.
1553 if (!DeleteIsArrayForm && Ptr.getType() != InitialType &&
1554 !hasVirtualDestructor(InitialType)) {
1555 S.FFDiag(S.Current->getSource(OpPC),
1556 diag::note_constexpr_delete_base_nonvirt_dtor)
1557 << InitialType << Ptr.getType();
1558 return false;
1559 }
1560
1561 if (!Ptr.isRoot() || (Ptr.isOnePastEnd() && !Ptr.isZeroSizeArray()) ||
1562 (Ptr.isArrayElement() && Ptr.getIndex() != 0)) {
1563 const SourceInfo &Loc = S.Current->getSource(OpPC);
1564 S.FFDiag(Loc, diag::note_constexpr_delete_subobject)
1565 << Ptr.toDiagnosticString(S.getASTContext()) << Ptr.isOnePastEnd();
1566 return false;
1567 }
1568
1569 if (!CheckDeleteSource(S, OpPC, Ptr))
1570 return false;
1571
1572 // For a class type with a virtual destructor, the selected operator delete
1573 // is the one looked up when building the destructor.
1574 if (!DeleteIsArrayForm && !IsGlobalDelete) {
1575 QualType AllocType = Ptr.getType();
1576 auto getVirtualOperatorDelete = [](QualType T) -> const FunctionDecl * {
1577 if (const CXXRecordDecl *RD = T->getAsCXXRecordDecl())
1578 if (const CXXDestructorDecl *DD = RD->getDestructor())
1579 return DD->isVirtual() ? DD->getOperatorDelete() : nullptr;
1580 return nullptr;
1581 };
1582
1583 if (const FunctionDecl *VirtualDelete =
1584 getVirtualOperatorDelete(AllocType);
1585 VirtualDelete &&
1586 !VirtualDelete
1588 S.FFDiag(S.Current->getSource(OpPC),
1589 diag::note_constexpr_new_non_replaceable)
1590 << isa<CXXMethodDecl>(VirtualDelete) << VirtualDelete;
1591 return false;
1592 }
1593 }
1594 }
1595 assert(Source);
1596 assert(BlockToDelete);
1597
1598 // Invoke destructors before deallocating the memory.
1599 if (!RunDestructors(S, OpPC, BlockToDelete))
1600 return false;
1601
1602 if (!Allocator.deallocate(Source, BlockToDelete)) {
1603 // Nothing has been deallocated, this must be a double-delete.
1604 const SourceInfo &Loc = S.Current->getSource(OpPC);
1605 S.FFDiag(Loc, diag::note_constexpr_double_delete);
1606 return false;
1607 }
1608
1609 return true;
1610}
1611
1613 const APSInt &Value) {
1614 llvm::APInt Min;
1615 llvm::APInt Max;
1616 ED->getValueRange(Max, Min);
1617 --Max;
1618
1619 if (ED->getNumNegativeBits() &&
1620 (Max.slt(Value.getSExtValue()) || Min.sgt(Value.getSExtValue()))) {
1621 const SourceLocation &Loc = S.Current->getLocation(OpPC);
1622 S.CCEDiag(Loc, diag::note_constexpr_unscoped_enum_out_of_range)
1623 << llvm::toString(Value, 10) << Min.getSExtValue() << Max.getSExtValue()
1624 << ED;
1625 } else if (!ED->getNumNegativeBits() && Max.ult(Value.getZExtValue())) {
1626 const SourceLocation &Loc = S.Current->getLocation(OpPC);
1627 S.CCEDiag(Loc, diag::note_constexpr_unscoped_enum_out_of_range)
1628 << llvm::toString(Value, 10) << Min.getZExtValue() << Max.getZExtValue()
1629 << ED;
1630 }
1631}
1632
1634 assert(T);
1635 assert(!S.getLangOpts().CPlusPlus23);
1636
1637 // C++1y: A constant initializer for an object o [...] may also invoke
1638 // constexpr constructors for o and its subobjects even if those objects
1639 // are of non-literal class types.
1640 //
1641 // C++11 missed this detail for aggregates, so classes like this:
1642 // struct foo_t { union { int i; volatile int j; } u; };
1643 // are not (obviously) initializable like so:
1644 // __attribute__((__require_constant_initialization__))
1645 // static const foo_t x = {{0}};
1646 // because "i" is a subobject with non-literal initialization (due to the
1647 // volatile member of the union). See:
1648 // http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#1677
1649 // Therefore, we use the C++1y behavior.
1650
1651 if (!S.Current->isBottomFrame() &&
1654 return true;
1655 }
1656
1657 const Expr *E = S.Current->getExpr(OpPC);
1658 if (S.getLangOpts().CPlusPlus11)
1659 S.FFDiag(E, diag::note_constexpr_nonliteral) << E->getType();
1660 else
1661 S.FFDiag(E, diag::note_invalid_subexpr_in_const_expr);
1662 return false;
1663}
1664
1666 const Pointer &Ptr, unsigned Offset) {
1667 assert(Ptr.isTypeidPointer());
1668 const Record *R = S.getContext().getRecord(
1669 Ptr.asTypeidPointer().TypeInfoType->getAsRecordDecl());
1670 if (!R)
1671 return false;
1672 const Record::Field *Field = R->findField(Offset);
1673 if (!Field)
1674 return false;
1675
1676 std::string TypeIdStr;
1677 llvm::raw_string_ostream SS(TypeIdStr);
1678 SS << "typeid(";
1679 QualType(Ptr.asTypeidPointer().TypePtr, 0)
1681 SS << ").";
1682 SS << Field->Decl->getNameAsString();
1683
1684 S.FFDiag(S.Current->getSource(OpPC),
1685 diag::note_constexpr_access_unreadable_object)
1686 << AK_Read << TypeIdStr;
1687 return false;
1688}
1689
1690static bool allowNullSubObj(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
1691 return Ptr.isZero() && S.emitRelaxedDiag(S.Current->getSource(OpPC).getLoc(),
1692 diag::note_constexpr_null_subobject);
1693}
1694
1695static bool getField(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1696 uint32_t Off) {
1697 if (S.getLangOpts().CPlusPlus && S.inConstantContext() &&
1698 !allowNullSubObj(S, OpPC, Ptr) && !CheckNull(S, OpPC, Ptr, CSK_Field))
1699 return false;
1700
1701 if (!CheckRange(S, OpPC, Ptr, CSK_Field))
1702 return false;
1703 if (!CheckArray(S, OpPC, Ptr))
1704 return false;
1705 if (!CheckSubobject(S, OpPC, Ptr, CSK_Field))
1706 return false;
1707
1708 if (Ptr.isIntegralPointer()) {
1709 if (std::optional<IntPointer> IntPtr =
1710 Ptr.asIntPointer().atOffset(S.Ctx, Off)) {
1711 S.Stk.push<Pointer>(std::move(*IntPtr));
1712 return true;
1713 }
1714 return false;
1715 }
1716
1717 if (Ptr.isOpaquePointer()) {
1718 const OpaquePointer &OP = Ptr.asOpaquePointer();
1719 const RecordDecl *RD = OP.getFieldType()->getAsRecordDecl();
1720 if (!RD)
1721 return false;
1722 const Record *R = S.getContext().getRecord(RD);
1723 if (!R)
1724 return false;
1725
1726 const Record::Field *F = R->findField(Off);
1727 if (!F)
1728 return false;
1729
1731 OP.PathLength + 1, OP.Path, PointerPathEntry::field(F->Decl));
1732
1733 S.Stk.push<Pointer>(OP.withPath(NewPath, OP.PathLength + 1,
1734 F->Decl->getType().getTypePtr()),
1735 Ptr.getByteOffset());
1736
1737 return true;
1738 }
1739
1740 if (!Ptr.isBlockPointer()) {
1741 // If we're trying to get the field of a TypeId pointer, try to produce a
1742 // proper diagnostic.
1743 if (Ptr.isTypeidPointer())
1744 return diagnoseTypeIdField(S, OpPC, Ptr, Off);
1745 return false;
1746 }
1747
1748 // We can't get the field of something that's not a record.
1749 if (!Ptr.getFieldDesc()->isRecord())
1750 return false;
1751
1752 if ((Ptr.getByteOffset() + Off) >= Ptr.block()->getSize())
1753 return false;
1754
1755 S.Stk.push<Pointer>(Ptr.atField(Off));
1756 return true;
1757}
1758
1759bool GetPtrField(InterpState &S, CodePtr OpPC, uint32_t Off) {
1760 const auto &Ptr = S.Stk.peek<Pointer>();
1761 return getField(S, OpPC, Ptr, Off);
1762}
1763
1764bool GetPtrFieldPop(InterpState &S, CodePtr OpPC, uint32_t Off) {
1765 const auto &Ptr = S.Stk.pop<Pointer>();
1766 return getField(S, OpPC, Ptr, Off);
1767}
1768
1769static bool getBase(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
1770 uint32_t Off, bool NullOK) {
1771 if (!NullOK && !CheckNull(S, OpPC, Ptr, CSK_Base))
1772 return false;
1773
1774 if (Ptr.isOpaquePointer()) {
1775 const OpaquePointer &OP = Ptr.asOpaquePointer();
1776 const RecordDecl *RD = OP.getFieldType()->getAsRecordDecl();
1777 if (!RD)
1778 return false;
1779 const Record *R = S.getContext().getRecord(RD);
1780 assert(R);
1781
1782 const Record::Base *B = R->findBase(Off);
1783 if (!B)
1784 return false;
1785
1787 OP.PathLength + 1, OP.Path,
1789 S.Stk.push<Pointer>(
1790 OP.withPath(
1791 NewPath, OP.PathLength + 1,
1793 Ptr.getByteOffset());
1794 return true;
1795 }
1796
1797 if (!Ptr.isBlockPointer()) {
1798 if (!Ptr.isIntegralPointer())
1799 return false;
1800 S.Stk.push<Pointer>(Ptr.asIntPointer().baseCast(S.Ctx, Off));
1801 return true;
1802 }
1803
1804 if (!CheckSubobject(S, OpPC, Ptr, CSK_Base))
1805 return false;
1806
1807 // In case this isn't something we can get the base of at all,
1808 // just return the pointer itself so it can be diagnosed later.
1809 if (!Ptr.getFieldDesc()->isRecord()) {
1810 S.Stk.push<Pointer>(Ptr);
1811 return true;
1812 }
1813
1814 const Pointer &Result = Ptr.atField(Off);
1815 if (Result.isPastEnd() || !Result.isBaseClass())
1816 return false;
1817 S.Stk.push<Pointer>(Result);
1818 return true;
1819}
1820
1821bool GetPtrBase(InterpState &S, CodePtr OpPC, uint32_t Off) {
1822 const auto &Ptr = S.Stk.peek<Pointer>();
1823 return getBase(S, OpPC, Ptr.narrow(), Off, /*NullOK=*/true);
1824}
1825bool GetPtrBasePop(InterpState &S, CodePtr OpPC, uint32_t Off, bool NullOK) {
1826 const auto &Ptr = S.Stk.pop<Pointer>();
1827 return getBase(S, OpPC, Ptr.narrow(), Off, NullOK);
1828}
1829
1830// Do ONE step of a BaseToDerived cast.
1831bool GetPtrDerivedPop(InterpState &S, CodePtr OpPC, bool NullOK,
1832 const Type *TargetType, const Type *FinalType) {
1833 const Pointer &Ptr = S.Stk.pop<Pointer>().narrow();
1834 if (!NullOK && !CheckNull(S, OpPC, Ptr, CSK_Derived))
1835 return false;
1836
1837 if (!Ptr.isBlockPointer()) {
1838 // FIXME: We don't have the necessary information in integral pointers.
1839 // The Descriptor only has a record, but that does of course not include
1840 // the potential derived classes of said record.
1841 S.Stk.push<Pointer>(Ptr);
1842 return true;
1843 }
1844
1845 if (!Ptr.getFieldDesc()->isRecord()) {
1846 S.Stk.push<Pointer>(Ptr);
1847 return true;
1848 }
1849
1850 if (!CheckSubobject(S, OpPC, Ptr, CSK_Derived))
1851 return false;
1852
1853 auto diagFailedCast = [&]() -> bool {
1854 QualType MostDerivedType = Ptr.getDeclDesc()->getType();
1855 S.CCEDiag(S.Current->getSource(OpPC), diag::note_constexpr_invalid_downcast)
1856 << MostDerivedType << QualType(FinalType, 0);
1857 return false;
1858 };
1859
1860 // We're casting down one level, which isn't possible if the pointer is
1861 // already the root.
1862 if (Ptr.isRoot())
1863 return diagFailedCast();
1864
1865 auto unwrapPointerType = [](QualType T) -> const Type * {
1866 if (T->isPointerOrReferenceType())
1867 return T->getPointeeType().getTypePtr();
1868 return T.getTypePtr();
1869 };
1870
1871 PtrView BasePtr = Ptr.view().getBase();
1872 const Type *BaseTy = unwrapPointerType(BasePtr.getType());
1873 if (!ASTContext::hasSameType(BaseTy, TargetType))
1874 return diagFailedCast();
1875
1876 S.Stk.push<Pointer>(BasePtr);
1877 return true;
1878}
1879
1880static bool checkConstructor(InterpState &S, CodePtr OpPC, const Function *Func,
1881 const Pointer &ThisPtr) {
1882 assert(Func->isConstructor());
1883
1884 if (Func->getParentDecl()->isInvalidDecl())
1885 return false;
1886
1887 const Descriptor *D = ThisPtr.getFieldDesc();
1888 // FIXME: I think this case is not 100% correct. E.g. a pointer into a
1889 // subobject of a composite array.
1890 if (!D->ElemRecord)
1891 return true;
1892
1893 if (S.getLangOpts().CPlusPlus26)
1894 return true;
1895
1896 if (D->ElemRecord->getNumVirtualBases() == 0)
1897 return true;
1898
1899 S.FFDiag(S.Current->getLocation(OpPC), diag::note_constexpr_virtual_base)
1900 << Func->getParentDecl();
1901 return false;
1902}
1903
1905 const Pointer &Ptr) {
1906 assert(Ptr.getLifetime() != Lifetime::Started);
1907 // Try to use the declaration for better diagnostics
1908 if (const Decl *D = Ptr.getDeclDesc()->asDecl()) {
1909 auto *ND = cast<NamedDecl>(D);
1910 S.FFDiag(ND->getLocation(), diag::note_constexpr_destroy_out_of_lifetime)
1911 << ND->getNameAsString();
1912 } else {
1913 S.FFDiag(Ptr.getDeclDesc()->getLocation(),
1914 diag::note_constexpr_destroy_out_of_lifetime)
1915 << Ptr.toDiagnosticString(S.getASTContext());
1916 }
1917 return false;
1918}
1919
1920bool checkDestructor(InterpState &S, CodePtr OpPC, const Pointer &Ptr) {
1921 if (!CheckLive(S, OpPC, Ptr, AK_Destroy))
1922 return false;
1923 if (!CheckTemporary(S, OpPC, Ptr, AK_Destroy))
1924 return false;
1925 if (!CheckRange(S, OpPC, Ptr, AK_Destroy))
1926 return false;
1927
1928 if (Ptr.getLifetime() == Lifetime::Destroyed)
1929 return diagnoseOutOfLifetimeDestroy(S, OpPC, Ptr);
1930 if (Ptr.getLifetime() == Lifetime::Ended)
1931 return CheckLifetime(S, OpPC, Ptr, AK_Destroy);
1932
1933 // We _can_ call the destructor on the global variable we're checking constant
1934 // destruction for.
1935 if (S.checkingConstantDestruction(Ptr))
1936 return true;
1937
1938 // String pointers are immutable, so can't call a destructor on them.
1939 if (Ptr.isStringPointer()) {
1940 S.FFDiag(S.Current->getSource(OpPC),
1941 diag::note_constexpr_access_unreadable_object)
1942 << AK_Destroy << Ptr.toDiagnosticString(S.getASTContext());
1943 return false;
1944 }
1945
1946 // Can't call a dtor on a global variable.
1947 if (Ptr.isOpaquePointer() || Ptr.block()->isGlobal()) {
1948 const SourceInfo &E = S.Current->getSource(OpPC);
1949 S.FFDiag(E, diag::note_constexpr_modify_global);
1950 return false;
1951 }
1952 return CheckActive(S, OpPC, Ptr, AK_Destroy);
1953}
1954
1955/// Opcode. Check if the function decl can be called at compile time.
1958 return false;
1959
1960 const FunctionDecl *Definition = nullptr;
1961 bool HasBody = FD->hasBody(Definition);
1962
1963 if (Definition && HasBody &&
1964 (Definition->isConstexpr() || (S.Current->MSVCConstexprAllowed &&
1965 Definition->hasAttr<MSConstexprAttr>())))
1966 return true;
1967
1968 return diagnoseCallableDecl(S, OpPC, FD);
1969}
1970
1971bool CheckBitCast(InterpState &S, CodePtr OpPC, const Type *TargetType,
1972 bool SrcIsVoidPtr) {
1973 const auto &Ptr = S.Stk.peek<Pointer>();
1974 if (Ptr.isZero())
1975 return true;
1976 if (!Ptr.isBlockPointer())
1977 return true;
1978
1979 if (TargetType->isIntegerType())
1980 return true;
1981
1982 if (SrcIsVoidPtr && S.getLangOpts().CPlusPlus) {
1983 bool HasValidResult = !Ptr.isZero();
1984
1985 if (HasValidResult) {
1986 if (S.getStdAllocatorCaller("allocate"))
1987 return true;
1988
1989 const auto *E = cast<CastExpr>(S.Current->getExpr(OpPC));
1990 if (S.getLangOpts().CPlusPlus26 &&
1991 S.getASTContext().hasSimilarType(Ptr.getType(),
1992 QualType(TargetType, 0)))
1993 return true;
1994
1995 S.CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
1996 << E->getSubExpr()->getType() << S.getLangOpts().CPlusPlus26
1997 << Ptr.getType().getCanonicalType() << E->getType()->getPointeeType();
1998 } else if (!S.getLangOpts().CPlusPlus26) {
1999 const SourceInfo &E = S.Current->getSource(OpPC);
2000 S.CCEDiag(E, diag::note_constexpr_invalid_cast)
2001 << diag::ConstexprInvalidCastKind::CastFrom << "'void *'"
2002 << S.Current->getRange(OpPC);
2003 }
2004 }
2005
2006 QualType PtrType = Ptr.getType();
2007 if (PtrType->isRecordType() &&
2008 PtrType->getAsRecordDecl() != TargetType->getAsRecordDecl()) {
2009 S.CCEDiag(S.Current->getSource(OpPC), diag::note_constexpr_invalid_cast)
2010 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
2011 << S.getLangOpts().CPlusPlus << S.Current->getRange(OpPC);
2012 }
2013 return true;
2014}
2015
2016bool PtrPtrCast(InterpState &S, CodePtr OpPC, bool SrcIsVoidPtr,
2017 const Type *TargetType) {
2018 const auto &Ptr = S.Stk.peek<Pointer>();
2019
2020 if (SrcIsVoidPtr && S.getLangOpts().CPlusPlus) {
2021 bool HasValidResult = !Ptr.isZero();
2022
2023 if (HasValidResult) {
2024 if (S.getStdAllocatorCaller("allocate"))
2025 return true;
2026
2027 if (S.getLangOpts().CPlusPlus26 &&
2028 S.getASTContext().hasSimilarType(Ptr.getType(),
2029 TargetType->getPointeeType()))
2030 return true;
2031
2032 const auto *E = cast<CastExpr>(S.Current->getExpr(OpPC));
2033 S.CCEDiag(E, diag::note_constexpr_invalid_void_star_cast)
2034 << E->getSubExpr()->getType() << S.getLangOpts().CPlusPlus26
2035 << Ptr.getType().getCanonicalType() << E->getType()->getPointeeType();
2036 } else if (!S.getLangOpts().CPlusPlus26) {
2037 const SourceInfo &E = S.Current->getSource(OpPC);
2038 S.CCEDiag(E, diag::note_constexpr_invalid_cast)
2039 << diag::ConstexprInvalidCastKind::CastFrom << "'void *'"
2040 << S.Current->getRange(OpPC);
2041 }
2042 } else {
2043 const SourceInfo &E = S.Current->getSource(OpPC);
2044 S.CCEDiag(E, diag::note_constexpr_invalid_cast)
2045 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
2046 << S.getLangOpts().CPlusPlus << S.Current->getRange(OpPC);
2047 }
2048
2049 // Retain the casted type for opaque pointers.
2050 if (Ptr.isOpaquePointer()) {
2051 Pointer P = S.Stk.pop<Pointer>();
2052 const OpaquePointer &OP = P.asOpaquePointer();
2053
2054 if (OP.hasDeclBase() && !validType(TargetType->getPointeeType()))
2055 return Invalid(S, OpPC);
2056
2057 S.Stk.push<Pointer>(OP.withFieldType(TargetType), P.getByteOffset());
2058 }
2059
2060 return true;
2061}
2062
2064 CodePtr OpPC) {
2065 const FunctionDecl *Fn = Func->getDecl();
2066
2067 // [C++26] [temp.inst] p5
2068 // [...] the function template specialization is implicitly instantiated
2069 // when the specialization is referenced in a context that requires a function
2070 // definition to exist or if the existence of the definition affects the
2071 // semantics of the program.
2073 SemaProxy *SProxy = S.getSemaProxy();
2074 if (!SProxy)
2075 return;
2077 const_cast<FunctionDecl *>(Fn));
2078 }
2079
2080 const FunctionDecl *Definition;
2081 if (!Fn->hasBody(Definition))
2082 return;
2083 if (!Definition)
2084 return;
2085
2087 .compileFunc(Definition, const_cast<Function *>(Func));
2088}
2089
2091 uint32_t VarArgSize) {
2092 if (Func->hasThisPointer()) {
2093 size_t ArgSize = Func->getArgSize() + VarArgSize;
2094 size_t ThisOffset = ArgSize - (Func->hasRVO() ? primSize(PT_Ptr) : 0);
2095 const Pointer &ThisPtr = S.Stk.peek<Pointer>(ThisOffset);
2096
2097 // If the current function is a lambda static invoker and
2098 // the function we're about to call is a lambda call operator,
2099 // skip the CheckInvoke, since the ThisPtr is a null pointer
2100 // anyway.
2101 if (!(S.Current->getFunction() &&
2103 Func->isLambdaCallOperator())) {
2104 if (!CheckInvoke(S, OpPC, ThisPtr, Func->isConstructor(),
2105 Func->isDestructor()))
2106 return false;
2107 }
2108
2110 return false;
2111 }
2112
2113 if (!Func->isFullyCompiled())
2114 compileFunction(S, Func, OpPC);
2115
2116 if (!CheckCallable(S, OpPC, Func))
2117 return false;
2118
2119 if (!CheckCallDepth(S, OpPC))
2120 return false;
2121
2122 InterpFrame *NewFrame = S.allocFrame(Func, S.PC, VarArgSize);
2123 S.enterFrame(NewFrame);
2124
2125 InterpStateCCOverride CCOverride(S, Func->isImmediate());
2126 bool Success = Interpret(S);
2127 S.exitFrame();
2128 return Success;
2129}
2130
2131bool Call(InterpState &S, CodePtr OpPC, const Function *Func,
2132 uint32_t VarArgSize) {
2133
2134 // C doesn't have constexpr functions.
2135 if (!S.getLangOpts().CPlusPlus)
2136 return Invalid(S, OpPC);
2137
2138 assert(Func);
2139 auto cleanup = [&]() -> bool {
2141 return false;
2142 };
2143
2144 bool InstancePtrTracked = false;
2145 if (Func->hasThisPointer()) {
2146 size_t ArgSize = Func->getArgSize() + VarArgSize;
2147 size_t ThisOffset = ArgSize - (Func->hasRVO() ? primSize(PT_Ptr) : 0);
2148
2149 const Pointer &ThisPtr = S.Stk.peek<Pointer>(ThisOffset);
2150
2151 // C++23 [expr.const]p5.6
2152 // an invocation of a virtual function ([class.virtual]) for an object whose
2153 // dynamic type is constexpr-unknown;
2154 if (ThisPtr.isDummy() && Func->isVirtual())
2155 return false;
2156
2157 // If the current function is a lambda static invoker and
2158 // the function we're about to call is a lambda call operator,
2159 // skip the CheckInvoke, since the ThisPtr is a null pointer
2160 // anyway.
2161 if (S.Current->getFunction() &&
2163 Func->isLambdaCallOperator()) {
2164 assert(ThisPtr.isZero());
2165 } else {
2166 if (!CheckInvoke(S, OpPC, ThisPtr, Func->isConstructor(),
2167 Func->isDestructor()))
2168 return cleanup();
2169
2170 if (Func->isCopyOrMoveOperator() || Func->isCopyOrMoveConstructor()) {
2171 const Pointer &RVOPtr =
2172 S.Stk.peek<Pointer>(ThisOffset - align(sizeof(Pointer)));
2173 if (!CheckInvoke(S, OpPC, RVOPtr, /*IsCtor=*/true, /*IsDtor=*/false))
2174 return cleanup();
2175 }
2176
2177 if (!Func->isConstructor() && !Func->isDestructor() &&
2178 !CheckActive(S, OpPC, ThisPtr, AK_MemberCall))
2179 return false;
2180 }
2181
2182 if (Func->isConstructor() && !checkConstructor(S, OpPC, Func, ThisPtr))
2183 return false;
2184 if (Func->isDestructor() && !checkDestructor(S, OpPC, ThisPtr))
2185 return false;
2186
2187 InstancePtrTracked = (Func->isConstructor() || Func->isDestructor());
2188 if (InstancePtrTracked)
2189 S.InitializingPtrs.push_back(ThisPtr.view());
2190 }
2191
2192 if (!Func->isFullyCompiled())
2193 compileFunction(S, Func, OpPC);
2194
2195 if (!CheckCallable(S, OpPC, Func))
2196 return cleanup();
2197
2198 // Do not evaluate any function calls in checkingPotentialConstantExpression
2199 // mode. Constructors will be aborted later when their initializers are
2200 // evaluated.
2201 if (S.checkingPotentialConstantExpression() && !Func->isConstructor())
2202 return false;
2203
2204 if (!CheckCallDepth(S, OpPC))
2205 return cleanup();
2206
2207 InterpFrame *NewFrame = S.allocFrame(Func, S.PC, VarArgSize);
2208 S.enterFrame(NewFrame);
2209
2210 InterpStateCCOverride CCOverride(S, Func->isImmediate());
2211 bool Success = Interpret(S);
2212 // Remove initializing block again.
2213 if (InstancePtrTracked)
2214 S.InitializingPtrs.pop_back();
2215
2216 S.exitFrame();
2217 return Success;
2218}
2219
2220static bool getDynamicDecl(InterpState &S, CodePtr OpPC, const Pointer &Ptr,
2221 const CXXRecordDecl *&DynamicDecl) {
2222
2223 auto diagUnknownDynamicType = [&](const Pointer &P) -> bool {
2224 APValue V = P.toAPValue(S.getASTContext());
2225 QualType TT = S.getASTContext().getLValueReferenceType(P.getType());
2226 S.FFDiag(S.Current->getSource(OpPC),
2227 diag::note_constexpr_polymorphic_unknown_dynamic_type)
2228 << AK_MemberCall << V.getAsString(S.getASTContext(), TT);
2229 return false;
2230 };
2231
2232 if (!Ptr.isBlockPointer())
2233 return diagUnknownDynamicType(Ptr);
2234
2235 PtrView TypePtr = Ptr.view();
2236 if (S.InitializingPtrs.empty()) {
2237 TypePtr = TypePtr.stripBaseCasts();
2238 } else {
2239 auto depth = [](PtrView V) -> unsigned {
2240 unsigned C = 1;
2241 while (!V.isRoot()) {
2242 ++C;
2243 V = V.getBase();
2244 }
2245 return C;
2246 };
2247 // Consider a 'normal' diamond hierarchy:
2248 // A A 3
2249 // | |
2250 // B C 2
2251 // \ /
2252 // \ /
2253 // D 1
2254 // When we use a pointer of D*, cast it to B's A* and
2255 // use it during the construction of C*, the expected
2256 // dynamic type is B.
2257 PtrView InitPtr = S.InitializingPtrs.back();
2258 assert(depth(TypePtr) >= depth(InitPtr));
2259 unsigned D = depth(TypePtr) - depth(InitPtr);
2260 for (unsigned I = 0; I != D; ++I)
2261 TypePtr = TypePtr.getBase();
2262 }
2263
2264 QualType DynamicType = TypePtr.getType();
2265 if (TypePtr.Pointee->isGlobal() || TypePtr.isConst()) {
2266 if (const VarDecl *VD = Pointer(TypePtr).getRootVarDecl();
2267 VD && !VD->isConstexpr())
2268 return diagUnknownDynamicType(Pointer(TypePtr));
2269 }
2270
2271 if (DynamicType->isPointerType() || DynamicType->isReferenceType()) {
2272 DynamicDecl = DynamicType->getPointeeCXXRecordDecl();
2273 } else if (DynamicType->isArrayType()) {
2274 const Type *ElemType = DynamicType->getPointeeOrArrayElementType();
2275 assert(ElemType);
2276 DynamicDecl = ElemType->getAsCXXRecordDecl();
2277 } else {
2278 DynamicDecl = DynamicType->getAsCXXRecordDecl();
2279 }
2280 return DynamicDecl != nullptr;
2281}
2282
2283namespace {
2284struct DynamicCastResult {
2285 UnsignedOrNone Offset = std::nullopt;
2286 bool Ambiguous = false;
2287
2288 bool valid() const { return !Ambiguous && Offset; }
2289
2290 void setOffset(unsigned O) {
2291 if (!Offset)
2292 Offset = O;
2293 else {
2294 Ambiguous = true;
2295 }
2296 }
2297
2298 void merge(DynamicCastResult C) {
2299 Ambiguous |= C.Ambiguous;
2300 if (C.Offset) {
2301 if (!Offset)
2302 Offset = C.Offset;
2303 else
2304 Ambiguous = true;
2305 }
2306 }
2307};
2308} // namespace
2309
2310// Walk UP the type hierarchy, starting at the decl of R to find Needle.
2311static DynamicCastResult findRecordBase(const ASTContext &Ctx, const Record *R,
2312 QualType Needle) {
2313 DynamicCastResult Res;
2314
2315 if (Ctx.hasSimilarType(Needle, Ctx.getCanonicalTagType(R->getDecl())))
2316 Res.setOffset(0);
2317
2318 for (const Record::Base &B : R->bases()) {
2319 auto N = findRecordBase(Ctx, B.R, Needle);
2320 if (N.Offset)
2321 N.Offset = *N.Offset + B.Offset;
2322 Res.merge(N);
2323 }
2324
2325 return Res;
2326}
2327
2328bool DynamicCast(InterpState &S, CodePtr OpPC, const Type *DestTypePtr,
2329 bool IsReferenceCast) {
2330 const auto &Ptr = S.Stk.pop<Pointer>();
2331 QualType TargetType = QualType(DestTypePtr, 0);
2332
2333 if (Ptr.isConstexprUnknown() || Ptr.isOpaquePointer()) {
2334 QualType T = Ptr.getType();
2335 const Expr *E = S.Current->getExpr(OpPC);
2336 APValue V = Ptr.toAPValue(S.getASTContext());
2338 S.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
2339 << AK_DynamicCast << V.getAsString(S.getASTContext(), TT);
2340 return false;
2341 }
2342
2343 if (!Ptr.isBlockPointer() || !Ptr.getRecord())
2344 return false;
2345
2346 if (!Ptr.isInitialized())
2347 return diagnoseUninitialized(S, OpPC, Ptr, AK_Read);
2348
2349 // Our given pointer, limited by the base that's currently being initialized,
2350 // if any.
2351 PtrView LimitedPtr;
2352 if (S.InitializingPtrs.empty() ||
2353 S.InitializingPtrs.back().block() != Ptr.block()) {
2354 LimitedPtr = Ptr.stripBaseCasts().view();
2355 } else {
2356 LimitedPtr = S.InitializingPtrs.back();
2357 assert(LimitedPtr.block() == Ptr.block());
2358 }
2359 assert(LimitedPtr.getRecord());
2360
2361 // C++ [expr.dynamic.cast]p7:
2362 // If T is "pointer to cv void", then the result is a pointer to the most
2363 // derived object
2364 if (TargetType->isVoidType()) {
2365 S.Stk.push<Pointer>(LimitedPtr);
2366 return true;
2367 }
2368
2369 assert(!TargetType.isNull());
2370 assert(!TargetType->isVoidType());
2371 assert(TargetType->isRecordType());
2372
2373 // Helper lambdas.
2374 auto typesMatch = [&](QualType A, QualType B) -> bool {
2375 return S.getASTContext().hasSimilarType(A, B);
2376 };
2377 auto getRecord = [](PtrView P) -> const CXXRecordDecl * {
2378 assert(P.getRecord());
2379 return cast<CXXRecordDecl>(P.getRecord()->getDecl());
2380 };
2381
2382 auto baseIsPrivate = [&](PtrView P) -> bool {
2383 if (P.isRoot() || !P.isBaseClass())
2384 return false;
2385
2386 CXXBasePaths Paths;
2387 getRecord(P.getBase())->isDerivedFrom(getRecord(P), Paths);
2388
2389 // Through virtual bases, there might be more than one "direct" base. They
2390 // can have different access specifiers. They must all be private to be
2391 // considered private.
2392 return llvm::all_of(Paths, [](const CXXBasePath &P) -> bool {
2393 return P.Access == AS_private;
2394 });
2395 };
2396
2397 enum {
2398 DiagPrivateBase = 0,
2399 DiagNoBase = 1,
2400 DiagAmbiguous = 2,
2401 DiagPrivateSibling = 3
2402 };
2403
2404 auto diag = [&](int DiagKind, QualType ResultType) -> bool {
2405 // Pointer casts return nullptr on failure.
2406 if (!IsReferenceCast) {
2407 S.Stk.push<Pointer>(0, DestTypePtr);
2408 return true;
2409 }
2411 S.FFDiag(S.Current->getSource(OpPC),
2412 diag::note_constexpr_dynamic_cast_to_reference_failed)
2413 << DiagKind << ResultType << DynamicType << TargetType;
2414 return false;
2415 };
2416
2417 // Check if Ptr's dynamic type is derived from our target type at all.
2418 // If it isn't, diagnose this as "operand does not have base class of type
2419 // [...]".
2420 {
2421 CXXBasePaths Paths;
2422 getRecord(LimitedPtr)
2423 ->isDerivedFrom(TargetType->castAsCXXRecordDecl(), Paths);
2424 if (std::distance(Paths.begin(), Paths.end()) == 0 &&
2425 !typesMatch(LimitedPtr.getType(), TargetType)) {
2426 return diag(DiagNoBase, TargetType);
2427 }
2428 }
2429
2430 // Current base is already private.
2431 if (baseIsPrivate(Ptr.view()))
2432 return diag(DiagPrivateBase, Ptr.getType());
2433
2434 std::optional<PtrView> Result;
2435 // First, check simple downcasts without ambiguities.
2436 for (PtrView Iter = Ptr.view();;) {
2437 if (Iter.isRoot() || !Iter.isBaseClass())
2438 break;
2439
2440 if (typesMatch(TargetType, Iter.getType())) {
2441 Result = Iter;
2442 break;
2443 }
2444 // Moving DOWN the type hierarchy.
2445 Iter = Iter.getBase();
2446 }
2447
2448 // Simply walking down the type hierarchy has produced a valid result, use
2449 // that.
2450 if (Result) {
2451 if (baseIsPrivate(*Result))
2452 return diag(DiagPrivateBase, Result->getType());
2453 S.Stk.push<Pointer>(*Result);
2454 return true;
2455 }
2456
2457 // Otherwise, we need to do a deep hierarchy check.
2458 bool Ambiguous = false;
2459 for (PtrView Iter = LimitedPtr;;) {
2460 // If we can move up the hierarchy from this level and reach the target type
2461 // unambiguously, we're fine.
2462 auto R = findRecordBase(S.getASTContext(), Iter.getRecord(), TargetType);
2463
2464 if (R.valid()) {
2465 Result = Iter.atField(*R.Offset);
2466 break;
2467 }
2468 if (R.Ambiguous) {
2469 Ambiguous = true;
2470 break;
2471 }
2472
2473 if (Iter.isRoot() || !Iter.isBaseClass())
2474 break;
2475 // This moves us DOWN the type hierarchy.
2476 Iter = Iter.getBase();
2477 }
2478
2479 if (Ambiguous)
2480 return diag(DiagAmbiguous, TargetType);
2481
2482 if (Result) {
2483 // Might still be invalid due to resulting in a private base though.
2484 if (baseIsPrivate(*Result))
2485 return diag(DiagPrivateSibling, TargetType);
2486 S.Stk.push<Pointer>(*Result);
2487 return true;
2488 }
2489
2490 // We couldn't find the requested base.
2491 return diag(DiagNoBase, TargetType);
2492}
2493
2495 uint32_t VarArgSize) {
2496 // This happens in error cases.
2497 if (!Func->hasThisPointer()) {
2498 assert(!Func->isValid());
2499 return diagnoseCallableDecl(S, OpPC, Func->getDecl());
2500 }
2501
2502 assert(Func->hasThisPointer());
2503 assert(Func->isVirtual());
2504 size_t ArgSize = Func->getArgSize() + VarArgSize;
2505 size_t ThisOffset = ArgSize - (Func->hasRVO() ? primSize(PT_Ptr) : 0);
2506 Pointer &ThisPtr = S.Stk.peek<Pointer>(ThisOffset);
2507
2508 if (!ThisPtr.isBlockPointer() && !ThisPtr.isOpaquePointer())
2509 return false;
2510
2511 const FunctionDecl *Callee = Func->getDecl();
2512
2513 const CXXRecordDecl *DynamicDecl = nullptr;
2514 if (!getDynamicDecl(S, OpPC, ThisPtr, DynamicDecl))
2515 return false;
2516 assert(DynamicDecl);
2517
2518 const auto *StaticDecl = Func->getParentDecl();
2519 const auto *InitialFunction = cast<CXXMethodDecl>(Callee);
2520 const CXXMethodDecl *Overrider;
2521
2522 if (StaticDecl != DynamicDecl) {
2523 if (!DynamicDecl->isDerivedFrom(StaticDecl))
2524 return false;
2525 Overrider = S.getContext().getOverridingFunction(DynamicDecl, StaticDecl,
2526 InitialFunction);
2527
2528 } else {
2529 Overrider = InitialFunction;
2530 }
2531
2532 // C++2a [class.abstract]p6:
2533 // the effect of making a virtual call to a pure virtual function [...] is
2534 // undefined
2535 if (Overrider->isPureVirtual()) {
2536 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_pure_virtual_call,
2537 1)
2538 << Callee;
2539 S.Note(Callee->getLocation(), diag::note_declared_at);
2540 return false;
2541 }
2542
2543 if (Overrider != InitialFunction) {
2544 // DR1872: An instantiated virtual constexpr function can't be called in a
2545 // constant expression (prior to C++20). We can still constant-fold such a
2546 // call.
2547 if (!S.getLangOpts().CPlusPlus20 && Overrider->isVirtual()) {
2548 const Expr *E = S.Current->getExpr(OpPC);
2549 S.CCEDiag(E, diag::note_constexpr_virtual_call) << E->getSourceRange();
2550 }
2551
2552 Func = S.getContext().getOrCreateFunction(Overrider);
2553
2554 const CXXRecordDecl *ThisFieldDecl =
2556 if (Func->getParentDecl()->isDerivedFrom(ThisFieldDecl)) {
2557 // If the function we call is further DOWN the hierarchy than the
2558 // FieldDesc of our pointer, just go up the hierarchy of this field
2559 // the furthest we can go.
2560 ThisPtr = ThisPtr.stripBaseCasts();
2561 }
2562 }
2563
2564 if (!Call(S, OpPC, Func, VarArgSize))
2565 return false;
2566
2567 // Covariant return types. The return type of Overrider is a pointer
2568 // or reference to a class type.
2569 if (Overrider != InitialFunction &&
2570 Overrider->getReturnType()->isPointerOrReferenceType() &&
2571 InitialFunction->getReturnType()->isPointerOrReferenceType()) {
2572 QualType OverriderPointeeType =
2573 Overrider->getReturnType()->getPointeeType();
2574 QualType InitialPointeeType =
2575 InitialFunction->getReturnType()->getPointeeType();
2576
2577 // Nothing to do if the types already match.
2578 if (S.getASTContext().hasSimilarType(InitialPointeeType,
2579 OverriderPointeeType))
2580 return true;
2581
2582 // See, the base cast from the return value of InitialFunction to that of
2583 // Overrider might be ambiguous due to mutliple inheritance. HOWEVER, this
2584 // ambiguity can be cleared up by looking at the return values for all the
2585 // overriding functions in the base path from InitialFunction to Overrider.
2586 // This is all terrible and slow, but if you use this, you get what you
2587 // deserve.
2588
2589 CXXBasePaths Paths(/*FindAmbiguities=*/true);
2590 Overrider->getParent()->isDerivedFrom(InitialFunction->getParent(), Paths);
2591
2592 // The path of the parent classes of the virtual methods should not be
2593 // ambiguous.
2594 if (std::distance(Paths.begin(), Paths.end()) != 1)
2595 return false;
2596
2597 // Calling Overrider above returned a pointer of type OverriderPointeeType.
2598 const RecordDecl *CurPtrType = OverriderPointeeType->getAsRecordDecl();
2599
2600 CXXBasePath Path = *Paths.begin();
2601 for (const CXXBasePathElement &Elem : llvm::drop_begin(Path)) {
2602 const CXXMethodDecl *FuncInThisBase =
2604 Elem.Class, /*MayBeBase=*/false);
2605
2606 QualType FuncReturnTy = FuncInThisBase->getReturnType()->getPointeeType();
2607 unsigned Offset = S.getContext().collectBaseOffset(
2608 FuncReturnTy->getAsRecordDecl(), CurPtrType);
2609
2610 if (!GetPtrBasePop(S, OpPC, Offset, /*IsNullOK=*/true))
2611 return false;
2612
2613 CurPtrType = FuncReturnTy->getAsRecordDecl();
2614 }
2615
2616 // The path above does not include the final step to InitialFunction's
2617 // parent class. Do it here.
2618 unsigned Offset = S.getContext().collectBaseOffset(
2619 InitialPointeeType->getAsRecordDecl(), CurPtrType);
2620 return GetPtrBasePop(S, OpPC, Offset, /*IsNullOK=*/true);
2621 }
2622
2623 return true;
2624}
2625
2626bool CallBI(InterpState &S, CodePtr OpPC, const CallExpr *CE,
2627 uint32_t BuiltinID) {
2628 // A little arbitrary, but the current interpreter allows evaluation
2629 // of builtin functions in this mode, with some exceptions.
2630 if (BuiltinID == Builtin::BI__builtin_operator_new &&
2632 return false;
2633
2634 return InterpretBuiltin(S, OpPC, CE, BuiltinID);
2635}
2636
2637bool CallPtr(InterpState &S, CodePtr OpPC, uint32_t ArgSize,
2638 const CallExpr *CE) {
2639 const Pointer &Ptr = S.Stk.pop<Pointer>();
2640
2641 if (Ptr.isZero()) {
2642 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_null_callee)
2643 << const_cast<Expr *>(CE->getCallee()) << CE->getSourceRange();
2644 return false;
2645 }
2646
2647 if (!Ptr.isFunctionPointer())
2648 return Invalid(S, OpPC);
2649
2650 const Function *F = Ptr.asFunctionPointer().Func;
2651 assert(F);
2652 // Don't allow calling block pointers.
2653 if (!F->getDecl())
2654 return Invalid(S, OpPC);
2655
2656 // This happens when the call expression has been cast to
2657 // something else, but we don't support that.
2658 if (S.Ctx.classify(F->getDecl()->getReturnType()) !=
2660 return false;
2661
2662 // Check argument nullability state.
2663 if (F->hasNonNullAttr()) {
2664 if (!CheckNonNullArgs(S, OpPC, F, CE, ArgSize))
2665 return false;
2666 }
2667
2668 // Can happen when casting function pointers around.
2669 QualType CalleeType = CE->getCallee()->getType();
2670 if (CalleeType->isPointerType() &&
2672 F->getDecl()->getType(), CalleeType->getPointeeType())) {
2673 return false;
2674 }
2675
2676 // We nedd to compile (and check) early for function pointer calls
2677 // because the Call/CallVirt below might access the instance pointer
2678 // but the Function's information about them is wrong.
2679 if (!F->isFullyCompiled())
2680 compileFunction(S, F, OpPC);
2681
2682 if (!CheckCallable(S, OpPC, F))
2683 return false;
2684
2685 assert(ArgSize >= F->getWrittenArgSize());
2686 uint32_t VarArgSize = ArgSize - F->getWrittenArgSize();
2687
2688 // We need to do this explicitly here since we don't have the necessary
2689 // information to do it automatically.
2690 if (F->hasExplicitThisPointer())
2691 VarArgSize -= align(primSize(PT_Ptr));
2692
2693 if (F->isVirtual())
2694 return CallVirt(S, OpPC, F, VarArgSize);
2695
2696 return Call(S, OpPC, F, VarArgSize);
2697}
2698
2700 if (const Record *R = Ptr.getRecord()) {
2701 Ptr.startLifetime();
2702
2703 for (const Record::Field &Fi : R->fields()) {
2704 PtrView FP = Ptr.atField(Fi.Offset);
2705 if (FP.getLifetime() != Lifetime::Started)
2707 }
2708 return;
2709 }
2710
2711 if (const Descriptor *FieldDesc = Ptr.getFieldDesc();
2712 FieldDesc->isCompositeArray()) {
2713 for (unsigned I = 0; I != FieldDesc->getNumElems(); ++I) {
2714 PtrView EP = Ptr.atIndex(I).narrow();
2715 if (EP.getLifetime() != Lifetime::Started)
2717 }
2718 return;
2719 }
2720
2721 Ptr.startLifetime();
2722}
2723
2726 return true;
2727
2728 const auto &Ptr = S.Current->getThis();
2729 if (!Ptr.isBlockPointer())
2730 return false;
2731 startLifetimeRecurse(Ptr.view());
2732 return true;
2733}
2734
2737 return true;
2738
2739 const auto &Ptr = S.Current->getThis();
2740 if (!Ptr.isBlockPointer())
2741 return false;
2742 Ptr.startLifetime();
2743 return true;
2744}
2745
2746// FIXME: It might be better to the recursing as part of the generated code for
2747// a destructor?
2749 if (const Record *R = Ptr.getRecord()) {
2750 Ptr.setLifeState(L);
2751 for (const Record::Field &Fi : R->fields())
2752 setLifeStateRecurse(Ptr.atField(Fi.Offset), L);
2753 return;
2754 }
2755
2756 if (const Descriptor *FieldDesc = Ptr.getFieldDesc();
2757 FieldDesc->isCompositeArray()) {
2758 // No endLifetime() for primitive array roots.
2759 if (Ptr.getFieldDesc()->isPrimitiveArray())
2760 assert(Ptr.getLifetime() == Lifetime::Started);
2761 for (unsigned I = 0; I != FieldDesc->getNumElems(); ++I)
2762 setLifeStateRecurse(Ptr.atIndex(I).narrow(), L);
2763 return;
2764 }
2765
2766 Ptr.setLifeState(L);
2767}
2768
2769/// Ends the lifetime of the peek'd pointer.
2771 const auto &Ptr = S.Stk.peek<Pointer>();
2772 if (!CheckDummy(S, OpPC, Ptr, AK_Destroy))
2773 return false;
2774
2775 setLifeStateRecurse(Ptr.view().narrow(), Lifetime::Ended);
2776 return true;
2777}
2778
2779/// Ends the lifetime of the pop'd pointer.
2781 const auto &Ptr = S.Stk.pop<Pointer>();
2782 if (!checkDestructor(S, OpPC, Ptr))
2783 return false;
2784 setLifeStateRecurse(Ptr.view().narrow(), Lifetime::Ended);
2785 return true;
2786}
2787
2789 const auto &Ptr = S.Stk.peek<Pointer>();
2790 if (!CheckDummy(S, OpPC, Ptr, AK_Destroy))
2791 return false;
2792
2793 setLifeStateRecurse(Ptr.view().narrow(), Lifetime::Destroyed);
2794 return true;
2795}
2796
2797// Initializes all bases and virtual bases.
2798// Only starts the lifetime of fields, but doesn't initialize them.
2799static void initBasesRecurse(PtrView Ptr) {
2800 assert(Ptr.getRecord());
2801
2802 const Record *R = Ptr.getRecord();
2803 for (const Record::Base &B : R->bases()) {
2804 PtrView BasePtr = Ptr.atField(B.Offset);
2805 BasePtr.initialize();
2806 BasePtr.startLifetime();
2807 initBasesRecurse(BasePtr);
2808 }
2809
2810 for (const Record::Field &F : R->fields()) {
2811 PtrView FieldPtr = Ptr.atField(F.Offset);
2812 FieldPtr.startLifetime();
2813 if (FieldPtr.getRecord())
2814 initBasesRecurse(FieldPtr);
2815 }
2816
2817 for (const Record::Base &B : R->virtual_bases()) {
2818 PtrView BasePtr = Ptr.atField(B.Offset);
2819 BasePtr.initialize();
2820 BasePtr.startLifetime();
2821 initBasesRecurse(BasePtr);
2822 }
2823}
2824
2826 auto Ptr = S.Stk.peek<Pointer>();
2827
2828 if (!Ptr.isBlockPointer())
2829 return false;
2830 const Record *R = Ptr.getRecord();
2831 if (!R)
2832 return false;
2833
2834 if (Ctor->isInvalidDecl() || Ctor->getParent()->isInvalidDecl())
2835 return false;
2836
2837 if (!Ctor->isConstexpr()) {
2838 if (S.getLangOpts().CPlusPlus11) {
2839 // FIXME: If DiagDecl is an implicitly-declared special member function,
2840 // we should be much more explicit about why it's not constexpr.
2841 S.CCEDiag(S.Current->getSource(OpPC),
2842 diag::note_constexpr_invalid_function, 1)
2843 << /*IsConstexpr*/ 0 << /*IsConstructor*/ 1 << Ctor;
2844 S.Note(Ctor->getLocation(), diag::note_declared_at);
2845 } else {
2846 S.CCEDiag(S.Current->getSource(OpPC),
2847 diag::note_invalid_subexpr_in_const_expr);
2848 }
2849 }
2850
2851 Ptr.startLifetime();
2852 Ptr.initialize();
2853
2854 startLifetimeRecurse(Ptr.view());
2855 initBasesRecurse(Ptr.view());
2856
2857 return true;
2858}
2859
2861 std::optional<uint64_t> ArraySize) {
2862 Pointer &Orig = S.Stk.peek<Pointer>();
2863 Pointer Ptr = Orig;
2864
2865 auto directBaseIsUnion = [](const Pointer &Ptr) -> bool {
2866 if (Ptr.isArrayElement())
2867 return false;
2868 const Record *R = Ptr.getBase().getRecord();
2869 return R && R->isUnion();
2870 };
2871
2872 if (Ptr.inUnion() && directBaseIsUnion(Ptr))
2873 Ptr.activate();
2874
2875 if (Ptr.isZero()) {
2876 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_null)
2877 << AK_Construct;
2878 return false;
2879 }
2880
2881 if (Ptr.isDummy())
2882 return diagnoseDummy(S, OpPC, Ptr, AK_Construct);
2883 if (!Ptr.isBlockPointer())
2884 return false;
2885
2886 if (!CheckRange(S, OpPC, Ptr, AK_Construct))
2887 return false;
2888
2889 startLifetimeRecurse(Ptr.view());
2890
2891 // Similar to CheckStore(), but with the additional CheckTemporary() call and
2892 // the AccessKinds are different.
2893 if (!Ptr.block()->isAccessible()) {
2894 if (!CheckExtern(S, OpPC, Ptr))
2895 return false;
2896 if (!CheckLive(S, OpPC, Ptr, AK_Construct))
2897 return false;
2898 return diagnoseDummy(S, OpPC, Ptr, AK_Construct);
2899 }
2900 if (!CheckTemporary(S, OpPC, Ptr, AK_Construct))
2901 return false;
2902
2903 // CheckLifetime for this and all base pointers.
2904 for (PtrView P = Ptr.view();;) {
2905 if (!CheckLifetime(S, OpPC, P.getLifetime(), P.Pointee, AK_Construct))
2906 return false;
2907
2908 if (P.isRoot())
2909 break;
2910 P = P.getBase();
2911 }
2912
2913 if (!CheckRange(S, OpPC, Ptr, AK_Construct))
2914 return false;
2915 if (!CheckGlobal(S, OpPC, Ptr.block()))
2916 return false;
2917 if (!CheckConst(S, OpPC, Ptr.view()))
2918 return false;
2919
2920 const auto *NewExpr = cast<CXXNewExpr>(E);
2921 const ASTContext &ASTCtx = S.getASTContext();
2922 QualType StorageType = Ptr.getType();
2923 QualType AllocType;
2924 if (ArraySize) {
2925 AllocType = ASTCtx.getConstantArrayType(
2926 NewExpr->getAllocatedType(),
2927 APInt(64, static_cast<uint64_t>(*ArraySize), false), nullptr,
2929 } else {
2930 AllocType = NewExpr->getAllocatedType();
2931 }
2932
2933 if (AllocType->isArrayType() && Ptr.isArrayElement() &&
2934 Ptr.expand().getIndex() == 0) {
2935 // The destination of placement new is pointing to the first element
2936 // of an array. There's a special case in [expr.const]: "[...] if T is an
2937 // array type, to the first element of such an object [...]". Handle
2938 // that case here by using the base of the Pointer.
2939 QualType AllocElementType =
2940 ASTCtx.getAsArrayType(AllocType)->getElementType();
2941 if (ASTCtx.hasSimilarType(AllocElementType, StorageType)) {
2942 StorageType = Ptr.expand().getArray().getType();
2943 Orig = Orig.expand();
2944 }
2945 }
2946
2947 if (!ASTCtx.hasSimilarType(AllocType, StorageType)) {
2948 S.FFDiag(S.Current->getLocation(OpPC),
2949 diag::note_constexpr_placement_new_wrong_type)
2950 << StorageType << AllocType;
2951 return false;
2952 }
2953
2954 // Can't activate fields in a union, unless the direct base is the union.
2955 if (Ptr.inUnion() && !Ptr.isActive() && !directBaseIsUnion(Ptr))
2956 return CheckActive(S, OpPC, Ptr, AK_Construct);
2957
2958 return true;
2959}
2960
2962 assert(E);
2963 const SourceInfo &Loc = S.Current->getSource(OpPC);
2964
2965 if (const auto *NewExpr = dyn_cast<CXXNewExpr>(E)) {
2966 const FunctionDecl *OperatorNew = NewExpr->getOperatorNew();
2967
2968 // The only new-placement list we support is (std::nothrow), and only for
2969 // the replaceable global allocation functions.
2970 bool IsNothrowForm = NewExpr->getNumPlacementArgs() == 1 &&
2971 NewExpr->getPlacementArg(0)->getType()->isNothrowT();
2972 if (NewExpr->getNumPlacementArgs() > 0 && !IsNothrowForm) {
2973 S.FFDiag(Loc, diag::note_constexpr_new_placement)
2974 << /*Unsupported*/ 0 << E->getSourceRange();
2975 return false;
2976 }
2977
2978 assert(
2979 !OperatorNew->isUsableAsGlobalAllocationFunctionInConstantEvaluation());
2980 S.FFDiag(Loc, diag::note_constexpr_new_non_replaceable)
2981 << isa<CXXMethodDecl>(OperatorNew) << OperatorNew;
2982 return false;
2983 }
2984
2985 const auto *DeleteExpr = cast<CXXDeleteExpr>(E);
2986 const FunctionDecl *OperatorDelete = DeleteExpr->getOperatorDelete();
2987 assert(!OperatorDelete
2988 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation());
2989 S.FFDiag(Loc, diag::note_constexpr_new_non_replaceable)
2990 << isa<CXXMethodDecl>(OperatorDelete) << OperatorDelete;
2991 return false;
2992}
2993
2994bool CheckPlacementNew(InterpState &S, CodePtr OpPC, const Expr *E) {
2995 // Placement new is allowed in C++26. Before that, it is only allowed in a
2996 // std:: function or if [[msvc::constexpr]] was used.
2997 if (S.getLangOpts().CPlusPlus26 || S.Current->isStdFunction() ||
2999 return true;
3000
3001 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_new_placement)
3002 << /*C++26 feature*/ 1 << E->getSourceRange();
3003 return false;
3004}
3005
3007 const FixedPoint &FP) {
3008 const Expr *E = S.Current->getExpr(OpPC);
3011 E->getExprLoc(), diag::warn_fixedpoint_constant_overflow)
3012 << FP.toDiagnosticString(S.getASTContext()) << E->getType();
3013 }
3014 S.CCEDiag(E, diag::note_constexpr_overflow)
3015 << FP.toDiagnosticString(S.getASTContext()) << E->getType();
3016 return S.noteUndefinedBehavior();
3017}
3018
3019bool InvalidShuffleVectorIndex(InterpState &S, CodePtr OpPC, uint32_t Index) {
3020 const SourceInfo &Loc = S.Current->getSource(OpPC);
3021 S.FFDiag(Loc,
3022 diag::err_shufflevector_minus_one_is_undefined_behavior_constexpr)
3023 << Index;
3024 return false;
3025}
3026
3028 const Pointer &Ptr, unsigned BitWidth) {
3029 SourceInfo E = S.Current->getSource(OpPC);
3030
3031 S.CCEDiag(E, diag::note_constexpr_invalid_cast_ptrtoint)
3032 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
3033 << S.getLangOpts().CPlusPlus << S.Current->getRange(OpPC);
3034 if ((Ptr.isBlockPointer() && !Ptr.isZero()) || Ptr.isOpaquePointer())
3035 S.CCEDiag(E, diag::note_constexpr_has_lvalue) << S.Current->getRange(OpPC);
3036 if (Ptr.isIntegralPointer())
3037 return true;
3038
3039 if (Ptr.isOpaquePointer()) {
3040 if (!CheckIntegralAddressCast(S, OpPC, BitWidth))
3041 return false;
3042 return Ptr.isRoot();
3043 }
3044
3045 if (!Ptr.isZero()) {
3046 // Only allow based lvalue casts if they are lossless.
3047 if (!CheckIntegralAddressCast(S, OpPC, BitWidth))
3048 return Invalid(S, OpPC);
3049 }
3050 return true;
3051}
3052
3053bool CheckIntegralAddressCast(InterpState &S, CodePtr OpPC, unsigned BitWidth) {
3055 BitWidth);
3056}
3057
3058bool CastPointerIntegralAP(InterpState &S, CodePtr OpPC, uint32_t BitWidth) {
3059 const Pointer &Ptr = S.Stk.pop<Pointer>();
3060
3061 if (!CheckPointerToIntegralCast(S, OpPC, Ptr, BitWidth))
3062 return false;
3063
3064 auto Result = S.allocAP<IntegralAP<false>>(BitWidth);
3065 Result.copy(APInt(BitWidth, Ptr.getIntegerRepresentation()));
3066
3068 return true;
3069}
3070
3071bool CastPointerIntegralAPS(InterpState &S, CodePtr OpPC, uint32_t BitWidth) {
3072 const Pointer &Ptr = S.Stk.pop<Pointer>();
3073
3074 if (!CheckPointerToIntegralCast(S, OpPC, Ptr, BitWidth))
3075 return false;
3076
3077 auto Result = S.allocAP<IntegralAP<true>>(BitWidth);
3078 Result.copy(APInt(BitWidth, Ptr.getIntegerRepresentation()));
3079
3081 return true;
3082}
3083
3084bool CheckBitCast(InterpState &S, CodePtr OpPC, bool HasIndeterminateBits,
3085 bool TargetIsUCharOrByte) {
3086 // This is always fine.
3087 if (!HasIndeterminateBits)
3088 return true;
3089
3090 // Indeterminate bits can only be bitcast to unsigned char or std::byte.
3091 if (TargetIsUCharOrByte)
3092 return true;
3093
3094 const Expr *E = S.Current->getExpr(OpPC);
3095 QualType ExprType = E->getType();
3096 S.FFDiag(E, diag::note_constexpr_bit_cast_indet_dest)
3097 << ExprType << S.getLangOpts().CharIsSigned << E->getSourceRange();
3098 return false;
3099}
3100
3102 if (B->isConstexprUnknown()) {
3103 S.Stk.push<Pointer>(B);
3104 return true;
3105 }
3106
3107 const auto &ID = B->getBlockDesc<LocalInlineDescriptor>();
3108 if (!ID.IsInitialized) {
3110 S.FFDiag(S.Current->getSource(OpPC),
3111 diag::note_constexpr_use_uninit_reference);
3112 return false;
3113 }
3114
3115 assert(B->getDescriptor()->getPrimType() == PT_Ptr);
3116 S.Stk.push<Pointer>(B->deref<Pointer>());
3117 return true;
3118}
3119
3120bool GetTypeid(InterpState &S, const Type *TypePtr, const Type *TypeInfoType) {
3121 S.Stk.push<Pointer>(TypePtr, TypeInfoType);
3122 return true;
3123}
3124
3125bool GetTypeidPtr(InterpState &S, CodePtr OpPC, const Type *TypeInfoType) {
3126 const auto &P = S.Stk.pop<Pointer>();
3127
3128 if (!P.isBlockPointer() && !P.isOpaquePointer())
3129 return false;
3130
3131 if (P.isConstexprUnknown()) {
3132 QualType DynamicType = P.getType();
3133 const Expr *E = S.Current->getExpr(OpPC);
3134 APValue V = P.toAPValue(S.getASTContext());
3136 S.FFDiag(E, diag::note_constexpr_polymorphic_unknown_dynamic_type)
3137 << AK_TypeId << V.getAsString(S.getASTContext(), TT);
3138 return false;
3139 }
3140
3141 // Pick the most-derived type.
3142 CanQualType T;
3143 if (P.isBlockPointer())
3144 T = P.stripBaseCasts().getType()->getCanonicalTypeUnqualified();
3145 else
3146 T = P.getType()->getCanonicalTypeUnqualified();
3147
3148 // ... unless we're currently constructing this object.
3149 // FIXME: We have a similar check to this in more places.
3150 if (S.Current->getFunction()) {
3151 for (const InterpFrame *Frame = S.Current; Frame; Frame = Frame->Caller) {
3152 if (const Function *Func = Frame->getFunction();
3153 Func && (Func->isConstructor() || Func->isDestructor()) &&
3154 P.block() == Frame->getThis().block()) {
3156 Func->getParentDecl());
3157 break;
3158 }
3159 }
3160 }
3161
3162 S.Stk.push<Pointer>(T->getTypePtr(), TypeInfoType);
3163 return true;
3164}
3165
3167 const auto *E = cast<CXXTypeidExpr>(S.Current->getExpr(OpPC));
3168 S.CCEDiag(E, diag::note_constexpr_typeid_polymorphic)
3169 << E->getExprOperand()->getType()
3170 << E->getExprOperand()->getSourceRange();
3171 return false;
3172}
3173
3175 const Pointer &RHS) {
3176 assert(LHS.isStringPointer());
3177 assert(RHS.isStringPointer());
3178
3179 unsigned LHSOffset = LHS.isOnePastEnd() ? LHS.getNumElems() : LHS.getIndex();
3180 unsigned RHSOffset = RHS.isOnePastEnd() ? RHS.getNumElems() : RHS.getIndex();
3181 const auto *LHSLit = cast<StringLiteral>(LHS.getRootExpr());
3182 const auto *RHSLit = cast<StringLiteral>(RHS.getRootExpr());
3183
3184 StringRef LHSStr(LHSLit->getBytes());
3185 unsigned LHSLength = LHSStr.size();
3186 StringRef RHSStr(RHSLit->getBytes());
3187 unsigned RHSLength = RHSStr.size();
3188
3189 int32_t IndexDiff = RHSOffset - LHSOffset;
3190 if (IndexDiff < 0) {
3191 if (static_cast<int32_t>(LHSLength) < -IndexDiff)
3192 return false;
3193 LHSStr = LHSStr.drop_front(-IndexDiff);
3194 } else {
3195 if (static_cast<int32_t>(RHSLength) < IndexDiff)
3196 return false;
3197 RHSStr = RHSStr.drop_front(IndexDiff);
3198 }
3199
3200 unsigned ShorterCharWidth;
3201 StringRef Shorter;
3202 StringRef Longer;
3203 if (LHSLength < RHSLength) {
3204 ShorterCharWidth = LHSLit->getCharByteWidth();
3205 Shorter = LHSStr;
3206 Longer = RHSStr;
3207 } else {
3208 ShorterCharWidth = RHSLit->getCharByteWidth();
3209 Shorter = RHSStr;
3210 Longer = LHSStr;
3211 }
3212
3213 // The null terminator isn't included in the string data, so check for it
3214 // manually. If the longer string doesn't have a null terminator where the
3215 // shorter string ends, they aren't potentially overlapping.
3216 for (unsigned NullByte : llvm::seq(ShorterCharWidth)) {
3217 if (Shorter.size() + NullByte >= Longer.size())
3218 break;
3219 if (Longer[Shorter.size() + NullByte])
3220 return false;
3221 }
3222 return Shorter == Longer.take_front(Shorter.size());
3223}
3224
3226 if (T == PT_IntAPS) {
3227 auto &Val = Ptr.deref<IntegralAP<true>>();
3228 if (!Val.singleWord()) {
3229 uint64_t *NewMemory = new (S.P) uint64_t[Val.numWords()];
3230 Val.take(NewMemory);
3231 }
3232 } else if (T == PT_IntAP) {
3233 auto &Val = Ptr.deref<IntegralAP<false>>();
3234 if (!Val.singleWord()) {
3235 uint64_t *NewMemory = new (S.P) uint64_t[Val.numWords()];
3236 Val.take(NewMemory);
3237 }
3238 } else if (T == PT_Float) {
3239 auto &Val = Ptr.deref<Floating>();
3240 if (!Val.singleWord()) {
3241 uint64_t *NewMemory = new (S.P) uint64_t[Val.numWords()];
3242 Val.take(NewMemory);
3243 }
3244 } else if (T == PT_MemberPtr) {
3245 auto &Val = Ptr.deref<MemberPointer>();
3246 unsigned PathLength = Val.getPathLength();
3247 auto *NewPath = new (S.P) const CXXRecordDecl *[PathLength];
3248 std::copy_n(Val.path(), PathLength, NewPath);
3249 Val.takePath(NewPath);
3250 } else if (T == PT_Ptr) {
3251 auto &Val = Ptr.deref<Pointer>();
3252 if (Val.isOpaquePointer() && Val.asOpaquePointer().PathLength != 0) {
3253 const OpaquePointer &OP = Val.asOpaquePointer();
3254 auto *NewPath = new (S.P) PointerPathEntry[OP.PathLength];
3255 std::memcpy(NewPath, OP.Path, OP.PathLength * sizeof(PointerPathEntry));
3256 Val = Pointer(OP.withPath(NewPath, OP.PathLength,
3257 OP.getFieldType().getTypePtr(),
3258 OP.isOnePastEnd()),
3259 Val.getByteOffset());
3260 }
3261 }
3262}
3263
3264template <typename T>
3266 assert(needsAlloc<T>());
3267 if constexpr (std::is_same_v<T, MemberPointer>) {
3268 auto &Val = Ptr.deref<MemberPointer>();
3269 unsigned PathLength = Val.getPathLength();
3270 auto *NewPath = new (S.P) const CXXRecordDecl *[PathLength];
3271 std::copy_n(Val.path(), PathLength, NewPath);
3272 Val.takePath(NewPath);
3273 } else if constexpr (std::is_same_v<T, Pointer>) {
3274 auto &Val = Ptr.deref<Pointer>();
3275 if (Val.isOpaquePointer() && Val.asOpaquePointer().PathLength != 0) {
3276 const OpaquePointer &OP = Val.asOpaquePointer();
3277 auto *NewPath = new (S.P) PointerPathEntry[OP.PathLength];
3278 std::memcpy(NewPath, OP.Path, OP.PathLength * sizeof(PointerPathEntry));
3279 Val = Pointer(OP.withPath(NewPath, OP.PathLength,
3280 OP.getFieldType().getTypePtr(),
3281 OP.isOnePastEnd()),
3282 Val.getByteOffset());
3283 }
3284 } else {
3285 auto &Val = Ptr.deref<T>();
3286 if (!Val.singleWord()) {
3287 uint64_t *NewMemory = new (S.P) uint64_t[Val.numWords()];
3288 Val.take(NewMemory);
3289 }
3290 }
3291}
3292
3294 if (const Record *R = Ptr.getRecord()) {
3295 for (const Record::Field &Fi : R->fields()) {
3296 if (Fi.Desc->isPrimitive()) {
3297 TYPE_SWITCH_ALLOC(Fi.Desc->getPrimType(), {
3298 copyPrimitiveMemory<T>(S, Ptr.atField(Fi.Offset));
3299 });
3300 } else {
3301 finishGlobalRecurse(S, Ptr.atField(Fi.Offset));
3302 }
3303 }
3304 return;
3305 }
3306
3307 if (const Descriptor *D = Ptr.getFieldDesc(); D && D->isArray()) {
3308 unsigned NumElems = D->getNumElems();
3309 if (NumElems == 0)
3310 return;
3311
3312 if (D->isPrimitiveArray()) {
3313 PrimType PT = D->getPrimType();
3314 if (!needsAlloc(PT))
3315 return;
3316 assert(NumElems >= 1);
3317 PtrView EP = Ptr.atIndex(0);
3318 bool AllSingleWord = true;
3319 TYPE_SWITCH_ALLOC(PT, {
3320 if (!EP.deref<T>().singleWord()) {
3322 AllSingleWord = false;
3323 }
3324 });
3325 if (AllSingleWord)
3326 return;
3327 for (unsigned I = 1; I != D->getNumElems(); ++I) {
3328 PtrView EP = Ptr.atIndex(I);
3329 copyPrimitiveMemory(S, EP, PT);
3330 }
3331 } else {
3332 assert(D->isCompositeArray());
3333 for (unsigned I = 0; I != D->getNumElems(); ++I) {
3334 PtrView EP = Ptr.atIndex(I).narrow();
3335 finishGlobalRecurse(S, EP);
3336 }
3337 }
3338 }
3339}
3340
3342 const Pointer &Ptr = S.Stk.pop<Pointer>();
3343 if (!Ptr.isBlockPointer())
3344 return true;
3345
3346 finishGlobalRecurse(S, Ptr.view());
3347 Ptr.initialize();
3348 Ptr.activate();
3349
3350 return true;
3351}
3352
3353bool InvalidCast(InterpState &S, CodePtr OpPC, CastKind Kind, bool Fatal) {
3354 switch (Kind) {
3356 S.CCEDiag(S.Current->getSource(OpPC), diag::note_constexpr_invalid_cast)
3357 << diag::ConstexprInvalidCastKind::Reinterpret
3358 << S.Current->getRange(OpPC);
3359 return !Fatal;
3361 // Don't emit anything as we'll emit diag
3362 // for this in CheckPointerToIntegralCast
3363 assert(!Fatal);
3364 return true;
3366 S.CCEDiag(S.Current->getSource(OpPC), diag::note_constexpr_invalid_cast)
3367 << diag::ConstexprInvalidCastKind::ThisConversionOrReinterpret
3368 << S.getLangOpts().CPlusPlus << S.Current->getRange(OpPC);
3369 return !Fatal;
3370 case CastKind::Volatile:
3372 const auto *E = S.Current->getExpr(OpPC);
3373 const auto *CE = dyn_cast<CastExpr>(E);
3374 if (CE && S.getLangOpts().CPlusPlus)
3375 S.FFDiag(E, diag::note_constexpr_access_volatile_type)
3376 << AK_Read << CE->getSubExpr()->getType();
3377 else
3378 S.FFDiag(E);
3379 }
3380
3381 return false;
3382 case CastKind::Dynamic:
3383 assert(!S.getLangOpts().CPlusPlus20);
3384 S.CCEDiag(S.Current->getSource(OpPC), diag::note_constexpr_invalid_cast)
3385 << diag::ConstexprInvalidCastKind::Dynamic;
3386 return true;
3387 }
3388 llvm_unreachable("Unhandled CastKind");
3389 return false;
3390}
3391
3392// Destroy one scope: deallocate all local variables of the scope and diagnose
3393// out-of-lifetime destroys.
3394bool Destroy(InterpState &S, CodePtr OpPC, uint32_t I) {
3395 assert(S.Current->getFunction());
3396 for (auto &Local : S.Current->getFunction()->getScope(I).locals_reverse()) {
3397 Block *LocalBlock = S.Current->getLocalBlock(Local.Offset);
3398
3399 if (!LocalBlock->isInitialized())
3400 continue;
3401
3402 if (LocalBlock->getBlockDesc<LocalInlineDescriptor>().getLifetime() ==
3404 const Pointer Ptr = S.Current->getLocalPointer(Local.Offset);
3405 return diagnoseOutOfLifetimeDestroy(S, OpPC, Ptr);
3406 }
3407
3408 S.deallocate(LocalBlock);
3409 }
3410
3411 return true;
3412}
3413
3414// Perform a cast towards the class of the Decl (either up or down the
3415// hierarchy).
3417 const MemberPointer &MemberPtr,
3418 int32_t BaseOffset,
3419 const RecordDecl *BaseDecl) {
3420 if (!MemberPtr.getDecl()) {
3421 S.Stk.push<MemberPointer>(MemberPtr);
3422 return true;
3423 }
3424
3425 const CXXRecordDecl *Expected;
3426 if (MemberPtr.getPathLength() >= 2)
3427 Expected = MemberPtr.getPathEntry(MemberPtr.getPathLength() - 2);
3428 else
3429 Expected = MemberPtr.getRecordDecl();
3430
3431 assert(Expected);
3432 if (Expected->getCanonicalDecl() != BaseDecl->getCanonicalDecl()) {
3433 // C++11 [expr.static.cast]p12: In a conversion from (D::*) to (B::*),
3434 // if B does not contain the original member and is not a base or
3435 // derived class of the class containing the original member, the result
3436 // of the cast is undefined.
3437 // C++11 [conv.mem]p2 does not cover this case for a cast from (B::*) to
3438 // (D::*). We consider that to be a language defect.
3439 return false;
3440 }
3441
3442 unsigned OldPathLength = MemberPtr.getPathLength();
3443 unsigned NewPathLength = OldPathLength - 1;
3444 bool IsDerivedMember = NewPathLength != 0;
3445 auto *NewPath = S.allocMemberPointerPath(NewPathLength);
3446 std::copy_n(MemberPtr.path(), NewPathLength, NewPath);
3447
3448 S.Stk.push<MemberPointer>(MemberPtr.atInstanceBase(BaseOffset, NewPathLength,
3449 NewPath, IsDerivedMember));
3450 return true;
3451}
3452
3454 const MemberPointer &MemberPtr,
3455 int32_t BaseOffset,
3456 const RecordDecl *BaseDecl,
3457 bool IsDerivedMember) {
3458 unsigned OldPathLength = MemberPtr.getPathLength();
3459 unsigned NewPathLength = OldPathLength + 1;
3460
3461 auto *NewPath = S.allocMemberPointerPath(NewPathLength);
3462 std::copy_n(MemberPtr.path(), OldPathLength, NewPath);
3463 NewPath[OldPathLength] = cast<CXXRecordDecl>(BaseDecl);
3464
3465 S.Stk.push<MemberPointer>(MemberPtr.atInstanceBase(BaseOffset, NewPathLength,
3466 NewPath, IsDerivedMember));
3467 return true;
3468}
3469
3470/// DerivedToBaseMemberPointer
3472 const RecordDecl *BaseDecl) {
3473 const auto &Ptr = S.Stk.pop<MemberPointer>();
3474
3475 if (!Ptr.isDerivedMember() && Ptr.hasPath())
3476 return castBackMemberPointer(S, Ptr, Off, BaseDecl);
3477
3478 bool IsDerivedMember = Ptr.isDerivedMember() || !Ptr.hasPath();
3479 return appendToMemberPointer(S, Ptr, Off, BaseDecl, IsDerivedMember);
3480}
3481
3482/// BaseToDerivedMemberPointer
3484 const RecordDecl *BaseDecl) {
3485 const auto &Ptr = S.Stk.pop<MemberPointer>();
3486
3487 if (!Ptr.isDerivedMember()) {
3488 // Simply append.
3489 return appendToMemberPointer(S, Ptr, Off, BaseDecl,
3490 /*IsDerivedMember=*/false);
3491 }
3492
3493 return castBackMemberPointer(S, Ptr, Off, BaseDecl);
3494}
3495
3497 S.Stk.push<MemberPointer>(D);
3498 return true;
3499}
3500
3502 const auto &MP = S.Stk.pop<MemberPointer>();
3503
3504 if (!MP.isBaseCastPossible())
3505 return false;
3506
3507 S.Stk.push<Pointer>(MP.getBase());
3508 return true;
3509}
3510
3512 const auto &MP = S.Stk.pop<MemberPointer>();
3513
3514 const ValueDecl *D = MP.getDecl();
3515 const auto *FD = dyn_cast_if_present<FunctionDecl>(D);
3516 if (!FD)
3517 return false;
3518
3519 const auto *Method = dyn_cast<CXXMethodDecl>(FD);
3520 if (!Method)
3521 return false;
3522
3523 const Pointer &Base = MP.getBase();
3524 // The method must be accessible via the base of the MemberPointer.
3525 const CXXRecordDecl *MethodParent = Method->getParent();
3526 if (!Base.getRecord() || Base.getRecord()->getDecl() != MethodParent)
3527 return false;
3528
3529 const auto *Func = S.getContext().getOrCreateFunction(FD);
3530 if (!Func)
3531 return false;
3532 S.Stk.push<Pointer>(Func);
3533 return true;
3534}
3535
3536/// Just append the given Entry to the MemberPointer's path.
3537/// This is used to re-inject APValues into the bytecode interpreter.
3539 bool IsDerived) {
3540 const auto &MemberPtr = S.Stk.pop<MemberPointer>();
3541
3542 unsigned OldPathLength = MemberPtr.getPathLength();
3543 unsigned NewPathLength = OldPathLength + 1;
3544
3545 auto *NewPath = S.allocMemberPointerPath(NewPathLength);
3546 std::copy_n(MemberPtr.path(), OldPathLength, NewPath);
3547 NewPath[OldPathLength] = cast<CXXRecordDecl>(Entry);
3548
3550 MemberPtr.withPath(NewPathLength, NewPath, IsDerived));
3551 return true;
3552}
3553
3554template <bool Signed>
3555static bool floatAPCast(InterpState &S, CodePtr OpPC, const Floating &F,
3556 uint32_t BitWidth, uint32_t FPOI) {
3557 APSInt Result(BitWidth, /*IsUnsigned=*/!Signed);
3558 auto Status = F.convertToInteger(Result);
3559
3560 // Float-to-Integral overflow check.
3561 if ((Status & APFloat::opStatus::opInvalidOp) && F.isFinite() &&
3562 !handleOverflow(S, OpPC, F.getAPFloat()))
3563 return false;
3564
3566
3567 auto ResultAP = S.allocAP<IntegralAP<Signed>>(BitWidth);
3568 ResultAP.copy(Result);
3569
3570 S.Stk.push<IntegralAP<Signed>>(ResultAP);
3571
3572 return CheckFloatResult(S, OpPC, F, Status, FPO);
3573}
3574
3575bool CastFloatingIntegralAP(InterpState &S, CodePtr OpPC, uint32_t BitWidth,
3576 uint32_t FPOI) {
3577 Floating F = S.Stk.pop<Floating>();
3578 return floatAPCast<false>(S, OpPC, F, BitWidth, FPOI);
3579}
3580
3581bool CastFloatingIntegralAPS(InterpState &S, CodePtr OpPC, uint32_t BitWidth,
3582 uint32_t FPOI) {
3583 Floating F = S.Stk.pop<Floating>();
3584 return floatAPCast<true>(S, OpPC, F, BitWidth, FPOI);
3585}
3586
3588 APSInt &&Index, bool AllowReplace) {
3589 const OpaquePointer &OP = Ptr.asOpaquePointer();
3590 QualType ArrTy = OP.getSurroundingArray();
3591
3592 if (isa<VariableArrayType>(ArrTy) && OP.PathLength != 0)
3593 return false;
3594
3595 QualType ElemType;
3596 if (const ArrayType *AT = ArrTy->getAsArrayTypeUnsafe())
3597 ElemType = AT->getElementType();
3598 else
3599 ElemType = ArrTy;
3600
3601 if (ArrTy->isArrayType()) {
3602 unsigned IndexBits = std::max(Index.getBitWidth(), 32u) + 1;
3603 APSInt NewIndex =
3604 Index.extend(IndexBits) +
3605 APSInt(APInt(IndexBits, Ptr.getIndex()), Index.isUnsigned());
3606
3607 if (NewIndex > Ptr.getNumElems() || NewIndex.isNegative())
3608 diagnoseArrayIndex(S, OpPC, NewIndex, Ptr.getNumElems(),
3609 OP.isArrayElement());
3610
3611 if (NewIndex.getActiveBits() > 64)
3612 return false;
3613
3614 unsigned NewPathLength;
3615 if (AllowReplace && OP.isArrayElement()) {
3616 // This is what happens after an array-to-pointer-decay. We don't enter
3617 // the array element but simply change the index in the array we're
3618 // already pointing into.
3619 NewPathLength = OP.PathLength;
3620 } else {
3621 NewPathLength = OP.PathLength + 1;
3622 }
3623
3624 PointerPathEntry NewEntry;
3625 if (Index.isNonNegative())
3626 NewEntry = PointerPathEntry::array(Index.getZExtValue());
3627 else
3628 NewEntry = PointerPathEntry::negativeArray((-Index).getZExtValue());
3629
3630 PointerPathEntry *NewPath =
3631 S.extendPointerPath(NewPathLength, OP.Path, NewEntry);
3632 S.Stk.push<Pointer>(
3633 OP.withPath(NewPath, NewPathLength, ElemType.getTypePtr()),
3634 Ptr.getByteOffset());
3635
3636 } else {
3637 unsigned IndexBits = std::max(Index.getBitWidth(), 64u) + 1;
3638 size_t CurrentIndex = Ptr.getByteOffset();
3639 APSInt NewOffset =
3640 Index.extend(IndexBits) +
3641 APSInt(APInt(IndexBits, CurrentIndex), Index.isUnsigned());
3642 if (NewOffset > 1 || NewOffset.isNegative())
3643 diagnoseArrayIndex(S, OpPC, NewOffset, 0, false);
3644
3645 if (NewOffset.getActiveBits() > 64)
3646 return false;
3647
3648 size_t NewByteOffset = CurrentIndex + Index.getZExtValue();
3649 bool PastEnd = NewByteOffset != 0;
3650 S.Stk.push<Pointer>(OP.withFieldType(ElemType.getTypePtr(), PastEnd),
3651 NewByteOffset);
3652 }
3653 return true;
3654}
3655
3656std::optional<Pointer> addSubOffsetOpaque(InterpState &S, CodePtr OpPC,
3657 const Pointer &Ptr, APSInt &&Offset,
3658 ArithOp Op) {
3659 assert(Ptr.isOpaquePointer());
3660 if (Offset.isZero())
3661 return Ptr;
3662
3663 const OpaquePointer &OP = Ptr.asOpaquePointer();
3665 QualType ElemTy = OP.getFieldType();
3666 unsigned NumElems = 1;
3667
3668 if (OP.isArrayElement()) {
3669 if (const ConstantArrayType *CAT =
3671 NumElems = CAT->getZExtSize();
3672 } else {
3673 ArrTy = ElemTy;
3674 }
3675
3676 if (isa<IncompleteArrayType>(ArrTy)) {
3677 const SourceInfo &E = S.Current->getSource(OpPC);
3678 S.FFDiag(E, diag::note_constexpr_unsized_array_indexed);
3679 return std::nullopt;
3680 }
3681
3682 if (!validType(ElemTy) || !validType(ArrTy)) {
3683 Invalid(S, OpPC);
3684 return std::nullopt;
3685 }
3686
3687 APSInt NewIndex;
3688 if (Op == ArithOp::Add) {
3689 if (OP.isArrayElement()) {
3690 NewIndex = Ptr.getIndex() + (Offset.extend(Offset.getBitWidth() + 2));
3691 } else {
3692 NewIndex =
3693 (Ptr.getByteOffset()) + (Offset.extend(Offset.getBitWidth() + 2));
3694 }
3695 } else {
3696 if (OP.isArrayElement()) {
3697 NewIndex = Ptr.getIndex() - (Offset.extend(Offset.getBitWidth() + 2));
3698 } else {
3699 NewIndex =
3700 (Ptr.getByteOffset()) - (Offset.extend(Offset.getBitWidth() + 2));
3701 }
3702 }
3703
3704 if (NewIndex > NumElems || NewIndex < 0)
3705 diagnoseArrayIndex(S, OpPC, NewIndex, NumElems, OP.isArrayElement());
3706
3707 if (NewIndex.getActiveBits() > 64)
3708 return std::nullopt;
3709
3710 // If the pointer is an array element, advance that index.
3711 if (OP.isArrayElement()) {
3712 unsigned NewPathLength = OP.PathLength;
3713 PointerPathEntry *NewPath = S.allocPointerPath(OP.PathLength, OP.Path);
3714
3715 if (Op == ArithOp::Add)
3716 NewPath[NewPathLength - 1].Index += Offset.getZExtValue();
3717 else
3718 NewPath[NewPathLength - 1].Index -= Offset.getZExtValue();
3719 return OP.withPath(NewPath, NewPathLength, OP.FieldType.getPointer());
3720 }
3721
3722 return Pointer(OP.withPastEnd(true), NewIndex.getZExtValue());
3723}
3724
3726 const Pointer &Ptr) {
3727 if (Ptr.isOpaquePointer()) {
3728 const OpaquePointer &OP = Ptr.asOpaquePointer();
3729 if (!OP.getFieldType()->isRecordType()) {
3730 S.Stk.push<Pointer>(Ptr);
3731 return true;
3732 }
3733
3734 PointerPathEntry *NewPath =
3735 S.extendPointerPath(OP.PathLength + 1, OP.Path,
3736 PointerPathEntry::base(Decl, /*IsVirtual=*/true));
3737
3738 S.Stk.push<Pointer>(
3739 OP.withPath(NewPath, OP.PathLength + 1,
3741 Ptr.getByteOffset());
3742 return true;
3743 }
3744
3745 if (!Ptr.isBlockPointer())
3746 return false;
3747 if (!Ptr.getFieldDesc()->isRecord())
3748 return false;
3749 Pointer Base = Ptr.stripBaseCasts();
3750 const Record::Base *VirtBase = Base.getRecord()->findVirtualBase(Decl);
3751 if (!VirtBase)
3752 return false;
3753 S.Stk.push<Pointer>(Base.atField(VirtBase->Offset));
3754 return true;
3755}
3756
3758 const Pointer &Src = S.Stk.pop<Pointer>();
3759 Pointer &Dest = S.Stk.peek<Pointer>();
3760
3761 if (Src.isDummy() || !Src.isBlockPointer())
3762 return false;
3763 if (!Dest.isBlockPointer())
3764 return false;
3765
3766 if (!CheckLoad(S, OpPC, Src))
3767 return false;
3768
3769 return DoMemcpy(S, OpPC, Src, Dest);
3770}
3771
3773 const Function *Func) {
3774 const Pointer &Src = S.Stk.pop<Pointer>();
3775 Pointer &Dest = S.Stk.peek<Pointer>();
3776
3777 if (Src.isDummy() || Src.isConstexprUnknown() || !Src.isBlockPointer())
3778 return false;
3779 if (!Dest.isBlockPointer() || Dest.isDummy() || Dest.isConstexprUnknown())
3780 return false;
3781
3782 if (!CheckStore(S, OpPC, Dest, AK_MemberCall,
3783 /*WillBeActivated=*/Activate))
3784 return false;
3785
3787 return false;
3788
3789 // NOTE: This is a fake function frame that doesn't do anything except show up
3790 // in the "in call to" diagnostics. Since the copies we replace with this
3791 // opcode are always defaulted/trivial, they don't add much there either
3792 // though. Once we default to the bytecode interpreter, we shoud consider just
3793 // removing it.
3794 auto Memory = std::make_unique<char[]>(InterpFrame::allocSize(Func));
3795 auto *NewFrame =
3796 new (Memory.get()) InterpFrame(S, Func, S.PC, /*VarArgSize=*/0);
3797 InterpFrame *FrameBefore = S.Current;
3798 S.Current = NewFrame;
3799
3800 if (!CheckLoad(S, OpPC, Src, AK_Read)) {
3801 S.Current = FrameBefore;
3802 return false;
3803 }
3804
3805 bool Result = DoMemcpy(S, OpPC, Src, Dest, Activate, /*Diagnose=*/true);
3806 S.Current = FrameBefore;
3807
3808 return Result;
3809}
3810
3811// FIXME: Would be nice to generate this instead of hardcoding it here.
3812[[maybe_unused]] static constexpr bool OpReturns(Opcode Op) {
3813 return Op == OP_RetVoid || Op == OP_RetValue || Op == OP_NoRet ||
3814 Op == OP_RetSint8 || Op == OP_RetUint8 || Op == OP_RetSint16 ||
3815 Op == OP_RetUint16 || Op == OP_RetSint32 || Op == OP_RetUint32 ||
3816 Op == OP_RetSint64 || Op == OP_RetUint64 || Op == OP_RetIntAP ||
3817 Op == OP_RetIntAPS || Op == OP_RetBool || Op == OP_RetFixedPoint ||
3818 Op == OP_RetPtr || Op == OP_RetMemberPtr || Op == OP_RetFloat ||
3819 Op == OP_RetReflect || Op == OP_EndSpeculation;
3820}
3821
3822#if USE_TAILCALLS
3823PRESERVE_NONE static bool InterpNext(InterpState &S);
3824#endif
3825
3826// The dispatcher functions read the opcode arguments from the
3827// bytecode and call the implementation function.
3828#define GET_INTERPFN_DISPATCHERS
3829#include "Opcodes.inc"
3830#undef GET_INTERPFN_DISPATCHERS
3831
3833// Array of the dispatcher functions defined above.
3835#define GET_INTERPFN_LIST
3836#include "Opcodes.inc"
3837#undef GET_INTERPFN_LIST
3838};
3839
3840#if USE_TAILCALLS
3841// Read the next opcode and call the dispatcher function.
3842PRESERVE_NONE static bool InterpNext(InterpState &S) {
3843 auto Op = S.PC.read<Opcode>();
3844 auto Fn = InterpFunctions[Op];
3845 MUSTTAIL return Fn(S);
3846}
3847#endif
3848
3850 assert(S.Current->getFunction());
3851
3852 S.PC = S.Current->getFunction()->getCodeBegin();
3853
3854#if USE_TAILCALLS
3855 return InterpNext(S);
3856#else
3857 while (true) {
3858 auto Op = S.PC.read<Opcode>();
3859 auto Fn = InterpFunctions[Op];
3860
3861 if (!Fn(S))
3862 return false;
3863 if (OpReturns(Op))
3864 break;
3865 }
3866 return true;
3867#endif
3868}
3869
3870/// This is used to implement speculative execution via __builtin_constant_p
3871/// when we generate bytecode.
3872///
3873/// The setup here is that we use the same tailcall mechanism for speculative
3874/// evaluation that we use for the regular one.
3875/// Since each speculative execution ends with an EndSpeculation opcode,
3876/// that one does NOT call InterpNext() but simply returns true.
3877/// This way, we return back to this function when we see an EndSpeculation,
3878/// OR (of course), when we encounter an error and one of the opcodes
3879/// returns false.
3880PRESERVE_NONE static bool BCP(InterpState &S, CodePtr OpPC, int32_t Offset,
3881 PrimType PT) {
3882 // PC after reading the BCP opcode and both Offset/PT arguments.
3883 [[maybe_unused]] CodePtr PCBefore = S.PC;
3884 size_t StackSizeBefore = S.Stk.size();
3885
3886 // Speculation depth must be at least 1 here, since we must have
3887 // passed a StartSpeculation op before.
3888#ifndef NDEBUG
3889 [[maybe_unused]] unsigned DepthBefore = S.SpeculationDepth;
3890 assert(DepthBefore >= 1);
3891#endif
3892
3893 auto SpeculativeInterp = [&S]() -> bool {
3894 // Ignore diagnostics during speculative execution.
3895 PushIgnoreDiags(S);
3896 auto _ = llvm::scope_exit([&]() { PopIgnoreDiags(S); });
3897
3898#if USE_TAILCALLS
3899 auto Op = S.PC.read<Opcode>();
3900 auto Fn = InterpFunctions[Op];
3901 return Fn(S);
3902#else
3903 while (true) {
3904 auto Op = S.PC.read<Opcode>();
3905 auto Fn = InterpFunctions[Op];
3906
3907 if (!Fn(S))
3908 return false;
3909 if (OpReturns(Op))
3910 break;
3911 }
3912 return true;
3913#endif
3914 };
3915
3916 if (SpeculativeInterp()) {
3917 // Speculation must've ended naturally via a EndSpeculation opcode.
3918 assert(S.SpeculationDepth == DepthBefore - 1);
3919 if (PT == PT_Ptr) {
3920 const auto &Ptr = S.Stk.pop<Pointer>();
3921 assert(S.Stk.size() == StackSizeBefore);
3924 } else {
3925 // Pop the result from the stack and return success.
3926 TYPE_SWITCH(PT, S.Stk.discard<T>(););
3927 assert(S.Stk.size() == StackSizeBefore);
3929 }
3930 } else {
3931 // Jump to the end of the speculation, just after the actual EndSpeculation
3932 // op.
3933 S.PC = PCBefore + Offset - align(sizeof(Opcode));
3934
3935 // End the speculation manually since we didn't call EndSpeculation
3936 // naturally.
3937 EndSpeculation(S);
3938
3939 if (!S.inConstantContext())
3940 return Invalid(S, OpPC);
3941
3942 S.Stk.clearTo(StackSizeBefore);
3944 }
3945
3946 // We have already evaluated this speculation's EndSpeculation opcode.
3947 assert(S.SpeculationDepth == DepthBefore - 1);
3948
3949 return true;
3950}
3951
3952} // namespace interp
3953} // namespace clang
Defines the clang::ASTContext interface.
#define V(N, I)
Defines the clang::Expr interface and subclasses for C++ expressions.
static const FunctionDecl * getVirtualOperatorDelete(QualType T)
bool FunctionDefinitionCanBeLazilyInstantiated(const FunctionDecl *FD)
Whether we can instantiate FD during constant evaluation.
static PRESERVE_NONE bool RetValue(InterpState &S)
Definition Interp.cpp:64
static bool CheckGlobal(InterpState &S, CodePtr OpPC, const Block *B)
Definition Interp.cpp:202
static bool Jf(InterpState &S, CodePtr OpPC, int32_t Offset)
Definition Interp.cpp:85
static bool Jmp(InterpState &S, CodePtr OpPC, int32_t Offset)
Definition Interp.cpp:72
static bool validType(QualType T)
Definition Interp.cpp:56
static bool diagnoseUnknownDecl(InterpState &S, CodePtr OpPC, const ValueDecl *D, AccessKinds AK=AK_Read)
Definition Interp.cpp:103
static void diagnoseNonConstVariable(InterpState &S, CodePtr OpPC, const ValueDecl *VD, AccessKinds AK=AK_Read)
Definition Interp.cpp:152
static bool isModification(AccessKinds AK)
Definition Interp.cpp:147
#define MUSTTAIL
Definition Interp.cpp:49
static void diagnoseMissingInitializer(InterpState &S, CodePtr OpPC, const ValueDecl *VD)
Definition Interp.cpp:93
static bool Jt(InterpState &S, CodePtr OpPC, int32_t Offset)
Definition Interp.cpp:77
#define PRESERVE_NONE
Definition Interp.h:50
#define TYPE_SWITCH_ALLOC(Expr, B)
Definition PrimType.h:315
#define TYPE_SWITCH(Expr, B)
Definition PrimType.h:240
static bool hasLayout(const RecordDecl *D)
Whether layout (offset and size) information can be queried for D.
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
const ConstantArrayType * getAsConstantArrayType(QualType T) const
bool hasSameFunctionTypeIgnoringExceptionSpec(QualType T, QualType U) const
Determine whether two function types are the same, ignoring exception specifications in cases where t...
QualType getLValueReferenceType(QualType T, bool SpelledAsLValue=true) const
Return the uniqued reference to the type for an lvalue reference to the specified type.
QualType getConstantArrayType(QualType EltTy, const llvm::APInt &ArySize, const Expr *SizeExpr, ArraySizeModifier ASM, unsigned IndexTypeQuals) const
Return the unique reference to the type for a constant array of the specified element type.
const clang::PrintingPolicy & getPrintingPolicy() const
Definition ASTContext.h:908
const ArrayType * getAsArrayType(QualType T) const
Type Query functions.
static bool hasSameType(QualType T1, QualType T2)
Determine whether the given types T1 and T2 are equivalent.
bool hasSimilarType(QualType T1, QualType T2) const
Determine if two types are similar, according to the C++ rules.
DiagnosticsEngine & getDiagnostics() const
const TargetInfo & getTargetInfo() const
Definition ASTContext.h:974
CanQualType getCanonicalTagType(const TagDecl *TD) const
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3820
QualType getElementType() const
Definition TypeBase.h:3832
Represents a path from a specific derived class (which is not represented as part of the path) to a p...
AccessSpecifier Access
The access along this inheritance path.
BasePaths - Represents the set of paths from a derived class to one of its (direct or indirect) bases...
paths_iterator begin()
paths_iterator end()
Represents a C++ constructor within a class.
Definition DeclCXX.h:2645
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2153
CXXMethodDecl * getCorrespondingMethodDeclaredInClass(const CXXRecordDecl *RD, bool MayBeBase=false)
Find if RD declares a function that overrides this function, and if so, return it.
Definition DeclCXX.cpp:2439
bool isVirtual() const
Definition DeclCXX.h:2208
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2296
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool isDerivedFrom(const CXXRecordDecl *Base) const
Determine whether this class is derived from the class Base.
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getCallee()
Definition Expr.h:3159
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3203
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3206
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1635
const T * getTypePtr() const
Retrieve the underlying type pointer, which refers to a canonical type.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3858
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
ValueDecl * getDecl()
Definition Expr.h:1383
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInvalidDecl() const
Definition DeclBase.h:597
SourceLocation getLocation() const
Definition DeclBase.h:448
bool hasAttr() const
Definition DeclBase.h:586
virtual SourceRange getSourceRange() const LLVM_READONLY
Source range that this declaration covers.
Definition DeclBase.h:436
DiagnosticBuilder Report(SourceLocation Loc, unsigned DiagID)
Issue the message to the client.
Represents an enum.
Definition Decl.h:4192
unsigned getNumNegativeBits() const
Returns the width in bits required to store all the negative enumerators of this enum.
Definition Decl.h:4402
void getValueRange(llvm::APInt &Max, llvm::APInt &Min) const
Calculates the [Min,Max) values the enum can store based on the NumPositiveBits and NumNegativeBits.
Definition Decl.cpp:5300
This represents one expression.
Definition Expr.h:114
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
LangOptions::FPExceptionModeKind getExceptionMode() const
static FPOptions getFromOpaqueInt(storage_type Value)
RoundingMode getRoundingMode() const
Represents a member of a struct/union/class.
Definition Decl.h:3341
Represents a function declaration or definition.
Definition Decl.h:2082
QualType getReturnType() const
Definition Decl.h:3022
StorageClass getStorageClass() const
Returns the storage class as written in the source.
Definition Decl.h:3065
bool isConstexpr() const
Whether this is a (C++11) constexpr function or constexpr constructor.
Definition Decl.h:2639
bool isPureVirtual() const
Whether this virtual function is pure, i.e.
Definition Decl.h:2522
bool isUsableAsGlobalAllocationFunctionInConstantEvaluation(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions described in i...
Definition Decl.cpp:3502
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3207
bool isDefined(const FunctionDecl *&Definition, bool CheckForPendingFriendDefinition=false) const
Returns true if the function has a definition that does not need to be instantiated.
Definition Decl.cpp:3254
@ FPE_Ignore
Assume that floating-point exceptions are masked.
This represents a decl that may have a name.
Definition Decl.h:276
IdentifierInfo * getIdentifier() const
Get the identifier that names this declaration, if there is one.
Definition Decl.h:297
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8662
void addConst()
Add the const type qualifier to this QualType.
Definition TypeBase.h:1172
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8578
void print(raw_ostream &OS, const PrintingPolicy &Policy, const Twine &PlaceHolder=Twine(), unsigned Indentation=0) const
QualType getCanonicalType() const
Definition TypeBase.h:8630
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8651
Represents a struct/union/class.
Definition Decl.h:4506
Classes implementing SemaProxy present a restricted view of the (possibly mutating) actions and queri...
Definition SemaProxy.h:29
virtual void instantiateFunctionDefinition(SourceLocation PointOfInstantiation, FunctionDecl *Function)=0
Encodes a location in the source.
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
TagDecl * getCanonicalDecl() override
Retrieves the "canonical" declaration of the given declaration.
Definition Decl.cpp:5010
uint64_t getPointerWidth(LangAS AddrSpace) const
Return the width of pointers on this target, for the specified address space.
Definition TargetInfo.h:497
The base class of the type hierarchy.
Definition TypeBase.h:1879
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isNothrowT() const
Definition Type.cpp:3437
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isArrayType() const
Definition TypeBase.h:8914
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isPointerType() const
Definition TypeBase.h:8815
CanQualType getCanonicalTypeUnqualified() const
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9248
bool isReferenceType() const
Definition TypeBase.h:8839
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9326
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9484
bool isPointerOrReferenceType() const
Definition TypeBase.h:8819
bool isRecordType() const
Definition TypeBase.h:8942
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1606
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1308
A memory block, either on the stack or in the heap.
Definition Block.h:68
const T & deref() const
Definition Block.h:143
bool isExtern() const
Checks if the block is extern.
Definition Block.h:107
bool isGlobal() const
Definition Block.h:99
const Descriptor * getDescriptor() const
Returns the block's descriptor.
Definition Block.h:103
bool isConstexprUnknown() const
Definition Block.h:118
bool isTemporary() const
Checks if the block is temporary.
Definition Block.h:109
bool isInitialized() const
Returns whether the data of this block has been initialized via invoking the Ctor func.
Definition Block.h:130
bool isDynamic() const
Definition Block.h:111
UnsignedOrNone getDeclID() const
Returns the declaration ID.
Definition Block.h:127
unsigned getEvalID() const
The Evaluation ID this block was created in.
Definition Block.h:132
bool isWeak() const
Definition Block.h:110
bool isAccessible() const
Definition Block.h:121
Pointer into the code segment.
Definition Source.h:31
std::enable_if_t<!std::is_pointer< T >::value, T > read()
Reads data and advances the pointer.
Definition Source.h:60
Compilation context for expressions.
Definition Compiler.h:116
unsigned collectBaseOffset(const RecordDecl *BaseDecl, const RecordDecl *DerivedDecl) const
Definition Context.cpp:808
const Record * getRecord(const RecordDecl *D) const
Definition Context.cpp:839
const Function * getOrCreateFunction(const FunctionDecl *FuncDecl)
Definition Context.cpp:673
ASTContext & getASTContext() const
Returns the AST context.
Definition Context.h:116
OptPrimType classify(QualType T) const
Classifies a type.
Definition Context.cpp:524
const CXXMethodDecl * getOverridingFunction(const CXXRecordDecl *DynamicDecl, const CXXRecordDecl *StaticDecl, const CXXMethodDecl *InitialFunction) const
Definition Context.cpp:637
Manages dynamic memory allocations done during bytecode interpretation.
std::optional< Form > getAllocationForm(const Expr *Source) const
Checks whether the allocation done at the given source is an array allocation.
bool deallocate(const Expr *Source, const Block *BlockToDelete)
Deallocate the given source+block combination.
Wrapper around fixed point types.
Definition FixedPoint.h:23
std::string toDiagnosticString(const ASTContext &Ctx) const
Definition FixedPoint.h:81
If a Floating is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition Floating.h:35
bool isFinite() const
Definition Floating.h:151
APFloat::opStatus convertToInteger(APSInt &Result) const
Definition Floating.h:71
APFloat getAPFloat() const
Definition Floating.h:64
Base class for stack frames, shared between VM and walker.
Definition Frame.h:28
Bytecode function.
Definition Function.h:98
bool hasExplicitThisPointer() const
Definition Function.h:231
Scope & getScope(unsigned Idx)
Returns a specific scope.
Definition Function.h:178
CodePtr getCodeBegin() const
Returns a pointer to the start of the code.
Definition Function.h:128
bool isDestructor() const
Checks if the function is a destructor.
Definition Function.h:201
bool isVirtual() const
Checks if the function is virtual.
Definition Function.h:188
bool hasNonNullAttr() const
Definition Function.h:162
bool isFullyCompiled() const
Checks if the function is fully done compiling.
Definition Function.h:228
bool isConstructor() const
Checks if the function is a constructor.
Definition Function.h:193
const FunctionDecl * getDecl() const
Returns the original FunctionDecl.
Definition Function.h:133
bool hasBody() const
Checks if the function already has a body attached.
Definition Function.h:239
bool isConstexpr() const
Definition Function.h:190
unsigned getWrittenArgSize() const
Definition Function.h:257
unsigned getArgSize() const
Returns the size of the argument stack.
Definition Function.h:125
bool isLambdaStaticInvoker() const
Returns whether this function is a lambda static invoker, which we generate custom byte code for.
Definition Function.h:209
bool isValid() const
Checks if the function is valid to call.
Definition Function.h:185
If an IntegralAP is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition IntegralAP.h:36
void copy(const APInt &V)
Definition IntegralAP.h:78
Wrapper around numeric types.
Definition Integral.h:69
static std::enable_if_t<!std::is_same_v< ValT, IntegralKind >, Integral > from(ValT V, unsigned NumBits=0)
Definition Integral.h:332
Frame storing local variables.
Definition InterpFrame.h:27
SourceLocation getLocation(CodePtr PC) const
InterpFrame * Caller
The frame of the previous function.
Pointer getLocalPointer(unsigned Offset) const
Returns a pointer to a local variables.
SourceInfo getSource(CodePtr PC) const
Map a location to a source.
SourceRange getRange(CodePtr PC) const
const Pointer & getThis() const
Returns the 'this' pointer.
const Function * getFunction() const
Returns the current function.
Definition InterpFrame.h:81
unsigned getArgSize() const
Block * getLocalBlock(unsigned Offset) const
const Expr * getExpr(CodePtr PC) const
static size_t allocSize(const Function *F)
Returns the number of bytes needed to allocate an InterpFrame for the given function.
Definition InterpFrame.h:48
void clearTo(size_t NewSize)
T pop()
Returns the value from the top of the stack and removes it.
Definition InterpStack.h:40
void push(Tys &&...Args)
Constructs a value in place on the top of the stack.
Definition InterpStack.h:34
size_t size() const
Returns the size of the stack in bytes.
Definition InterpStack.h:79
void discard()
Discards the top value from the stack.
Definition InterpStack.h:51
T & peek() const
Returns a reference to the value on the top of the stack.
Definition InterpStack.h:64
Interpreter context.
Definition InterpState.h:47
bool lifetimeStartedInEvaluation(const Block *B) const
Context & getContext() const
Definition InterpState.h:93
bool initializingBlock(const Block *B) const
DynamicAllocator & getAllocator()
Definition InterpState.h:97
Context & Ctx
Interpreter Context.
const unsigned EvalID
ID identifying this evaluation.
bool noteStep(CodePtr OpPC)
Note that a step has been executed.
InterpFrame * allocFrame(const Function *F, Ts &&...Args)
Allocate memory and create a new InterpFrame for the given function.
InterpStack & Stk
Temporary stack.
bool checkingConstantDestruction() const
Return if we're checking if a global variable has a constant destructor.
const VarDecl * EvaluatingDecl
Declaration we're initializing/evaluting, if any.
InterpFrame * Current
The current frame.
void enterFrame(InterpFrame *F)
Set the given frame as the current one.
PointerPathEntry * allocPointerPath(unsigned Length, const PointerPathEntry *OldPP)
const CXXRecordDecl ** allocMemberPointerPath(unsigned Length)
void deallocate(Block *B)
Deallocates a pointer.
Definition InterpState.h:75
void exitFrame()
Free resources associated with the current frame and set the caller to be the new current frame.
PointerPathEntry * extendPointerPath(unsigned NewLength, const PointerPathEntry *OldPP, PointerPathEntry NewEntry)
Allocate a new pointer path of Length NewLength.
llvm::SmallVector< PtrView > InitializingPtrs
List of blocks we're currently running either constructors or destructors for.
T allocAP(unsigned BitWidth)
StdAllocatorCaller getStdAllocatorCaller(StringRef Name) const
Program & P
Reference to the module containing all bytecode.
unsigned getPathLength() const
Return the length of the cast path.
PrimType value_or(PrimType PT) const
Definition PrimType.h:90
A pointer to a memory block, live or dead.
Definition Pointer.h:544
Pointer narrow() const
Restricts the scope of an array element pointer.
Definition Pointer.h:642
Pointer stripBaseCasts() const
Strip base casts from this Pointer.
Definition Pointer.h:1282
const Expr * getRootExpr() const
Definition Pointer.cpp:1324
Pointer atIndex(uint64_t Idx) const
Offsets a pointer inside an array.
Definition Pointer.h:613
bool isDummy() const
Checks if the pointer points to a dummy value.
Definition Pointer.h:959
int64_t getIndex() const
Returns the index into an array.
Definition Pointer.h:1028
bool isOpaquePointer() const
Definition Pointer.h:875
bool isStringPointer() const
Definition Pointer.h:874
unsigned getNumElems() const
Returns the number of elements.
Definition Pointer.h:996
uint64_t getByteOffset() const
Returns the byte offset from the start.
Definition Pointer.h:989
bool isZero() const
Checks if the pointer is null.
Definition Pointer.h:656
bool isConstexprUnknown() const
Definition Pointer.h:1182
const Descriptor * getDeclDesc() const
Accessor for information about the declaration site.
Definition Pointer.h:686
static bool pointToSameBlock(const Pointer &A, const Pointer &B)
Checks if both given pointers point to the same block.
Definition Pointer.cpp:996
const OpaquePointer & asOpaquePointer() const
Definition Pointer.h:865
bool isOnePastEnd() const
Checks if the index is one past end.
Definition Pointer.h:1043
Pointer expand() const
Expands a pointer to the containing array, undoing narrowing.
Definition Pointer.h:649
bool isBlockPointer() const
Definition Pointer.h:870
const Descriptor * getFieldDesc() const
Accessors for information about the innermost field.
Definition Pointer.h:714
PtrView view() const
Definition Pointer.h:603
UnsignedOrNone getCurrentDecl() const
Returns the current declaration ID.
Definition Program.h:154
Structure/Class descriptor.
Definition Record.h:27
unsigned getNumVirtualBases() const
Definition Record.h:130
llvm::iterator_range< LocalVectorTy::const_reverse_iterator > locals_reverse() const
Definition Function.h:56
Describes the statement/declaration an opcode was generated from.
Definition Source.h:77
SourceLocation getLoc() const
Definition Source.cpp:15
bool checkingForUndefinedBehavior() const
Are we checking an expression for overflow?
Definition State.h:129
OptionalDiagnostic Note(SourceLocation Loc, diag::kind DiagId)
Add a note to a prior diagnostic.
Definition State.cpp:86
bool emitRelaxedDiag(SourceLocation Loc, diag::kind DiagId)
If DiagId should be relaxed as per the current evaluation settings, emit it as a warning instead of a...
Definition State.cpp:20
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
SemaProxy * getSemaProxy() const
Definition State.h:93
ASTContext & getASTContext() const
Definition State.h:92
bool noteUndefinedBehavior() const
Note that we hit something that was technically undefined behavior, but that we can evaluate past it ...
Definition State.h:118
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:94
bool checkingPotentialConstantExpression() const
Are we checking whether the expression is a potential constant expression?
Definition State.h:125
Defines the clang::TargetInfo interface.
bool arePotentiallyOverlappingStringLiterals(const Pointer &LHS, const Pointer &RHS)
Definition Interp.cpp:3174
static bool CheckActive(InterpState &S, CodePtr OpPC, PtrView Ptr, AccessKinds AK, bool WillActivate=false)
Definition Interp.cpp:362
bool CheckRange(InterpState &S, CodePtr OpPC, const Pointer &Ptr, CheckSubobjectKind CSK)
Checks if a field from which a pointer is going to be derived is valid.
Definition Interp.cpp:607
bool GetPtrFieldPop(InterpState &S, CodePtr OpPC, uint32_t Off)
Definition Interp.cpp:1764
bool GetMemberPtrBase(InterpState &S)
Definition Interp.cpp:3501
bool PseudoDtor(InterpState &S, CodePtr OpPC)
Ends the lifetime of the pop'd pointer.
Definition Interp.cpp:2780
static bool CheckCallDepth(InterpState &S, CodePtr OpPC)
Definition Interp.cpp:1249
bool PtrPtrCast(InterpState &S, CodePtr OpPC, bool SrcIsVoidPtr, const Type *TargetType)
Definition Interp.cpp:2016
static constexpr bool OpReturns(Opcode Op)
Definition Interp.cpp:3812
const InterpFn InterpFunctions[]
Definition Interp.cpp:3834
static bool diagnoseCallableDecl(InterpState &S, CodePtr OpPC, const FunctionDecl *DiagDecl)
Definition Interp.cpp:1143
bool GetTypeid(InterpState &S, const Type *TypePtr, const Type *TypeInfoType)
Typeid support.
Definition Interp.cpp:3120
bool CastPointerIntegralAPS(InterpState &S, CodePtr OpPC, uint32_t BitWidth)
Definition Interp.cpp:3071
bool CastPointerIntegralAP(InterpState &S, CodePtr OpPC, uint32_t BitWidth)
Definition Interp.cpp:3058
bool CheckInit(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Checks if a value can be initialized.
Definition Interp.cpp:1133
bool arrayElemPtrOpaque(InterpState &S, CodePtr OpPC, const Pointer &Ptr, APSInt &&Index, bool AllowReplace)
Definition Interp.cpp:3587
bool CheckFunctionDecl(InterpState &S, CodePtr OpPC, const FunctionDecl *FD)
Opcode. Check if the function decl can be called at compile time.
Definition Interp.cpp:1956
std::optional< Pointer > addSubOffsetOpaque(InterpState &S, CodePtr OpPC, const Pointer &Ptr, APSInt &&Offset, ArithOp Op)
Definition Interp.cpp:3656
bool handleOverflow(InterpState &S, CodePtr OpPC, const T &SrcValue)
static bool appendToMemberPointer(InterpState &S, const MemberPointer &MemberPtr, int32_t BaseOffset, const RecordDecl *BaseDecl, bool IsDerivedMember)
Definition Interp.cpp:3453
static bool getDynamicDecl(InterpState &S, CodePtr OpPC, const Pointer &Ptr, const CXXRecordDecl *&DynamicDecl)
Definition Interp.cpp:2220
static bool CheckCallable(InterpState &S, CodePtr OpPC, const Function *F)
Definition Interp.cpp:1225
bool StartThisLifetime(InterpState &S)
Definition Interp.cpp:2724
void cleanupAfterFunctionCall(InterpState &S, const Function *Func)
Definition Interp.cpp:317
static bool runRecordDestructor(InterpState &S, CodePtr OpPC, const Pointer &BasePtr, const Descriptor *Desc)
Definition Interp.cpp:1446
bool CheckConstant(InterpState &S, CodePtr OpPC, const Descriptor *Desc, AccessKinds AK)
Checks if the Descriptor is of a constexpr or const global variable.
Definition Interp.cpp:514
bool GetTypeidPtr(InterpState &S, CodePtr OpPC, const Type *TypeInfoType)
Definition Interp.cpp:3125
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1505
bool CheckNewDeleteForms(InterpState &S, CodePtr OpPC, DynamicAllocator::Form AllocForm, DynamicAllocator::Form DeleteForm, const Descriptor *D, const Expr *NewExpr)
Diagnose mismatched new[]/delete or new/delete[] pairs.
Definition Interp.cpp:1345
static void initBasesRecurse(PtrView Ptr)
Definition Interp.cpp:2799
static void setLifeStateRecurse(PtrView Ptr, Lifetime L)
Definition Interp.cpp:2748
bool PushIgnoreDiags(InterpState &S)
Definition Interp.h:3690
bool CheckGlobalLoad(InterpState &S, CodePtr OpPC, const Block *B)
Checks a direct load of a primitive value from a global or local variable.
Definition Interp.cpp:870
bool CheckDeclRef(InterpState &S, CodePtr OpPC, const DeclRefExpr *DR)
We aleady know the given DeclRefExpr is invalid for some reason, now figure out why and print appropr...
Definition Interp.cpp:1377
bool EndLifetime(InterpState &S, CodePtr OpPC)
Ends the lifetime of the peek'd pointer.
Definition Interp.cpp:2770
bool CheckDeleteSource(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Check the source of the pointer passed to delete/delete[] has actually been heap allocated by us.
Definition Interp.cpp:1363
bool CastMemberPtrDerivedPop(InterpState &S, int32_t Off, const RecordDecl *BaseDecl)
BaseToDerivedMemberPointer.
Definition Interp.cpp:3483
static DynamicCastResult findRecordBase(const ASTContext &Ctx, const Record *R, QualType Needle)
Definition Interp.cpp:2311
static void compileFunction(InterpState &S, const Function *Func, CodePtr OpPC)
Definition Interp.cpp:2063
static bool CheckWeak(InterpState &S, CodePtr OpPC, const Block *B)
Definition Interp.cpp:853
static void copyPrimitiveMemory(InterpState &S, PtrView Ptr, PrimType T)
Definition Interp.cpp:3225
bool CheckPointerToIntegralCast(InterpState &S, CodePtr OpPC, const Pointer &Ptr, unsigned BitWidth)
Definition Interp.cpp:3027
static bool RunDestructors(InterpState &S, CodePtr OpPC, const Block *B)
Definition Interp.cpp:1473
static bool CheckConst(InterpState &S, CodePtr OpPC, PtrView Ptr)
Definition Interp.cpp:628
bool GetPtrField(InterpState &S, CodePtr OpPC, uint32_t Off)
1) Peeks a Pointer 2) Pushes Pointer.atField(Off) on the stack
Definition Interp.cpp:1759
static bool CheckNonNullArgs(InterpState &S, CodePtr OpPC, const Function *F, const CallExpr *CE, unsigned ArgSize)
Definition Interp.cpp:1424
bool CheckSubobject(InterpState &S, CodePtr OpPC, const Pointer &Ptr, CheckSubobjectKind CSK)
Checks if Ptr is a one-past-the-end pointer.
Definition Interp.cpp:617
bool handleFixedPointOverflow(InterpState &S, CodePtr OpPC, const FixedPoint &FP)
Definition Interp.cpp:3006
bool PopIgnoreDiags(InterpState &S)
Definition Interp.h:3702
bool GetMemberPtrDecl(InterpState &S)
Definition Interp.cpp:3511
bool handleReference(InterpState &S, CodePtr OpPC, Block *B)
Definition Interp.cpp:3101
bool CheckBitCast(InterpState &S, CodePtr OpPC, const Type *TargetType, bool SrcIsVoidPtr)
Definition Interp.cpp:1971
bool CopyMemberPtrPath(InterpState &S, const RecordDecl *Entry, bool IsDerived)
Just append the given Entry to the MemberPointer's path.
Definition Interp.cpp:3538
static bool getField(InterpState &S, CodePtr OpPC, const Pointer &Ptr, uint32_t Off)
Definition Interp.cpp:1695
static void startLifetimeRecurse(PtrView Ptr)
Definition Interp.cpp:2699
static bool hasVirtualDestructor(QualType T)
Definition Interp.cpp:1504
static bool getBase(InterpState &S, CodePtr OpPC, const Pointer &Ptr, uint32_t Off, bool NullOK)
Definition Interp.cpp:1769
static void finishGlobalRecurse(InterpState &S, PtrView Ptr)
Definition Interp.cpp:3293
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:218
bool GetPtrDerivedPop(InterpState &S, CodePtr OpPC, bool NullOK, const Type *TargetType, const Type *FinalType)
Definition Interp.cpp:1831
bool CheckBCPResult(InterpState &S, const Pointer &Ptr)
Definition Interp.cpp:342
PRESERVE_NONE bool EndSpeculation(InterpState &S)
Definition Interp.h:3740
bool diagnoseShiftFailure(InterpState &S, CodePtr OpPC, ShiftFailure Failure, const APSInt *Value, unsigned Bits)
Definition Interp.cpp:280
bool CheckDynamicMemoryAllocation(InterpState &S, CodePtr OpPC)
Checks if dynamic memory allocation is available in the current language mode.
Definition Interp.cpp:1336
static bool CheckExtern(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Definition Interp.cpp:451
bool CheckLive(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK)
Checks if a pointer is live and accessible.
Definition Interp.cpp:484
bool DiagTypeid(InterpState &S, CodePtr OpPC)
Definition Interp.cpp:3166
bool diagnoseUninitialized(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK)
Definition Interp.cpp:767
bool CheckFinalLoad(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
This is not used by any of the opcodes directly.
Definition Interp.cpp:1045
bool CheckStore(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK, bool WillBeActivated)
Checks if a value can be stored in a block.
Definition Interp.cpp:1082
bool virtBaseHelper(InterpState &S, const CXXRecordDecl *Decl, const Pointer &Ptr)
Definition Interp.cpp:3725
static bool checkConstructor(InterpState &S, CodePtr OpPC, const Function *Func, const Pointer &ThisPtr)
Definition Interp.cpp:1880
llvm::APInt APInt
Definition FixedPoint.h:19
void diagnoseEnumValue(InterpState &S, CodePtr OpPC, const EnumDecl *ED, const APSInt &Value)
Definition Interp.cpp:1612
bool StartThisLifetime1(InterpState &S)
Definition Interp.cpp:2735
bool RVOPtr(InterpState &S)
Definition Interp.h:3213
bool InvalidDeclRef(InterpState &S, CodePtr OpPC, const DeclRefExpr *DR, bool InitializerFailed)
Definition Interp.cpp:1385
bool diagnoseDummy(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK)
Definition Interp.cpp:1400
bool CheckNull(InterpState &S, CodePtr OpPC, const Pointer &Ptr, CheckSubobjectKind CSK)
Checks if a pointer is null.
Definition Interp.cpp:596
bool CheckFloatResult(InterpState &S, CodePtr OpPC, const Floating &Result, APFloat::opStatus Status, FPOptions FPO)
Checks if the result of a floating-point operation is valid in the current context.
Definition Interp.cpp:1316
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:35
static void noteValueLocation(InterpState &S, const Block *B)
Definition Interp.cpp:219
static bool CheckInvoke(InterpState &S, CodePtr OpPC, const Pointer &Ptr, bool IsCtor, bool IsDtor)
Definition Interp.cpp:1120
bool InterpretBuiltin(InterpState &S, CodePtr OpPC, const CallExpr *Call, uint32_t BuiltinID)
Interpret a builtin function.
bool CallVar(InterpState &S, CodePtr OpPC, const Function *Func, uint32_t VarArgSize)
Definition Interp.cpp:2090
constexpr bool needsAlloc()
Definition PrimType.h:135
bool(*)(InterpState &) PRESERVE_NONE InterpFn
Definition Interp.cpp:3832
bool InvalidShuffleVectorIndex(InterpState &S, CodePtr OpPC, uint32_t Index)
Definition Interp.cpp:3019
static bool diagnoseOutOfLifetimeDestroy(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Definition Interp.cpp:1904
static bool floatAPCast(InterpState &S, CodePtr OpPC, const Floating &F, uint32_t BitWidth, uint32_t FPOI)
Definition Interp.cpp:3555
bool CheckNewTypeMismatch(InterpState &S, CodePtr OpPC, const Expr *E, std::optional< uint64_t > ArraySize)
Check if the initializer and storage types of a placement-new expression match.
Definition Interp.cpp:2860
bool checkDestructor(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Definition Interp.cpp:1920
bool diagnoseArrayIndex(InterpState &S, CodePtr OpPC, const APSInt &Index, std::optional< uint64_t > NumElems, bool IsArray)
Definition Interp.cpp:307
static bool Activate(InterpState &S)
Definition Interp.h:2276
static bool CheckVolatile(InterpState &S, CodePtr OpPC, PtrView Ptr, AccessKinds AK)
Definition Interp.cpp:720
bool CheckLiteralType(InterpState &S, CodePtr OpPC, const Type *T)
Definition Interp.cpp:1633
bool DoMemcpy(InterpState &S, CodePtr OpPC, const Pointer &Src, Pointer &Dest, bool Activate, bool Diagnose)
Copy the contents of Src into Dest.
bool CheckArray(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Checks if the array is offsetable.
Definition Interp.cpp:476
bool CheckFloatStatus(InterpState &S, CodePtr OpPC, APFloat::opStatus Status, FPOptions FPO)
Check if the given floating-point evaluation status is allowed for compile-time constant folding duri...
Definition Interp.cpp:1280
bool GetPtrBase(InterpState &S, CodePtr OpPC, uint32_t Off)
Definition Interp.cpp:1821
bool CheckDummy(InterpState &S, CodePtr OpPC, const Pointer &Ptr, AccessKinds AK)
Checks if a pointer is a dummy pointer.
Definition Interp.cpp:1417
bool DefaultInit(InterpState &S, CodePtr OpPC, const CXXConstructorDecl *Ctor)
Definition Interp.cpp:2825
bool CheckThis(InterpState &S, CodePtr OpPC)
Checks the 'this' pointer.
Definition Interp.cpp:1260
bool CastFloatingIntegralAPS(InterpState &S, CodePtr OpPC, uint32_t BitWidth, uint32_t FPOI)
Definition Interp.cpp:3581
bool CheckIntegralAddressCast(InterpState &S, CodePtr OpPC, unsigned BitWidth)
Definition Interp.cpp:3053
bool CheckPlacementNew(InterpState &S, CodePtr OpPC, const Expr *E)
Definition Interp.cpp:2994
bool Destroy(InterpState &S, CodePtr OpPC, uint32_t I)
Definition Interp.cpp:3394
bool CheckMutable(InterpState &S, CodePtr OpPC, PtrView Ptr, AccessKinds AK)
Checks if a pointer points to a mutable field.
Definition Interp.cpp:693
size_t primSize(PrimType Type)
Returns the size of a primitive type in bytes.
Definition PrimType.cpp:25
bool Free(InterpState &S, CodePtr OpPC, bool DeleteIsArrayForm, bool IsGlobalDelete)
Definition Interp.cpp:1511
bool InvalidNewDeleteExpr(InterpState &S, CodePtr OpPC, const Expr *E)
Definition Interp.cpp:2961
bool CallBI(InterpState &S, CodePtr OpPC, const CallExpr *CE, uint32_t BuiltinID)
Definition Interp.cpp:2626
bool CheckLocalLoad(InterpState &S, CodePtr OpPC, const Block *B)
Definition Interp.cpp:901
bool CheckLoad(InterpState &S, CodePtr OpPC, PtrView Ptr, AccessKinds AK)
Definition Interp.cpp:933
static bool CheckLifetime(InterpState &S, CodePtr OpPC, Lifetime LT, const Block *B, AccessKinds AK)
Definition Interp.cpp:834
static bool allowNullSubObj(InterpState &S, CodePtr OpPC, const Pointer &Ptr)
Definition Interp.cpp:1690
bool FinishInitGlobal(InterpState &S)
Definition Interp.cpp:3341
static bool CheckTemporary(InterpState &S, CodePtr OpPC, const Block *B, AccessKinds AK)
Definition Interp.cpp:244
bool GetPtrBasePop(InterpState &S, CodePtr OpPC, uint32_t Off, bool NullOK)
Definition Interp.cpp:1825
llvm::BitVector collectNonNullArgs(const FunctionDecl *F, ArrayRef< const Expr * > Args)
static bool castBackMemberPointer(InterpState &S, const MemberPointer &MemberPtr, int32_t BaseOffset, const RecordDecl *BaseDecl)
Definition Interp.cpp:3416
bool Memcpy(InterpState &S, CodePtr OpPC)
Definition Interp.cpp:3757
bool CallPtr(InterpState &S, CodePtr OpPC, uint32_t ArgSize, const CallExpr *CE)
Definition Interp.cpp:2637
bool TrivialCopy(InterpState &S, CodePtr OpPC, bool Activate, const Function *Func)
Definition Interp.cpp:3772
bool CastFloatingIntegralAP(InterpState &S, CodePtr OpPC, uint32_t BitWidth, uint32_t FPOI)
Definition Interp.cpp:3575
bool MarkDestroyed(InterpState &S, CodePtr OpPC)
Definition Interp.cpp:2788
bool CallVirt(InterpState &S, CodePtr OpPC, const Function *Func, uint32_t VarArgSize)
Definition Interp.cpp:2494
bool Interpret(InterpState &S)
Interpreter entry point.
Definition Interp.cpp:3849
bool GetMemberPtr(InterpState &S, const ValueDecl *D)
Definition Interp.cpp:3496
static PRESERVE_NONE bool BCP(InterpState &S, CodePtr OpPC, int32_t Offset, PrimType PT)
This is used to implement speculative execution via __builtin_constant_p when we generate bytecode.
Definition Interp.cpp:3880
bool CastMemberPtrBasePop(InterpState &S, int32_t Off, const RecordDecl *BaseDecl)
DerivedToBaseMemberPointer.
Definition Interp.cpp:3471
llvm::APSInt APSInt
Definition FixedPoint.h:20
bool InvalidCast(InterpState &S, CodePtr OpPC, CastKind Kind, bool Fatal)
Definition Interp.cpp:3353
bool DynamicCast(InterpState &S, CodePtr OpPC, const Type *DestTypePtr, bool IsReferenceCast)
Definition Interp.cpp:2328
static bool diagnoseTypeIdField(InterpState &S, CodePtr OpPC, const Pointer &Ptr, unsigned Offset)
Definition Interp.cpp:1665
RangeSelector merge(RangeSelector First, RangeSelector Second)
Selects the merge of the two ranges, i.e.
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ Ambiguous
Name lookup results in an ambiguity; use getAmbiguityKind to figure out what kind of ambiguity we hav...
Definition Lookup.h:64
@ Success
Annotation was successful.
Definition Parser.h:65
@ AS_private
Definition Specifiers.h:130
@ SC_Extern
Definition Specifiers.h:255
CheckSubobjectKind
The order of this enum is important for diagnostics.
Definition State.h:44
@ CSK_Derived
Definition State.h:46
@ CSK_Base
Definition State.h:45
@ CSK_Field
Definition State.h:47
@ Result
The result type of a method or function.
Definition TypeBase.h:906
AccessKinds
Kinds of access we can perform on an object, for diagnostics.
Definition State.h:28
@ AK_TypeId
Definition State.h:36
@ AK_Construct
Definition State.h:37
@ AK_Increment
Definition State.h:32
@ AK_DynamicCast
Definition State.h:35
@ AK_Read
Definition State.h:29
@ AK_Assign
Definition State.h:31
@ AK_MemberCall
Definition State.h:34
@ AK_Destroy
Definition State.h:38
@ AK_Decrement
Definition State.h:33
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
@ Off
Never emit colors regardless of the output stream.
U cast(CodeGen::Address addr)
Definition Address.h:327
__builtin_elementwise_add_sat __builtin_elementwise_sub_sat int32_t
Represents an element in a path from a derived class to a base class.
A quantity in bits.
Describes a memory block created by an allocation site.
Definition Descriptor.h:126
unsigned getNumElems() const
Returns the number of elements stored in the block.
Definition Descriptor.h:249
SourceLocation getLocation() const
Definition Descriptor.h:201
bool isPrimitive() const
Checks if the descriptor is of a primitive.
Definition Descriptor.h:263
bool hasTrivialDtor() const
Whether variables of this descriptor need their destructor called or not.
bool isCompositeArray() const
Checks if the descriptor is of an array of composites.
Definition Descriptor.h:256
const ValueDecl * asValueDecl() const
Definition Descriptor.h:208
QualType getType() const
const Decl * asDecl() const
Definition Descriptor.h:204
const Descriptor *const ElemDesc
Descriptor of the array element.
Definition Descriptor.h:152
QualType getDataType(const ASTContext &Ctx) const
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition Descriptor.h:254
const VarDecl * asVarDecl() const
Definition Descriptor.h:212
PrimType getPrimType() const
Definition Descriptor.h:234
bool isRecord() const
Checks if the descriptor is of a record.
Definition Descriptor.h:268
const Record *const ElemRecord
Pointer to the record, if block contains records.
Definition Descriptor.h:150
const Expr * asExpr() const
Definition Descriptor.h:205
Descriptor used for global variables.
Definition Descriptor.h:48
OpaquePointer withFieldType(const Type *FieldTy, std::optional< bool > PastEnd=std::nullopt) const
Definition Pointer.h:456
llvm::PointerIntPair< const Type *, 2, unsigned > FieldType
Definition Pointer.h:444
OpaquePointer withPastEnd(bool PastEnd) const
Definition Pointer.h:475
QualType getSurroundingArray() const
If this is pointing to an array element, return the array.
Definition Pointer.cpp:1463
const PointerPathEntry * Path
Definition Pointer.h:445
bool isArrayElement() const
Definition Pointer.h:496
QualType getFieldType() const
Definition Pointer.h:490
OpaquePointer withPath(const PointerPathEntry *Path, unsigned PathLength, const Type *FieldTy, std::optional< bool > PastEnd=std::nullopt) const
Definition Pointer.h:465
static PointerPathEntry array(int64_t Index)
Definition Pointer.h:419
static PointerPathEntry field(const FieldDecl *FD)
Definition Pointer.h:433
static PointerPathEntry negativeArray(int64_t Index)
Definition Pointer.h:426
static PointerPathEntry base(const CXXRecordDecl *RD, bool Virtual=false)
Definition Pointer.h:412
const Record * getRecord() const
Definition Pointer.h:155
const Descriptor * getFieldDesc() const
Definition Pointer.h:82
const FieldDecl * getField() const
Definition Pointer.h:160
void startLifetime() const
Definition Pointer.h:336
const Block * block() const
Definition Pointer.h:62
bool isMutable() const
Definition Pointer.h:49
void initialize() const
Definition Pointer.cpp:817
QualType getType() const
Definition Pointer.h:276
bool isConst() const
Definition Pointer.h:66
bool isRoot() const
Definition Pointer.h:64
Lifetime getLifetime() const
Definition Pointer.cpp:763
PtrView getBase() const
Definition Pointer.h:266
bool isActive() const
Definition Pointer.h:45
T & deref() const
Definition Pointer.h:246
PtrView stripBaseCasts() const
Definition Pointer.h:143