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