clang 24.0.0git
Context.cpp
Go to the documentation of this file.
1//===--- Context.cpp - Context 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 "Context.h"
10#include "Boolean.h"
11#include "ByteCodeEmitter.h"
12#include "Char.h"
13#include "Compiler.h"
14#include "EvalEmitter.h"
15#include "EvalSettings.h"
16#include "Integral.h"
17#include "InterpFrame.h"
18#include "InterpHelpers.h"
19#include "InterpStack.h"
20#include "Pointer.h"
21#include "PrimType.h"
22#include "Program.h"
23#include "clang/AST/ASTLambda.h"
24#include "clang/AST/Expr.h"
26
27using namespace clang;
28using namespace clang::interp;
29
30Context::Context(ASTContext &Ctx) : Ctx(Ctx), P(new Program(*this)) {
31 this->ShortWidth = Ctx.getTargetInfo().getShortWidth();
32 this->IntWidth = Ctx.getTargetInfo().getIntWidth();
33 this->LongWidth = Ctx.getTargetInfo().getLongWidth();
34 this->LongLongWidth = Ctx.getTargetInfo().getLongLongWidth();
35 assert(Ctx.getTargetInfo().getCharWidth() == 8 &&
36 "We're assuming 8 bit chars");
37}
38
39Context::~Context() = default;
40
42 const FunctionDecl *FD) {
43 assert(Stk.empty());
44
45 // Get a function handle.
47 if (!Func)
48 return false;
49
50 // Compile the function.
51 Compiler<ByteCodeEmitter>(*this, *P).compileFunc(
52 FD, const_cast<Function *>(Func));
53
54 if (!Func->isValid())
55 return false;
56
57 ++EvalID;
58 // And run it.
59 return Run(Settings, Func);
60}
61
63 const Expr *E,
64 const FunctionDecl *FD) {
65 assert(Stk.empty());
66 ++EvalID;
67 size_t StackSizeBefore = Stk.size();
68 Compiler<EvalEmitter> C(*this, *P, Settings, Stk, FrameAlloc);
69
70 if (!C.interpretCall(FD, E)) {
71 C.cleanup();
72 Stk.clearTo(StackSizeBefore);
73 }
74}
75
76bool Context::evaluateAsRValue(const EvalSettings &Settings, const Expr *E,
77 APValue &Result) {
78 ++EvalID;
79 bool Recursing = !Stk.empty();
80 size_t StackSizeBefore = Stk.size();
81 Compiler<EvalEmitter> C(*this, *P, Settings, Stk, FrameAlloc);
82
83 auto Res = C.interpretExpr(E);
84
85 if (Res.isInvalid()) {
86 C.cleanup();
87 Stk.clearTo(StackSizeBefore);
88 return false;
89 }
90
91 if (!Recursing) {
92 // We *can* actually get here with a non-empty stack, since
93 // things like InterpState::noteSideEffect() exist.
94 C.cleanup();
95#ifndef NDEBUG
96 // Make sure we don't rely on some value being still alive in
97 // InterpStack memory.
98 Stk.clearTo(StackSizeBefore);
99#endif
100 }
101
102 Result = Res.stealAPValue();
103 return true;
104}
105
106bool Context::evaluate(const EvalSettings &Settings, const Expr *E,
107 APValue &Result) {
108 ++EvalID;
109 bool Recursing = !Stk.empty();
110 size_t StackSizeBefore = Stk.size();
111 Compiler<EvalEmitter> C(*this, *P, Settings, Stk, FrameAlloc);
112
113 // The object of an initializer outlives the evaluation.
114 auto Res = C.interpretExpr(E, /*ConvertResultToRValue=*/false,
115 /*DestroyToplevelScope=*/Settings.ConstexprKind !=
116 ConstantExprKind::Initializer);
117 if (Res.isInvalid()) {
118 C.cleanup();
119 Stk.clearTo(StackSizeBefore);
120 return false;
121 }
122
123 if (!Recursing) {
124 assert(Stk.empty());
125 C.cleanup();
126#ifndef NDEBUG
127 // Make sure we don't rely on some value being still alive in
128 // InterpStack memory.
129 Stk.clearTo(StackSizeBefore);
130#endif
131 }
132
133 Result = Res.stealAPValue();
134 return true;
135}
136
138 const VarDecl *VD, const Expr *Init,
139 APValue &Result) {
140 ++EvalID;
141 bool Recursing = !Stk.empty();
142 size_t StackSizeBefore = Stk.size();
143 Compiler<EvalEmitter> C(*this, *P, Settings, Stk, FrameAlloc);
144
145 bool CheckGlobalInitialized =
146 (VD->getType()->isRecordType() || VD->getType()->isArrayType());
147
148 auto Res = C.interpretDecl(VD, Init, CheckGlobalInitialized);
149 if (Res.isInvalid()) {
150 C.cleanup();
151 Stk.clearTo(StackSizeBefore);
152
153 return false;
154 }
155
156 if (!Recursing) {
157 assert(Stk.empty());
158 C.cleanup();
159#ifndef NDEBUG
160 // Make sure we don't rely on some value being still alive in
161 // InterpStack memory.
162 Stk.clearTo(StackSizeBefore);
163#endif
164 }
165
166 Result = Res.stealAPValue();
167 return true;
168}
169
171 const VarDecl *VD, APValue Value) {
172 assert(Stk.empty());
173 Compiler<EvalEmitter> C(*this, *P, Settings, Stk, FrameAlloc);
174
175 auto Res = C.interpretDestructor(VD, Value);
176
177 if (Res.isInvalid()) {
178 C.cleanup();
179 Stk.clear();
180 return false;
181 }
182
183 assert(Stk.empty());
184
185 return true;
186}
187
188void Context::registerRedecl(const VarDecl *VD, const APValue &V) {
189 Expr::EvalStatus Status;
190 Compiler<EvalEmitter> C(*this, *P, Status, Stk, FrameAlloc);
191
192 C.registerRedecl(VD, V);
193}
194
195template <typename ResultT>
196bool Context::evaluateStringRepr(const EvalSettings &Settings,
197 const Expr *SizeExpr, const Expr *PtrExpr,
198 ResultT &Result) {
199 assert(Stk.empty());
200 Compiler<EvalEmitter> C(*this, *P, Settings, Stk, FrameAlloc);
201
202 // Evaluate size value.
203 APValue SizeValue;
204 if (!evaluateAsRValue(Settings, SizeExpr, SizeValue))
205 return false;
206
207 if (!SizeValue.isInt())
208 return false;
209 uint64_t Size = SizeValue.getInt().getZExtValue();
210
211 auto PtrRes = C.interpretAsPointer(PtrExpr, [&](InterpState &S, CodePtr OpPC,
212 const Pointer &Ptr) {
213 if (Size == 0) {
214 if constexpr (std::is_same_v<ResultT, APValue>)
216 return true;
217 }
218
219 if (Ptr.isZero()) {
220 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_null)
221 << AK_Read;
222 return false;
223 }
224
225 if (!Ptr.isLive() || !Ptr.isInitialized() || Ptr.isUnknownSizeArray() ||
226 !Ptr.inArray())
227 return false;
228
229 // Must be char.
230 if (Ptr.isBlockPointer() &&
231 Ptr.getFieldDesc()->getElemDataSize() != 1 /*bytes*/)
232 return false;
233 if (Ptr.isStringPointer() &&
234 !Ptr.asStringPointer().getLiteral()->isOrdinary())
235 return false;
236
237 bool Limited = false;
238 if (Size > Ptr.getNumElems()) {
239 S.FFDiag(S.Current->getSource(OpPC), diag::note_constexpr_access_past_end)
240 << AK_Read;
241 Size = Ptr.getNumElems();
242 Limited = true;
243 }
244
245 if constexpr (std::is_same_v<ResultT, APValue>) {
246 QualType CharTy = PtrExpr->getType()->getPointeeType();
247 Result = APValue(APValue::UninitArray{}, Size, Size);
248 for (uint64_t I = 0; I != Size; ++I) {
249 if (std::optional<APValue> ElemVal =
250 Ptr.atIndex(I).toRValue(*this, CharTy))
251 Result.getArrayInitializedElt(I) = *ElemVal;
252 else
253 return false;
254 }
255 } else {
256 assert((std::is_same_v<ResultT, std::string>));
257 if (Size < Result.max_size())
258 Result.resize(Size);
259
260 const char *Addr = reinterpret_cast<const char *>(Ptr.getRawAddress());
261
262 if (Ptr.isStringPointer())
263 Result.assign(Addr, Size - static_cast<unsigned>(Limited));
264 else
265 Result.assign(Addr, Size);
266 }
267
268 return true;
269 });
270
271 if (PtrRes.isInvalid()) {
272 C.cleanup();
273 Stk.clear();
274 return false;
275 }
276
277 return true;
278}
279
281 const Expr *SizeExpr, const Expr *PtrExpr,
282 APValue &Result) {
283 assert(SizeExpr);
284 assert(PtrExpr);
285
286 return evaluateStringRepr(Settings, SizeExpr, PtrExpr, Result);
287}
288
290 const Expr *SizeExpr, const Expr *PtrExpr,
291 std::string &Result) {
292 assert(SizeExpr);
293 assert(PtrExpr);
294
295 return evaluateStringRepr(Settings, SizeExpr, PtrExpr, Result);
296}
297
298bool Context::evaluateString(const EvalSettings &Settings, const Expr *E,
299 std::string &Result) {
300 assert(Stk.empty());
301 Compiler<EvalEmitter> C(*this, *P, Settings, Stk, FrameAlloc);
302
303 auto PtrRes = C.interpretAsPointer(E, [&](InterpState &S, CodePtr OpPC,
304 const Pointer &Ptr) {
305 if (!Ptr.isReadablePointerType())
306 return false;
307
308 if (!Ptr.isConst())
309 return false;
310
311 if (Ptr.isDummy() || Ptr.isUnknownSizeArray() || Ptr.isPastEnd())
312 return false;
313
314 unsigned N = Ptr.getNumElems();
315
316 if (Ptr.elemSize() == 1 /* bytes */) {
317 const char *Chars = reinterpret_cast<const char *>(Ptr.getRawAddress());
318 if (Ptr.isStringPointer()) {
319 Result.assign(Chars, N - 1);
320 return true;
321 }
322 unsigned Length = strnlen(Chars, N);
323 // Wasn't null terminated.
324 if (N == Length)
325 return false;
326 Result.assign(Chars, Length);
327 return true;
328 }
329
330 PrimType ElemT;
331 if (Ptr.isBlockPointer()) {
332 ElemT = Ptr.getFieldDesc()->getPrimType();
333 } else {
334 // It may happen here that the string literal has not been decayed or
335 // indexed, so check the element type in that case.
336 assert(Ptr.isStringPointer());
337 if (!Ptr.asStringPointer().Decayed)
338 ElemT =
339 *classify(Ptr.getType()->getAsArrayTypeUnsafe()->getElementType());
340 else
341 ElemT = *classify(Ptr.getType());
342 }
343 for (unsigned I = Ptr.getIndex(); I != N; ++I) {
344 INT_TYPE_SWITCH(ElemT, {
345 auto Elem = Ptr.loadElem<T>(I);
346 if (Elem.isZero())
347 return true;
348 Result.push_back(static_cast<char>(Elem));
349 });
350 }
351 // We didn't find a 0 byte.
352 return false;
353 });
354
355 if (PtrRes.isInvalid()) {
356 C.cleanup();
357 Stk.clear();
358 return false;
359 }
360 return true;
361}
362
363std::optional<uint64_t> Context::evaluateStrlen(const EvalSettings &Settings,
364 const Expr *E) {
365 assert(Stk.empty());
366 Compiler<EvalEmitter> C(*this, *P, Settings, Stk, FrameAlloc);
367
368 std::optional<uint64_t> Result;
369 auto PtrRes = C.interpretAsPointer(E, [&](InterpState &S, CodePtr OpPC,
370 const Pointer &Ptr) {
371 if (!Ptr.isReadablePointerType())
372 return false;
373
374 if (Ptr.isPastEnd())
375 return false;
376
377 if (Ptr.isStringPointer()) {
378 const auto *Lit = Ptr.asStringPointer().getLiteral();
379 int64_t Off = Ptr.getByteOffset();
380 if (Off < 0)
381 return false;
382
383 UnsignedOrNone ZeroIndex = Lit->findZeroCodeUnit(Off);
384 if (!ZeroIndex)
385 return false;
386 Result = *ZeroIndex;
387 return true;
388 }
389
390 const Descriptor *FieldDesc = Ptr.getFieldDesc();
391 if (!FieldDesc->isPrimitiveArray())
392 return false;
393
394 if (Ptr.isDummy() || Ptr.isUnknownSizeArray())
395 return false;
396
397 PrimType ElemT = FieldDesc->getPrimType();
398 if (!isIntegerType(ElemT))
399 return false;
400
401 unsigned N = Ptr.getNumElems();
402 if (Ptr.elemSize() == 1) {
403 unsigned Size = N - Ptr.getIndex();
404 Result =
405 strnlen(reinterpret_cast<const char *>(Ptr.getRawAddress()), Size);
406 return Result != Size;
407 }
408
409 Result = 0;
410 for (unsigned I = Ptr.getIndex(); I != N; ++I) {
411 INT_TYPE_SWITCH(ElemT, {
412 auto Elem = Ptr.elem<T>(I);
413 if (Elem.isZero())
414 return true;
415 ++(*Result);
416 });
417 }
418 // We didn't find a 0 byte.
419 return false;
420 });
421
422 if (PtrRes.isInvalid()) {
423 C.cleanup();
424 Stk.clear();
425 return std::nullopt;
426 }
427 return Result;
428}
429
430std::optional<uint64_t>
432 unsigned Kind, bool IsDynamic) {
433 assert(Stk.empty());
434 Compiler<EvalEmitter> C(*this, *P, Settings, Stk, FrameAlloc);
435
436 std::optional<uint64_t> Result;
437 auto PtrRes = C.interpretAsLValuePointer(E, [&](InterpState &S, CodePtr OpPC,
438 const Pointer &Ptr) {
439 QualType T = Ptr.getType().getNonReferenceType();
440 if (T->isIncompleteType() || T->isFunctionType() ||
441 !T->isConstantSizeType())
442 return false;
443
444 Pointer P = Ptr;
445 if (auto ObjectSize =
446 evaluateBuiltinObjectSize(getASTContext(), Kind, P, E, IsDynamic)) {
447 Result = *ObjectSize;
448 return true;
449 }
450 return false;
451 });
452
453 if (PtrRes.isInvalid()) {
454 C.cleanup();
455 Stk.clear();
456 return std::nullopt;
457 }
458 return Result;
459}
460
462 const EvalSettings &Settings, const FunctionDecl *Callee,
463 ArrayRef<const Expr *> Args, const Expr *This, const Expr *Condition) {
464 if (OptPrimType ConditionT = classify(Condition);
465 !ConditionT || ConditionT != PT_Bool) {
466 return std::nullopt;
467 }
468
469 assert(Stk.empty());
470 Compiler<EvalEmitter> C(*this, *P, Settings, Stk, FrameAlloc);
471 std::optional<bool> Result =
472 C.interpretWithSubstitutions(Callee, Args, This, Condition);
473
474 // This is somewhat of a special case here. We don't allow
475 // evaluateWithSubstitution to recurse (see the Stk.empty() assertion above),
476 // BUT we allow the args to fail evaluation, which means they can leave some
477 // garbage on the stack. So we always clear() here, not only if the evaluation
478 // failed.
479 Stk.clear();
480 if (!Result) {
481 C.cleanup();
482 return std::nullopt;
483 }
484 return Result;
485}
486
487const LangOptions &Context::getLangOpts() const { return Ctx.getLangOpts(); }
488
489static PrimType integralTypeToPrimTypeS(unsigned BitWidth) {
490 switch (BitWidth) {
491 case 64:
492 return PT_Sint64;
493 case 32:
494 return PT_Sint32;
495 case 16:
496 return PT_Sint16;
497 case 8:
498 return PT_Sint8;
499 default:
500 return PT_IntAPS;
501 }
502 llvm_unreachable("Unhandled BitWidth");
503}
504
505static PrimType integralTypeToPrimTypeU(unsigned BitWidth) {
506 switch (BitWidth) {
507 case 64:
508 return PT_Uint64;
509 case 32:
510 return PT_Uint32;
511 case 16:
512 return PT_Uint16;
513 case 8:
514 return PT_Uint8;
515 default:
516 return PT_IntAP;
517 }
518 llvm_unreachable("Unhandled BitWidth");
519}
520
522 T = T.getCanonicalType();
523
524 if (const auto *BT = dyn_cast<BuiltinType>(T)) {
525 auto Kind = BT->getKind();
526 if (Kind == BuiltinType::Bool)
527 return PT_Bool;
528 if (Kind == BuiltinType::NullPtr)
529 return PT_Ptr;
530 if (Kind == BuiltinType::BoundMember)
531 return PT_MemberPtr;
532
533 // Just trying to avoid the ASTContext::getIntWidth call below.
534 if (Kind == BuiltinType::Short)
535 return integralTypeToPrimTypeS(this->ShortWidth);
536 if (Kind == BuiltinType::UShort)
537 return integralTypeToPrimTypeU(this->ShortWidth);
538
539 if (Kind == BuiltinType::Int)
540 return integralTypeToPrimTypeS(this->IntWidth);
541 if (Kind == BuiltinType::UInt)
542 return integralTypeToPrimTypeU(this->IntWidth);
543 if (Kind == BuiltinType::Long)
544 return integralTypeToPrimTypeS(this->LongWidth);
545 if (Kind == BuiltinType::ULong)
546 return integralTypeToPrimTypeU(this->LongWidth);
547 if (Kind == BuiltinType::LongLong)
548 return integralTypeToPrimTypeS(this->LongLongWidth);
549 if (Kind == BuiltinType::ULongLong)
550 return integralTypeToPrimTypeU(this->LongLongWidth);
551
552 if (Kind == BuiltinType::SChar || Kind == BuiltinType::Char_S)
553 return integralTypeToPrimTypeS(8);
554 if (Kind == BuiltinType::UChar || Kind == BuiltinType::Char_U ||
555 Kind == BuiltinType::Char8)
556 return integralTypeToPrimTypeU(8);
557
558 if (BT->isSignedInteger())
559 return integralTypeToPrimTypeS(Ctx.getIntWidth(T));
560 if (BT->isUnsignedInteger())
561 return integralTypeToPrimTypeU(Ctx.getIntWidth(T));
562
563 if (BT->isFloatingPoint())
564 return PT_Float;
565 }
566
567 if (T->isPointerOrReferenceType())
568 return PT_Ptr;
569
570 if (T->isMemberPointerType())
571 return PT_MemberPtr;
572
573 if (const auto *BT = T->getAs<BitIntType>()) {
574 if (BT->isSigned())
575 return integralTypeToPrimTypeS(BT->getNumBits());
576 return integralTypeToPrimTypeU(BT->getNumBits());
577 }
578
579 if (const auto *D = T->getAsEnumDecl()) {
580 if (!D->isComplete())
581 return std::nullopt;
582 return classify(D->getIntegerType());
583 }
584
585 if (const auto *AT = T->getAs<AtomicType>())
586 return classify(AT->getValueType());
587
588 if (const auto *OBT = T->getAs<OverflowBehaviorType>())
589 return classify(OBT->getUnderlyingType());
590
591 if (T->isObjCObjectPointerType() || T->isBlockPointerType())
592 return PT_Ptr;
593
594 if (T->isFixedPointType())
595 return PT_FixedPoint;
596
597 if (T->isMetaInfoType())
598 return PT_Reflect;
599
600 // Vector and complex types get here.
601 return std::nullopt;
602}
603
604unsigned Context::getCharBit() const {
605 return Ctx.getTargetInfo().getCharWidth();
606}
607
608/// Simple wrapper around getFloatTypeSemantics() to make code a
609/// little shorter.
610const llvm::fltSemantics &Context::getFloatSemantics(QualType T) const {
611 return Ctx.getFloatTypeSemantics(T);
612}
613
614bool Context::Run(const EvalSettings &Settings, const Function *Func) {
615 auto Memory = std::make_unique<char[]>(InterpFrame::allocSize(Func));
616 InterpState State(Settings, *P, Stk, FrameAlloc, *this, Func);
617 InterpFrame *Frame = new (Memory.get()) InterpFrame(
618 State, Func, /*Caller=*/nullptr, CodePtr(), Func->getArgSize());
619 State.Current = Frame;
620
621 if (Interpret(State)) {
622 assert(Stk.empty());
623 return true;
624 }
625
626 Stk.clear();
627 Frame->~InterpFrame();
628 State.Current = &State.BottomFrame;
629 return false;
630}
631
632const CXXMethodDecl *
634 const CXXRecordDecl *StaticDecl,
635 const CXXMethodDecl *InitialFunction) const {
636 assert(DynamicDecl);
637 assert(StaticDecl);
638 assert(InitialFunction);
639
640 const CXXRecordDecl *CurRecord = DynamicDecl;
641 const CXXMethodDecl *FoundFunction = InitialFunction;
642 for (;;) {
643 const CXXMethodDecl *Overrider =
644 FoundFunction->getCorrespondingMethodDeclaredInClass(CurRecord, false);
645 if (Overrider)
646 return Overrider;
647
648 // Common case of only one base class.
649 if (CurRecord->getNumBases() == 1) {
650 CurRecord = CurRecord->bases_begin()->getType()->getAsCXXRecordDecl();
651 continue;
652 }
653
654 // Otherwise, go to the base class that will lead to the StaticDecl.
655 for (const CXXBaseSpecifier &Spec : CurRecord->bases()) {
656 const CXXRecordDecl *Base = Spec.getType()->getAsCXXRecordDecl();
657 if (Base == StaticDecl || Base->isDerivedFrom(StaticDecl)) {
658 CurRecord = Base;
659 break;
660 }
661 }
662 }
663
664 llvm_unreachable(
665 "Couldn't find an overriding function in the class hierarchy?");
666 return nullptr;
667}
668
670 assert(FuncDecl);
671 if (const Function *Func = P->getFunction(FuncDecl))
672 return Func;
673
674 // Manually created functions that haven't been assigned proper
675 // parameters yet.
676 if (!FuncDecl->param_empty() && !FuncDecl->param_begin())
677 return nullptr;
678
679 bool IsLambdaStaticInvoker = false;
680 if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl);
681 MD && MD->isLambdaStaticInvoker()) {
682 // For a lambda static invoker, we might have to pick a specialized
683 // version if the lambda is generic. In that case, the picked function
684 // will *NOT* be a static invoker anymore. However, it will still
685 // be a non-static member function, this (usually) requiring an
686 // instance pointer. We suppress that later in this function.
687 IsLambdaStaticInvoker = true;
688 }
689 // Set up argument indices.
690 unsigned ParamOffset = 0;
691
692 // If the return is not a primitive, a pointer to the storage where the
693 // value is initialized in is passed as the first argument. See 'RVO'
694 // elsewhere in the code.
695 QualType Ty = FuncDecl->getReturnType();
696 bool HasRVO = false;
697 if (!Ty->isVoidType() && !canClassify(Ty)) {
698 HasRVO = true;
700 }
701
702 // If the function decl is a member decl, the next parameter is
703 // the 'this' pointer. This parameter is pop()ed from the
704 // InterpStack when calling the function.
705 bool HasThisPointer = false;
706 if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl)) {
707 if (!IsLambdaStaticInvoker) {
708 HasThisPointer = MD->isInstance();
709 if (MD->isImplicitObjectMemberFunction())
711 }
712
713 if (isLambdaCallOperator(MD)) {
714 // The parent record needs to be complete, we need to know about all
715 // the lambda captures.
716 if (!MD->getParent()->isCompleteDefinition())
717 return nullptr;
718 if (MD->isStatic()) {
719 llvm::DenseMap<const ValueDecl *, FieldDecl *> LC;
720 FieldDecl *LTC;
721
722 MD->getParent()->getCaptureFields(LC, LTC);
723 // Static lambdas cannot have any captures. If this one does,
724 // it has already been diagnosed and we can only ignore it.
725 if (!LC.empty())
726 return nullptr;
727 }
728 }
729 }
730
731 // Assign descriptors to all parameters.
732 // Composite objects are lowered to pointers.
734 ParamDescriptors.reserve(FuncDecl->getNumParams());
735
736 const auto *FuncProto = FuncDecl->getType()->getAs<FunctionProtoType>();
737 unsigned BlockOffset = 0;
738 for (auto [ParamIndex, PD] : llvm::enumerate(FuncDecl->parameters())) {
739 bool IsConst = PD->getType().isConstQualified();
740 bool IsVolatile = PD->getType().isVolatileQualified();
741
742 if (PD->isInvalidDecl() ||
743 !getASTContext().hasSameType(PD->getType(),
744 FuncProto->getParamType(ParamIndex)))
745 return nullptr;
746
747 OptPrimType T = classify(PD->getType());
748 PrimType PT = T.value_or(PT_Ptr);
749 Descriptor *Desc = P->createDescriptor(PD, PT, nullptr, IsConst,
750 /*IsTemporary=*/false,
751 /*IsMutable=*/false, IsVolatile);
752 unsigned PrimTSize = align(primSize(PT));
753 ParamDescriptors.emplace_back(Desc, ParamOffset, BlockOffset, PT);
754 ParamOffset += PrimTSize;
755 BlockOffset += sizeof(Block) + PrimTSize;
756 }
757
758 // Create a handle over the emitted code.
759 assert(!P->getFunction(FuncDecl));
760 const Function *Func =
761 P->createFunction(FuncDecl, ParamOffset, std::move(ParamDescriptors),
762 HasThisPointer, HasRVO, IsLambdaStaticInvoker);
763 return Func;
764}
765
767 const BlockDecl *BD = E->getBlockDecl();
768 // Set up argument indices.
769 unsigned ParamOffset = 0;
771
772 // Assign descriptors to all parameters.
773 // Composite objects are lowered to pointers.
774 for (const ParmVarDecl *PD : BD->parameters()) {
775 bool IsConst = PD->getType().isConstQualified();
776 bool IsVolatile = PD->getType().isVolatileQualified();
777
778 OptPrimType T = classify(PD->getType());
779 PrimType PT = T.value_or(PT_Ptr);
780 Descriptor *Desc = P->createDescriptor(PD, PT, nullptr, IsConst,
781 /*IsTemporary=*/false,
782 /*IsMutable=*/false, IsVolatile);
783 ParamDescriptors.emplace_back(Desc, ParamOffset, ~0u, PT);
784 ParamOffset += align(primSize(PT));
785 }
786
787 if (BD->hasCaptures())
788 return nullptr;
789
790 // Create a handle over the emitted code.
791 Function *Func =
792 P->createFunction(E, ParamOffset, std::move(ParamDescriptors),
793 /*HasThisPointer=*/false, /*HasRVO=*/false,
794 /*IsLambdaStaticInvoker=*/false);
795
796 assert(Func);
797 Func->setDefined(true);
798 // We don't compile the BlockDecl code at all right now.
799 Func->setIsFullyCompiled(true);
800
801 return Func;
802}
803
804unsigned Context::collectBaseOffset(const RecordDecl *BaseDecl,
805 const RecordDecl *DerivedDecl) const {
806 assert(BaseDecl);
807 assert(DerivedDecl);
808 const auto *FinalDecl = cast<CXXRecordDecl>(BaseDecl);
809 const RecordDecl *CurDecl = DerivedDecl;
810 const Record *CurRecord = P->getOrCreateRecord(CurDecl);
811 assert(CurDecl && FinalDecl);
812
813 unsigned OffsetSum = 0;
814 for (;;) {
815 assert(CurRecord->getNumBases() > 0);
816 // One level up
817 for (const Record::Base &B : CurRecord->bases()) {
818 const auto *BaseDecl = cast<CXXRecordDecl>(B.Decl);
819
820 if (BaseDecl == FinalDecl || BaseDecl->isDerivedFrom(FinalDecl)) {
821 OffsetSum += B.Offset;
822 CurRecord = B.R;
823 CurDecl = BaseDecl;
824 break;
825 }
826 }
827 if (CurDecl == FinalDecl)
828 break;
829 }
830
831 assert(OffsetSum > 0);
832 return OffsetSum;
833}
834
835const Record *Context::getRecord(const RecordDecl *D) const {
836 return P->getOrCreateRecord(D);
837}
838
840 return ID == Builtin::BI__builtin_classify_type ||
841 ID == Builtin::BI__builtin_os_log_format_buffer_size ||
842 ID == Builtin::BI__builtin_constant_p || ID == Builtin::BI__noop;
843}
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
static PrimType integralTypeToPrimTypeS(unsigned BitWidth)
Definition Context.cpp:489
static PrimType integralTypeToPrimTypeU(unsigned BitWidth)
Definition Context.cpp:505
#define INT_TYPE_SWITCH(Expr, B)
Definition PrimType.h:262
static bool isRecordType(QualType T)
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:158
APSInt & getInt()
Definition APValue.h:573
bool isInt() const
Definition APValue.h:549
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:245
A fixed int type of a specified bitwidth.
Definition TypeBase.h:8304
Represents a block literal declaration, which is like an unnamed FunctionDecl.
Definition Decl.h:4814
bool hasCaptures() const
True if this block (or its nested blocks) captures anything of local storage from its enclosing scope...
Definition Decl.h:4933
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:4900
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6726
const BlockDecl * getBlockDecl() const
Definition Expr.h:6738
Represents a base class of a C++ class.
Definition DeclCXX.h:146
QualType getType() const
Retrieves the type of the base class.
Definition DeclCXX.h:249
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2150
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
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
base_class_range bases()
Definition DeclCXX.h:609
unsigned getNumBases() const
Retrieves the number of base classes of this class.
Definition DeclCXX.h:603
base_class_iterator bases_begin()
Definition DeclCXX.h:616
This represents one expression.
Definition Expr.h:113
QualType getType() const
Definition Expr.h:145
Represents a member of a struct/union/class.
Definition Decl.h:3299
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3535
Represents a function declaration or definition.
Definition Decl.h:2059
QualType getReturnType() const
Definition Decl.h:2980
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2905
param_iterator param_begin()
Definition Decl.h:2917
bool param_empty() const
Definition Decl.h:2916
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3873
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5416
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
Represents a parameter to a function.
Definition Decl.h:1820
A (possibly-)qualified type.
Definition TypeBase.h:938
Represents a struct/union/class.
Definition Decl.h:4464
bool isVoidType() const
Definition TypeBase.h:9068
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 isArrayType() const
Definition TypeBase.h:8782
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9299
QualType getType() const
Definition Decl.h:724
Represents a variable declaration or definition.
Definition Decl.h:933
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:43
Pointer into the code segment.
Definition Source.h:31
Compilation context for expressions.
Definition Compiler.h:119
std::optional< uint64_t > tryEvaluateObjectSize(const EvalSettings &Settings, const Expr *E, unsigned Kind, bool IsDynamic)
If.
Definition Context.cpp:431
const LangOptions & getLangOpts() const
Returns the language options.
Definition Context.cpp:487
void registerRedecl(const VarDecl *VD, const APValue &V)
Definition Context.cpp:188
const Function * getOrCreateObjCBlock(const BlockExpr *E)
Definition Context.cpp:766
bool evaluateString(const EvalSettings &Settings, const Expr *E, std::string &Result)
Evaluate.
Definition Context.cpp:298
~Context()
Cleans up the constexpr VM.
bool evaluateDestruction(const EvalSettings &Settings, const VarDecl *VD, APValue Value)
Evaluates the destruction of a variable.
Definition Context.cpp:170
Context(ASTContext &Ctx)
Initialises the constexpr VM.
Definition Context.cpp:30
bool isPotentialConstantExpr(const EvalSettings &Settings, const FunctionDecl *FD)
Checks if a function is a potential constant expression.
Definition Context.cpp:41
static bool isUnevaluatedBuiltin(unsigned ID)
Unevaluated builtins don't get their arguments put on the stack automatically.
Definition Context.cpp:839
unsigned getCharBit() const
Returns CHAR_BIT.
Definition Context.cpp:604
std::optional< bool > evaluateWithSubstitution(const EvalSettings &Settings, const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This, const Expr *Condition)
Definition Context.cpp:461
bool evaluate(const EvalSettings &Settings, const Expr *E, APValue &Result)
Like evaluateAsRvalue(), but does no implicit lvalue-to-rvalue conversion.
Definition Context.cpp:106
const llvm::fltSemantics & getFloatSemantics(QualType T) const
Return the floating-point semantics for T.
Definition Context.cpp:610
bool evaluateAsInitializer(const EvalSettings &Settings, const VarDecl *VD, const Expr *Init, APValue &Result)
Evaluates a toplevel initializer.
Definition Context.cpp:137
unsigned collectBaseOffset(const RecordDecl *BaseDecl, const RecordDecl *DerivedDecl) const
Definition Context.cpp:804
const Record * getRecord(const RecordDecl *D) const
Definition Context.cpp:835
bool evaluateAsRValue(const EvalSettings &Settings, const Expr *E, APValue &Result)
Evaluates a toplevel expression as an rvalue.
Definition Context.cpp:76
const Function * getOrCreateFunction(const FunctionDecl *FuncDecl)
Definition Context.cpp:669
ASTContext & getASTContext() const
Returns the AST context.
Definition Context.h:116
OptPrimType classify(QualType T) const
Classifies a type.
Definition Context.cpp:521
bool evaluateCharRange(const EvalSettings &Settings, const Expr *SizeExpr, const Expr *PtrExpr, APValue &Result)
Definition Context.cpp:280
std::optional< uint64_t > evaluateStrlen(const EvalSettings &Settings, const Expr *E)
Evalute.
Definition Context.cpp:363
bool canClassify(QualType T) const
Definition Context.h:138
const CXXMethodDecl * getOverridingFunction(const CXXRecordDecl *DynamicDecl, const CXXRecordDecl *StaticDecl, const CXXMethodDecl *InitialFunction) const
Definition Context.cpp:633
void isPotentialConstantExprUnevaluated(const EvalSettings &Settings, const Expr *E, const FunctionDecl *FD)
Definition Context.cpp:62
Base class for stack frames, shared between VM and walker.
Definition Frame.h:28
Bytecode function.
Definition Function.h:98
Frame storing local variables.
Definition InterpFrame.h:27
SourceInfo getSource(CodePtr PC) const
Map a location to a source.
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 clear()
Clears the stack.
bool empty() const
Returns whether the stack is empty.
Definition InterpStack.h:86
Interpreter context.
Definition InterpState.h:47
InterpFrame * Current
The current frame.
A pointer to a memory block, live or dead.
Definition Pointer.h:546
The program contains and links the bytecode for all functions.
Definition Program.h:38
Structure/Class descriptor.
Definition Record.h:27
unsigned getNumBases() const
Definition Record.h:111
llvm::iterator_range< const_base_iter > bases() const
Definition Record.h:107
Interface for the VM to interact with the AST walker's context.
Definition State.h:79
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
Defines the clang::TargetInfo interface.
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:218
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3223
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:35
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2420
size_t primSize(PrimType Type)
Returns the size of a primitive type in bytes.
Definition PrimType.cpp:25
UnsignedOrNone evaluateBuiltinObjectSize(const ASTContext &ASTCtx, unsigned Kind, Pointer &Ptr, const Expr *E, bool IsDynamic)
Evaluate __builtin_object_size or __builtin_dynamic_object_size for the given pointer and Kind.
constexpr bool isIntegerType(PrimType T)
Definition PrimType.h:55
bool Interpret(InterpState &S)
Interpreter entry point.
Definition Interp.cpp:3810
Top level wrappers for InstallAPI frontend operations.
bool isLambdaCallOperator(const CXXMethodDecl *MD)
Definition ASTLambda.h:28
@ Result
The result type of a method or function.
Definition TypeBase.h:906
@ AK_Read
Definition State.h:27
OptionalUnsigned< unsigned > UnsignedOrNone
const FunctionProtoType * T
@ Off
Never emit colors regardless of the output stream.
U cast(CodeGen::Address addr)
Definition Address.h:327
EvalStatus is a struct with detailed info about an evaluation in progress.
Definition Expr.h:622
Describes a memory block created by an allocation site.
Definition Descriptor.h:123
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition Descriptor.h:252
PrimType getPrimType() const
Definition Descriptor.h:232
const ConstantExprKind ConstexprKind