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