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"
24#include "clang/Basic/TargetInfo.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
40bool Context::isPotentialConstantExpr(State &Parent, const FunctionDecl *FD) {
41 assert(Stk.empty());
42
43 // Get a function handle.
44 const Function *Func = getOrCreateFunction(FuncDecl: FD);
45 if (!Func)
46 return false;
47
48 // Compile the function.
49 Compiler<ByteCodeEmitter>(*this, *P).compileFunc(
50 FuncDecl: FD, Func: 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
60void Context::isPotentialConstantExprUnevaluated(State &Parent, const Expr *E,
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(NewSize: StackSizeBefore);
70 }
71}
72
73bool Context::evaluateAsRValue(State &Parent, const Expr *E, APValue &Result) {
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(NewSize: 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(NewSize: 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
132bool Context::evaluateAsInitializer(State &Parent, const VarDecl *VD,
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 =
140 shouldBeGloballyIndexed(VD) &&
141 (VD->getType()->isRecordType() || VD->getType()->isArrayType());
142 auto Res = C.interpretDecl(VD, Init, CheckFullyInitialized: CheckGlobalInitialized);
143 if (Res.isInvalid()) {
144 C.cleanup();
145 Stk.clearTo(NewSize: 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
164bool Context::evaluateDestruction(State &Parent, const VarDecl *VD,
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, E: SizeExpr, Result&: 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(E: PtrExpr, PtrCB: [&](InterpState &S, CodePtr OpPC,
198 const Pointer &Ptr) {
199 if (Size == 0) {
200 if constexpr (std::is_same_v<ResultT, APValue>)
201 Result = APValue(APValue::UninitArray{}, 0, 0);
202 return true;
203 }
204
205 if (Ptr.isZero()) {
206 S.FFDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_access_null)
207 << AK_Read;
208 return false;
209 }
210
211 if (!Ptr.isLive() || !Ptr.getFieldDesc()->isPrimitiveArray())
212 return false;
213
214 // Must be char.
215 if (Ptr.getFieldDesc()->getElemDataSize() != 1 /*bytes*/)
216 return false;
217
218 if (Size > Ptr.getNumElems()) {
219 S.FFDiag(SI: S.Current->getSource(PC: OpPC), DiagId: diag::note_constexpr_access_past_end)
220 << AK_Read;
221 Size = Ptr.getNumElems();
222 }
223
224 if constexpr (std::is_same_v<ResultT, APValue>) {
225 QualType CharTy = PtrExpr->getType()->getPointeeType();
226 Result = APValue(APValue::UninitArray{}, Size, Size);
227 for (uint64_t I = 0; I != Size; ++I) {
228 if (std::optional<APValue> ElemVal =
229 Ptr.atIndex(Idx: I).toRValue(Ctx: *this, ResultType: CharTy))
230 Result.getArrayInitializedElt(I) = *ElemVal;
231 else
232 return false;
233 }
234 } else {
235 assert((std::is_same_v<ResultT, std::string>));
236 if (Size < Result.max_size())
237 Result.resize(Size);
238 Result.assign(reinterpret_cast<const char *>(Ptr.getRawAddress()), Size);
239 }
240
241 return true;
242 });
243
244 if (PtrRes.isInvalid()) {
245 C.cleanup();
246 Stk.clear();
247 return false;
248 }
249
250 return true;
251}
252
253bool Context::evaluateCharRange(State &Parent, const Expr *SizeExpr,
254 const Expr *PtrExpr, APValue &Result) {
255 assert(SizeExpr);
256 assert(PtrExpr);
257
258 return evaluateStringRepr(Parent, SizeExpr, PtrExpr, Result);
259}
260
261bool Context::evaluateCharRange(State &Parent, const Expr *SizeExpr,
262 const Expr *PtrExpr, std::string &Result) {
263 assert(SizeExpr);
264 assert(PtrExpr);
265
266 return evaluateStringRepr(Parent, SizeExpr, PtrExpr, Result);
267}
268
269bool Context::evaluateString(State &Parent, const Expr *E,
270 std::string &Result) {
271 assert(Stk.empty());
272 Compiler<EvalEmitter> C(*this, *P, Parent, Stk);
273
274 auto PtrRes = C.interpretAsPointer(E, PtrCB: [&](InterpState &S, CodePtr OpPC,
275 const Pointer &Ptr) {
276 if (!Ptr.isBlockPointer())
277 return false;
278
279 const Descriptor *FieldDesc = Ptr.getFieldDesc();
280 if (!FieldDesc->isPrimitiveArray())
281 return false;
282
283 if (!Ptr.isConst())
284 return false;
285
286 unsigned N = Ptr.getNumElems();
287
288 if (Ptr.elemSize() == 1 /* bytes */) {
289 const char *Chars = reinterpret_cast<const char *>(Ptr.getRawAddress());
290 unsigned Length = strnlen(string: Chars, maxlen: N);
291 // Wasn't null terminated.
292 if (N == Length)
293 return false;
294 Result.assign(s: Chars, n: Length);
295 return true;
296 }
297
298 PrimType ElemT = FieldDesc->getPrimType();
299 for (unsigned I = Ptr.getIndex(); I != N; ++I) {
300 INT_TYPE_SWITCH(ElemT, {
301 auto Elem = Ptr.elem<T>(I);
302 if (Elem.isZero())
303 return true;
304 Result.push_back(static_cast<char>(Elem));
305 });
306 }
307 // We didn't find a 0 byte.
308 return false;
309 });
310
311 if (PtrRes.isInvalid()) {
312 C.cleanup();
313 Stk.clear();
314 return false;
315 }
316 return true;
317}
318
319std::optional<uint64_t> Context::evaluateStrlen(State &Parent, const Expr *E) {
320 assert(Stk.empty());
321 Compiler<EvalEmitter> C(*this, *P, Parent, Stk);
322
323 std::optional<uint64_t> Result;
324 auto PtrRes = C.interpretAsPointer(E, PtrCB: [&](InterpState &S, CodePtr OpPC,
325 const Pointer &Ptr) {
326 if (!Ptr.isBlockPointer())
327 return false;
328
329 const Descriptor *FieldDesc = Ptr.getFieldDesc();
330 if (!FieldDesc->isPrimitiveArray())
331 return false;
332
333 if (Ptr.isDummy() || Ptr.isUnknownSizeArray() || Ptr.isPastEnd())
334 return false;
335
336 PrimType ElemT = FieldDesc->getPrimType();
337 if (!isIntegerType(T: ElemT))
338 return false;
339
340 unsigned N = Ptr.getNumElems();
341 if (Ptr.elemSize() == 1) {
342 unsigned Size = N - Ptr.getIndex();
343 Result =
344 strnlen(string: reinterpret_cast<const char *>(Ptr.getRawAddress()), maxlen: Size);
345 return Result != Size;
346 }
347
348 Result = 0;
349 for (unsigned I = Ptr.getIndex(); I != N; ++I) {
350 INT_TYPE_SWITCH(ElemT, {
351 auto Elem = Ptr.elem<T>(I);
352 if (Elem.isZero())
353 return true;
354 ++(*Result);
355 });
356 }
357 // We didn't find a 0 byte.
358 return false;
359 });
360
361 if (PtrRes.isInvalid()) {
362 C.cleanup();
363 Stk.clear();
364 return std::nullopt;
365 }
366 return Result;
367}
368
369std::optional<uint64_t>
370Context::tryEvaluateObjectSize(State &Parent, const Expr *E, unsigned Kind) {
371 assert(Stk.empty());
372 Compiler<EvalEmitter> C(*this, *P, Parent, Stk);
373
374 std::optional<uint64_t> Result;
375
376 auto PtrRes = C.interpretAsLValuePointer(E, PtrCB: [&](InterpState &S, CodePtr OpPC,
377 const Pointer &Ptr) {
378 const Descriptor *DeclDesc = Ptr.getDeclDesc();
379 if (!DeclDesc)
380 return false;
381
382 QualType T = DeclDesc->getType().getNonReferenceType();
383 if (T->isIncompleteType() || T->isFunctionType() ||
384 !T->isConstantSizeType())
385 return false;
386
387 Pointer P = Ptr;
388 if (auto ObjectSize = evaluateBuiltinObjectSize(ASTCtx: getASTContext(), Kind, Ptr&: P)) {
389 Result = *ObjectSize;
390 return true;
391 }
392 return false;
393 });
394
395 if (PtrRes.isInvalid()) {
396 C.cleanup();
397 Stk.clear();
398 return std::nullopt;
399 }
400 return Result;
401}
402
403std::optional<bool>
404Context::evaluateWithSubstitution(State &Parent, const FunctionDecl *Callee,
405 ArrayRef<const Expr *> Args, const Expr *This,
406 const Expr *Condition) {
407 if (OptPrimType ConditionT = classify(E: Condition);
408 !ConditionT || ConditionT != PT_Bool) {
409 return std::nullopt;
410 }
411
412 assert(Stk.empty());
413 Compiler<EvalEmitter> C(*this, *P, Parent, Stk);
414 std::optional<bool> Result =
415 C.interpretWithSubstitutions(Callee, Args, This, Condition);
416
417 // This is somewhat of a special case here. We don't allow
418 // evaluateWithSubstitution to recurse (see the Stk.empty() assertion above),
419 // BUT we allow the args to fail evaluation, which means they can leave some
420 // garbage on the stack. So we always clear() here, not only if the evaluation
421 // failed.
422 Stk.clear();
423 if (!Result) {
424 C.cleanup();
425 return std::nullopt;
426 }
427 return Result;
428}
429
430const LangOptions &Context::getLangOpts() const { return Ctx.getLangOpts(); }
431
432static PrimType integralTypeToPrimTypeS(unsigned BitWidth) {
433 switch (BitWidth) {
434 case 64:
435 return PT_Sint64;
436 case 32:
437 return PT_Sint32;
438 case 16:
439 return PT_Sint16;
440 case 8:
441 return PT_Sint8;
442 default:
443 return PT_IntAPS;
444 }
445 llvm_unreachable("Unhandled BitWidth");
446}
447
448static PrimType integralTypeToPrimTypeU(unsigned BitWidth) {
449 switch (BitWidth) {
450 case 64:
451 return PT_Uint64;
452 case 32:
453 return PT_Uint32;
454 case 16:
455 return PT_Uint16;
456 case 8:
457 return PT_Uint8;
458 default:
459 return PT_IntAP;
460 }
461 llvm_unreachable("Unhandled BitWidth");
462}
463
464OptPrimType Context::classify(QualType T) const {
465
466 if (const auto *BT = dyn_cast<BuiltinType>(Val: T.getCanonicalType())) {
467 auto Kind = BT->getKind();
468 if (Kind == BuiltinType::Bool)
469 return PT_Bool;
470 if (Kind == BuiltinType::NullPtr)
471 return PT_Ptr;
472 if (Kind == BuiltinType::BoundMember)
473 return PT_MemberPtr;
474
475 // Just trying to avoid the ASTContext::getIntWidth call below.
476 if (Kind == BuiltinType::Short)
477 return integralTypeToPrimTypeS(BitWidth: this->ShortWidth);
478 if (Kind == BuiltinType::UShort)
479 return integralTypeToPrimTypeU(BitWidth: this->ShortWidth);
480
481 if (Kind == BuiltinType::Int)
482 return integralTypeToPrimTypeS(BitWidth: this->IntWidth);
483 if (Kind == BuiltinType::UInt)
484 return integralTypeToPrimTypeU(BitWidth: this->IntWidth);
485 if (Kind == BuiltinType::Long)
486 return integralTypeToPrimTypeS(BitWidth: this->LongWidth);
487 if (Kind == BuiltinType::ULong)
488 return integralTypeToPrimTypeU(BitWidth: this->LongWidth);
489 if (Kind == BuiltinType::LongLong)
490 return integralTypeToPrimTypeS(BitWidth: this->LongLongWidth);
491 if (Kind == BuiltinType::ULongLong)
492 return integralTypeToPrimTypeU(BitWidth: this->LongLongWidth);
493
494 if (Kind == BuiltinType::SChar || Kind == BuiltinType::Char_S)
495 return integralTypeToPrimTypeS(BitWidth: 8);
496 if (Kind == BuiltinType::UChar || Kind == BuiltinType::Char_U ||
497 Kind == BuiltinType::Char8)
498 return integralTypeToPrimTypeU(BitWidth: 8);
499
500 if (BT->isSignedInteger())
501 return integralTypeToPrimTypeS(BitWidth: Ctx.getIntWidth(T));
502 if (BT->isUnsignedInteger())
503 return integralTypeToPrimTypeU(BitWidth: Ctx.getIntWidth(T));
504
505 if (BT->isFloatingPoint())
506 return PT_Float;
507 }
508
509 if (T->isPointerOrReferenceType())
510 return PT_Ptr;
511
512 if (T->isMemberPointerType())
513 return PT_MemberPtr;
514
515 if (const auto *BT = T->getAs<BitIntType>()) {
516 if (BT->isSigned())
517 return integralTypeToPrimTypeS(BitWidth: BT->getNumBits());
518 return integralTypeToPrimTypeU(BitWidth: BT->getNumBits());
519 }
520
521 if (const auto *D = T->getAsEnumDecl()) {
522 if (!D->isComplete())
523 return std::nullopt;
524 return classify(T: D->getIntegerType());
525 }
526
527 if (const auto *AT = T->getAs<AtomicType>())
528 return classify(T: AT->getValueType());
529
530 if (const auto *DT = dyn_cast<DecltypeType>(Val&: T))
531 return classify(T: DT->getUnderlyingType());
532
533 if (const auto *OBT = T.getCanonicalType()->getAs<OverflowBehaviorType>())
534 return classify(T: OBT->getUnderlyingType());
535
536 if (T->isObjCObjectPointerType() || T->isBlockPointerType())
537 return PT_Ptr;
538
539 if (T->isFixedPointType())
540 return PT_FixedPoint;
541
542 // Vector and complex types get here.
543 return std::nullopt;
544}
545
546unsigned Context::getCharBit() const {
547 return Ctx.getTargetInfo().getCharWidth();
548}
549
550/// Simple wrapper around getFloatTypeSemantics() to make code a
551/// little shorter.
552const llvm::fltSemantics &Context::getFloatSemantics(QualType T) const {
553 return Ctx.getFloatTypeSemantics(T);
554}
555
556bool Context::Run(State &Parent, const Function *Func) {
557 InterpState State(Parent, *P, Stk, *this, Func);
558 auto Memory = std::make_unique<char[]>(num: InterpFrame::allocSize(F: Func));
559 InterpFrame *Frame = new (Memory.get()) InterpFrame(
560 State, Func, /*Caller=*/nullptr, CodePtr(), Func->getArgSize());
561 State.Current = Frame;
562
563 if (Interpret(S&: State)) {
564 assert(Stk.empty());
565 return true;
566 }
567
568 Stk.clear();
569 Frame->~InterpFrame();
570 State.Current = &State.BottomFrame;
571 return false;
572}
573
574const CXXMethodDecl *
575Context::getOverridingFunction(const CXXRecordDecl *DynamicDecl,
576 const CXXRecordDecl *StaticDecl,
577 const CXXMethodDecl *InitialFunction) const {
578 assert(DynamicDecl);
579 assert(StaticDecl);
580 assert(InitialFunction);
581
582 const CXXRecordDecl *CurRecord = DynamicDecl;
583 const CXXMethodDecl *FoundFunction = InitialFunction;
584 for (;;) {
585 const CXXMethodDecl *Overrider =
586 FoundFunction->getCorrespondingMethodDeclaredInClass(RD: CurRecord, MayBeBase: false);
587 if (Overrider)
588 return Overrider;
589
590 // Common case of only one base class.
591 if (CurRecord->getNumBases() == 1) {
592 CurRecord = CurRecord->bases_begin()->getType()->getAsCXXRecordDecl();
593 continue;
594 }
595
596 // Otherwise, go to the base class that will lead to the StaticDecl.
597 for (const CXXBaseSpecifier &Spec : CurRecord->bases()) {
598 const CXXRecordDecl *Base = Spec.getType()->getAsCXXRecordDecl();
599 if (Base == StaticDecl || Base->isDerivedFrom(Base: StaticDecl)) {
600 CurRecord = Base;
601 break;
602 }
603 }
604 }
605
606 llvm_unreachable(
607 "Couldn't find an overriding function in the class hierarchy?");
608 return nullptr;
609}
610
611const Function *Context::getOrCreateFunction(const FunctionDecl *FuncDecl) {
612 assert(FuncDecl);
613 if (const Function *Func = P->getFunction(F: FuncDecl))
614 return Func;
615
616 // Manually created functions that haven't been assigned proper
617 // parameters yet.
618 if (!FuncDecl->param_empty() && !FuncDecl->param_begin())
619 return nullptr;
620
621 bool IsLambdaStaticInvoker = false;
622 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FuncDecl);
623 MD && MD->isLambdaStaticInvoker()) {
624 // For a lambda static invoker, we might have to pick a specialized
625 // version if the lambda is generic. In that case, the picked function
626 // will *NOT* be a static invoker anymore. However, it will still
627 // be a non-static member function, this (usually) requiring an
628 // instance pointer. We suppress that later in this function.
629 IsLambdaStaticInvoker = true;
630 }
631 // Set up argument indices.
632 unsigned ParamOffset = 0;
633 llvm::SmallVector<Function::ParamDescriptor> ParamDescriptors;
634
635 // If the return is not a primitive, a pointer to the storage where the
636 // value is initialized in is passed as the first argument. See 'RVO'
637 // elsewhere in the code.
638 QualType Ty = FuncDecl->getReturnType();
639 bool HasRVO = false;
640 if (!Ty->isVoidType() && !canClassify(T: Ty)) {
641 HasRVO = true;
642 ParamOffset += align(Size: primSize(Type: PT_Ptr));
643 }
644
645 // If the function decl is a member decl, the next parameter is
646 // the 'this' pointer. This parameter is pop()ed from the
647 // InterpStack when calling the function.
648 bool HasThisPointer = false;
649 if (const auto *MD = dyn_cast<CXXMethodDecl>(Val: FuncDecl)) {
650 if (!IsLambdaStaticInvoker) {
651 HasThisPointer = MD->isInstance();
652 if (MD->isImplicitObjectMemberFunction())
653 ParamOffset += align(Size: primSize(Type: PT_Ptr));
654 }
655
656 if (isLambdaCallOperator(MD)) {
657 // The parent record needs to be complete, we need to know about all
658 // the lambda captures.
659 if (!MD->getParent()->isCompleteDefinition())
660 return nullptr;
661 if (MD->isStatic()) {
662 llvm::DenseMap<const ValueDecl *, FieldDecl *> LC;
663 FieldDecl *LTC;
664
665 MD->getParent()->getCaptureFields(Captures&: LC, ThisCapture&: LTC);
666 // Static lambdas cannot have any captures. If this one does,
667 // it has already been diagnosed and we can only ignore it.
668 if (!LC.empty())
669 return nullptr;
670 }
671 }
672 }
673
674 // Assign descriptors to all parameters.
675 // Composite objects are lowered to pointers.
676 const auto *FuncProto = FuncDecl->getType()->getAs<FunctionProtoType>();
677 unsigned BlockOffset = 0;
678 for (auto [ParamIndex, PD] : llvm::enumerate(First: FuncDecl->parameters())) {
679 bool IsConst = PD->getType().isConstQualified();
680 bool IsVolatile = PD->getType().isVolatileQualified();
681
682 if (PD->isInvalidDecl() ||
683 !getASTContext().hasSameType(T1: PD->getType(),
684 T2: FuncProto->getParamType(i: ParamIndex)))
685 return nullptr;
686
687 OptPrimType T = classify(T: PD->getType());
688 PrimType PT = T.value_or(PT: PT_Ptr);
689 Descriptor *Desc = P->createDescriptor(D: PD, T: PT, SourceTy: nullptr, MDSize: std::nullopt,
690 IsConst, /*IsTemporary=*/false,
691 /*IsMutable=*/false, IsVolatile);
692 unsigned PrimTSize = align(Size: primSize(Type: PT));
693 ParamDescriptors.emplace_back(Args&: Desc, Args&: ParamOffset, Args&: BlockOffset, Args&: PT);
694 ParamOffset += PrimTSize;
695 BlockOffset += sizeof(Block) + PrimTSize;
696 }
697
698 // Create a handle over the emitted code.
699 assert(!P->getFunction(FuncDecl));
700 const Function *Func =
701 P->createFunction(Def: FuncDecl, Args&: ParamOffset, Args: std::move(ParamDescriptors),
702 Args&: HasThisPointer, Args&: HasRVO, Args&: IsLambdaStaticInvoker);
703 return Func;
704}
705
706const Function *Context::getOrCreateObjCBlock(const BlockExpr *E) {
707 const BlockDecl *BD = E->getBlockDecl();
708 // Set up argument indices.
709 unsigned ParamOffset = 0;
710 llvm::SmallVector<Function::ParamDescriptor> ParamDescriptors;
711
712 // Assign descriptors to all parameters.
713 // Composite objects are lowered to pointers.
714 for (const ParmVarDecl *PD : BD->parameters()) {
715 bool IsConst = PD->getType().isConstQualified();
716 bool IsVolatile = PD->getType().isVolatileQualified();
717
718 OptPrimType T = classify(T: PD->getType());
719 PrimType PT = T.value_or(PT: PT_Ptr);
720 Descriptor *Desc = P->createDescriptor(D: PD, T: PT, SourceTy: nullptr, MDSize: std::nullopt,
721 IsConst, /*IsTemporary=*/false,
722 /*IsMutable=*/false, IsVolatile);
723 ParamDescriptors.emplace_back(Args&: Desc, Args&: ParamOffset, Args: ~0u, Args&: PT);
724 ParamOffset += align(Size: primSize(Type: PT));
725 }
726
727 if (BD->hasCaptures())
728 return nullptr;
729
730 // Create a handle over the emitted code.
731 Function *Func =
732 P->createFunction(Args&: E, Args&: ParamOffset, Args: std::move(ParamDescriptors),
733 /*HasThisPointer=*/Args: false, /*HasRVO=*/Args: false,
734 /*IsLambdaStaticInvoker=*/Args: false);
735
736 assert(Func);
737 Func->setDefined(true);
738 // We don't compile the BlockDecl code at all right now.
739 Func->setIsFullyCompiled(true);
740
741 return Func;
742}
743
744unsigned Context::collectBaseOffset(const RecordDecl *BaseDecl,
745 const RecordDecl *DerivedDecl) const {
746 assert(BaseDecl);
747 assert(DerivedDecl);
748 const auto *FinalDecl = cast<CXXRecordDecl>(Val: BaseDecl);
749 const RecordDecl *CurDecl = DerivedDecl;
750 const Record *CurRecord = P->getOrCreateRecord(RD: CurDecl);
751 assert(CurDecl && FinalDecl);
752
753 unsigned OffsetSum = 0;
754 for (;;) {
755 assert(CurRecord->getNumBases() > 0);
756 // One level up
757 for (const Record::Base &B : CurRecord->bases()) {
758 const auto *BaseDecl = cast<CXXRecordDecl>(Val: B.Decl);
759
760 if (BaseDecl == FinalDecl || BaseDecl->isDerivedFrom(Base: FinalDecl)) {
761 OffsetSum += B.Offset;
762 CurRecord = B.R;
763 CurDecl = BaseDecl;
764 break;
765 }
766 }
767 if (CurDecl == FinalDecl)
768 break;
769 }
770
771 assert(OffsetSum > 0);
772 return OffsetSum;
773}
774
775const Record *Context::getRecord(const RecordDecl *D) const {
776 return P->getOrCreateRecord(RD: D);
777}
778
779bool Context::isUnevaluatedBuiltin(unsigned ID) {
780 return ID == Builtin::BI__builtin_classify_type ||
781 ID == Builtin::BI__builtin_os_log_format_buffer_size ||
782 ID == Builtin::BI__builtin_constant_p || ID == Builtin::BI__noop;
783}
784