clang 23.0.0git
Compiler.cpp
Go to the documentation of this file.
1//===--- Compiler.cpp - Code generator for expressions ---*- 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 "Compiler.h"
10#include "ByteCodeEmitter.h"
11#include "Context.h"
12#include "FixedPoint.h"
13#include "Floating.h"
14#include "Function.h"
15#include "InterpShared.h"
16#include "PrimType.h"
17#include "Program.h"
18#include "clang/AST/Attr.h"
20#include "llvm/Support/SaveAndRestore.h"
21
22using namespace clang;
23using namespace clang::interp;
24
25using APSInt = llvm::APSInt;
26
27namespace clang {
28namespace interp {
29
30static std::optional<bool> getBoolValue(const Expr *E) {
31 if (const auto *CE = dyn_cast_if_present<ConstantExpr>(E);
32 CE && CE->hasAPValueResult() &&
33 CE->getResultAPValueKind() == APValue::ValueKind::Int) {
34 return CE->getResultAsAPSInt().getBoolValue();
35 }
36
37 return std::nullopt;
38}
39
40/// Scope used to handle temporaries in toplevel variable declarations.
41template <class Emitter> class DeclScope final : public LocalScope<Emitter> {
42public:
44 : LocalScope<Emitter>(Ctx), Scope(Ctx->P),
45 OldInitializingDecl(Ctx->InitializingDecl) {
46 Ctx->InitializingDecl = VD;
47 Ctx->InitStack.push_back(InitLink::Decl(VD));
48 }
49
51 this->Ctx->InitializingDecl = OldInitializingDecl;
52 this->Ctx->InitStack.pop_back();
53 }
54
55private:
57 const ValueDecl *OldInitializingDecl;
58};
59
60/// Scope used to handle initialization methods.
61template <class Emitter> class OptionScope final {
62public:
63 /// Root constructor, compiling or discarding primitives.
64 OptionScope(Compiler<Emitter> *Ctx, bool NewDiscardResult,
65 bool NewInitializing, bool NewToLValue)
66 : Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult),
67 OldInitializing(Ctx->Initializing), OldToLValue(Ctx->ToLValue) {
68 Ctx->DiscardResult = NewDiscardResult;
69 Ctx->Initializing = NewInitializing;
70 Ctx->ToLValue = NewToLValue;
71 }
72
74 Ctx->DiscardResult = OldDiscardResult;
75 Ctx->Initializing = OldInitializing;
76 Ctx->ToLValue = OldToLValue;
77 }
78
79private:
80 /// Parent context.
82 /// Old discard flag to restore.
83 bool OldDiscardResult;
84 bool OldInitializing;
85 bool OldToLValue;
86};
87
88template <class Emitter>
89bool InitLink::emit(Compiler<Emitter> *Ctx, const Expr *E) const {
90 switch (Kind) {
91 case K_This:
92 return Ctx->emitThis(E);
93 case K_Field:
94 // We're assuming there's a base pointer on the stack already.
95 return Ctx->emitGetPtrFieldPop(Offset, E);
96 case K_Temp:
97 return Ctx->emitGetPtrLocal(Offset, E);
98 case K_Decl:
99 return Ctx->visitDeclRef(D, E);
100 case K_Elem:
101 if (!Ctx->emitConstUint32(Offset, E))
102 return false;
103 return Ctx->emitArrayElemPtrPopUint32(E);
104 case K_RVO:
105 return Ctx->emitRVOPtr(E);
106 case K_InitList:
107 return true;
108 default:
109 llvm_unreachable("Unhandled InitLink kind");
110 }
111 return true;
112}
113
114/// Sets the context for break/continue statements.
115template <class Emitter> class LoopScope final {
116public:
120
121 LoopScope(Compiler<Emitter> *Ctx, const Stmt *Name, LabelTy BreakLabel,
122 LabelTy ContinueLabel)
123 : Ctx(Ctx) {
124#ifndef NDEBUG
125 for (const LabelInfo &LI : Ctx->LabelInfoStack)
126 assert(LI.Name != Name);
127#endif
128
129 this->Ctx->LabelInfoStack.emplace_back(Name, BreakLabel, ContinueLabel,
130 /*DefaultLabel=*/std::nullopt,
131 Ctx->VarScope);
132 }
133
134 ~LoopScope() { this->Ctx->LabelInfoStack.pop_back(); }
135
136private:
138};
139
140// Sets the context for a switch scope, mapping labels.
141template <class Emitter> class SwitchScope final {
142public:
147
148 SwitchScope(Compiler<Emitter> *Ctx, const Stmt *Name, CaseMap &&CaseLabels,
149 LabelTy BreakLabel, OptLabelTy DefaultLabel)
150 : Ctx(Ctx), OldCaseLabels(std::move(this->Ctx->CaseLabels)) {
151#ifndef NDEBUG
152 for (const LabelInfo &LI : Ctx->LabelInfoStack)
153 assert(LI.Name != Name);
154#endif
155
156 this->Ctx->CaseLabels = std::move(CaseLabels);
157 this->Ctx->LabelInfoStack.emplace_back(Name, BreakLabel,
158 /*ContinueLabel=*/std::nullopt,
159 DefaultLabel, Ctx->VarScope);
160 }
161
163 this->Ctx->CaseLabels = std::move(OldCaseLabels);
164 this->Ctx->LabelInfoStack.pop_back();
165 }
166
167private:
169 CaseMap OldCaseLabels;
170};
171
172/// When generating code for e.g. implicit field initializers in constructors,
173/// we don't have anything to point to in case the initializer causes an error.
174/// In that case, we need to disable location tracking for the initializer so
175/// we later point to the call range instead.
176template <class Emitter> class LocOverrideScope final {
177public:
179 bool Enabled = true)
180 : Ctx(Ctx), OldFlag(Ctx->LocOverride), Enabled(Enabled) {
181
182 if (Enabled)
183 Ctx->LocOverride = NewValue;
184 }
185
187 if (Enabled)
188 Ctx->LocOverride = OldFlag;
189 }
190
191private:
193 std::optional<SourceInfo> OldFlag;
194 bool Enabled;
195};
196
197} // namespace interp
198} // namespace clang
199
200template <class Emitter>
202 const Expr *SubExpr = E->getSubExpr();
203
204 if (DiscardResult)
205 return this->delegate(SubExpr);
206
207 switch (E->getCastKind()) {
208 case CK_LValueToRValue: {
209 if (ToLValue && E->getType()->isPointerType())
210 return this->delegate(SubExpr);
211
212 if (SubExpr->getType().isVolatileQualified())
213 return this->emitInvalidCast(CastKind::Volatile, /*Fatal=*/true, E);
214
215 OptPrimType SubExprT = classify(SubExpr->getType());
216 // Try to load the value directly. This is purely a performance
217 // optimization.
218 if (SubExprT) {
219 if (const auto *DRE = dyn_cast<DeclRefExpr>(SubExpr)) {
220 const ValueDecl *D = DRE->getDecl();
221 bool IsReference = D->getType()->isReferenceType();
222
223 if (!IsReference) {
225 if (auto GlobalIndex = P.getGlobal(D))
226 return this->emitGetGlobal(*SubExprT, *GlobalIndex, E);
227 } else if (auto It = Locals.find(D); It != Locals.end()) {
228 return this->emitGetLocal(*SubExprT, It->second.Offset, E);
229 } else if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
230 if (auto It = this->Params.find(PVD); It != this->Params.end()) {
231 return this->emitGetParam(*SubExprT, It->second.Index, E);
232 }
233 }
234 }
235 }
236 }
237
238 // Prepare storage for the result.
239 if (!Initializing && !SubExprT) {
240 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
241 if (!LocalIndex)
242 return false;
243 if (!this->emitGetPtrLocal(*LocalIndex, E))
244 return false;
245 }
246
247 if (!this->visit(SubExpr))
248 return false;
249
250 if (SubExprT)
251 return this->emitLoadPop(*SubExprT, E);
252
253 // If the subexpr type is not primitive, we need to perform a copy here.
254 // This happens for example in C when dereferencing a pointer of struct
255 // type.
256 return this->emitMemcpy(E);
257 }
258
259 case CK_DerivedToBaseMemberPointer: {
260 if (E->containsErrors())
261 return false;
262 assert(classifyPrim(E) == PT_MemberPtr);
263 assert(classifyPrim(SubExpr) == PT_MemberPtr);
264
265 if (!this->delegate(SubExpr))
266 return false;
267
268 const CXXRecordDecl *CurDecl = SubExpr->getType()
270 ->getMostRecentCXXRecordDecl();
271 for (const CXXBaseSpecifier *B : E->path()) {
272 const CXXRecordDecl *ToDecl = B->getType()->getAsCXXRecordDecl();
273 unsigned DerivedOffset = Ctx.collectBaseOffset(ToDecl, CurDecl);
274
275 if (!this->emitCastMemberPtrBasePop(DerivedOffset, ToDecl, E))
276 return false;
277 CurDecl = ToDecl;
278 }
279
280 return true;
281 }
282
283 case CK_BaseToDerivedMemberPointer: {
284 if (E->containsErrors())
285 return false;
286 assert(classifyPrim(E) == PT_MemberPtr);
287 assert(classifyPrim(SubExpr) == PT_MemberPtr);
288
289 if (!this->delegate(SubExpr))
290 return false;
291
292 const CXXRecordDecl *CurDecl = SubExpr->getType()
294 ->getMostRecentCXXRecordDecl();
295 // Base-to-derived member pointer casts store the path in derived-to-base
296 // order, so iterate backwards. The CXXBaseSpecifier also provides us with
297 // the wrong end of the derived->base arc, so stagger the path by one class.
298 typedef std::reverse_iterator<CastExpr::path_const_iterator> ReverseIter;
299 for (ReverseIter PathI(E->path_end() - 1), PathE(E->path_begin());
300 PathI != PathE; ++PathI) {
301 const CXXRecordDecl *ToDecl = (*PathI)->getType()->getAsCXXRecordDecl();
302 unsigned DerivedOffset = Ctx.collectBaseOffset(CurDecl, ToDecl);
303
304 if (!this->emitCastMemberPtrDerivedPop(-DerivedOffset, ToDecl, E))
305 return false;
306 CurDecl = ToDecl;
307 }
308
309 const CXXRecordDecl *ToDecl =
310 E->getType()->castAs<MemberPointerType>()->getMostRecentCXXRecordDecl();
311 assert(ToDecl != CurDecl);
312 unsigned DerivedOffset = Ctx.collectBaseOffset(CurDecl, ToDecl);
313
314 if (!this->emitCastMemberPtrDerivedPop(-DerivedOffset, ToDecl, E))
315 return false;
316
317 return true;
318 }
319
320 case CK_UncheckedDerivedToBase:
321 case CK_DerivedToBase: {
322 if (!this->delegate(SubExpr))
323 return false;
324
325 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
326 if (const auto *PT = dyn_cast<PointerType>(Ty))
327 return PT->getPointeeType()->getAsCXXRecordDecl();
328 return Ty->getAsCXXRecordDecl();
329 };
330
331 // FIXME: We can express a series of non-virtual casts as a single
332 // GetPtrBasePop op.
333 QualType CurType = SubExpr->getType();
334 for (const CXXBaseSpecifier *B : E->path()) {
335 if (B->isVirtual()) {
336 if (!this->emitGetPtrVirtBasePop(extractRecordDecl(B->getType()), E))
337 return false;
338 CurType = B->getType();
339 } else {
340 unsigned DerivedOffset = collectBaseOffset(B->getType(), CurType);
341 if (!this->emitGetPtrBasePop(
342 DerivedOffset, /*NullOK=*/E->getType()->isPointerType(), E))
343 return false;
344 CurType = B->getType();
345 }
346 }
347
348 return true;
349 }
350
351 case CK_BaseToDerived: {
352 if (!this->delegate(SubExpr))
353 return false;
354 unsigned DerivedOffset =
355 collectBaseOffset(SubExpr->getType(), E->getType());
356
357 const Type *TargetType = E->getType().getTypePtr();
358 if (TargetType->isPointerOrReferenceType())
359 TargetType = TargetType->getPointeeType().getTypePtr();
360 return this->emitGetPtrDerivedPop(DerivedOffset,
361 /*NullOK=*/E->getType()->isPointerType(),
362 TargetType, E);
363 }
364
365 case CK_FloatingCast: {
366 // HLSL uses CK_FloatingCast to cast between vectors.
367 if (E->getType()->isVectorType())
368 return this->emitVectorConversion(E->getSubExpr(), E);
369 if (!SubExpr->getType()->isFloatingType() ||
370 !E->getType()->isFloatingType())
371 return false;
372 if (!this->visit(SubExpr))
373 return false;
374 const auto *TargetSemantics = &Ctx.getFloatSemantics(E->getType());
375 return this->emitCastFP(TargetSemantics, getRoundingMode(E), E);
376 }
377
378 case CK_IntegralToFloating: {
379 if (E->getType()->isVectorType())
380 return this->emitVectorConversion(E->getSubExpr(), E);
381 if (!E->getType()->isRealFloatingType())
382 return false;
383 if (!this->visit(SubExpr))
384 return false;
385 const auto *TargetSemantics = &Ctx.getFloatSemantics(E->getType());
386 return this->emitCastIntegralFloating(classifyPrim(SubExpr),
387 TargetSemantics, getFPOptions(E), E);
388 }
389
390 case CK_FloatingToBoolean: {
391 if (E->getType()->isVectorType())
392 return this->emitVectorConversion(E->getSubExpr(), E);
393 if (!SubExpr->getType()->isRealFloatingType() ||
394 !E->getType()->isBooleanType())
395 return false;
396 if (const auto *FL = dyn_cast<FloatingLiteral>(SubExpr))
397 return this->emitConstBool(FL->getValue().isNonZero(), E);
398 if (!this->visit(SubExpr))
399 return false;
400 return this->emitCastFloatingIntegralBool(getFPOptions(E), E);
401 }
402
403 case CK_FloatingToIntegral: {
404 if (E->getType()->isVectorType())
405 return this->emitVectorConversion(E->getSubExpr(), E);
407 return false;
408 if (!this->visit(SubExpr))
409 return false;
410 PrimType ToT = classifyPrim(E);
411 if (ToT == PT_IntAP)
412 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(E->getType()),
413 getFPOptions(E), E);
414 if (ToT == PT_IntAPS)
415 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(E->getType()),
416 getFPOptions(E), E);
417
418 return this->emitCastFloatingIntegral(ToT, getFPOptions(E), E);
419 }
420
421 case CK_NullToPointer:
422 case CK_NullToMemberPointer: {
423 if (!this->discard(SubExpr))
424 return false;
425 uint64_t Val = Ctx.getASTContext().getTargetNullPointerValue(E->getType());
426 return this->emitNull(classifyPrim(E->getType()), Val,
427 E->getType().getTypePtr(), E);
428 }
429
430 case CK_PointerToIntegral: {
431 if (!this->visit(SubExpr))
432 return false;
433
434 // If SubExpr doesn't result in a pointer, make it one.
435 if (PrimType FromT = classifyPrim(SubExpr->getType()); FromT != PT_Ptr) {
436 assert(isPtrType(FromT));
437 if (!this->emitDecayPtr(FromT, PT_Ptr, E))
438 return false;
439 }
440
441 PrimType T = classifyPrim(E->getType());
442 if (T == PT_IntAP)
443 return this->emitCastPointerIntegralAP(Ctx.getBitWidth(E->getType()), E);
444 if (T == PT_IntAPS)
445 return this->emitCastPointerIntegralAPS(Ctx.getBitWidth(E->getType()), E);
446 return this->emitCastPointerIntegral(T, E);
447 }
448
449 case CK_ArrayToPointerDecay: {
450 if (!this->visit(SubExpr))
451 return false;
452 return this->emitArrayDecay(E);
453 }
454
455 case CK_IntegralToPointer: {
456 QualType IntType = SubExpr->getType();
457 assert(IntType->isIntegralOrEnumerationType());
458 if (!this->visit(SubExpr))
459 return false;
460 // FIXME: I think the discard is wrong since the int->ptr cast might cause a
461 // diagnostic.
462 PrimType T = classifyPrim(IntType);
463 if (!this->emitGetIntPtr(T, E->getType().getTypePtr(), E))
464 return false;
465
466 QualType PtrType = E->getType();
467 PrimType DestPtrT = classifyPrim(PtrType);
468 if (DestPtrT == PT_Ptr)
469 return true;
470
471 // In case we're converting the integer to a non-Pointer.
472 return this->emitDecayPtr(PT_Ptr, DestPtrT, E);
473 }
474
475 case CK_AtomicToNonAtomic:
476 case CK_ConstructorConversion:
477 case CK_FunctionToPointerDecay:
478 case CK_NonAtomicToAtomic:
479 case CK_NoOp:
480 case CK_UserDefinedConversion:
481 case CK_AddressSpaceConversion:
482 case CK_CPointerToObjCPointerCast:
483 return this->delegate(SubExpr);
484
485 case CK_BitCast: {
486 if (E->containsErrors())
487 return false;
488 QualType ETy = E->getType();
489 // Reject bitcasts to atomic types.
490 if (ETy->isAtomicType()) {
491 if (!this->discard(SubExpr))
492 return false;
493 return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, E);
494 }
495 QualType SubExprTy = SubExpr->getType();
496 OptPrimType FromT = classify(SubExprTy);
497 // Casts from integer/vector to vector.
498 if (E->getType()->isVectorType())
499 return this->emitBuiltinBitCast(E);
500
501 OptPrimType ToT = classify(E->getType());
502 if (!FromT || !ToT)
503 return false;
504
505 assert(isPtrType(*FromT));
506 assert(isPtrType(*ToT));
507 bool SrcIsVoidPtr = SubExprTy->isVoidPointerType();
508 if (FromT == ToT) {
509 if (E->getType()->isVoidPointerType() &&
510 !SubExprTy->isFunctionPointerType()) {
511 return this->delegate(SubExpr);
512 }
513
514 if (!this->visit(SubExpr))
515 return false;
516 if (!this->emitCheckBitCast(ETy->getPointeeType().getTypePtr(),
517 SrcIsVoidPtr, E))
518 return false;
519
520 if (E->getType()->isFunctionPointerType() ||
521 SubExprTy->isFunctionPointerType()) {
522 return this->emitFnPtrCast(E);
523 }
524 if (FromT == PT_Ptr)
525 return this->emitPtrPtrCast(SubExprTy->isVoidPointerType(), E);
526 return true;
527 }
528
529 if (!this->visit(SubExpr))
530 return false;
531 return this->emitDecayPtr(*FromT, *ToT, E);
532 }
533 case CK_IntegralToBoolean:
534 case CK_FixedPointToBoolean: {
535 if (E->getType()->isVectorType())
536 return this->emitVectorConversion(E->getSubExpr(), E);
537 // HLSL uses this to cast to one-element vectors.
538 OptPrimType FromT = classify(SubExpr->getType());
539 if (!FromT)
540 return false;
541
542 if (const auto *IL = dyn_cast<IntegerLiteral>(SubExpr))
543 return this->emitConst(IL->getValue(), E);
544 if (!this->visit(SubExpr))
545 return false;
546 return this->emitCast(*FromT, classifyPrim(E), E);
547 }
548
549 case CK_IntegralCast:
550 if (E->getType()->isVectorType())
551 return this->emitVectorConversion(E->getSubExpr(), E);
552 [[fallthrough]];
553 case CK_BooleanToSignedIntegral: {
554 OptPrimType FromT = classify(SubExpr->getType());
555 OptPrimType ToT = classify(E->getType());
556 if (!FromT || !ToT)
557 return false;
558
559 // Try to emit a casted known constant value directly.
560 if (const auto *IL = dyn_cast<IntegerLiteral>(SubExpr)) {
561 if (ToT != PT_IntAP && ToT != PT_IntAPS && FromT != PT_IntAP &&
562 FromT != PT_IntAPS && !E->getType()->isEnumeralType())
563 return this->emitConst(APSInt(IL->getValue(), !isSignedType(*FromT)),
564 E);
565 if (!this->emitConst(IL->getValue(), SubExpr))
566 return false;
567 } else {
568 if (!this->visit(SubExpr))
569 return false;
570 }
571
572 // Possibly diagnose casts to enum types if the target type does not
573 // have a fixed size.
574 if (Ctx.getLangOpts().CPlusPlus && E->getType()->isEnumeralType()) {
575 const auto *ED = E->getType()->castAsEnumDecl();
576 if (!ED->isFixed()) {
577 if (!this->emitCheckEnumValue(*FromT, ED, E))
578 return false;
579 }
580 }
581
582 if (ToT == PT_IntAP) {
583 if (!this->emitCastAP(*FromT, Ctx.getBitWidth(E->getType()), E))
584 return false;
585 } else if (ToT == PT_IntAPS) {
586 if (!this->emitCastAPS(*FromT, Ctx.getBitWidth(E->getType()), E))
587 return false;
588 } else {
589 if (FromT == ToT)
590 return true;
591 if (!this->emitCast(*FromT, *ToT, E))
592 return false;
593 }
594 if (E->getCastKind() == CK_BooleanToSignedIntegral)
595 return this->emitNeg(*ToT, E);
596 return true;
597 }
598
599 case CK_PointerToBoolean:
600 case CK_MemberPointerToBoolean: {
601 PrimType PtrT = classifyPrim(SubExpr->getType());
602
603 if (!this->visit(SubExpr))
604 return false;
605 return this->emitIsNonNull(PtrT, E);
606 }
607
608 case CK_IntegralComplexToBoolean:
609 case CK_FloatingComplexToBoolean: {
610 if (!this->visit(SubExpr))
611 return false;
612 return this->emitComplexBoolCast(SubExpr);
613 }
614
615 case CK_IntegralComplexToReal:
616 case CK_FloatingComplexToReal:
617 return this->emitComplexReal(SubExpr);
618
619 case CK_IntegralRealToComplex:
620 case CK_FloatingRealToComplex: {
621 // We're creating a complex value here, so we need to
622 // allocate storage for it.
623 if (!Initializing) {
624 UnsignedOrNone LocalIndex = allocateTemporary(E);
625 if (!LocalIndex)
626 return false;
627 if (!this->emitGetPtrLocal(*LocalIndex, E))
628 return false;
629 }
630
631 PrimType T = classifyPrim(SubExpr->getType());
632 // Init the complex value to {SubExpr, 0}.
633 if (!this->visitArrayElemInit(0, SubExpr, T))
634 return false;
635 // Zero-init the second element.
636 if (!this->visitZeroInitializer(T, SubExpr->getType(), SubExpr))
637 return false;
638 return this->emitInitElem(T, 1, SubExpr);
639 }
640
641 case CK_IntegralComplexCast:
642 case CK_FloatingComplexCast:
643 case CK_IntegralComplexToFloatingComplex:
644 case CK_FloatingComplexToIntegralComplex: {
645 assert(E->getType()->isAnyComplexType());
646 assert(SubExpr->getType()->isAnyComplexType());
647 if (!Initializing) {
648 UnsignedOrNone LocalIndex = allocateLocal(E);
649 if (!LocalIndex)
650 return false;
651 if (!this->emitGetPtrLocal(*LocalIndex, E))
652 return false;
653 }
654
655 // Location for the SubExpr.
656 // Since SubExpr is of complex type, visiting it results in a pointer
657 // anyway, so we just create a temporary pointer variable.
658 unsigned SubExprOffset =
659 allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
660 if (!this->visit(SubExpr))
661 return false;
662 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E))
663 return false;
664
665 PrimType SourceElemT = classifyComplexElementType(SubExpr->getType());
666 QualType DestElemType =
667 E->getType()->getAs<ComplexType>()->getElementType();
668 PrimType DestElemT = classifyPrim(DestElemType);
669 // Cast both elements individually.
670 for (unsigned I = 0; I != 2; ++I) {
671 if (!this->emitGetLocal(PT_Ptr, SubExprOffset, E))
672 return false;
673 if (!this->emitArrayElemPop(SourceElemT, I, E))
674 return false;
675
676 // Do the cast.
677 if (!this->emitPrimCast(SourceElemT, DestElemT, DestElemType, E))
678 return false;
679
680 // Save the value.
681 if (!this->emitInitElem(DestElemT, I, E))
682 return false;
683 }
684 return true;
685 }
686
687 case CK_VectorSplat: {
688 assert(!canClassify(E->getType()));
689 assert(E->getType()->isVectorType());
690
691 if (!canClassify(SubExpr->getType()))
692 return false;
693
694 if (!Initializing) {
695 UnsignedOrNone LocalIndex = allocateLocal(E);
696 if (!LocalIndex)
697 return false;
698 if (!this->emitGetPtrLocal(*LocalIndex, E))
699 return false;
700 }
701
702 const auto *VT = E->getType()->getAs<VectorType>();
703 PrimType ElemT = classifyPrim(SubExpr->getType());
704 unsigned ElemOffset =
705 allocateLocalPrimitive(SubExpr, ElemT, /*IsConst=*/true);
706
707 // Prepare a local variable for the scalar value.
708 if (!this->visit(SubExpr))
709 return false;
710 if (classifyPrim(SubExpr) == PT_Ptr && !this->emitLoadPop(ElemT, E))
711 return false;
712
713 if (!this->emitSetLocal(ElemT, ElemOffset, E))
714 return false;
715
716 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
717 if (!this->emitGetLocal(ElemT, ElemOffset, E))
718 return false;
719 if (!this->emitInitElem(ElemT, I, E))
720 return false;
721 }
722
723 return true;
724 }
725
726 case CK_HLSLVectorTruncation: {
727 assert(SubExpr->getType()->isVectorType());
728 if (OptPrimType ResultT = classify(E)) {
729 assert(!DiscardResult);
730 // Result must be either a float or integer. Take the first element.
731 if (!this->visit(SubExpr))
732 return false;
733 return this->emitArrayElemPop(*ResultT, 0, E);
734 }
735 // Otherwise, this truncates from one vector type to another.
736 assert(E->getType()->isVectorType());
737
738 if (!Initializing) {
739 UnsignedOrNone LocalIndex = allocateTemporary(E);
740 if (!LocalIndex)
741 return false;
742 if (!this->emitGetPtrLocal(*LocalIndex, E))
743 return false;
744 }
745 unsigned ToSize = E->getType()->getAs<VectorType>()->getNumElements();
746 assert(SubExpr->getType()->getAs<VectorType>()->getNumElements() > ToSize);
747 if (!this->visit(SubExpr))
748 return false;
749 return this->emitCopyArray(classifyVectorElementType(E->getType()), 0, 0,
750 ToSize, E);
751 };
752
753 case CK_IntegralToFixedPoint: {
754 if (!this->visit(SubExpr))
755 return false;
756
757 auto Sem =
758 Ctx.getASTContext().getFixedPointSemantics(E->getType()).toOpaqueInt();
759 if (!this->emitCastIntegralFixedPoint(classifyPrim(SubExpr->getType()), Sem,
760 E))
761 return false;
762 if (DiscardResult)
763 return this->emitPopFixedPoint(E);
764 return true;
765 }
766 case CK_FloatingToFixedPoint: {
767 if (!this->visit(SubExpr))
768 return false;
769
770 auto Sem =
771 Ctx.getASTContext().getFixedPointSemantics(E->getType()).toOpaqueInt();
772 if (!this->emitCastFloatingFixedPoint(Sem, E))
773 return false;
774 if (DiscardResult)
775 return this->emitPopFixedPoint(E);
776 return true;
777 }
778 case CK_FixedPointToFloating: {
779 if (!this->visit(SubExpr))
780 return false;
781 const auto *TargetSemantics = &Ctx.getFloatSemantics(E->getType());
782 if (!this->emitCastFixedPointFloating(TargetSemantics, E))
783 return false;
784 if (DiscardResult)
785 return this->emitPopFloat(E);
786 return true;
787 }
788 case CK_FixedPointToIntegral: {
789 if (!this->visit(SubExpr))
790 return false;
791 PrimType IntegralT = classifyPrim(E->getType());
792 if (!this->emitCastFixedPointIntegral(IntegralT, E))
793 return false;
794 if (DiscardResult)
795 return this->emitPop(IntegralT, E);
796 return true;
797 }
798 case CK_FixedPointCast: {
799 if (!this->visit(SubExpr))
800 return false;
801 auto Sem =
802 Ctx.getASTContext().getFixedPointSemantics(E->getType()).toOpaqueInt();
803 if (!this->emitCastFixedPoint(Sem, E))
804 return false;
805 if (DiscardResult)
806 return this->emitPopFixedPoint(E);
807 return true;
808 }
809
810 case CK_ToVoid:
811 return discard(SubExpr);
812
813 case CK_Dynamic:
814 llvm_unreachable("CXXDynamicCastExpr has its own function");
815
816 case CK_LValueBitCast:
817 if (!this->emitInvalidCast(CastKind::ReinterpretLike, /*Fatal=*/false, E))
818 return false;
819 return this->delegate(SubExpr);
820
821 case CK_HLSLArrayRValue: {
822 // Non-decaying array rvalue cast - creates an rvalue copy of an lvalue
823 // array, similar to LValueToRValue for composite types.
824 if (!Initializing) {
825 UnsignedOrNone LocalIndex = allocateLocal(E);
826 if (!LocalIndex)
827 return false;
828 if (!this->emitGetPtrLocal(*LocalIndex, E))
829 return false;
830 }
831 if (!this->visit(SubExpr))
832 return false;
833 return this->emitMemcpy(E);
834 }
835
836 case CK_HLSLMatrixTruncation: {
837 assert(SubExpr->getType()->isConstantMatrixType());
838 if (OptPrimType ResultT = classify(E)) {
839 assert(!DiscardResult);
840 // Result must be either a float or integer. Take the first element.
841 if (!this->visit(SubExpr))
842 return false;
843 return this->emitArrayElemPop(*ResultT, 0, E);
844 }
845 // Otherwise, this truncates to a a constant matrix type.
846 assert(E->getType()->isConstantMatrixType());
847
848 if (!Initializing) {
849 UnsignedOrNone LocalIndex = allocateTemporary(E);
850 if (!LocalIndex)
851 return false;
852 if (!this->emitGetPtrLocal(*LocalIndex, E))
853 return false;
854 }
855 unsigned ToSize =
856 E->getType()->getAs<ConstantMatrixType>()->getNumElementsFlattened();
857 if (!this->visit(SubExpr))
858 return false;
859 return this->emitCopyArray(classifyMatrixElementType(SubExpr->getType()), 0,
860 0, ToSize, E);
861 }
862
863 case CK_HLSLAggregateSplatCast: {
864 // Aggregate splat cast: convert a scalar value to one of an aggregate type
865 // by replicating and casting the scalar to every element of the destination
866 // aggregate (vector, matrix, array, or struct).
867 assert(canClassify(SubExpr->getType()));
868
869 if (!Initializing) {
870 UnsignedOrNone LocalIndex = allocateLocal(E);
871 if (!LocalIndex)
872 return false;
873 if (!this->emitGetPtrLocal(*LocalIndex, E))
874 return false;
875 }
876
877 // The scalar to be splatted is stored in a local to be repeatedly loaded
878 // once for every scalar element of the destination.
879 PrimType SrcElemT = classifyPrim(SubExpr->getType());
880 unsigned SrcOffset =
881 allocateLocalPrimitive(SubExpr, SrcElemT, /*IsConst=*/true);
882
883 if (!this->visit(SubExpr))
884 return false;
885 if (!this->emitSetLocal(SrcElemT, SrcOffset, E))
886 return false;
887
888 // Recursively splat the scalar into every element of the destination.
889 return emitHLSLAggregateSplat(SrcElemT, SrcOffset, E->getType(), E);
890 }
891
892 case CK_HLSLElementwiseCast: {
893 // Elementwise cast: flatten the elements of one aggregate source type and
894 // store to a destination scalar or aggregate type of the same or fewer
895 // number of elements. Casts are inserted element-wise to convert each
896 // source scalar element to its corresponding destination scalar element.
897 QualType SrcType = SubExpr->getType();
898 QualType DestType = E->getType();
899
900 if (OptPrimType DestT = classify(DestType)) {
901 // When the destination is a scalar, we only need the first scalar
902 // element of the source.
903 unsigned SrcPtrOffset =
904 allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
905 if (!this->visit(SubExpr))
906 return false;
907 if (!this->emitSetLocal(PT_Ptr, SrcPtrOffset, E))
908 return false;
909
911 if (!emitHLSLFlattenAggregate(SrcType, SrcPtrOffset, Elements, 1, E))
912 return false;
913 if (Elements.empty())
914 return false;
915
916 const HLSLFlatElement &Src = Elements[0];
917 if (!this->emitGetLocal(Src.Type, Src.LocalOffset, E))
918 return false;
919 return this->emitPrimCast(Src.Type, *DestT, DestType, E);
920 }
921
922 if (!Initializing) {
923 UnsignedOrNone LocalIndex = allocateLocal(E);
924 if (!LocalIndex)
925 return false;
926 if (!this->emitGetPtrLocal(*LocalIndex, E))
927 return false;
928 }
929
930 unsigned SrcOffset =
931 allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
932 if (!this->visit(SubExpr))
933 return false;
934 if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
935 return false;
936
937 // Only flatten as many source elements as the destination requires.
938 unsigned ElemCount = countHLSLFlatElements(DestType);
939
941 Elements.reserve(ElemCount);
942 if (!emitHLSLFlattenAggregate(SrcType, SrcOffset, Elements, ElemCount, E))
943 return false;
944
945 // Sema is expected to reject an elementwise cast whose source has fewer
946 // scalar elements than the destination.
947 assert(Elements.size() == ElemCount &&
948 "Source type has fewer scalar elements than the destination type");
949
950 return emitHLSLConstructAggregate(DestType, Elements, E);
951 }
952
953 case CK_ToUnion: {
954 const FieldDecl *UnionField = E->getTargetUnionField();
955 const Record *R = this->getRecord(E->getType());
956 assert(R);
957 const Record::Field *RF = R->getField(UnionField);
958 QualType FieldType = RF->Decl->getType();
959
960 if (OptPrimType PT = classify(FieldType)) {
961 if (!this->visit(SubExpr))
962 return false;
963 if (RF->isBitField())
964 return this->emitInitBitFieldActivate(*PT, RF->Offset, RF->bitWidth(),
965 E);
966 return this->emitInitFieldActivate(*PT, RF->Offset, E);
967 }
968
969 if (!this->emitGetPtrField(RF->Offset, E))
970 return false;
971 if (!this->emitActivate(E))
972 return false;
973 return this->visitInitializerPop(SubExpr);
974 }
975
976 default:
977 return this->emitInvalid(E);
978 }
979 llvm_unreachable("Unhandled clang::CastKind enum");
980}
981
982template <class Emitter>
984 return this->emitBuiltinBitCast(E);
985}
986
987template <class Emitter>
989 if (DiscardResult)
990 return true;
991
992 return this->emitConst(LE->getValue(), LE);
993}
994
995template <class Emitter>
997 if (DiscardResult)
998 return true;
999
1000 APFloat F = E->getValue();
1001 return this->emitFloat(F, E);
1002}
1003
1004template <class Emitter>
1006 assert(E->getType()->isAnyComplexType());
1007 if (DiscardResult)
1008 return true;
1009
1010 if (!Initializing) {
1011 UnsignedOrNone LocalIndex = allocateTemporary(E);
1012 if (!LocalIndex)
1013 return false;
1014 if (!this->emitGetPtrLocal(*LocalIndex, E))
1015 return false;
1016 }
1017
1018 const Expr *SubExpr = E->getSubExpr();
1019 PrimType SubExprT = classifyPrim(SubExpr->getType());
1020
1021 if (!this->visitZeroInitializer(SubExprT, SubExpr->getType(), SubExpr))
1022 return false;
1023 if (!this->emitInitElem(SubExprT, 0, SubExpr))
1024 return false;
1025 return this->visitArrayElemInit(1, SubExpr, SubExprT);
1026}
1027
1028template <class Emitter>
1030 assert(E->getType()->isFixedPointType());
1031 assert(classifyPrim(E) == PT_FixedPoint);
1032
1033 if (DiscardResult)
1034 return true;
1035
1036 auto Sem = Ctx.getASTContext().getFixedPointSemantics(E->getType());
1037 APInt Value = E->getValue();
1038 return this->emitConstFixedPoint(FixedPoint(Value, Sem), E);
1039}
1040
1041template <class Emitter>
1043 return this->delegate(E->getSubExpr());
1044}
1045
1046template <class Emitter>
1048 // Need short-circuiting for these.
1049 if (E->isLogicalOp() && !E->getType()->isVectorType())
1050 return this->VisitLogicalBinOp(E);
1051
1052 const Expr *LHS = E->getLHS();
1053 const Expr *RHS = E->getRHS();
1054
1055 // Handle comma operators. Just discard the LHS
1056 // and delegate to RHS.
1057 if (E->isCommaOp()) {
1058 if (!this->discard(LHS))
1059 return false;
1060 if (RHS->getType()->isVoidType())
1061 return this->discard(RHS);
1062
1063 return this->delegate(RHS);
1064 }
1065
1066 if (E->getType()->isAnyComplexType())
1067 return this->VisitComplexBinOp(E);
1068 if (E->getType()->isVectorType())
1069 return this->VisitVectorBinOp(E);
1070 if ((LHS->getType()->isAnyComplexType() ||
1071 RHS->getType()->isAnyComplexType()) &&
1072 E->isComparisonOp())
1073 return this->emitComplexComparison(LHS, RHS, E);
1074 if (LHS->getType()->isFixedPointType() || RHS->getType()->isFixedPointType())
1075 return this->VisitFixedPointBinOp(E);
1076
1077 if (E->isPtrMemOp()) {
1078 if (E->containsErrors())
1079 return false;
1080
1081 if (!this->visit(LHS))
1082 return false;
1083
1084 if (!this->visit(RHS))
1085 return false;
1086
1087 if (!this->emitToMemberPtr(E))
1088 return false;
1089
1090 if (classifyPrim(E) == PT_MemberPtr)
1091 return true;
1092
1093 if (!this->emitCastMemberPtrPtr(E))
1094 return false;
1095 return DiscardResult ? this->emitPopPtr(E) : true;
1096 }
1097
1098 // Typecheck the args.
1099 OptPrimType LT = classify(LHS);
1100 OptPrimType RT = classify(RHS);
1101 OptPrimType T = classify(E->getType());
1102
1103 // Special case for C++'s three-way/spaceship operator <=>, which
1104 // returns a std::{strong,weak,partial}_ordering (which is a class, so doesn't
1105 // have a PrimType).
1106 if (!T && E->getOpcode() == BO_Cmp) {
1107 if (DiscardResult)
1108 return true;
1109 const ComparisonCategoryInfo *CmpInfo =
1110 Ctx.getASTContext().CompCategories.lookupInfoForType(E->getType());
1111 assert(CmpInfo);
1112
1113 // We need a temporary variable holding our return value.
1114 if (!Initializing) {
1115 UnsignedOrNone ResultIndex = this->allocateLocal(E);
1116 if (!this->emitGetPtrLocal(*ResultIndex, E))
1117 return false;
1118 }
1119
1120 if (!visit(LHS) || !visit(RHS))
1121 return false;
1122
1123 return this->emitCMP3(*LT, CmpInfo, E);
1124 }
1125
1126 if (!LT || !RT || !T)
1127 return false;
1128
1129 // Pointer arithmetic special case.
1130 if (E->getOpcode() == BO_Add || E->getOpcode() == BO_Sub) {
1131 if (isPtrType(*T) || (isPtrType(*LT) && isPtrType(*RT)))
1132 return this->VisitPointerArithBinOp(E);
1133 }
1134
1135 if (E->getOpcode() == BO_Assign)
1136 return this->visitAssignment(LHS, RHS, E);
1137
1138 if (!visit(LHS) || !visit(RHS))
1139 return false;
1140
1141 // For languages such as C, cast the result of one
1142 // of our comparision opcodes to T (which is usually int).
1143 auto MaybeCastToBool = [this, T, E](bool Result) {
1144 if (!Result)
1145 return false;
1146 if (DiscardResult)
1147 return this->emitPopBool(E);
1148 if (T != PT_Bool)
1149 return this->emitCast(PT_Bool, *T, E);
1150 return true;
1151 };
1152
1153 auto Discard = [this, T, E](bool Result) {
1154 if (!Result)
1155 return false;
1156 return DiscardResult ? this->emitPop(*T, E) : true;
1157 };
1158
1159 switch (E->getOpcode()) {
1160 case BO_EQ:
1161 return MaybeCastToBool(this->emitEQ(*LT, E));
1162 case BO_NE:
1163 return MaybeCastToBool(this->emitNE(*LT, E));
1164 case BO_LT:
1165 return MaybeCastToBool(this->emitLT(*LT, E));
1166 case BO_LE:
1167 return MaybeCastToBool(this->emitLE(*LT, E));
1168 case BO_GT:
1169 return MaybeCastToBool(this->emitGT(*LT, E));
1170 case BO_GE:
1171 return MaybeCastToBool(this->emitGE(*LT, E));
1172 case BO_Sub:
1173 if (E->getType()->isFloatingType())
1174 return Discard(this->emitSubf(getFPOptions(E), E));
1175 return Discard(this->emitSub(*T, E));
1176 case BO_Add:
1177 if (E->getType()->isFloatingType())
1178 return Discard(this->emitAddf(getFPOptions(E), E));
1179 return Discard(this->emitAdd(*T, E));
1180 case BO_Mul:
1181 if (E->getType()->isFloatingType())
1182 return Discard(this->emitMulf(getFPOptions(E), E));
1183 return Discard(this->emitMul(*T, E));
1184 case BO_Rem:
1185 return Discard(this->emitRem(*T, E));
1186 case BO_Div:
1187 if (E->getType()->isFloatingType())
1188 return Discard(this->emitDivf(getFPOptions(E), E));
1189 return Discard(this->emitDiv(*T, E));
1190 case BO_And:
1191 return Discard(this->emitBitAnd(*T, E));
1192 case BO_Or:
1193 return Discard(this->emitBitOr(*T, E));
1194 case BO_Shl:
1195 return Discard(this->emitShl(*LT, *RT, E));
1196 case BO_Shr:
1197 return Discard(this->emitShr(*LT, *RT, E));
1198 case BO_Xor:
1199 return Discard(this->emitBitXor(*T, E));
1200 case BO_LOr:
1201 case BO_LAnd:
1202 llvm_unreachable("Already handled earlier");
1203 default:
1204 return false;
1205 }
1206
1207 llvm_unreachable("Unhandled binary op");
1208}
1209
1210/// Perform addition/subtraction of a pointer and an integer or
1211/// subtraction of two pointers.
1212template <class Emitter>
1214 BinaryOperatorKind Op = E->getOpcode();
1215 const Expr *LHS = E->getLHS();
1216 const Expr *RHS = E->getRHS();
1217
1218 if ((Op != BO_Add && Op != BO_Sub) ||
1219 (!LHS->getType()->isPointerType() && !RHS->getType()->isPointerType()))
1220 return false;
1221
1222 OptPrimType LT = classify(LHS);
1223 OptPrimType RT = classify(RHS);
1224
1225 if (!LT || !RT)
1226 return false;
1227
1228 // Visit the given pointer expression and optionally convert to a PT_Ptr.
1229 auto visitAsPointer = [&](const Expr *E, PrimType T) -> bool {
1230 if (!this->visit(E))
1231 return false;
1232 if (T != PT_Ptr)
1233 return this->emitDecayPtr(T, PT_Ptr, E);
1234 return true;
1235 };
1236
1237 if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) {
1238 if (Op != BO_Sub)
1239 return false;
1240
1241 assert(E->getType()->isIntegerType());
1242 if (!visitAsPointer(RHS, *RT) || !visitAsPointer(LHS, *LT))
1243 return false;
1244
1245 QualType ElemType = LHS->getType()->getPointeeType();
1246 CharUnits ElemTypeSize;
1247 if (ElemType->isVoidType() || ElemType->isFunctionType())
1248 ElemTypeSize = CharUnits::One();
1249 else
1250 ElemTypeSize = Ctx.getASTContext().getTypeSizeInChars(ElemType);
1251
1252 PrimType IntT = classifyPrim(E->getType());
1253 if (!this->emitSubPtr(IntT, ElemTypeSize.getQuantity(), E))
1254 return false;
1255 return DiscardResult ? this->emitPop(IntT, E) : true;
1256 }
1257
1258 PrimType OffsetType;
1259 if (LHS->getType()->isIntegerType()) {
1260 if (!visitAsPointer(RHS, *RT))
1261 return false;
1262 if (!this->visit(LHS))
1263 return false;
1264 OffsetType = *LT;
1265 } else if (RHS->getType()->isIntegerType()) {
1266 if (!visitAsPointer(LHS, *LT))
1267 return false;
1268 if (!this->visit(RHS))
1269 return false;
1270 OffsetType = *RT;
1271 } else {
1272 return false;
1273 }
1274
1275 // Do the operation and optionally transform to
1276 // result pointer type.
1277 switch (Op) {
1278 case BO_Add:
1279 if (!this->emitAddOffset(OffsetType, E))
1280 return false;
1281 break;
1282 case BO_Sub:
1283 if (!this->emitSubOffset(OffsetType, E))
1284 return false;
1285 break;
1286 default:
1287 return false;
1288 }
1289
1290 if (classifyPrim(E) != PT_Ptr) {
1291 if (!this->emitDecayPtr(PT_Ptr, classifyPrim(E), E))
1292 return false;
1293 }
1294
1295 if (DiscardResult)
1296 return this->emitPop(classifyPrim(E), E);
1297 return true;
1298}
1299
1300template <class Emitter>
1302 assert(E->isLogicalOp());
1303 BinaryOperatorKind Op = E->getOpcode();
1304 const Expr *LHS = E->getLHS();
1305 const Expr *RHS = E->getRHS();
1306 OptPrimType T = classify(E->getType());
1307
1308 if (Op == BO_LOr) {
1309 // Logical OR. Visit LHS and only evaluate RHS if LHS was FALSE.
1310 LabelTy LabelTrue = this->getLabel();
1311 LabelTy LabelEnd = this->getLabel();
1312
1313 if (!this->visitBool(LHS))
1314 return false;
1315 if (!this->jumpTrue(LabelTrue, E))
1316 return false;
1317
1318 if (!this->visitBool(RHS))
1319 return false;
1320 if (!this->jump(LabelEnd, E))
1321 return false;
1322
1323 this->emitLabel(LabelTrue);
1324 this->emitConstBool(true, E);
1325 this->fallthrough(LabelEnd);
1326 this->emitLabel(LabelEnd);
1327
1328 } else {
1329 assert(Op == BO_LAnd);
1330 // Logical AND.
1331 // Visit LHS. Only visit RHS if LHS was TRUE.
1332 LabelTy LabelFalse = this->getLabel();
1333 LabelTy LabelEnd = this->getLabel();
1334
1335 if (!this->visitBool(LHS))
1336 return false;
1337 if (!this->jumpFalse(LabelFalse, E))
1338 return false;
1339
1340 if (!this->visitBool(RHS))
1341 return false;
1342 if (!this->jump(LabelEnd, E))
1343 return false;
1344
1345 this->emitLabel(LabelFalse);
1346 this->emitConstBool(false, E);
1347 this->fallthrough(LabelEnd);
1348 this->emitLabel(LabelEnd);
1349 }
1350
1351 if (DiscardResult)
1352 return this->emitPopBool(E);
1353
1354 // For C, cast back to integer type.
1355 assert(T);
1356 if (T != PT_Bool)
1357 return this->emitCast(PT_Bool, *T, E);
1358 return true;
1359}
1360
1361template <class Emitter>
1363 // Prepare storage for result.
1364 if (!Initializing) {
1365 UnsignedOrNone LocalIndex = allocateTemporary(E);
1366 if (!LocalIndex)
1367 return false;
1368 if (!this->emitGetPtrLocal(*LocalIndex, E))
1369 return false;
1370 }
1371
1372 // Both LHS and RHS might _not_ be of complex type, but one of them
1373 // needs to be.
1374 const Expr *LHS = E->getLHS();
1375 const Expr *RHS = E->getRHS();
1376
1377 PrimType ResultElemT = this->classifyComplexElementType(E->getType());
1378 unsigned ResultOffset = ~0u;
1379 if (!DiscardResult)
1380 ResultOffset = this->allocateLocalPrimitive(E, PT_Ptr, /*IsConst=*/true);
1381
1382 // Save result pointer in ResultOffset
1383 if (!this->DiscardResult) {
1384 if (!this->emitDupPtr(E))
1385 return false;
1386 if (!this->emitSetLocal(PT_Ptr, ResultOffset, E))
1387 return false;
1388 }
1389 QualType LHSType = LHS->getType();
1390 if (const auto *AT = LHSType->getAs<AtomicType>())
1391 LHSType = AT->getValueType();
1392 QualType RHSType = RHS->getType();
1393 if (const auto *AT = RHSType->getAs<AtomicType>())
1394 RHSType = AT->getValueType();
1395
1396 bool LHSIsComplex = LHSType->isAnyComplexType();
1397 unsigned LHSOffset;
1398 bool RHSIsComplex = RHSType->isAnyComplexType();
1399
1400 // For ComplexComplex Mul, we have special ops to make their implementation
1401 // easier.
1402 BinaryOperatorKind Op = E->getOpcode();
1403 if (Op == BO_Mul && LHSIsComplex && RHSIsComplex) {
1404 assert(classifyPrim(LHSType->getAs<ComplexType>()->getElementType()) ==
1406 PrimType ElemT =
1408 if (!this->visit(LHS))
1409 return false;
1410 if (!this->visit(RHS))
1411 return false;
1412 if (!this->emitMulc(ElemT, E))
1413 return false;
1414 if (DiscardResult)
1415 return this->emitPopPtr(E);
1416 return true;
1417 }
1418
1419 if (Op == BO_Div && RHSIsComplex) {
1420 QualType ElemQT = RHSType->getAs<ComplexType>()->getElementType();
1421 PrimType ElemT = classifyPrim(ElemQT);
1422 // If the LHS is not complex, we still need to do the full complex
1423 // division, so just stub create a complex value and stub it out with
1424 // the LHS and a zero.
1425
1426 if (!LHSIsComplex) {
1427 // This is using the RHS type for the fake-complex LHS.
1428 UnsignedOrNone LocalIndex = allocateTemporary(RHS);
1429 if (!LocalIndex)
1430 return false;
1431 LHSOffset = *LocalIndex;
1432
1433 if (!this->emitGetPtrLocal(LHSOffset, E))
1434 return false;
1435
1436 if (!this->visit(LHS))
1437 return false;
1438 // real is LHS
1439 if (!this->emitInitElem(ElemT, 0, E))
1440 return false;
1441 // imag is zero
1442 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1443 return false;
1444 if (!this->emitInitElem(ElemT, 1, E))
1445 return false;
1446 } else {
1447 if (!this->visit(LHS))
1448 return false;
1449 }
1450
1451 if (!this->visit(RHS))
1452 return false;
1453 if (!this->emitDivc(ElemT, E))
1454 return false;
1455 if (DiscardResult)
1456 return this->emitPopPtr(E);
1457 return true;
1458 }
1459
1460 // Evaluate LHS and save value to LHSOffset.
1461 if (LHSType->isAnyComplexType()) {
1462 LHSOffset = this->allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
1463 if (!this->visit(LHS))
1464 return false;
1465 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
1466 return false;
1467 } else {
1468 PrimType LHST = classifyPrim(LHSType);
1469 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, /*IsConst=*/true);
1470 if (!this->visit(LHS))
1471 return false;
1472 if (!this->emitSetLocal(LHST, LHSOffset, E))
1473 return false;
1474 }
1475
1476 // Same with RHS.
1477 unsigned RHSOffset;
1478 if (RHSType->isAnyComplexType()) {
1479 RHSOffset = this->allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
1480 if (!this->visit(RHS))
1481 return false;
1482 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
1483 return false;
1484 } else {
1485 PrimType RHST = classifyPrim(RHSType);
1486 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, /*IsConst=*/true);
1487 if (!this->visit(RHS))
1488 return false;
1489 if (!this->emitSetLocal(RHST, RHSOffset, E))
1490 return false;
1491 }
1492
1493 // For both LHS and RHS, either load the value from the complex pointer, or
1494 // directly from the local variable. For index 1 (i.e. the imaginary part),
1495 // just load 0 and do the operation anyway.
1496 auto loadComplexValue = [this](bool IsComplex, bool LoadZero,
1497 unsigned ElemIndex, unsigned Offset,
1498 const Expr *E) -> bool {
1499 if (IsComplex) {
1500 if (!this->emitGetLocal(PT_Ptr, Offset, E))
1501 return false;
1502 return this->emitArrayElemPop(classifyComplexElementType(E->getType()),
1503 ElemIndex, E);
1504 }
1505 if (ElemIndex == 0 || !LoadZero)
1506 return this->emitGetLocal(classifyPrim(E->getType()), Offset, E);
1507 return this->visitZeroInitializer(classifyPrim(E->getType()), E->getType(),
1508 E);
1509 };
1510
1511 // Now we can get pointers to the LHS and RHS from the offsets above.
1512 for (unsigned ElemIndex = 0; ElemIndex != 2; ++ElemIndex) {
1513 // Result pointer for the store later.
1514 if (!this->DiscardResult) {
1515 if (!this->emitGetLocal(PT_Ptr, ResultOffset, E))
1516 return false;
1517 }
1518
1519 // The actual operation.
1520 switch (Op) {
1521 case BO_Add:
1522 if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1523 return false;
1524
1525 if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1526 return false;
1527 if (ResultElemT == PT_Float) {
1528 if (!this->emitAddf(getFPOptions(E), E))
1529 return false;
1530 } else {
1531 if (!this->emitAdd(ResultElemT, E))
1532 return false;
1533 }
1534 break;
1535 case BO_Sub:
1536 if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS))
1537 return false;
1538
1539 if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS))
1540 return false;
1541 if (ResultElemT == PT_Float) {
1542 if (!this->emitSubf(getFPOptions(E), E))
1543 return false;
1544 } else {
1545 if (!this->emitSub(ResultElemT, E))
1546 return false;
1547 }
1548 break;
1549 case BO_Mul:
1550 if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1551 return false;
1552
1553 if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1554 return false;
1555
1556 if (ResultElemT == PT_Float) {
1557 if (!this->emitMulf(getFPOptions(E), E))
1558 return false;
1559 } else {
1560 if (!this->emitMul(ResultElemT, E))
1561 return false;
1562 }
1563 break;
1564 case BO_Div:
1565 assert(!RHSIsComplex);
1566 if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS))
1567 return false;
1568
1569 if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS))
1570 return false;
1571
1572 if (ResultElemT == PT_Float) {
1573 if (!this->emitDivf(getFPOptions(E), E))
1574 return false;
1575 } else {
1576 if (!this->emitDiv(ResultElemT, E))
1577 return false;
1578 }
1579 break;
1580
1581 default:
1582 return false;
1583 }
1584
1585 if (!this->DiscardResult) {
1586 // Initialize array element with the value we just computed.
1587 if (!this->emitInitElemPop(ResultElemT, ElemIndex, E))
1588 return false;
1589 } else {
1590 if (!this->emitPop(ResultElemT, E))
1591 return false;
1592 // Remove the Complex temporary pointer we created ourselves at the
1593 // beginning of this function.
1594 if (!Initializing)
1595 return this->emitPopPtr(E);
1596 }
1597 }
1598 return true;
1599}
1600
1601template <class Emitter>
1603 const Expr *LHS = E->getLHS();
1604 const Expr *RHS = E->getRHS();
1605 assert(!E->isCommaOp() &&
1606 "Comma op should be handled in VisitBinaryOperator");
1607 assert(E->getType()->isVectorType());
1608 assert(LHS->getType()->isVectorType());
1609 assert(RHS->getType()->isVectorType());
1610
1611 // We can only handle vectors with primitive element types.
1613 return false;
1614
1615 // Prepare storage for result.
1616 if (!Initializing && !E->isCompoundAssignmentOp() && !E->isAssignmentOp()) {
1617 UnsignedOrNone LocalIndex = allocateTemporary(E);
1618 if (!LocalIndex)
1619 return false;
1620 if (!this->emitGetPtrLocal(*LocalIndex, E))
1621 return false;
1622 }
1623
1624 const auto *VecTy = E->getType()->getAs<VectorType>();
1625 auto Op = E->isCompoundAssignmentOp()
1627 : E->getOpcode();
1628
1629 PrimType ElemT = this->classifyVectorElementType(LHS->getType());
1630 PrimType RHSElemT = this->classifyVectorElementType(RHS->getType());
1631 PrimType ResultElemT = this->classifyVectorElementType(E->getType());
1632
1633 if (E->getOpcode() == BO_Assign) {
1634 assert(Ctx.getASTContext().hasSameUnqualifiedType(
1636 RHS->getType()->castAs<VectorType>()->getElementType()));
1637 if (!this->visit(LHS))
1638 return false;
1639 if (!this->visit(RHS))
1640 return false;
1641 if (!this->emitCopyArray(ElemT, 0, 0, VecTy->getNumElements(), E))
1642 return false;
1643 if (DiscardResult)
1644 return this->emitPopPtr(E);
1645 return true;
1646 }
1647
1648 // Evaluate LHS and save value to LHSOffset.
1649 unsigned LHSOffset =
1650 this->allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
1651 if (!this->visit(LHS))
1652 return false;
1653 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
1654 return false;
1655
1656 // Evaluate RHS and save value to RHSOffset.
1657 unsigned RHSOffset =
1658 this->allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
1659 if (!this->visit(RHS))
1660 return false;
1661 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
1662 return false;
1663
1664 if (E->isCompoundAssignmentOp() && !this->emitGetLocal(PT_Ptr, LHSOffset, E))
1665 return false;
1666
1667 // BitAdd/BitOr/BitXor/Shl/Shr doesn't support bool type, we need perform the
1668 // integer promotion.
1669 bool NeedIntPromot = ElemT == PT_Bool && (E->isBitwiseOp() || E->isShiftOp());
1670 QualType PromotTy;
1671 PrimType PromotT = PT_Bool;
1672 PrimType OpT = ElemT;
1673 if (NeedIntPromot) {
1674 PromotTy =
1675 Ctx.getASTContext().getPromotedIntegerType(Ctx.getASTContext().BoolTy);
1676 PromotT = classifyPrim(PromotTy);
1677 OpT = PromotT;
1678 }
1679
1680 auto getElem = [=](unsigned Offset, PrimType ElemT, unsigned Index) {
1681 if (!this->emitGetLocal(PT_Ptr, Offset, E))
1682 return false;
1683 if (!this->emitArrayElemPop(ElemT, Index, E))
1684 return false;
1685 if (E->isLogicalOp()) {
1686 if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
1687 return false;
1688 if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), E))
1689 return false;
1690 } else if (NeedIntPromot) {
1691 if (!this->emitPrimCast(ElemT, PromotT, PromotTy, E))
1692 return false;
1693 }
1694 return true;
1695 };
1696
1697#define EMIT_ARITH_OP(OP) \
1698 { \
1699 if (ElemT == PT_Float) { \
1700 if (!this->emit##OP##f(getFPOptions(E), E)) \
1701 return false; \
1702 } else { \
1703 if (!this->emit##OP(ElemT, E)) \
1704 return false; \
1705 } \
1706 break; \
1707 }
1708
1709 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
1710 if (!getElem(LHSOffset, ElemT, I))
1711 return false;
1712 if (!getElem(RHSOffset, RHSElemT, I))
1713 return false;
1714 switch (Op) {
1715 case BO_Add:
1717 case BO_Sub:
1719 case BO_Mul:
1721 case BO_Div:
1723 case BO_Rem:
1724 if (!this->emitRem(ElemT, E))
1725 return false;
1726 break;
1727 case BO_And:
1728 if (!this->emitBitAnd(OpT, E))
1729 return false;
1730 break;
1731 case BO_Or:
1732 if (!this->emitBitOr(OpT, E))
1733 return false;
1734 break;
1735 case BO_Xor:
1736 if (!this->emitBitXor(OpT, E))
1737 return false;
1738 break;
1739 case BO_Shl:
1740 if (!this->emitShl(OpT, RHSElemT, E))
1741 return false;
1742 break;
1743 case BO_Shr:
1744 if (!this->emitShr(OpT, RHSElemT, E))
1745 return false;
1746 break;
1747 case BO_EQ:
1748 if (!this->emitEQ(ElemT, E))
1749 return false;
1750 break;
1751 case BO_NE:
1752 if (!this->emitNE(ElemT, E))
1753 return false;
1754 break;
1755 case BO_LE:
1756 if (!this->emitLE(ElemT, E))
1757 return false;
1758 break;
1759 case BO_LT:
1760 if (!this->emitLT(ElemT, E))
1761 return false;
1762 break;
1763 case BO_GE:
1764 if (!this->emitGE(ElemT, E))
1765 return false;
1766 break;
1767 case BO_GT:
1768 if (!this->emitGT(ElemT, E))
1769 return false;
1770 break;
1771 case BO_LAnd:
1772 // a && b is equivalent to a!=0 & b!=0
1773 if (!this->emitBitAnd(ResultElemT, E))
1774 return false;
1775 break;
1776 case BO_LOr:
1777 // a || b is equivalent to a!=0 | b!=0
1778 if (!this->emitBitOr(ResultElemT, E))
1779 return false;
1780 break;
1781 default:
1782 return this->emitInvalid(E);
1783 }
1784
1785 // The result of the comparison is a vector of the same width and number
1786 // of elements as the comparison operands with a signed integral element
1787 // type.
1788 //
1789 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
1790 if (E->isComparisonOp()) {
1791 if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), E))
1792 return false;
1793 if (!this->emitNeg(ResultElemT, E))
1794 return false;
1795 }
1796
1797 // If we performed an integer promotion, we need to cast the compute result
1798 // into result vector element type.
1799 if (NeedIntPromot &&
1800 !this->emitPrimCast(PromotT, ResultElemT, VecTy->getElementType(), E))
1801 return false;
1802
1803 // Initialize array element with the value we just computed.
1804 if (!this->emitInitElem(ResultElemT, I, E))
1805 return false;
1806 }
1807
1808 if (DiscardResult && E->isCompoundAssignmentOp() && !this->emitPopPtr(E))
1809 return false;
1810 return true;
1811}
1812
1813template <class Emitter>
1815 const Expr *LHS = E->getLHS();
1816 const Expr *RHS = E->getRHS();
1817 const ASTContext &ASTCtx = Ctx.getASTContext();
1818
1819 assert(LHS->getType()->isFixedPointType() ||
1820 RHS->getType()->isFixedPointType());
1821
1822 auto LHSSema = ASTCtx.getFixedPointSemantics(LHS->getType());
1823 auto LHSSemaInt = LHSSema.toOpaqueInt();
1824 auto RHSSema = ASTCtx.getFixedPointSemantics(RHS->getType());
1825 auto RHSSemaInt = RHSSema.toOpaqueInt();
1826
1827 if (!this->visit(LHS))
1828 return false;
1829 if (!LHS->getType()->isFixedPointType()) {
1830 if (!this->emitCastIntegralFixedPoint(classifyPrim(LHS->getType()),
1831 LHSSemaInt, E))
1832 return false;
1833 }
1834
1835 if (!this->visit(RHS))
1836 return false;
1837 if (!RHS->getType()->isFixedPointType()) {
1838 if (!this->emitCastIntegralFixedPoint(classifyPrim(RHS->getType()),
1839 RHSSemaInt, E))
1840 return false;
1841 }
1842
1843 // Convert the result to the target semantics.
1844 auto ConvertResult = [&](bool R) -> bool {
1845 if (!R)
1846 return false;
1847 auto ResultSema = ASTCtx.getFixedPointSemantics(E->getType()).toOpaqueInt();
1848 auto CommonSema = LHSSema.getCommonSemantics(RHSSema).toOpaqueInt();
1849 if (ResultSema != CommonSema)
1850 return this->emitCastFixedPoint(ResultSema, E);
1851 return true;
1852 };
1853
1854 auto MaybeCastToBool = [&](bool Result) {
1855 if (!Result)
1856 return false;
1857 PrimType T = classifyPrim(E);
1858 if (DiscardResult)
1859 return this->emitPop(T, E);
1860 if (T != PT_Bool)
1861 return this->emitCast(PT_Bool, T, E);
1862 return true;
1863 };
1864
1865 switch (E->getOpcode()) {
1866 case BO_EQ:
1867 return MaybeCastToBool(this->emitEQFixedPoint(E));
1868 case BO_NE:
1869 return MaybeCastToBool(this->emitNEFixedPoint(E));
1870 case BO_LT:
1871 return MaybeCastToBool(this->emitLTFixedPoint(E));
1872 case BO_LE:
1873 return MaybeCastToBool(this->emitLEFixedPoint(E));
1874 case BO_GT:
1875 return MaybeCastToBool(this->emitGTFixedPoint(E));
1876 case BO_GE:
1877 return MaybeCastToBool(this->emitGEFixedPoint(E));
1878 case BO_Add:
1879 return ConvertResult(this->emitAddFixedPoint(E));
1880 case BO_Sub:
1881 return ConvertResult(this->emitSubFixedPoint(E));
1882 case BO_Mul:
1883 return ConvertResult(this->emitMulFixedPoint(E));
1884 case BO_Div:
1885 return ConvertResult(this->emitDivFixedPoint(E));
1886 case BO_Shl:
1887 return ConvertResult(this->emitShiftFixedPoint(/*Left=*/true, E));
1888 case BO_Shr:
1889 return ConvertResult(this->emitShiftFixedPoint(/*Left=*/false, E));
1890
1891 default:
1892 return this->emitInvalid(E);
1893 }
1894
1895 llvm_unreachable("unhandled binop opcode");
1896}
1897
1898template <class Emitter>
1900 const Expr *SubExpr = E->getSubExpr();
1901 assert(SubExpr->getType()->isFixedPointType());
1902
1903 switch (E->getOpcode()) {
1904 case UO_Plus:
1905 return this->delegate(SubExpr);
1906 case UO_Minus:
1907 if (!this->visit(SubExpr))
1908 return false;
1909 if (!this->emitNegFixedPoint(E))
1910 return false;
1911 if (DiscardResult)
1912 return this->emitPopFixedPoint(E);
1913 return true;
1914 default:
1915 return false;
1916 }
1917
1918 llvm_unreachable("Unhandled unary opcode");
1919}
1920
1921template <class Emitter>
1923 const ImplicitValueInitExpr *E) {
1924 if (DiscardResult)
1925 return true;
1926
1927 QualType QT = E->getType();
1928
1929 if (OptPrimType T = classify(QT))
1930 return this->visitZeroInitializer(*T, QT, E);
1931
1932 if (QT->isRecordType()) {
1933 const RecordDecl *RD = QT->getAsRecordDecl();
1934 assert(RD);
1935 if (RD->isInvalidDecl())
1936 return false;
1937
1938 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD);
1939 CXXRD && CXXRD->getNumVBases() > 0) {
1940 // TODO: Diagnose.
1941 return false;
1942 }
1943
1944 const Record *R = getRecord(QT);
1945 if (!R)
1946 return false;
1947
1948 assert(Initializing);
1949 return this->visitZeroRecordInitializer(R, E);
1950 }
1951
1952 if (QT->isIncompleteArrayType())
1953 return true;
1954
1955 if (QT->isArrayType())
1956 return this->visitZeroArrayInitializer(QT, E);
1957
1958 if (const auto *ComplexTy = E->getType()->getAs<ComplexType>()) {
1959 assert(Initializing);
1960 QualType ElemQT = ComplexTy->getElementType();
1961 PrimType ElemT = classifyPrim(ElemQT);
1962 for (unsigned I = 0; I < 2; ++I) {
1963 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1964 return false;
1965 if (!this->emitInitElem(ElemT, I, E))
1966 return false;
1967 }
1968 return true;
1969 }
1970
1971 if (const auto *VecT = E->getType()->getAs<VectorType>()) {
1972 unsigned NumVecElements = VecT->getNumElements();
1973 QualType ElemQT = VecT->getElementType();
1974 PrimType ElemT = classifyPrim(ElemQT);
1975
1976 for (unsigned I = 0; I < NumVecElements; ++I) {
1977 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1978 return false;
1979 if (!this->emitInitElem(ElemT, I, E))
1980 return false;
1981 }
1982 return true;
1983 }
1984
1985 if (const auto *MT = E->getType()->getAs<ConstantMatrixType>()) {
1986 unsigned NumElems = MT->getNumElementsFlattened();
1987 QualType ElemQT = MT->getElementType();
1988 PrimType ElemT = classifyPrim(ElemQT);
1989
1990 for (unsigned I = 0; I != NumElems; ++I) {
1991 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
1992 return false;
1993 if (!this->emitInitElem(ElemT, I, E))
1994 return false;
1995 }
1996 return true;
1997 }
1998
1999 return false;
2000}
2001
2002template <class Emitter>
2004 if (E->getType()->isVoidType() || E->containsErrors())
2005 return false;
2006
2007 const Expr *LHS = E->getLHS();
2008 const Expr *RHS = E->getRHS();
2009 const Expr *Index = E->getIdx();
2010 const Expr *Base = E->getBase();
2011
2012 // C++17's rules require us to evaluate the LHS first, regardless of which
2013 // side is the base.
2014 bool Success = true;
2015 for (const Expr *SubExpr : {LHS, RHS}) {
2016 if (!this->visit(SubExpr)) {
2017 Success = false;
2018 continue;
2019 }
2020
2021 // Expand the base if this is a subscript on a
2022 // pointer expression.
2023 if (SubExpr == Base && Base->getType()->isPointerType()) {
2024 if (!this->emitExpandPtr(E))
2025 Success = false;
2026 }
2027 }
2028
2029 if (!Success)
2030 return false;
2031
2032 OptPrimType IndexT = classify(Index->getType());
2033 // In error-recovery cases, the index expression has a dependent type.
2034 if (!IndexT)
2035 return this->emitError(E);
2036 // If the index is first, we need to change that.
2037 if (LHS == Index) {
2038 if (!this->emitFlip(PT_Ptr, *IndexT, E))
2039 return false;
2040 }
2041
2042 if (!this->emitArrayElemPtrPop(*IndexT, E))
2043 return false;
2044 if (DiscardResult)
2045 return this->emitPopPtr(E);
2046
2047 if (E->isGLValue())
2048 return true;
2049
2051 return this->emitLoadPop(*T, E);
2052}
2053
2054template <class Emitter>
2056 const Expr *ArrayFiller, const Expr *E) {
2058
2059 QualType QT = E->getType();
2060 if (const auto *AT = QT->getAs<AtomicType>())
2061 QT = AT->getValueType();
2062
2063 if (QT->isVoidType()) {
2064 if (Inits.size() == 0)
2065 return true;
2066 return this->emitInvalid(E);
2067 }
2068
2069 // Handle discarding first.
2070 if (DiscardResult) {
2071 for (const Expr *Init : Inits) {
2072 if (!this->discard(Init))
2073 return false;
2074 }
2075 return true;
2076 }
2077
2078 // Primitive values.
2079 if (OptPrimType T = classify(QT)) {
2080 assert(!DiscardResult);
2081 if (Inits.size() == 0)
2082 return this->visitZeroInitializer(*T, QT, E);
2083 assert(Inits.size() == 1);
2084 return this->delegate(Inits[0]);
2085 }
2086
2087 if (QT->isRecordType()) {
2088 const Record *R = getRecord(QT);
2089
2090 if (Inits.size() == 1 && E->getType() == Inits[0]->getType())
2091 return this->delegate(Inits[0]);
2092
2093 if (!R)
2094 return false;
2095
2096 auto initPrimitiveField = [=](const Record::Field *FieldToInit,
2097 const Expr *Init, PrimType T,
2098 bool Activate = false) -> bool {
2100 if (!this->visit(Init))
2101 return false;
2102
2103 bool BitField = FieldToInit->isBitField();
2104 if (BitField && Activate)
2105 return this->emitInitBitFieldActivate(T, FieldToInit->Offset,
2106 FieldToInit->bitWidth(), E);
2107 if (BitField)
2108 return this->emitInitBitField(T, FieldToInit->Offset,
2109 FieldToInit->bitWidth(), E);
2110 if (Activate)
2111 return this->emitInitFieldActivate(T, FieldToInit->Offset, E);
2112 return this->emitInitField(T, FieldToInit->Offset, E);
2113 };
2114
2115 auto initCompositeField = [=](const Record::Field *FieldToInit,
2116 const Expr *Init,
2117 bool Activate = false) -> bool {
2119 InitLinkScope<Emitter> ILS(this, InitLink::Field(FieldToInit->Offset));
2120
2121 // Non-primitive case. Get a pointer to the field-to-initialize
2122 // on the stack and recurse into visitInitializer().
2123 if (!this->emitGetPtrField(FieldToInit->Offset, Init))
2124 return false;
2125
2126 if (Activate && !this->emitActivate(E))
2127 return false;
2128
2129 return this->visitInitializerPop(Init);
2130 };
2131
2132 if (R->isUnion()) {
2133 if (Inits.size() == 0) {
2134 if (!this->visitZeroRecordInitializer(R, E))
2135 return false;
2136 } else {
2137 const Expr *Init = Inits[0];
2138 const FieldDecl *FToInit = nullptr;
2139 if (const auto *ILE = dyn_cast<InitListExpr>(E))
2140 FToInit = ILE->getInitializedFieldInUnion();
2141 else
2142 FToInit = cast<CXXParenListInitExpr>(E)->getInitializedFieldInUnion();
2143
2144 const Record::Field *FieldToInit = R->getField(FToInit);
2145 if (OptPrimType T = classify(Init)) {
2146 if (!initPrimitiveField(FieldToInit, Init, *T, /*Activate=*/true))
2147 return false;
2148 } else {
2149 if (!initCompositeField(FieldToInit, Init, /*Activate=*/true))
2150 return false;
2151 }
2152 }
2153 return this->emitFinishInit(E);
2154 }
2155
2156 assert(!R->isUnion());
2157 for (unsigned BI = 0; BI != R->getNumBases(); ++BI) {
2158 const Expr *Init = Inits[BI];
2159 const Record::Base *B = R->getBase(BI);
2160 if (!this->emitGetPtrBase(B->Offset, Init))
2161 return false;
2162 if (!this->visitInitializerPop(Init))
2163 return false;
2164 }
2165
2166 unsigned FieldIndex = 0;
2167 for (unsigned FI = R->getNumBases(); FI != Inits.size();) {
2168 const Record::Field *FieldToInit = R->getField(FieldIndex);
2169 if (FieldToInit->isUnnamedBitField()) {
2170 ++FieldIndex;
2171 continue;
2172 }
2173
2174 const Expr *Init = Inits[FI];
2175 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
2176 // aren't supposed to be modified.
2177 if (isa<NoInitExpr>(Init)) {
2178 ++FieldIndex;
2179 ++FI;
2180 continue;
2181 }
2182
2183 if (OptPrimType T = classify(Init)) {
2184 if (!initPrimitiveField(FieldToInit, Init, *T))
2185 return false;
2186 } else if (!initCompositeField(FieldToInit, Init)) {
2187 return false;
2188 }
2189
2190 ++FI;
2191 ++FieldIndex;
2192 }
2193
2194 assert(R->getNumVirtualBases() == 0);
2195
2196 return this->emitFinishInit(E);
2197 }
2198
2199 if (QT->isArrayType()) {
2200 const ConstantArrayType *CAT =
2201 Ctx.getASTContext().getAsConstantArrayType(QT);
2202 uint64_t NumElems = CAT->getZExtSize();
2203
2204 if (Initializing && !this->emitCheckArrayDestSize(NumElems, E))
2205 return false;
2206
2207 if (Inits.size() == 1 && QT == Inits[0]->getType())
2208 return this->delegate(Inits[0]);
2209
2210 OptPrimType InitT = classify(CAT->getElementType());
2211 unsigned ElementIndex = 0;
2212 for (const Expr *Init : Inits) {
2213 if (const auto *EmbedS =
2214 dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) {
2215 PrimType TargetT = classifyPrim(Init->getType());
2216
2217 auto Eval = [&](const IntegerLiteral *IL, unsigned ElemIndex) {
2218 if (TargetT == PT_Float) {
2219 if (!this->emitConst(IL->getValue(), classifyPrim(IL), Init))
2220 return false;
2221 const auto *Sem = &Ctx.getFloatSemantics(CAT->getElementType());
2222 if (!this->emitCastIntegralFloating(classifyPrim(IL), Sem,
2223 getFPOptions(E), E))
2224 return false;
2225 } else {
2226 if (!this->emitConst(IL->getValue(), TargetT, Init))
2227 return false;
2228 }
2229 return this->emitInitElem(TargetT, ElemIndex, IL);
2230 };
2231 if (!EmbedS->doForEachDataElement(Eval, ElementIndex))
2232 return false;
2233 } else if (isa<NoInitExpr>(Init)) {
2234 // If this is a child of a DesignatedInitUpdateExpr, skip elements which
2235 // aren't supposed to be modified.
2236 ++ElementIndex;
2237 } else {
2238 if (!this->visitArrayElemInit(ElementIndex, Init, InitT))
2239 return false;
2240 ++ElementIndex;
2241 }
2242 }
2243
2244 // Expand the filler expression.
2245 // FIXME: This should go away.
2246 if (ArrayFiller && !isa<NoInitExpr>(ArrayFiller)) {
2247 for (; ElementIndex != NumElems; ++ElementIndex) {
2248 if (!this->visitArrayElemInit(ElementIndex, ArrayFiller, InitT))
2249 return false;
2250 }
2251 }
2252
2253 return this->emitFinishInit(E);
2254 }
2255
2256 if (const auto *ComplexTy = QT->getAs<ComplexType>()) {
2257 unsigned NumInits = Inits.size();
2258
2259 if (NumInits == 1)
2260 return this->delegate(Inits[0]);
2261
2262 QualType ElemQT = ComplexTy->getElementType();
2263 PrimType ElemT = classifyPrim(ElemQT);
2264 if (NumInits == 0) {
2265 // Zero-initialize both elements.
2266 for (unsigned I = 0; I < 2; ++I) {
2267 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2268 return false;
2269 if (!this->emitInitElem(ElemT, I, E))
2270 return false;
2271 }
2272 } else if (NumInits == 2) {
2273 unsigned InitIndex = 0;
2274 for (const Expr *Init : Inits) {
2275 if (!this->visit(Init))
2276 return false;
2277
2278 if (!this->emitInitElem(ElemT, InitIndex, E))
2279 return false;
2280 ++InitIndex;
2281 }
2282 }
2283 return true;
2284 }
2285
2286 if (const auto *VecT = QT->getAs<VectorType>()) {
2287 unsigned NumVecElements = VecT->getNumElements();
2288 assert(NumVecElements >= Inits.size());
2289
2290 QualType ElemQT = VecT->getElementType();
2291 PrimType ElemT = classifyPrim(ElemQT);
2292
2293 // All initializer elements.
2294 unsigned InitIndex = 0;
2295 for (const Expr *Init : Inits) {
2296 if (!this->visit(Init))
2297 return false;
2298
2299 // If the initializer is of vector type itself, we have to deconstruct
2300 // that and initialize all the target fields from the initializer fields.
2301 if (const auto *InitVecT = Init->getType()->getAs<VectorType>()) {
2302 if (!this->emitCopyArray(ElemT, 0, InitIndex,
2303 InitVecT->getNumElements(), E))
2304 return false;
2305 InitIndex += InitVecT->getNumElements();
2306 } else {
2307 if (!this->emitInitElem(ElemT, InitIndex, E))
2308 return false;
2309 ++InitIndex;
2310 }
2311 }
2312
2313 assert(InitIndex <= NumVecElements);
2314
2315 // Fill the rest with zeroes.
2316 for (; InitIndex != NumVecElements; ++InitIndex) {
2317 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
2318 return false;
2319 if (!this->emitInitElem(ElemT, InitIndex, E))
2320 return false;
2321 }
2322 return true;
2323 }
2324
2325 if (const auto *MT = QT->getAs<ConstantMatrixType>()) {
2326 unsigned NumElems = MT->getNumElementsFlattened();
2327 assert(Inits.size() == NumElems);
2328
2329 QualType ElemQT = MT->getElementType();
2330 PrimType ElemT = classifyPrim(ElemQT);
2331
2332 // Matrix initializer list elements are in row-major order, which matches
2333 // the matrix APValue convention and therefore no index remapping is
2334 // required.
2335 for (unsigned I = 0; I != NumElems; ++I) {
2336 if (!this->visit(Inits[I]))
2337 return false;
2338 if (!this->emitInitElem(ElemT, I, E))
2339 return false;
2340 }
2341 return true;
2342 }
2343
2344 return false;
2345}
2346
2347/// Pointer to the array(not the element!) must be on the stack when calling
2348/// this.
2349template <class Emitter>
2350bool Compiler<Emitter>::visitArrayElemInit(unsigned ElemIndex, const Expr *Init,
2351 OptPrimType InitT) {
2352 if (InitT) {
2353 // Visit the primitive element like normal.
2354 if (!this->visit(Init))
2355 return false;
2356 return this->emitInitElem(*InitT, ElemIndex, Init);
2357 }
2358
2359 InitLinkScope<Emitter> ILS(this, InitLink::Elem(ElemIndex));
2360 // Advance the pointer currently on the stack to the given
2361 // dimension.
2362 if (!this->emitConstUint32(ElemIndex, Init))
2363 return false;
2364 if (!this->emitArrayElemPtrUint32(Init))
2365 return false;
2366 return this->visitInitializerPop(Init);
2367}
2368
2369template <class Emitter>
2371 const FunctionDecl *FuncDecl,
2372 bool Activate, bool IsOperatorCall) {
2373 assert(VarScope->getKind() == ScopeKind::Call);
2374 llvm::BitVector NonNullArgs;
2375 if (FuncDecl && FuncDecl->hasAttr<NonNullAttr>())
2376 NonNullArgs = collectNonNullArgs(FuncDecl, Args);
2377
2378 bool ExplicitMemberFn = false;
2379 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl))
2380 ExplicitMemberFn = MD->isExplicitObjectMemberFunction();
2381
2382 unsigned ArgIndex = 0;
2383 for (const Expr *Arg : Args) {
2384 if (canClassify(Arg)) {
2385 if (!this->visit(Arg))
2386 return false;
2387 } else {
2388
2389 DeclTy Source = Arg;
2390 if (FuncDecl) {
2391 // Try to use the parameter declaration instead of the argument
2392 // expression as a source.
2393 unsigned DeclIndex = ArgIndex - IsOperatorCall + ExplicitMemberFn;
2394 if (DeclIndex < FuncDecl->getNumParams())
2395 Source = FuncDecl->getParamDecl(ArgIndex - IsOperatorCall +
2396 ExplicitMemberFn);
2397 }
2398
2399 UnsignedOrNone LocalIndex =
2400 allocateLocal(std::move(Source), Arg->getType(), ScopeKind::Call);
2401 if (!LocalIndex)
2402 return false;
2403
2404 if (!this->emitGetPtrLocal(*LocalIndex, Arg))
2405 return false;
2406 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
2407 if (!this->visitInitializer(Arg))
2408 return false;
2409 }
2410
2411 if (ArgIndex == 1 && Activate) {
2412 if (!this->emitActivate(Arg))
2413 return false;
2414 }
2415
2416 if (!NonNullArgs.empty() && NonNullArgs[ArgIndex]) {
2417 PrimType ArgT = classify(Arg).value_or(PT_Ptr);
2418 if (ArgT == PT_Ptr) {
2419 if (!this->emitCheckNonNullArg(ArgT, Arg))
2420 return false;
2421 }
2422 }
2423
2424 ++ArgIndex;
2425 }
2426
2427 return true;
2428}
2429
2430template <class Emitter>
2432 return this->visitInitList(E->inits(), E->getArrayFiller(), E);
2433}
2434
2435template <class Emitter>
2440
2441template <class Emitter>
2446
2447template <class Emitter>
2449 if (!E->hasAPValueResult())
2450 return this->delegate(E->getSubExpr());
2451
2452 if (OptPrimType T = classify(E)) {
2453 // Try to emit the APValue directly, without visiting the subexpr.
2454 // This will only fail if we can't emit the APValue, so won't emit any
2455 // diagnostics or any double values.
2456 if (DiscardResult)
2457 return true;
2458 return this->visitAPValue(E->getAPValueResult(), *T, E);
2459 }
2460
2461 // Fall back to the subexpr for non-primitive APValues.
2462 return this->delegate(E->getSubExpr());
2463}
2464
2465template <class Emitter>
2467 auto It = E->begin();
2468 return this->visit(*It);
2469}
2470
2472 UnaryExprOrTypeTrait Kind) {
2473 bool AlignOfReturnsPreferred =
2474 ASTCtx.getLangOpts().isCompatibleWith(LangOptions::ClangABI::Ver7);
2475
2476 // C++ [expr.alignof]p3:
2477 // When alignof is applied to a reference type, the result is the
2478 // alignment of the referenced type.
2479 if (const auto *Ref = T->getAs<ReferenceType>())
2480 T = Ref->getPointeeType();
2481
2482 if (T.getQualifiers().hasUnaligned())
2483 return CharUnits::One();
2484
2485 // __alignof is defined to return the preferred alignment.
2486 // Before 8, clang returned the preferred alignment for alignof and
2487 // _Alignof as well.
2488 if (Kind == UETT_PreferredAlignOf || AlignOfReturnsPreferred)
2489 return ASTCtx.toCharUnitsFromBits(ASTCtx.getPreferredTypeAlign(T));
2490
2491 return ASTCtx.getTypeAlignInChars(T);
2492}
2493
2494template <class Emitter>
2496 const UnaryExprOrTypeTraitExpr *E) {
2497
2498 UnaryExprOrTypeTrait Kind = E->getKind();
2499 const ASTContext &ASTCtx = Ctx.getASTContext();
2500
2501 if (Kind == UETT_SizeOf || Kind == UETT_DataSizeOf) {
2503
2504 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type,
2505 // the result is the size of the referenced type."
2506 if (const auto *Ref = ArgType->getAs<ReferenceType>())
2507 ArgType = Ref->getPointeeType();
2508
2509 CharUnits Size;
2510 if (ArgType->isVoidType() || ArgType->isFunctionType())
2511 Size = CharUnits::One();
2512 else {
2513 if (ArgType->isDependentType() || !ArgType->isConstantSizeType())
2514 return this->emitInvalid(E);
2515
2516 if (Kind == UETT_SizeOf)
2517 Size = ASTCtx.getTypeSizeInChars(ArgType);
2518 else
2520 }
2521
2522 if (DiscardResult)
2523 return true;
2524
2525 return this->emitConst(Size.getQuantity(), E);
2526 }
2527
2528 if (Kind == UETT_CountOf) {
2529 QualType Ty = E->getTypeOfArgument();
2530 assert(Ty->isArrayType());
2531
2532 // We don't need to worry about array element qualifiers, so getting the
2533 // unsafe array type is fine.
2534 if (const auto *CAT =
2535 dyn_cast<ConstantArrayType>(Ty->getAsArrayTypeUnsafe())) {
2536 if (DiscardResult)
2537 return true;
2538 return this->emitConst(CAT->getSize(), E);
2539 }
2540
2541 assert(!Ty->isConstantSizeType());
2542
2543 // If it's a variable-length array type, we need to check whether it is a
2544 // multidimensional array. If so, we need to check the size expression of
2545 // the VLA to see if it's a constant size. If so, we can return that value.
2546 const auto *VAT = ASTCtx.getAsVariableArrayType(Ty);
2547 assert(VAT);
2548 if (VAT->getElementType()->isArrayType()) {
2549 std::optional<APSInt> Res =
2550 VAT->getSizeExpr()
2551 ? VAT->getSizeExpr()->getIntegerConstantExpr(ASTCtx)
2552 : std::nullopt;
2553 if (Res) {
2554 if (DiscardResult)
2555 return true;
2556 return this->emitConst(*Res, E);
2557 }
2558 }
2559 }
2560
2561 if (Kind == UETT_AlignOf || Kind == UETT_PreferredAlignOf) {
2562 CharUnits Size;
2563
2564 if (E->isArgumentType()) {
2566
2567 Size = AlignOfType(ArgType, ASTCtx, Kind);
2568 } else {
2569 // Argument is an expression, not a type.
2570 const Expr *Arg = E->getArgumentExpr()->IgnoreParens();
2571
2572 if (Arg->getType()->isDependentType())
2573 return false;
2574
2575 // The kinds of expressions that we have special-case logic here for
2576 // should be kept up to date with the special checks for those
2577 // expressions in Sema.
2578
2579 // alignof decl is always accepted, even if it doesn't make sense: we
2580 // default to 1 in those cases.
2581 if (const auto *DRE = dyn_cast<DeclRefExpr>(Arg))
2582 Size = ASTCtx.getDeclAlign(DRE->getDecl(),
2583 /*RefAsPointee*/ true);
2584 else if (const auto *ME = dyn_cast<MemberExpr>(Arg))
2585 Size = ASTCtx.getDeclAlign(ME->getMemberDecl(),
2586 /*RefAsPointee*/ true);
2587 else
2588 Size = AlignOfType(Arg->getType(), ASTCtx, Kind);
2589 }
2590
2591 if (DiscardResult)
2592 return true;
2593
2594 return this->emitConst(Size.getQuantity(), E);
2595 }
2596
2597 if (Kind == UETT_VectorElements) {
2598 if (E->containsErrors())
2599 return false;
2600
2601 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>())
2602 return this->emitConst(VT->getNumElements(), E);
2604 return this->emitSizelessVectorElementSize(E);
2605 }
2606
2607 if (Kind == UETT_VecStep) {
2608 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>()) {
2609 unsigned N = VT->getNumElements();
2610
2611 // The vec_step built-in functions that take a 3-component
2612 // vector return 4. (OpenCL 1.1 spec 6.11.12)
2613 if (N == 3)
2614 N = 4;
2615
2616 return this->emitConst(N, E);
2617 }
2618 return this->emitConst(1, E);
2619 }
2620
2621 if (Kind == UETT_OpenMPRequiredSimdAlign) {
2622 if (E->containsErrors())
2623 return false;
2624 assert(E->isArgumentType());
2625 unsigned Bits = ASTCtx.getOpenMPDefaultSimdAlign(E->getArgumentType());
2626
2627 return this->emitConst(ASTCtx.toCharUnitsFromBits(Bits).getQuantity(), E);
2628 }
2629
2630 if (Kind == UETT_PtrAuthTypeDiscriminator) {
2631 if (E->getArgumentType()->isDependentType())
2632 return this->emitInvalid(E);
2633
2634 return this->emitConst(
2635 const_cast<ASTContext &>(ASTCtx).getPointerAuthTypeDiscriminator(
2636 E->getArgumentType()),
2637 E);
2638 }
2639
2640 return false;
2641}
2642
2643template <class Emitter>
2645 // 'Base.Member'
2646 const Expr *Base = E->getBase();
2647 const ValueDecl *Member = E->getMemberDecl();
2648
2649 if (DiscardResult)
2650 return this->discard(Base);
2651
2652 if (const auto *VD = dyn_cast<VarDecl>(Member)) {
2653 // I am almost confident in saying that a var decl must be static
2654 // and therefore registered as a global variable.
2655 if (auto GlobalIndex = P.getGlobal(VD)) {
2656 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
2657 return false;
2658 if (Member->getType()->isReferenceType())
2659 return this->emitLoadPopPtr(E);
2660 return true;
2661 }
2662 return false;
2663 }
2664
2665 if (!isa<FieldDecl>(Member)) {
2666 // A non-static member function access only makes sense as part of the
2667 // enclosing call here. Don't try to evaluate it in isolation.
2668 if (const auto *MD = dyn_cast<CXXMethodDecl>(Member);
2669 MD && !MD->isStatic()) {
2670 return false;
2671 }
2672
2673 if (!this->discard(Base) && !this->emitSideEffect(E))
2674 return false;
2675
2676 return this->visitDeclRef(Member, E);
2677 }
2678
2679 if (!this->visit(Base))
2680 return false;
2681
2682 // Base above gives us a pointer on the stack.
2683 const auto *FD = cast<FieldDecl>(Member);
2684 const RecordDecl *RD = FD->getParent();
2685 const Record *R = getRecord(RD);
2686 if (!R)
2687 return false;
2688 const Record::Field *F = R->getField(FD);
2689
2690 // MemberExprs are almost always lvalues, in which case we don't need to
2691 // do the load. But sometimes they aren't.
2692 const auto maybeLoadValue = [&]() -> bool {
2693 if (E->isGLValue())
2694 return true;
2695 if (OptPrimType T = classify(E))
2696 return this->emitLoadPop(*T, E);
2697 return false;
2698 };
2699
2700 // Leave a pointer to the field on the stack.
2701 if (F->Decl->getType()->isReferenceType())
2702 return this->emitGetFieldPop(PT_Ptr, F->Offset, E) && maybeLoadValue();
2703 return this->emitGetPtrFieldPop(F->Offset, E) && maybeLoadValue();
2704}
2705
2706template <class Emitter>
2708 assert(!DiscardResult);
2709 // ArrayIndex might not be set if a ArrayInitIndexExpr is being evaluated
2710 // stand-alone, e.g. via EvaluateAsInt().
2711 if (!ArrayIndex)
2712 return false;
2713 return this->emitConst(*ArrayIndex, E);
2714}
2715
2716template <class Emitter>
2718 assert(Initializing);
2719 assert(!DiscardResult);
2720
2721 const Expr *Common = E->getCommonExpr();
2722 const Expr *SubExpr = E->getSubExpr();
2723 OptPrimType SubExprT = classify(SubExpr);
2724 size_t Size = E->getArraySize().getZExtValue();
2725
2726 if (SubExprT) {
2727 // Unwrap the OpaqueValueExpr so we don't cache something we won't reuse.
2728 Common = cast<OpaqueValueExpr>(Common)->getSourceExpr();
2729
2730 if (!this->visit(Common))
2731 return false;
2732 return this->emitCopyArray(*SubExprT, 0, 0, Size, E);
2733 }
2734
2735 // We visit the common opaque expression here once so we have its value
2736 // cached.
2737 if (!this->discard(Common))
2738 return false;
2739
2740 // TODO: This compiles to quite a lot of bytecode if the array is larger.
2741 // Investigate compiling this to a loop.
2742
2743 // So, every iteration, we execute an assignment here
2744 // where the LHS is on the stack (the target array)
2745 // and the RHS is our SubExpr.
2746 for (size_t I = 0; I != Size; ++I) {
2747 ArrayIndexScope<Emitter> IndexScope(this, I);
2749
2750 if (!this->visitArrayElemInit(I, SubExpr, SubExprT))
2751 return false;
2752 if (!BS.destroyLocals())
2753 return false;
2754 }
2755 return true;
2756}
2757
2758template <class Emitter>
2760 const Expr *SourceExpr = E->getSourceExpr();
2761 if (!SourceExpr)
2762 return false;
2763
2764 if (Initializing) {
2765 assert(!DiscardResult);
2766 return this->visitInitializer(SourceExpr);
2767 }
2768
2769 PrimType SubExprT = classify(SourceExpr).value_or(PT_Ptr);
2770 if (auto It = OpaqueExprs.find(E); It != OpaqueExprs.end()) {
2771 if (DiscardResult)
2772 return true;
2773 return this->emitGetLocal(SubExprT, It->second, E);
2774 }
2775
2776 if (!this->visit(SourceExpr))
2777 return false;
2778
2779 // At this point we either have the evaluated source expression or a pointer
2780 // to an object on the stack. We want to create a local variable that stores
2781 // this value.
2782 unsigned LocalIndex = allocateLocalPrimitive(E, SubExprT, /*IsConst=*/true);
2783 if (!this->emitSetLocal(SubExprT, LocalIndex, E))
2784 return false;
2785
2786 // This is cleaned up when the local variable is destroyed.
2787 OpaqueExprs.insert({E, LocalIndex});
2788
2789 // Here the local variable is created but the value is removed from the stack,
2790 // so we put it back if the caller needs it.
2791 if (!DiscardResult)
2792 return this->emitGetLocal(SubExprT, LocalIndex, E);
2793 return true;
2794}
2795
2796template <class Emitter>
2798 const AbstractConditionalOperator *E) {
2799 const Expr *Condition = E->getCond();
2800 const Expr *TrueExpr = E->getTrueExpr();
2801 const Expr *FalseExpr = E->getFalseExpr();
2802
2803 if (std::optional<bool> BoolValue = getBoolValue(Condition)) {
2804 if (*BoolValue)
2805 return this->delegate(TrueExpr);
2806 return this->delegate(FalseExpr);
2807 }
2808
2809 bool IsBcpCall = false;
2810 if (const auto *CE = dyn_cast<CallExpr>(Condition->IgnoreParenCasts());
2811 CE && CE->getBuiltinCallee() == Builtin::BI__builtin_constant_p) {
2812 IsBcpCall = true;
2813 }
2814
2815 LabelTy LabelEnd = this->getLabel(); // Label after the operator.
2816 LabelTy LabelFalse = this->getLabel(); // Label for the false expr.
2817
2818 if (IsBcpCall) {
2819 if (!this->emitPushIgnoreDiags(E))
2820 return false;
2821 }
2822
2823 if (!this->visitBool(Condition)) {
2824 // If the condition failed and we're checking for undefined behavior
2825 // (which only happens with EvalEmitter) check the TrueExpr and FalseExpr
2826 // as well.
2827 if (this->checkingForUndefinedBehavior()) {
2828 if (!this->discard(TrueExpr))
2829 return false;
2830 if (!this->discard(FalseExpr))
2831 return false;
2832 }
2833 return false;
2834 }
2835
2836 // Force-init the scope, which creates a InitScope op. This is necessary so
2837 // the scope is not only initialized in one arm of the conditional operator.
2838 this->VarScope->forceInit();
2839 // The TrueExpr and FalseExpr of a conditional operator do _not_ create a
2840 // scope, which means the local variables created within them unconditionally
2841 // always exist. However, we need to later differentiate which branch was
2842 // taken and only destroy the varibles of the active branch. This is what the
2843 // "enabled" flags on local variables are used for.
2844 llvm::SaveAndRestore LAAA(this->VarScope->LocalsAlwaysEnabled,
2845 /*NewValue=*/false);
2846
2847 if (!this->jumpFalse(LabelFalse, E))
2848 return false;
2849 if (!this->delegate(TrueExpr))
2850 return false;
2851
2852 if (!this->jump(LabelEnd, E))
2853 return false;
2854 this->emitLabel(LabelFalse);
2855 if (!this->delegate(FalseExpr))
2856 return false;
2857
2858 this->fallthrough(LabelEnd);
2859 this->emitLabel(LabelEnd);
2860
2861 if (IsBcpCall)
2862 return this->emitPopIgnoreDiags(E);
2863 return true;
2864}
2865
2866template <class Emitter>
2868 if (DiscardResult)
2869 return true;
2870
2871 if (!Initializing) {
2872 unsigned StringIndex = P.createGlobalString(E);
2873 return this->emitGetPtrGlobal(StringIndex, E);
2874 }
2875
2876 // We are initializing an array on the stack.
2877 const ConstantArrayType *CAT =
2878 Ctx.getASTContext().getAsConstantArrayType(E->getType());
2879 assert(CAT && "a string literal that's not a constant array?");
2880
2881 // If the initializer string is too long, a diagnostic has already been
2882 // emitted. Read only the array length from the string literal.
2883 unsigned ArraySize = CAT->getZExtSize();
2884 unsigned N = std::min(ArraySize, E->getLength());
2885 unsigned CharWidth = E->getCharByteWidth();
2886
2887 for (unsigned I = 0; I != N; ++I) {
2888 uint32_t CodeUnit = E->getCodeUnit(I);
2889
2890 if (CharWidth == 1) {
2891 this->emitConstSint8(CodeUnit, E);
2892 this->emitInitElemSint8(I, E);
2893 } else if (CharWidth == 2) {
2894 this->emitConstUint16(CodeUnit, E);
2895 this->emitInitElemUint16(I, E);
2896 } else if (CharWidth == 4) {
2897 this->emitConstUint32(CodeUnit, E);
2898 this->emitInitElemUint32(I, E);
2899 } else {
2900 llvm_unreachable("unsupported character width");
2901 }
2902 }
2903
2904 // Fill up the rest of the char array with NUL bytes.
2905 for (unsigned I = N; I != ArraySize; ++I) {
2906 if (CharWidth == 1) {
2907 this->emitConstSint8(0, E);
2908 this->emitInitElemSint8(I, E);
2909 } else if (CharWidth == 2) {
2910 this->emitConstUint16(0, E);
2911 this->emitInitElemUint16(I, E);
2912 } else if (CharWidth == 4) {
2913 this->emitConstUint32(0, E);
2914 this->emitInitElemUint32(I, E);
2915 } else {
2916 llvm_unreachable("unsupported character width");
2917 }
2918 }
2919
2920 return true;
2921}
2922
2923template <class Emitter>
2925 if (DiscardResult)
2926 return true;
2927 return this->emitDummyPtr(E, E);
2928}
2929
2930template <class Emitter>
2932 auto &A = Ctx.getASTContext();
2933 std::string Str;
2934 A.getObjCEncodingForType(E->getEncodedType(), Str);
2935 StringLiteral *SL =
2937 /*Pascal=*/false, E->getType(), E->getAtLoc());
2938 return this->delegate(SL);
2939}
2940
2941template <class Emitter>
2943 const SYCLUniqueStableNameExpr *E) {
2944 if (DiscardResult)
2945 return true;
2946
2947 assert(!Initializing);
2948
2949 auto &A = Ctx.getASTContext();
2950 std::string ResultStr = E->ComputeName(A);
2951
2952 QualType CharTy = A.CharTy.withConst();
2953 APInt Size(A.getTypeSize(A.getSizeType()), ResultStr.size() + 1);
2954 QualType ArrayTy = A.getConstantArrayType(CharTy, Size, nullptr,
2956
2957 StringLiteral *SL =
2959 /*Pascal=*/false, ArrayTy, E->getLocation());
2960
2961 unsigned StringIndex = P.createGlobalString(SL);
2962 return this->emitGetPtrGlobal(StringIndex, E);
2963}
2964
2965template <class Emitter>
2967 if (DiscardResult)
2968 return true;
2969 return this->emitConst(E->getValue(), E);
2970}
2971
2972template <class Emitter>
2974 const CompoundAssignOperator *E) {
2975
2976 const Expr *LHS = E->getLHS();
2977 const Expr *RHS = E->getRHS();
2978 QualType LHSType = LHS->getType();
2979 QualType LHSComputationType = E->getComputationLHSType();
2980 QualType ResultType = E->getComputationResultType();
2981 OptPrimType LT = classify(LHSComputationType);
2982 OptPrimType RT = classify(ResultType);
2983
2984 assert(ResultType->isFloatingType());
2985
2986 if (!LT || !RT)
2987 return false;
2988
2989 PrimType LHST = classifyPrim(LHSType);
2990
2991 // C++17 onwards require that we evaluate the RHS first.
2992 // Compute RHS and save it in a temporary variable so we can
2993 // load it again later.
2994 if (!visit(RHS))
2995 return false;
2996
2997 unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
2998 if (!this->emitSetLocal(*RT, TempOffset, E))
2999 return false;
3000
3001 // First, visit LHS.
3002 if (!visit(LHS))
3003 return false;
3004 if (!this->emitLoad(LHST, E))
3005 return false;
3006
3007 // If necessary, convert LHS to its computation type.
3008 if (!this->emitPrimCast(LHST, classifyPrim(LHSComputationType),
3009 LHSComputationType, E))
3010 return false;
3011
3012 // Now load RHS.
3013 if (!this->emitGetLocal(*RT, TempOffset, E))
3014 return false;
3015
3016 switch (E->getOpcode()) {
3017 case BO_AddAssign:
3018 if (!this->emitAddf(getFPOptions(E), E))
3019 return false;
3020 break;
3021 case BO_SubAssign:
3022 if (!this->emitSubf(getFPOptions(E), E))
3023 return false;
3024 break;
3025 case BO_MulAssign:
3026 if (!this->emitMulf(getFPOptions(E), E))
3027 return false;
3028 break;
3029 case BO_DivAssign:
3030 if (!this->emitDivf(getFPOptions(E), E))
3031 return false;
3032 break;
3033 default:
3034 return false;
3035 }
3036
3037 if (!this->emitPrimCast(classifyPrim(ResultType), LHST, LHS->getType(), E))
3038 return false;
3039
3040 if (DiscardResult)
3041 return this->emitStorePop(LHST, E);
3042 return this->emitStore(LHST, E);
3043}
3044
3045template <class Emitter>
3047 const CompoundAssignOperator *E) {
3048 BinaryOperatorKind Op = E->getOpcode();
3049 const Expr *LHS = E->getLHS();
3050 const Expr *RHS = E->getRHS();
3051 OptPrimType LT = classify(LHS->getType());
3052 OptPrimType RT = classify(RHS->getType());
3053
3054 if (Op != BO_AddAssign && Op != BO_SubAssign)
3055 return false;
3056
3057 if (!LT || !RT)
3058 return false;
3059
3060 if (!visit(LHS))
3061 return false;
3062
3063 if (!this->emitLoad(*LT, LHS))
3064 return false;
3065
3066 if (!visit(RHS))
3067 return false;
3068
3069 if (Op == BO_AddAssign) {
3070 if (!this->emitAddOffset(*RT, E))
3071 return false;
3072 } else {
3073 if (!this->emitSubOffset(*RT, E))
3074 return false;
3075 }
3076
3077 if (DiscardResult)
3078 return this->emitStorePopPtr(E);
3079 return this->emitStorePtr(E);
3080}
3081
3082template <class Emitter>
3084 const CompoundAssignOperator *E) {
3085 if (E->getType()->isVectorType())
3086 return VisitVectorBinOp(E);
3087
3088 const Expr *LHS = E->getLHS();
3089 const Expr *RHS = E->getRHS();
3090 OptPrimType LHSComputationT = classify(E->getComputationLHSType());
3091 OptPrimType LT = classify(LHS->getType());
3092 OptPrimType RT = classify(RHS->getType());
3093 OptPrimType ResultT = classify(E->getType());
3094
3095 if (!Ctx.getLangOpts().CPlusPlus14)
3096 return this->visit(RHS) && this->visit(LHS) && this->emitError(E);
3097
3098 if (!LT || !RT || !ResultT || !LHSComputationT)
3099 return false;
3100
3101 // Handle floating point operations separately here, since they
3102 // require special care.
3103
3104 if (ResultT == PT_Float || RT == PT_Float)
3106
3107 if (E->getType()->isPointerType())
3109
3110 assert(!E->getType()->isPointerType() && "Handled above");
3111 assert(!E->getType()->isFloatingType() && "Handled above");
3112
3113 // C++17 onwards require that we evaluate the RHS first.
3114 // Compute RHS and save it in a temporary variable so we can
3115 // load it again later.
3116 // FIXME: Compound assignments are unsequenced in C, so we might
3117 // have to figure out how to reject them.
3118 if (!visit(RHS))
3119 return false;
3120
3121 unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true);
3122
3123 if (!this->emitSetLocal(*RT, TempOffset, E))
3124 return false;
3125
3126 // Get LHS pointer, load its value and cast it to the
3127 // computation type if necessary.
3128 if (!visit(LHS))
3129 return false;
3130 if (!this->emitLoad(*LT, E))
3131 return false;
3132 if (LT != LHSComputationT &&
3133 !this->emitIntegralCast(*LT, *LHSComputationT, E->getComputationLHSType(),
3134 E))
3135 return false;
3136
3137 // Get the RHS value on the stack.
3138 if (!this->emitGetLocal(*RT, TempOffset, E))
3139 return false;
3140
3141 // Perform operation.
3142 switch (E->getOpcode()) {
3143 case BO_AddAssign:
3144 if (!this->emitAdd(*LHSComputationT, E))
3145 return false;
3146 break;
3147 case BO_SubAssign:
3148 if (!this->emitSub(*LHSComputationT, E))
3149 return false;
3150 break;
3151 case BO_MulAssign:
3152 if (!this->emitMul(*LHSComputationT, E))
3153 return false;
3154 break;
3155 case BO_DivAssign:
3156 if (!this->emitDiv(*LHSComputationT, E))
3157 return false;
3158 break;
3159 case BO_RemAssign:
3160 if (!this->emitRem(*LHSComputationT, E))
3161 return false;
3162 break;
3163 case BO_ShlAssign:
3164 if (!this->emitShl(*LHSComputationT, *RT, E))
3165 return false;
3166 break;
3167 case BO_ShrAssign:
3168 if (!this->emitShr(*LHSComputationT, *RT, E))
3169 return false;
3170 break;
3171 case BO_AndAssign:
3172 if (!this->emitBitAnd(*LHSComputationT, E))
3173 return false;
3174 break;
3175 case BO_XorAssign:
3176 if (!this->emitBitXor(*LHSComputationT, E))
3177 return false;
3178 break;
3179 case BO_OrAssign:
3180 if (!this->emitBitOr(*LHSComputationT, E))
3181 return false;
3182 break;
3183 default:
3184 llvm_unreachable("Unimplemented compound assign operator");
3185 }
3186
3187 // And now cast from LHSComputationT to ResultT.
3188 if (ResultT != LHSComputationT &&
3189 !this->emitIntegralCast(*LHSComputationT, *ResultT, E->getType(), E))
3190 return false;
3191
3192 // And store the result in LHS.
3193 if (DiscardResult) {
3194 if (LHS->refersToBitField())
3195 return this->emitStoreBitFieldPop(*ResultT, E);
3196 return this->emitStorePop(*ResultT, E);
3197 }
3198 if (LHS->refersToBitField())
3199 return this->emitStoreBitField(*ResultT, E);
3200 return this->emitStore(*ResultT, E);
3201}
3202
3203template <class Emitter>
3206 const Expr *SubExpr = E->getSubExpr();
3207
3208 return this->delegate(SubExpr) && ES.destroyLocals(E);
3209}
3210
3211template <class Emitter>
3213 const MaterializeTemporaryExpr *E) {
3214 if (Initializing) {
3215 // We already have a value, just initialize that.
3216 return this->delegate(E->getSubExpr());
3217 }
3218 // If we don't end up using the materialized temporary anyway, don't
3219 // bother creating it.
3220 if (DiscardResult)
3221 return this->discard(E->getSubExpr());
3222
3225 const Expr *Inner;
3226 if (!Ctx.getLangOpts().CPlusPlus11)
3227 Inner =
3228 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
3229 else
3230 Inner = E->getSubExpr();
3231
3232 // If we passed any comma operators, evaluate their LHSs.
3233 for (const Expr *LHS : CommaLHSs) {
3234 if (!this->discard(LHS))
3235 return false;
3236 }
3237
3238 // FIXME: Find a test case where Adjustments matters.
3239
3240 // When we're extending a global variable *or* the storage duration of
3241 // the temporary is explicitly static, create a global variable.
3242 OptPrimType InnerT = classify(Inner);
3243 const ValueDecl *ExtendingDecl = E->getExtendingDecl();
3244 bool IsStatic = E->getStorageDuration() == SD_Static;
3245 if (IsStatic ||
3246 (ExtendingDecl && Context::shouldBeGloballyIndexed(ExtendingDecl))) {
3247 UnsignedOrNone GlobalIndex = P.createGlobal(E, Inner->getType());
3248 if (!GlobalIndex)
3249 return false;
3250
3251 const LifetimeExtendedTemporaryDecl *TempDecl =
3253
3254 if (InnerT) {
3255 if (!this->visit(Inner))
3256 return false;
3257
3258 if (IsStatic) {
3259 assert(TempDecl);
3260 if (!this->emitInitGlobalTemp(*InnerT, *GlobalIndex, TempDecl, E))
3261 return false;
3262 } else {
3263 if (!this->emitInitGlobal(*InnerT, *GlobalIndex, E))
3264 return false;
3265 }
3266 return this->emitGetPtrGlobal(*GlobalIndex, E);
3267 }
3268
3269 if (!this->checkLiteralType(Inner))
3270 return false;
3271 // Non-primitive values.
3272 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3273 return false;
3274 if (!this->visitInitializer(Inner))
3275 return false;
3276 if (IsStatic) {
3277 assert(TempDecl);
3278 return this->emitInitGlobalTempComp(TempDecl, E);
3279 }
3280 return true;
3281 }
3282
3286
3287 // For everyhing else, use local variables.
3288 if (InnerT) {
3289 bool IsConst = Inner->getType().isConstQualified();
3290 bool IsVolatile = Inner->getType().isVolatileQualified();
3291 unsigned LocalIndex =
3292 allocateLocalPrimitive(E, *InnerT, IsConst, IsVolatile, VarScope);
3293 if (!this->VarScope->LocalsAlwaysEnabled &&
3294 !this->emitEnableLocal(LocalIndex, E))
3295 return false;
3296
3297 if (!this->visit(Inner))
3298 return false;
3299 if (!this->emitSetLocal(*InnerT, LocalIndex, E))
3300 return false;
3301
3302 return this->emitGetPtrLocal(LocalIndex, E);
3303 }
3304
3305 if (!this->checkLiteralType(Inner))
3306 return false;
3307
3308 if (UnsignedOrNone LocalIndex =
3309 allocateLocal(E, Inner->getType(), VarScope)) {
3310 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
3311
3312 if (!this->VarScope->LocalsAlwaysEnabled &&
3313 !this->emitEnableLocal(*LocalIndex, E))
3314 return false;
3315
3316 if (!this->emitGetPtrLocal(*LocalIndex, E))
3317 return false;
3318 return this->visitInitializer(Inner);
3319 }
3320 return false;
3321}
3322
3323template <class Emitter>
3325 const CXXBindTemporaryExpr *E) {
3326 const Expr *SubExpr = E->getSubExpr();
3327
3328 if (Initializing)
3329 return this->delegate(SubExpr);
3330
3331 // Make sure we create a temporary even if we're discarding, since that will
3332 // make sure we will also call the destructor.
3333
3334 if (!this->visit(SubExpr))
3335 return false;
3336
3337 if (DiscardResult)
3338 return this->emitPopPtr(E);
3339 return true;
3340}
3341
3342template <class Emitter>
3344 const Expr *Init = E->getInitializer();
3345 if (DiscardResult)
3346 return this->discard(Init);
3347
3348 if (Initializing) {
3349 // We already have a value, just initialize that.
3350 return this->visitInitializer(Init);
3351 }
3352
3353 OptPrimType T = classify(E->getType());
3354 if (E->isFileScope()) {
3355 // Avoid creating a variable if this is a primitive RValue anyway.
3356 if (T && !E->isLValue())
3357 return this->delegate(Init);
3358
3359 UnsignedOrNone GlobalIndex = P.createGlobal(E, E->getType());
3360 if (!GlobalIndex)
3361 return false;
3362
3363 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3364 return false;
3365
3366 // Since this is a global variable, we might've already seen,
3367 // don't do it again.
3368 if (P.isGlobalInitialized(*GlobalIndex))
3369 return true;
3370
3371 if (T) {
3372 if (!this->visit(Init))
3373 return false;
3374 return this->emitInitGlobal(*T, *GlobalIndex, E);
3375 }
3376
3377 return this->visitInitializer(Init);
3378 }
3379
3380 // Otherwise, use a local variable.
3381 if (T && !E->isLValue()) {
3382 // For primitive types, we just visit the initializer.
3383 return this->delegate(Init);
3384 }
3385
3386 unsigned LocalIndex;
3387 if (T)
3388 LocalIndex = this->allocateLocalPrimitive(Init, *T, /*IsConst=*/false);
3389 else if (UnsignedOrNone MaybeIndex = this->allocateLocal(Init))
3390 LocalIndex = *MaybeIndex;
3391 else
3392 return false;
3393
3394 if (!this->emitGetPtrLocal(LocalIndex, E))
3395 return false;
3396
3397 if (T)
3398 return this->visit(Init) && this->emitInit(*T, E);
3399 return this->visitInitializer(Init);
3400}
3401
3402template <class Emitter>
3404 if (DiscardResult)
3405 return true;
3406 if (E->isStoredAsBoolean()) {
3407 if (E->getType()->isBooleanType())
3408 return this->emitConstBool(E->getBoolValue(), E);
3409 return this->emitConst(E->getBoolValue(), E);
3410 }
3411 PrimType T = classifyPrim(E->getType());
3412 return this->visitAPValue(E->getAPValue(), T, E);
3413}
3414
3415template <class Emitter>
3417 if (DiscardResult)
3418 return true;
3419 return this->emitConst(E->getValue(), E);
3420}
3421
3422template <class Emitter>
3424 if (DiscardResult)
3425 return true;
3426
3427 assert(Initializing);
3428 const Record *R = P.getOrCreateRecord(E->getLambdaClass());
3429 if (!R)
3430 return false;
3431
3432 auto *CaptureInitIt = E->capture_init_begin();
3433 // Initialize all fields (which represent lambda captures) of the
3434 // record with their initializers.
3435 for (const Record::Field &F : R->fields()) {
3436 const Expr *Init = *CaptureInitIt;
3437 if (!Init || Init->containsErrors())
3438 continue;
3439 ++CaptureInitIt;
3440
3441 if (OptPrimType T = classify(Init)) {
3442 if (!this->visit(Init))
3443 return false;
3444
3445 if (!this->emitInitField(*T, F.Offset, E))
3446 return false;
3447 } else {
3448 if (!this->emitGetPtrField(F.Offset, E))
3449 return false;
3450
3451 if (!this->visitInitializerPop(Init))
3452 return false;
3453 }
3454 }
3455
3456 return true;
3457}
3458
3459template <class Emitter>
3461 if (DiscardResult)
3462 return true;
3463
3464 if (!Initializing) {
3465 unsigned StringIndex = P.createGlobalString(E->getFunctionName(), E);
3466 return this->emitGetPtrGlobal(StringIndex, E);
3467 }
3468
3469 return this->delegate(E->getFunctionName());
3470}
3471
3472template <class Emitter>
3474 if (E->getSubExpr() && !this->discard(E->getSubExpr()))
3475 return false;
3476
3477 return this->emitInvalid(E);
3478}
3479
3480template <class Emitter>
3482 const CXXReinterpretCastExpr *E) {
3483 const Expr *SubExpr = E->getSubExpr();
3484
3485 OptPrimType FromT = classify(SubExpr);
3486 OptPrimType ToT = classify(E);
3487
3488 if (!FromT || !ToT)
3489 return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, E);
3490
3491 if (FromT == PT_Ptr || ToT == PT_Ptr) {
3492 if (!this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/false, E))
3493 return false;
3494 if (E->getCastKind() == CK_LValueBitCast)
3495 return this->delegate(SubExpr);
3496 return this->VisitCastExpr(E);
3497 }
3498
3499 // Try to actually do the cast.
3500 bool Fatal = (ToT != FromT);
3501 if (!this->emitInvalidCast(CastKind::Reinterpret, Fatal, E))
3502 return false;
3503
3504 return this->VisitCastExpr(E);
3505}
3506
3507template <class Emitter>
3509 if (!Ctx.getLangOpts().CPlusPlus20) {
3510 if (!this->emitInvalidCast(CastKind::Dynamic, /*Fatal=*/false, E))
3511 return false;
3512 }
3513
3514 if (E->getCastKind() != CK_Dynamic)
3515 return this->VisitCastExpr(E);
3516
3517 QualType DestType = E->getType();
3518 // "target type must be a reference or pointer type to a defined class"
3519 if (DestType->isRecordType()) {
3520 assert(E->isGLValue());
3521 } else {
3522 assert(DestType->isPointerOrReferenceType());
3523 assert(DestType->isVoidPointerType() ||
3524 DestType->getPointeeType()->isRecordType());
3525 DestType = DestType->getPointeeType();
3526 }
3527
3528 if (!this->visit(E->getSubExpr()))
3529 return false;
3530 if (!this->emitDynamicCast(DestType.getTypePtr(),
3531 /*IsReferenceCast=*/E->isGLValue(), E))
3532 return false;
3533
3534 if (DiscardResult)
3535 return this->emitPopPtr(E);
3536 return true;
3537}
3538
3539template <class Emitter>
3541 assert(E->getType()->isBooleanType());
3542
3543 if (DiscardResult)
3544 return true;
3545 return this->emitConstBool(E->getValue(), E);
3546}
3547
3548template <class Emitter>
3550 QualType T = E->getType();
3551 assert(!canClassify(T));
3552
3553 if (T->isRecordType()) {
3554 const CXXConstructorDecl *Ctor = E->getConstructor();
3555
3556 // If we're discarding a construct expression, we still need
3557 // to allocate a variable and call the constructor and destructor.
3558 if (DiscardResult) {
3559 if (Ctor->isTrivial())
3560 return true;
3561 assert(!Initializing);
3562 UnsignedOrNone LocalIndex = allocateLocal(E);
3563
3564 if (!LocalIndex)
3565 return false;
3566
3567 if (!this->emitGetPtrLocal(*LocalIndex, E))
3568 return false;
3569 }
3570
3571 // Trivial copy/move constructor. Avoid copy.
3572 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
3573 Ctor->isTrivial() &&
3574 E->getArg(0)->isTemporaryObject(Ctx.getASTContext(),
3575 T->getAsCXXRecordDecl()))
3576 return this->visitInitializer(E->getArg(0));
3577
3578 // Zero initialization.
3579 bool ZeroInit = E->requiresZeroInitialization();
3580 if (ZeroInit) {
3581 const Record *R = getRecord(E->getType());
3582 if (!R)
3583 return false;
3584
3585 if (!this->visitZeroRecordInitializer(R, E))
3586 return false;
3587
3588 // If the constructor is trivial anyway, we're done.
3589 if (Ctor->isTrivial())
3590 return true;
3591 }
3592
3593 // Avoid materializing a temporary for an elidable copy/move constructor.
3594 if (!ZeroInit && E->isElidable()) {
3595 const Expr *SrcObj = E->getArg(0);
3596 assert(SrcObj->isTemporaryObject(Ctx.getASTContext(), Ctor->getParent()));
3597 assert(Ctx.getASTContext().hasSameUnqualifiedType(E->getType(),
3598 SrcObj->getType()));
3599 if (const auto *ME = dyn_cast<MaterializeTemporaryExpr>(SrcObj)) {
3600 if (!this->emitCheckFunctionDecl(Ctor, E))
3601 return false;
3602 return this->visitInitializer(ME->getSubExpr());
3603 }
3604 }
3605
3606 const Function *Func = getFunction(Ctor);
3607
3608 if (!Func)
3609 return false;
3610
3611 assert(Func->hasThisPointer());
3612 assert(!Func->hasRVO());
3613
3614 // The This pointer is already on the stack because this is an initializer,
3615 // but we need to dup() so the call() below has its own copy.
3616 if (!this->emitDupPtr(E))
3617 return false;
3618
3619 // Constructor arguments.
3620 for (const auto *Arg : E->arguments()) {
3621 if (!this->visit(Arg))
3622 return false;
3623 }
3624
3625 if (Func->isVariadic()) {
3626 uint32_t VarArgSize = 0;
3627 unsigned NumParams = Func->getNumWrittenParams();
3628 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) {
3629 VarArgSize +=
3630 align(primSize(classify(E->getArg(I)->getType()).value_or(PT_Ptr)));
3631 }
3632 if (!this->emitCallVar(Func, VarArgSize, E))
3633 return false;
3634 } else {
3635 if (!this->emitCall(Func, 0, E)) {
3636 // When discarding, we don't need the result anyway, so clean up
3637 // the instance dup we did earlier in case surrounding code wants
3638 // to keep evaluating.
3639 if (DiscardResult)
3640 (void)this->emitPopPtr(E);
3641 return false;
3642 }
3643 }
3644
3645 if (DiscardResult)
3646 return this->emitPopPtr(E);
3647 return true;
3648 }
3649
3650 if (T->isArrayType()) {
3651 const Function *Func = getFunction(E->getConstructor());
3652 if (!Func)
3653 return false;
3654
3655 if (!this->emitDupPtr(E))
3656 return false;
3657
3658 std::function<bool(QualType)> initArrayDimension;
3659 initArrayDimension = [&](QualType T) -> bool {
3660 if (!T->isArrayType()) {
3661 // Constructor arguments.
3662 for (const auto *Arg : E->arguments()) {
3663 if (!this->visit(Arg))
3664 return false;
3665 }
3666
3667 return this->emitCall(Func, 0, E);
3668 }
3669
3670 const ConstantArrayType *CAT =
3671 Ctx.getASTContext().getAsConstantArrayType(T);
3672 if (!CAT)
3673 return false;
3674 QualType ElemTy = CAT->getElementType();
3675 unsigned NumElems = CAT->getZExtSize();
3676 for (size_t I = 0; I != NumElems; ++I) {
3677 if (!this->emitConstUint64(I, E))
3678 return false;
3679 if (!this->emitArrayElemPtrUint64(E))
3680 return false;
3681 if (!initArrayDimension(ElemTy))
3682 return false;
3683 }
3684 return this->emitPopPtr(E);
3685 };
3686
3687 return initArrayDimension(E->getType());
3688 }
3689
3690 return false;
3691}
3692
3693template <class Emitter>
3695 if (DiscardResult)
3696 return true;
3697
3698 const APValue Val =
3699 E->EvaluateInContext(Ctx.getASTContext(), SourceLocDefaultExpr);
3700
3701 // Things like __builtin_LINE().
3702 if (E->getType()->isIntegerType()) {
3703 assert(Val.isInt());
3704 const APSInt &I = Val.getInt();
3705 return this->emitConst(I, E);
3706 }
3707 // Otherwise, the APValue is an LValue, with only one element.
3708 // Theoretically, we don't need the APValue at all of course.
3709 assert(E->getType()->isPointerType());
3710 assert(Val.isLValue());
3711 const APValue::LValueBase &Base = Val.getLValueBase();
3712 if (const Expr *LValueExpr = Base.dyn_cast<const Expr *>())
3713 return this->visit(LValueExpr);
3714
3715 // Otherwise, we have a decl (which is the case for
3716 // __builtin_source_location).
3717 assert(Base.is<const ValueDecl *>());
3718 assert(Val.getLValuePath().size() == 0);
3719 const auto *BaseDecl = Base.dyn_cast<const ValueDecl *>();
3720 assert(BaseDecl);
3721
3722 auto *UGCD = cast<UnnamedGlobalConstantDecl>(BaseDecl);
3723
3724 UnsignedOrNone GlobalIndex = P.getOrCreateGlobal(UGCD);
3725 if (!GlobalIndex)
3726 return false;
3727
3728 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
3729 return false;
3730
3731 const Record *R = getRecord(E->getType());
3732 const APValue &V = UGCD->getValue();
3733 for (unsigned I = 0, N = R->getNumFields(); I != N; ++I) {
3734 const Record::Field *F = R->getField(I);
3735 const APValue &FieldValue = V.getStructField(I);
3736
3737 PrimType FieldT = classifyPrim(F->Decl->getType());
3738
3739 if (!this->visitAPValue(FieldValue, FieldT, E))
3740 return false;
3741 if (!this->emitInitField(FieldT, F->Offset, E))
3742 return false;
3743 }
3744
3745 // Leave the pointer to the global on the stack.
3746 return true;
3747}
3748
3749template <class Emitter>
3751 unsigned N = E->getNumComponents();
3752 if (N == 0)
3753 return false;
3754
3755 for (unsigned I = 0; I != N; ++I) {
3756 const OffsetOfNode &Node = E->getComponent(I);
3757 if (Node.getKind() == OffsetOfNode::Array) {
3758 const Expr *ArrayIndexExpr = E->getIndexExpr(Node.getArrayExprIndex());
3759 PrimType IndexT = classifyPrim(ArrayIndexExpr->getType());
3760
3761 if (DiscardResult) {
3762 if (!this->discard(ArrayIndexExpr))
3763 return false;
3764 continue;
3765 }
3766
3767 if (!this->visit(ArrayIndexExpr))
3768 return false;
3769 // Cast to Sint64.
3770 if (IndexT != PT_Sint64) {
3771 if (!this->emitCast(IndexT, PT_Sint64, E))
3772 return false;
3773 }
3774 }
3775 }
3776
3777 if (DiscardResult)
3778 return true;
3779
3780 PrimType T = classifyPrim(E->getType());
3781 return this->emitOffsetOf(T, E, E);
3782}
3783
3784template <class Emitter>
3786 const CXXScalarValueInitExpr *E) {
3787 QualType Ty = E->getType();
3788
3789 if (DiscardResult || Ty->isVoidType())
3790 return true;
3791
3792 if (OptPrimType T = classify(Ty))
3793 return this->visitZeroInitializer(*T, Ty, E);
3794
3795 if (Ty->isAnyComplexType() || Ty->isVectorType()) {
3796 if (!Initializing) {
3797 UnsignedOrNone LocalIndex = allocateLocal(E);
3798 if (!LocalIndex)
3799 return false;
3800 if (!this->emitGetPtrLocal(*LocalIndex, E))
3801 return false;
3802 }
3803
3804 QualType ElemQT;
3805 unsigned NumElems;
3806 if (const auto *CT = Ty->getAs<ComplexType>()) {
3807 NumElems = 2;
3808 ElemQT = CT->getElementType();
3809 } else {
3810 const auto *VT = Ty->castAs<VectorType>();
3811 NumElems = VT->getNumElements();
3812 ElemQT = VT->getElementType();
3813 }
3814
3815 PrimType ElemT = classifyPrim(ElemQT);
3816
3817 // Initialize all fields to 0.
3818 for (unsigned I = 0, N = NumElems; I != N; ++I) {
3819 if (!this->visitZeroInitializer(ElemT, ElemQT, E))
3820 return false;
3821 if (!this->emitInitElem(ElemT, I, E))
3822 return false;
3823 }
3824 return true;
3825 }
3826
3827 return false;
3828}
3829
3830template <class Emitter>
3832 return this->emitConst(E->getPackLength(), E);
3833}
3834
3835template <class Emitter>
3840
3841template <class Emitter>
3843 return this->delegate(E->getChosenSubExpr());
3844}
3845
3846template <class Emitter>
3848 if (DiscardResult)
3849 return true;
3850
3851 return this->emitConst(E->getValue(), E);
3852}
3853
3854template <class Emitter>
3856 const CXXInheritedCtorInitExpr *E) {
3857 const CXXConstructorDecl *Ctor = E->getConstructor();
3858 assert(!Ctor->isTrivial() &&
3859 "Trivial CXXInheritedCtorInitExpr, implement. (possible?)");
3860 const Function *F = this->getFunction(Ctor);
3861 assert(F);
3862 assert(!F->hasRVO());
3863 assert(F->hasThisPointer());
3864
3865 if (!this->emitDupPtr(SourceInfo{}))
3866 return false;
3867
3868 // Forward all arguments of the current function (which should be a
3869 // constructor itself) to the inherited ctor.
3870 // This is necessary because the calling code has pushed the pointer
3871 // of the correct base for us already, but the arguments need
3872 // to come after.
3873 unsigned ParamIndex = 0;
3874 for (const ParmVarDecl *PD : Ctor->parameters()) {
3875 PrimType PT = this->classify(PD->getType()).value_or(PT_Ptr);
3876
3877 if (!this->emitGetParam(PT, ParamIndex, E))
3878 return false;
3879 ++ParamIndex;
3880 }
3881
3882 return this->emitCall(F, 0, E);
3883}
3884
3885// FIXME: This function has become rather unwieldy, especially
3886// the part where we initialize an array allocation of dynamic size.
3887template <class Emitter>
3889 assert(classifyPrim(E->getType()) == PT_Ptr);
3890 const Expr *Init = E->getInitializer();
3891 QualType ElementType = E->getAllocatedType();
3892 OptPrimType ElemT = classify(ElementType);
3893 unsigned PlacementArgs = E->getNumPlacementArgs();
3894 const FunctionDecl *OperatorNew = E->getOperatorNew();
3895 const Expr *PlacementDest = nullptr;
3896 bool IsNoThrow = false;
3897
3898 if (E->containsErrors())
3899 return false;
3900
3901 if (PlacementArgs != 0) {
3902 // FIXME: There is no restriction on this, but it's not clear that any
3903 // other form makes any sense. We get here for cases such as:
3904 //
3905 // new (std::align_val_t{N}) X(int)
3906 //
3907 // (which should presumably be valid only if N is a multiple of
3908 // alignof(int), and in any case can't be deallocated unless N is
3909 // alignof(X) and X has new-extended alignment).
3910 if (PlacementArgs == 1) {
3911 const Expr *Arg1 = E->getPlacementArg(0);
3912 if (Arg1->getType()->isNothrowT()) {
3913 if (!this->discard(Arg1))
3914 return false;
3915 IsNoThrow = true;
3916 } else {
3917 // Invalid unless we have C++26 or are in a std:: function.
3918 if (!this->emitInvalidNewDeleteExpr(E, E))
3919 return false;
3920
3921 // If we have a placement-new destination, we'll later use that instead
3922 // of allocating.
3923 if (OperatorNew->isReservedGlobalPlacementOperator())
3924 PlacementDest = Arg1;
3925 }
3926 } else {
3927 // Always invalid.
3928 return this->emitInvalid(E);
3929 }
3930 } else if (!OperatorNew
3931 ->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
3932 return this->emitInvalidNewDeleteExpr(E, E);
3933
3934 const Descriptor *Desc;
3935 if (!PlacementDest) {
3936 if (ElemT) {
3937 if (E->isArray())
3938 Desc = nullptr; // We're not going to use it in this case.
3939 else
3940 Desc = P.createDescriptor(E, *ElemT, /*SourceTy=*/nullptr,
3942 } else {
3943 Desc = P.createDescriptor(
3944 E, ElementType.getTypePtr(),
3945 E->isArray() ? std::nullopt : Descriptor::InlineDescMD,
3946 /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false,
3947 /*IsVolatile=*/false, Init);
3948 }
3949 }
3950
3951 if (E->isArray()) {
3952 std::optional<const Expr *> ArraySizeExpr = E->getArraySize();
3953 if (!ArraySizeExpr)
3954 return false;
3955
3956 const Expr *Stripped = *ArraySizeExpr;
3957 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped);
3958 Stripped = ICE->getSubExpr())
3959 if (ICE->getCastKind() != CK_NoOp &&
3960 ICE->getCastKind() != CK_IntegralCast)
3961 break;
3962
3963 PrimType SizeT = classifyPrim(Stripped->getType());
3964
3965 // Save evaluated array size to a variable.
3966 unsigned ArrayLen =
3967 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
3968 if (!this->visit(Stripped))
3969 return false;
3970 if (!this->emitSetLocal(SizeT, ArrayLen, E))
3971 return false;
3972
3973 if (PlacementDest) {
3974 if (!this->visit(PlacementDest))
3975 return false;
3976 if (!this->emitGetLocal(SizeT, ArrayLen, E))
3977 return false;
3978 if (!this->emitCheckNewTypeMismatchArray(SizeT, E, E))
3979 return false;
3980 } else {
3981 if (!this->emitGetLocal(SizeT, ArrayLen, E))
3982 return false;
3983
3984 if (ElemT) {
3985 // N primitive elements.
3986 if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E))
3987 return false;
3988 } else {
3989 // N Composite elements.
3990 if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E))
3991 return false;
3992 }
3993 }
3994
3995 if (Init) {
3996 QualType InitType = Init->getType();
3997 size_t StaticInitElems = 0;
3998 const Expr *DynamicInit = nullptr;
3999 OptPrimType ElemT;
4000
4001 if (const ConstantArrayType *CAT =
4002 Ctx.getASTContext().getAsConstantArrayType(InitType)) {
4003 StaticInitElems = CAT->getZExtSize();
4004 // Initialize the first S element from the initializer.
4005 if (!this->visitInitializer(Init))
4006 return false;
4007
4008 if (const auto *ILE = dyn_cast<InitListExpr>(Init)) {
4009 if (ILE->hasArrayFiller())
4010 DynamicInit = ILE->getArrayFiller();
4011 else if (StaticInitElems > 0 && isa<StringLiteral>(ILE->getInit(0)))
4012 ElemT = classifyPrim(CAT->getElementType());
4013 }
4014 }
4015
4016 // The initializer initializes a certain number of elements, S.
4017 // However, the complete number of elements, N, might be larger than that.
4018 // In this case, we need to get an initializer for the remaining elements.
4019 // There are three cases:
4020 // 1) For the form 'new Struct[n];', the initializer is a
4021 // CXXConstructExpr and its type is an IncompleteArrayType.
4022 // 2) For the form 'new Struct[n]{1,2,3}', the initializer is an
4023 // InitListExpr and the initializer for the remaining elements
4024 // is the array filler.
4025 // 3) StringLiterals don't have an array filler, so we need to zero
4026 // the remaining elements.
4027
4028 if (DynamicInit || ElemT || InitType->isIncompleteArrayType()) {
4029 const Function *CtorFunc = nullptr;
4030 if (const auto *CE = dyn_cast<CXXConstructExpr>(Init)) {
4031 CtorFunc = getFunction(CE->getConstructor());
4032 if (!CtorFunc)
4033 return false;
4034 } else if (!DynamicInit && !ElemT)
4035 DynamicInit = Init;
4036
4037 LabelTy EndLabel = this->getLabel();
4038 LabelTy StartLabel = this->getLabel();
4039
4040 // In the nothrow case, the alloc above might have returned nullptr.
4041 // Don't call any constructors that case.
4042 if (IsNoThrow) {
4043 if (!this->emitDupPtr(E))
4044 return false;
4045 if (!this->emitNullPtr(0, nullptr, E))
4046 return false;
4047 if (!this->emitEQPtr(E))
4048 return false;
4049 if (!this->jumpTrue(EndLabel, E))
4050 return false;
4051 }
4052
4053 // Create loop variables.
4054 unsigned Iter =
4055 allocateLocalPrimitive(Stripped, SizeT, /*IsConst=*/false);
4056 if (!this->emitConst(StaticInitElems, SizeT, E))
4057 return false;
4058 if (!this->emitSetLocal(SizeT, Iter, E))
4059 return false;
4060
4061 this->fallthrough(StartLabel);
4062 this->emitLabel(StartLabel);
4063 // Condition. Iter < ArrayLen?
4064 if (!this->emitGetLocal(SizeT, Iter, E))
4065 return false;
4066 if (!this->emitGetLocal(SizeT, ArrayLen, E))
4067 return false;
4068 if (!this->emitLT(SizeT, E))
4069 return false;
4070 if (!this->jumpFalse(EndLabel, E))
4071 return false;
4072
4073 // Pointer to the allocated array is already on the stack.
4074 if (!this->emitGetLocal(SizeT, Iter, E))
4075 return false;
4076 if (!this->emitArrayElemPtr(SizeT, E))
4077 return false;
4078
4079 if (isa_and_nonnull<ImplicitValueInitExpr>(DynamicInit) &&
4080 DynamicInit->getType()->isArrayType()) {
4081 QualType ElemType =
4082 DynamicInit->getType()->getAsArrayTypeUnsafe()->getElementType();
4083 if (OptPrimType InitT = classify(ElemType)) {
4084 if (!this->visitZeroInitializer(*InitT, ElemType, E))
4085 return false;
4086 if (!this->emitStorePop(*InitT, E))
4087 return false;
4088 } else {
4089 assert(ElemType->isArrayType());
4090 if (!this->visitZeroArrayInitializer(ElemType, E))
4091 return false;
4092 }
4093 } else if (DynamicInit) {
4094 if (OptPrimType InitT = classify(DynamicInit)) {
4095 if (!this->visit(DynamicInit))
4096 return false;
4097 if (!this->emitStorePop(*InitT, E))
4098 return false;
4099 } else {
4100 if (!this->visitInitializerPop(DynamicInit))
4101 return false;
4102 }
4103 } else if (ElemT) {
4104 if (!this->visitZeroInitializer(
4105 *ElemT, InitType->getAsArrayTypeUnsafe()->getElementType(),
4106 Init))
4107 return false;
4108 if (!this->emitStorePop(*ElemT, E))
4109 return false;
4110 } else {
4111 assert(CtorFunc);
4112 if (!this->emitCall(CtorFunc, 0, E))
4113 return false;
4114 }
4115
4116 // ++Iter;
4117 if (!this->emitGetPtrLocal(Iter, E))
4118 return false;
4119 if (!this->emitIncPop(SizeT, false, E))
4120 return false;
4121
4122 if (!this->jump(StartLabel, E))
4123 return false;
4124
4125 this->fallthrough(EndLabel);
4126 this->emitLabel(EndLabel);
4127 }
4128 }
4129 } else { // Non-array.
4130 if (PlacementDest) {
4131 if (!this->visit(PlacementDest))
4132 return false;
4133 if (!this->emitCheckNewTypeMismatch(E, E))
4134 return false;
4135
4136 } else {
4137 // Allocate just one element.
4138 if (!this->emitAlloc(Desc, E))
4139 return false;
4140 }
4141
4142 if (Init) {
4143 if (ElemT) {
4144 if (!this->visit(Init))
4145 return false;
4146
4147 if (!this->emitInit(*ElemT, E))
4148 return false;
4149 } else {
4150 // Composite.
4151 if (!this->visitInitializer(Init))
4152 return false;
4153 }
4154 }
4155 }
4156
4157 if (DiscardResult)
4158 return this->emitPopPtr(E);
4159
4160 return true;
4161}
4162
4163template <class Emitter>
4165 if (E->containsErrors())
4166 return false;
4167 const FunctionDecl *OperatorDelete = E->getOperatorDelete();
4168
4169 if (!OperatorDelete->isUsableAsGlobalAllocationFunctionInConstantEvaluation())
4170 return this->emitInvalidNewDeleteExpr(E, E);
4171
4172 // Arg must be an lvalue.
4173 if (!this->visit(E->getArgument()))
4174 return false;
4175
4176 return this->emitFree(E->isArrayForm(), E->isGlobalDelete(), E);
4177}
4178
4179template <class Emitter>
4181 if (DiscardResult)
4182 return true;
4183
4184 const Function *Func = nullptr;
4185 if (const Function *F = Ctx.getOrCreateObjCBlock(E))
4186 Func = F;
4187
4188 if (!Func)
4189 return false;
4190 return this->emitGetFnPtr(Func, E);
4191}
4192
4193template <class Emitter>
4195 const Type *TypeInfoType = E->getType().getTypePtr();
4196
4197 auto canonType = [](const Type *T) {
4198 return T->getCanonicalTypeUnqualified().getTypePtr();
4199 };
4200
4201 if (!E->isPotentiallyEvaluated()) {
4202 if (DiscardResult)
4203 return true;
4204
4205 if (E->isTypeOperand())
4206 return this->emitGetTypeid(
4207 canonType(E->getTypeOperand(Ctx.getASTContext()).getTypePtr()),
4208 TypeInfoType, E);
4209
4210 return this->emitGetTypeid(
4211 canonType(E->getExprOperand()->getType().getTypePtr()), TypeInfoType,
4212 E);
4213 }
4214
4215 // Otherwise, we need to evaluate the expression operand.
4216 assert(E->getExprOperand());
4217 assert(E->getExprOperand()->isLValue());
4218
4219 if (!Ctx.getLangOpts().CPlusPlus20 && !this->emitDiagTypeid(E))
4220 return false;
4221
4222 if (!this->visit(E->getExprOperand()))
4223 return false;
4224
4225 if (!this->emitGetTypeidPtr(TypeInfoType, E))
4226 return false;
4227 if (DiscardResult)
4228 return this->emitPopPtr(E);
4229 return true;
4230}
4231
4232template <class Emitter>
4234 const ObjCDictionaryLiteral *E) {
4236 return this->emitDummyPtr(E, E);
4237 return this->emitError(E);
4238}
4239
4240template <class Emitter>
4243 return this->emitDummyPtr(E, E);
4244 return this->emitError(E);
4245}
4246
4247template <class Emitter>
4249 assert(Ctx.getLangOpts().CPlusPlus);
4250 return this->emitConstBool(E->getValue(), E);
4251}
4252
4253template <class Emitter>
4255 if (DiscardResult)
4256 return true;
4257 assert(!Initializing);
4258
4259 const MSGuidDecl *GuidDecl = E->getGuidDecl();
4260 const RecordDecl *RD = GuidDecl->getType()->getAsRecordDecl();
4261 assert(RD);
4262 // If the definiton of the result type is incomplete, just return a dummy.
4263 // If (and when) that is read from, we will fail, but not now.
4264 if (!RD->isCompleteDefinition())
4265 return this->emitDummyPtr(GuidDecl, E);
4266
4267 UnsignedOrNone GlobalIndex = P.getOrCreateGlobal(GuidDecl);
4268 if (!GlobalIndex)
4269 return false;
4270 if (!this->emitGetPtrGlobal(*GlobalIndex, E))
4271 return false;
4272
4273 assert(this->getRecord(E->getType()));
4274
4275 const APValue &V = GuidDecl->getAsAPValue();
4276 if (V.getKind() == APValue::None)
4277 return true;
4278
4279 assert(V.isStruct());
4280 assert(V.getStructNumBases() == 0);
4281 if (!this->visitAPValueInitializer(V, E, E->getType()))
4282 return false;
4283
4284 return this->emitFinishInit(E);
4285}
4286
4287template <class Emitter>
4289 assert(classifyPrim(E->getType()) == PT_Bool);
4290 if (E->isValueDependent())
4291 return false;
4292 if (DiscardResult)
4293 return true;
4294 return this->emitConstBool(E->isSatisfied(), E);
4295}
4296
4297template <class Emitter>
4299 const ConceptSpecializationExpr *E) {
4300 assert(classifyPrim(E->getType()) == PT_Bool);
4301 if (DiscardResult)
4302 return true;
4303 return this->emitConstBool(E->isSatisfied(), E);
4304}
4305
4306template <class Emitter>
4311
4312template <class Emitter>
4314
4315 for (const Expr *SemE : E->semantics()) {
4316 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) {
4317 if (SemE == E->getResultExpr())
4318 return false;
4319
4320 if (OVE->isUnique())
4321 continue;
4322
4323 if (!this->discard(OVE))
4324 return false;
4325 } else if (SemE == E->getResultExpr()) {
4326 if (!this->delegate(SemE))
4327 return false;
4328 } else {
4329 if (!this->discard(SemE))
4330 return false;
4331 }
4332 }
4333 return true;
4334}
4335
4336template <class Emitter>
4340
4341template <class Emitter>
4343 return this->emitError(E);
4344}
4345
4346template <class Emitter>
4348 assert(E->getType()->isVoidPointerType());
4349 if (DiscardResult)
4350 return true;
4351
4352 return this->emitDummyPtr(E, E);
4353}
4354
4355template <class Emitter>
4356bool Compiler<Emitter>::emitVectorConversion(const Expr *Src, const Expr *E) {
4357 if (Src->containsErrors())
4358 return false;
4359
4360 const auto *VT = E->getType()->castAs<VectorType>();
4361 QualType ElemType = VT->getElementType();
4362 PrimType ElemT = classifyPrim(ElemType);
4363 QualType SrcType = Src->getType();
4364 PrimType SrcElemT = classifyVectorElementType(SrcType);
4365
4366 if (!Initializing) {
4367 UnsignedOrNone LocalIndex = allocateLocal(E);
4368 if (!LocalIndex)
4369 return false;
4370 if (!this->emitGetPtrLocal(*LocalIndex, E))
4371 return false;
4372 }
4373
4374 unsigned SrcOffset =
4375 this->allocateLocalPrimitive(Src, PT_Ptr, /*IsConst=*/true);
4376 if (!this->visit(Src))
4377 return false;
4378 if (!this->emitSetLocal(PT_Ptr, SrcOffset, E))
4379 return false;
4380
4381 for (unsigned I = 0; I != VT->getNumElements(); ++I) {
4382 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
4383 return false;
4384 if (!this->emitArrayElemPop(SrcElemT, I, E))
4385 return false;
4386
4387 // Cast to the desired result element type.
4388 if (SrcElemT != ElemT) {
4389 if (!this->emitPrimCast(SrcElemT, ElemT, ElemType, E))
4390 return false;
4391 } else if (ElemType->isFloatingType() && SrcType != ElemType) {
4392 const auto *TargetSemantics = &Ctx.getFloatSemantics(ElemType);
4393 if (!this->emitCastFP(TargetSemantics, getRoundingMode(E), E))
4394 return false;
4395 }
4396 if (!this->emitInitElem(ElemT, I, E))
4397 return false;
4398 }
4399 return true;
4400}
4401
4402template <class Emitter>
4404 return emitVectorConversion(E->getSrcExpr(), E);
4405}
4406
4407template <class Emitter>
4409 // FIXME: Unary shuffle with mask not currently supported.
4410 if (E->getNumSubExprs() == 2)
4411 return this->emitInvalid(E);
4412
4413 assert(E->getNumSubExprs() > 2);
4414
4415 const Expr *Vecs[] = {E->getExpr(0), E->getExpr(1)};
4416 const VectorType *VT = Vecs[0]->getType()->castAs<VectorType>();
4417 PrimType ElemT = classifyPrim(VT->getElementType());
4418 unsigned NumInputElems = VT->getNumElements();
4419 unsigned NumOutputElems = E->getNumSubExprs() - 2;
4420 assert(NumOutputElems > 0);
4421
4422 if (!Initializing) {
4423 UnsignedOrNone LocalIndex = allocateLocal(E);
4424 if (!LocalIndex)
4425 return false;
4426 if (!this->emitGetPtrLocal(*LocalIndex, E))
4427 return false;
4428 }
4429
4430 // Save both input vectors to a local variable.
4431 unsigned VectorOffsets[2];
4432 for (unsigned I = 0; I != 2; ++I) {
4433 VectorOffsets[I] =
4434 this->allocateLocalPrimitive(Vecs[I], PT_Ptr, /*IsConst=*/true);
4435 if (!this->visit(Vecs[I]))
4436 return false;
4437 if (!this->emitSetLocal(PT_Ptr, VectorOffsets[I], E))
4438 return false;
4439 }
4440 for (unsigned I = 0; I != NumOutputElems; ++I) {
4441 APSInt ShuffleIndex = E->getShuffleMaskIdx(I);
4442 assert(ShuffleIndex >= -1);
4443 if (ShuffleIndex == -1)
4444 return this->emitInvalidShuffleVectorIndex(I, E);
4445
4446 assert(ShuffleIndex < (NumInputElems * 2));
4447 if (!this->emitGetLocal(PT_Ptr,
4448 VectorOffsets[ShuffleIndex >= NumInputElems], E))
4449 return false;
4450 unsigned InputVectorIndex = ShuffleIndex.getZExtValue() % NumInputElems;
4451 if (!this->emitArrayElemPop(ElemT, InputVectorIndex, E))
4452 return false;
4453
4454 if (!this->emitInitElem(ElemT, I, E))
4455 return false;
4456 }
4457
4458 if (DiscardResult)
4459 return this->emitPopPtr(E);
4460
4461 return true;
4462}
4463
4464template <class Emitter>
4466 const ExtVectorElementExpr *E) {
4467 const Expr *Base = E->getBase();
4468 assert(
4469 Base->getType()->isVectorType() ||
4470 Base->getType()->getAs<PointerType>()->getPointeeType()->isVectorType());
4471
4473 E->getEncodedElementAccess(Indices);
4474
4475 if (Indices.size() == 1) {
4476 if (!this->visit(Base))
4477 return false;
4478
4479 if (E->isGLValue()) {
4480 if (!this->emitConstUint32(Indices[0], E))
4481 return false;
4482 return this->emitArrayElemPtrPop(PT_Uint32, E);
4483 }
4484 // Else, also load the value.
4485 return this->emitArrayElemPop(classifyPrim(E->getType()), Indices[0], E);
4486 }
4487
4488 // Create a local variable for the base.
4489 unsigned BaseOffset = allocateLocalPrimitive(Base, PT_Ptr, /*IsConst=*/true);
4490 if (!this->visit(Base))
4491 return false;
4492 if (!this->emitSetLocal(PT_Ptr, BaseOffset, E))
4493 return false;
4494
4495 // Now the vector variable for the return value.
4496 if (!Initializing) {
4497 UnsignedOrNone ResultIndex = allocateLocal(E);
4498 if (!ResultIndex)
4499 return false;
4500 if (!this->emitGetPtrLocal(*ResultIndex, E))
4501 return false;
4502 }
4503
4504 assert(Indices.size() == E->getType()->getAs<VectorType>()->getNumElements());
4505
4506 PrimType ElemT =
4508 uint32_t DstIndex = 0;
4509 for (uint32_t I : Indices) {
4510 if (!this->emitGetLocal(PT_Ptr, BaseOffset, E))
4511 return false;
4512 if (!this->emitArrayElemPop(ElemT, I, E))
4513 return false;
4514 if (!this->emitInitElem(ElemT, DstIndex, E))
4515 return false;
4516 ++DstIndex;
4517 }
4518
4519 // Leave the result pointer on the stack.
4520 assert(!DiscardResult);
4521 return true;
4522}
4523
4524template <class Emitter>
4526 const Expr *SubExpr = E->getSubExpr();
4528 return this->discard(SubExpr) && this->emitInvalid(E);
4529
4530 if (DiscardResult)
4531 return true;
4532
4533 assert(classifyPrim(E) == PT_Ptr);
4534 return this->emitDummyPtr(E, E);
4535}
4536
4537template <class Emitter>
4539 const CXXStdInitializerListExpr *E) {
4540 const Expr *SubExpr = E->getSubExpr();
4542 Ctx.getASTContext().getAsConstantArrayType(SubExpr->getType());
4543 const Record *R = getRecord(E->getType());
4544 assert(Initializing);
4545 assert(SubExpr->isGLValue());
4546
4547 if (!this->visit(SubExpr))
4548 return false;
4549 if (!this->emitConstUint8(0, E))
4550 return false;
4551 if (!this->emitArrayElemPtrPopUint8(E))
4552 return false;
4553 if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E))
4554 return false;
4555
4556 PrimType SecondFieldT = classifyPrim(R->getField(1u)->Decl->getType());
4557 if (isIntegerOrBoolType(SecondFieldT)) {
4558 if (!this->emitConst(ArrayType->getSize(), SecondFieldT, E))
4559 return false;
4560 return this->emitInitField(SecondFieldT, R->getField(1u)->Offset, E);
4561 }
4562 assert(SecondFieldT == PT_Ptr);
4563
4564 if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E))
4565 return false;
4566 if (!this->emitExpandPtr(E))
4567 return false;
4568 if (!this->emitConst(ArrayType->getSize(), PT_Uint64, E))
4569 return false;
4570 if (!this->emitArrayElemPtrPop(PT_Uint64, E))
4571 return false;
4572 return this->emitInitFieldPtr(R->getField(1u)->Offset, E);
4573}
4574
4575template <class Emitter>
4577 LocalScope<Emitter> BS(this);
4578 llvm::SaveAndRestore StmtExprSAR(this->InStmtExpr, true);
4579
4580 const CompoundStmt *CS = E->getSubStmt();
4581 const Stmt *Result = CS->body_back();
4582 for (const Stmt *S : CS->body()) {
4583 if (S != Result) {
4584 if (!this->visitStmt(S))
4585 return false;
4586 continue;
4587 }
4588
4589 assert(S == Result);
4590 if (const Expr *ResultExpr = dyn_cast<Expr>(S))
4591 return this->delegate(ResultExpr);
4592 if (!this->visitStmt(S))
4593 return false;
4594 return this->emitUnsupported(E);
4595 }
4596
4597 return BS.destroyLocals();
4598}
4599
4600template <class Emitter> bool Compiler<Emitter>::discard(const Expr *E) {
4601 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true,
4602 /*NewInitializing=*/false, /*ToLValue=*/false);
4603 return this->Visit(E);
4604}
4605
4606template <class Emitter> bool Compiler<Emitter>::delegate(const Expr *E) {
4607 // We're basically doing:
4608 // OptionScope<Emitter> Scope(this, DicardResult, Initializing, ToLValue);
4609 // but that's unnecessary of course.
4610 return this->Visit(E);
4611}
4612
4614 if (const auto *PE = dyn_cast<ParenExpr>(E))
4615 return stripCheckedDerivedToBaseCasts(PE->getSubExpr());
4616
4617 if (const auto *CE = dyn_cast<CastExpr>(E);
4618 CE &&
4619 (CE->getCastKind() == CK_DerivedToBase || CE->getCastKind() == CK_NoOp))
4620 return stripCheckedDerivedToBaseCasts(CE->getSubExpr());
4621
4622 return E;
4623}
4624
4625static const Expr *stripDerivedToBaseCasts(const Expr *E) {
4626 if (const auto *PE = dyn_cast<ParenExpr>(E))
4627 return stripDerivedToBaseCasts(PE->getSubExpr());
4628
4629 if (const auto *CE = dyn_cast<CastExpr>(E);
4630 CE && (CE->getCastKind() == CK_DerivedToBase ||
4631 CE->getCastKind() == CK_UncheckedDerivedToBase ||
4632 CE->getCastKind() == CK_NoOp))
4633 return stripDerivedToBaseCasts(CE->getSubExpr());
4634
4635 return E;
4636}
4637
4638template <class Emitter> bool Compiler<Emitter>::visit(const Expr *E) {
4639 if (E->getType().isNull())
4640 return false;
4641
4642 if (E->getType()->isVoidType())
4643 return this->discard(E);
4644
4645 // Create local variable to hold the return value.
4646 if (!E->isGLValue() && !canClassify(E->getType())) {
4647 UnsignedOrNone LocalIndex = allocateLocal(
4649 if (!LocalIndex)
4650 return false;
4651
4652 if (!this->emitGetPtrLocal(*LocalIndex, E))
4653 return false;
4654 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex));
4655 return this->visitInitializer(E);
4656 }
4657
4658 // Otherwise,we have a primitive return value, produce the value directly
4659 // and push it on the stack.
4660 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4661 /*NewInitializing=*/false, /*ToLValue=*/ToLValue);
4662 return this->Visit(E);
4663}
4664
4665template <class Emitter>
4667 assert(!canClassify(E->getType()));
4668
4669 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4670 /*NewInitializing=*/true, /*ToLValue=*/false);
4671 return this->Visit(E) && this->emitFinishInit(E);
4672}
4673
4674template <class Emitter>
4676 assert(!canClassify(E->getType()));
4677
4678 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4679 /*NewInitializing=*/true, /*ToLValue=*/false);
4680 return this->Visit(E) && this->emitFinishInitPop(E);
4681}
4682
4683template <class Emitter> bool Compiler<Emitter>::visitAsLValue(const Expr *E) {
4684 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4685 /*NewInitializing=*/false, /*ToLValue=*/true);
4686 return this->Visit(E);
4687}
4688
4689template <class Emitter> bool Compiler<Emitter>::visitBool(const Expr *E) {
4690 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
4691 /*NewInitializing=*/false, /*ToLValue=*/ToLValue);
4692
4693 OptPrimType T = classify(E->getType());
4694 if (!T) {
4695 // Convert complex values to bool.
4696 if (E->getType()->isAnyComplexType()) {
4697 if (!this->visit(E))
4698 return false;
4699 return this->emitComplexBoolCast(E);
4700 }
4701 return false;
4702 }
4703
4704 if (!this->visit(E))
4705 return false;
4706
4707 if (T == PT_Bool)
4708 return true;
4709
4710 // Convert pointers to bool.
4711 if (T == PT_Ptr)
4712 return this->emitIsNonNullPtr(E);
4713
4714 // Or Floats.
4715 if (T == PT_Float)
4716 return this->emitCastFloatingIntegralBool(getFPOptions(E), E);
4717
4718 // Or anything else we can.
4719 return this->emitCast(*T, PT_Bool, E);
4720}
4721
4722template <class Emitter>
4723bool Compiler<Emitter>::visitZeroInitializer(PrimType T, QualType QT,
4724 const Expr *E) {
4725 if (const auto *AT = QT->getAs<AtomicType>())
4726 QT = AT->getValueType();
4727
4728 switch (T) {
4729 case PT_Bool:
4730 return this->emitZeroBool(E);
4731 case PT_Sint8:
4732 return this->emitZeroSint8(E);
4733 case PT_Uint8:
4734 return this->emitZeroUint8(E);
4735 case PT_Sint16:
4736 return this->emitZeroSint16(E);
4737 case PT_Uint16:
4738 return this->emitZeroUint16(E);
4739 case PT_Sint32:
4740 return this->emitZeroSint32(E);
4741 case PT_Uint32:
4742 return this->emitZeroUint32(E);
4743 case PT_Sint64:
4744 return this->emitZeroSint64(E);
4745 case PT_Uint64:
4746 return this->emitZeroUint64(E);
4747 case PT_IntAP:
4748 return this->emitZeroIntAP(Ctx.getBitWidth(QT), E);
4749 case PT_IntAPS:
4750 return this->emitZeroIntAPS(Ctx.getBitWidth(QT), E);
4751 case PT_Ptr:
4752 return this->emitNullPtr(Ctx.getASTContext().getTargetNullPointerValue(QT),
4753 nullptr, E);
4754 case PT_MemberPtr:
4755 return this->emitNullMemberPtr(0, nullptr, E);
4756 case PT_Float: {
4757 APFloat F = APFloat::getZero(Ctx.getFloatSemantics(QT));
4758 return this->emitFloat(F, E);
4759 }
4760 case PT_FixedPoint: {
4761 auto Sem = Ctx.getASTContext().getFixedPointSemantics(QT);
4762 return this->emitConstFixedPoint(FixedPoint::zero(Sem), E);
4763 }
4764 }
4765 llvm_unreachable("unknown primitive type");
4766}
4767
4768template <class Emitter>
4769bool Compiler<Emitter>::visitZeroRecordInitializer(const Record *R,
4770 const Expr *E) {
4771 assert(E);
4772 assert(R);
4773 // Fields
4774 for (const Record::Field &Field : R->fields()) {
4775 if (Field.isUnnamedBitField())
4776 continue;
4777
4778 const Descriptor *D = Field.Desc;
4779 if (D->isPrimitive()) {
4780 QualType QT = D->getType();
4781 PrimType T = D->getPrimType();
4782 if (!this->visitZeroInitializer(T, QT, E))
4783 return false;
4784 if (R->isUnion()) {
4785 if (!this->emitInitFieldActivate(T, Field.Offset, E))
4786 return false;
4787 break;
4788 }
4789 if (!this->emitInitField(T, Field.Offset, E))
4790 return false;
4791 continue;
4792 }
4793
4794 if (!this->emitGetPtrField(Field.Offset, E))
4795 return false;
4796
4797 if (D->isPrimitiveArray()) {
4798 QualType ET = D->getElemQualType();
4799 PrimType T = D->getPrimType();
4800 for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) {
4801 if (!this->visitZeroInitializer(T, ET, E))
4802 return false;
4803 if (!this->emitInitElem(T, I, E))
4804 return false;
4805 }
4806 } else if (D->isCompositeArray()) {
4807 // Can't be a vector or complex field.
4808 if (!this->visitZeroArrayInitializer(D->getType(), E))
4809 return false;
4810 } else if (D->isRecord()) {
4811 if (!this->visitZeroRecordInitializer(D->ElemRecord, E))
4812 return false;
4813 } else
4814 return false;
4815
4816 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the
4817 // object's first non-static named data member is zero-initialized
4818 if (R->isUnion()) {
4819 if (!this->emitFinishInitActivatePop(E))
4820 return false;
4821 break;
4822 }
4823 if (!this->emitFinishInitPop(E))
4824 return false;
4825 }
4826
4827 for (const Record::Base &B : R->bases()) {
4828 if (!this->emitGetPtrBase(B.Offset, E))
4829 return false;
4830 if (!this->visitZeroRecordInitializer(B.R, E))
4831 return false;
4832 if (!this->emitFinishInitPop(E))
4833 return false;
4834 }
4835
4836 // FIXME: Virtual bases.
4837
4838 return true;
4839}
4840
4841template <class Emitter>
4842bool Compiler<Emitter>::visitZeroArrayInitializer(QualType T, const Expr *E) {
4843 assert(T->isArrayType() || T->isAnyComplexType() || T->isVectorType());
4844 const ArrayType *AT = T->getAsArrayTypeUnsafe();
4845 QualType ElemType = AT->getElementType();
4846 size_t NumElems = cast<ConstantArrayType>(AT)->getZExtSize();
4847
4848 if (OptPrimType ElemT = classify(ElemType)) {
4849 for (size_t I = 0; I != NumElems; ++I) {
4850 if (!this->visitZeroInitializer(*ElemT, ElemType, E))
4851 return false;
4852 if (!this->emitInitElem(*ElemT, I, E))
4853 return false;
4854 }
4855 return true;
4856 }
4857 if (ElemType->isRecordType()) {
4858 const Record *R = getRecord(ElemType);
4859 if (!R)
4860 return false;
4861
4862 for (size_t I = 0; I != NumElems; ++I) {
4863 if (!this->emitConstUint32(I, E))
4864 return false;
4865 if (!this->emitArrayElemPtr(PT_Uint32, E))
4866 return false;
4867 if (!this->visitZeroRecordInitializer(R, E))
4868 return false;
4869 if (!this->emitPopPtr(E))
4870 return false;
4871 }
4872 return true;
4873 }
4874 if (ElemType->isArrayType()) {
4875 for (size_t I = 0; I != NumElems; ++I) {
4876 if (!this->emitConstUint32(I, E))
4877 return false;
4878 if (!this->emitArrayElemPtr(PT_Uint32, E))
4879 return false;
4880 if (!this->visitZeroArrayInitializer(ElemType, E))
4881 return false;
4882 if (!this->emitPopPtr(E))
4883 return false;
4884 }
4885 return true;
4886 }
4887
4888 return false;
4889}
4890
4891template <class Emitter>
4892bool Compiler<Emitter>::visitAssignment(const Expr *LHS, const Expr *RHS,
4893 const Expr *E) {
4894 if (!canClassify(E->getType()))
4895 return false;
4896
4897 if (!this->visit(RHS))
4898 return false;
4899 if (!this->visit(LHS))
4900 return false;
4901
4902 if (LHS->getType().isVolatileQualified())
4903 return this->emitInvalidStore(LHS->getType().getTypePtr(), E);
4904
4905 // We don't support assignments in C.
4906 if (!Ctx.getLangOpts().CPlusPlus && !this->emitInvalid(E))
4907 return false;
4908
4909 PrimType RHT = classifyPrim(RHS);
4910 bool Activates = refersToUnion(LHS);
4911 bool BitField = LHS->refersToBitField();
4912
4913 if (!this->emitFlip(PT_Ptr, RHT, E))
4914 return false;
4915
4916 if (DiscardResult) {
4917 if (BitField && Activates)
4918 return this->emitStoreBitFieldActivatePop(RHT, E);
4919 if (BitField)
4920 return this->emitStoreBitFieldPop(RHT, E);
4921 if (Activates)
4922 return this->emitStoreActivatePop(RHT, E);
4923 // Otherwise, regular non-activating store.
4924 return this->emitStorePop(RHT, E);
4925 }
4926
4927 auto maybeLoad = [&](bool Result) -> bool {
4928 if (!Result)
4929 return false;
4930 // Assignments aren't necessarily lvalues in C.
4931 // Load from them in that case.
4932 if (!E->isLValue())
4933 return this->emitLoadPop(RHT, E);
4934 return true;
4935 };
4936
4937 if (BitField && Activates)
4938 return maybeLoad(this->emitStoreBitFieldActivate(RHT, E));
4939 if (BitField)
4940 return maybeLoad(this->emitStoreBitField(RHT, E));
4941 if (Activates)
4942 return maybeLoad(this->emitStoreActivate(RHT, E));
4943 // Otherwise, regular non-activating store.
4944 return maybeLoad(this->emitStore(RHT, E));
4945}
4946
4947template <class Emitter>
4948template <typename T>
4949bool Compiler<Emitter>::emitConst(T Value, PrimType Ty, SourceInfo Info) {
4950 switch (Ty) {
4951 case PT_Sint8:
4952 return this->emitConstSint8(Value, Info);
4953 case PT_Uint8:
4954 return this->emitConstUint8(Value, Info);
4955 case PT_Sint16:
4956 return this->emitConstSint16(Value, Info);
4957 case PT_Uint16:
4958 return this->emitConstUint16(Value, Info);
4959 case PT_Sint32:
4960 return this->emitConstSint32(Value, Info);
4961 case PT_Uint32:
4962 return this->emitConstUint32(Value, Info);
4963 case PT_Sint64:
4964 return this->emitConstSint64(Value, Info);
4965 case PT_Uint64:
4966 return this->emitConstUint64(Value, Info);
4967 case PT_Bool:
4968 return this->emitConstBool(Value, Info);
4969 case PT_Ptr:
4970 case PT_MemberPtr:
4971 case PT_Float:
4972 case PT_IntAP:
4973 case PT_IntAPS:
4974 case PT_FixedPoint:
4975 llvm_unreachable("Invalid integral type");
4976 break;
4977 }
4978 llvm_unreachable("unknown primitive type");
4979}
4980
4981template <class Emitter>
4982template <typename T>
4983bool Compiler<Emitter>::emitConst(T Value, const Expr *E) {
4984 return this->emitConst(Value, classifyPrim(E->getType()), E);
4985}
4986
4987template <class Emitter>
4988bool Compiler<Emitter>::emitConst(const APSInt &Value, PrimType Ty,
4989 SourceInfo Info) {
4990 if (Ty == PT_IntAPS)
4991 return this->emitConstIntAPS(Value, Info);
4992 if (Ty == PT_IntAP)
4993 return this->emitConstIntAP(Value, Info);
4994
4995 if (Value.isSigned())
4996 return this->emitConst(Value.getSExtValue(), Ty, Info);
4997 return this->emitConst(Value.getZExtValue(), Ty, Info);
4998}
4999
5000template <class Emitter>
5001bool Compiler<Emitter>::emitConst(const APInt &Value, PrimType Ty,
5002 SourceInfo Info) {
5003 if (Ty == PT_IntAPS)
5004 return this->emitConstIntAPS(Value, Info);
5005 if (Ty == PT_IntAP)
5006 return this->emitConstIntAP(Value, Info);
5007
5008 if (isSignedType(Ty))
5009 return this->emitConst(Value.getSExtValue(), Ty, Info);
5010 return this->emitConst(Value.getZExtValue(), Ty, Info);
5011}
5012
5013template <class Emitter>
5014bool Compiler<Emitter>::emitConst(const APSInt &Value, const Expr *E) {
5015 return this->emitConst(Value, classifyPrim(E->getType()), E);
5016}
5017
5018template <class Emitter>
5020 bool IsConst,
5021 bool IsVolatile,
5022 ScopeKind SC) {
5023 // FIXME: There are cases where Src.is<Expr*>() is wrong, e.g.
5024 // (int){12} in C. Consider using Expr::isTemporaryObject() instead
5025 // or isa<MaterializeTemporaryExpr>().
5026 Descriptor *D = P.createDescriptor(Src, Ty, nullptr, Descriptor::InlineDescMD,
5027 IsConst, isa<const Expr *>(Src),
5028 /*IsMutable=*/false, IsVolatile);
5030 Scope::Local Local = this->createLocal(D);
5031 if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>()))
5032 Locals.insert({VD, Local});
5033 VarScope->addForScopeKind(Local, SC);
5034 return Local.Offset;
5035}
5036
5037template <class Emitter>
5039 ScopeKind SC) {
5040 const ValueDecl *Key = nullptr;
5041 const Expr *Init = nullptr;
5042 bool IsTemporary = false;
5043 if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) {
5044 Key = VD;
5045
5046 if (const auto *VarD = dyn_cast<VarDecl>(VD))
5047 Init = VarD->getInit();
5048 }
5049 if (auto *E = Src.dyn_cast<const Expr *>()) {
5050 IsTemporary = true;
5051 if (Ty.isNull())
5052 Ty = E->getType();
5053 }
5054
5055 Descriptor *D = P.createDescriptor(
5057 IsTemporary, /*IsMutable=*/false, /*IsVolatile=*/Ty.isVolatileQualified(),
5058 Init);
5059 if (!D)
5060 return std::nullopt;
5062
5063 Scope::Local Local = this->createLocal(D);
5064 if (Key)
5065 Locals.insert({Key, Local});
5066 VarScope->addForScopeKind(Local, SC);
5067 return Local.Offset;
5068}
5069
5070template <class Emitter>
5072 QualType Ty = E->getType();
5073 assert(!Ty->isRecordType());
5074
5075 Descriptor *D = P.createDescriptor(
5077 /*IsTemporary=*/true);
5078
5079 if (!D)
5080 return std::nullopt;
5081
5082 Scope::Local Local = this->createLocal(D);
5084 assert(S);
5085 // Attach to topmost scope.
5086 while (S->getParent())
5087 S = S->getParent();
5088 assert(S && !S->getParent());
5089 S->addLocal(Local);
5090 return Local.Offset;
5091}
5092
5093template <class Emitter>
5095 if (const PointerType *PT = dyn_cast<PointerType>(Ty))
5096 return PT->getPointeeType()->getAsCanonical<RecordType>();
5097 return Ty->getAsCanonical<RecordType>();
5098}
5099
5100template <class Emitter> Record *Compiler<Emitter>::getRecord(QualType Ty) {
5101 if (const auto *RecordTy = getRecordTy(Ty))
5102 return getRecord(RecordTy->getDecl()->getDefinitionOrSelf());
5103 return nullptr;
5104}
5105
5106template <class Emitter>
5108 return P.getOrCreateRecord(RD);
5109}
5110
5111template <class Emitter>
5113 return Ctx.getOrCreateFunction(FD);
5114}
5115
5116template <class Emitter>
5117bool Compiler<Emitter>::visitExpr(const Expr *E, bool DestroyToplevelScope) {
5119
5120 auto maybeDestroyLocals = [&]() -> bool {
5121 if (DestroyToplevelScope)
5122 return RootScope.destroyLocals() && this->emitCheckAllocations(E);
5123 return this->emitCheckAllocations(E);
5124 };
5125
5126 // Void expressions.
5127 if (E->getType()->isVoidType()) {
5128 if (!visit(E))
5129 return false;
5130 return this->emitRetVoid(E) && maybeDestroyLocals();
5131 }
5132
5133 // Expressions with a primitive return type.
5134 if (OptPrimType T = classify(E)) {
5135 if (!visit(E))
5136 return false;
5137
5138 return this->emitRet(*T, E) && maybeDestroyLocals();
5139 }
5140
5141 // Expressions with a composite return type.
5142 // For us, that means everything we don't
5143 // have a PrimType for.
5144 if (UnsignedOrNone LocalOffset = this->allocateLocal(E)) {
5145 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalOffset));
5146 if (!this->emitGetPtrLocal(*LocalOffset, E))
5147 return false;
5148
5149 if (!visitInitializer(E))
5150 return false;
5151 // We are destroying the locals AFTER the Ret op.
5152 // The Ret op needs to copy the (alive) values, but the
5153 // destructors may still turn the entire expression invalid.
5154 return this->emitRetValue(E) && maybeDestroyLocals();
5155 }
5156
5157 return maybeDestroyLocals() && false;
5158}
5159
5160template <class Emitter>
5162 bool DestroyToplevelScope) {
5163 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false,
5164 /*NewInitializing=*/false, /*ToLValue=*/true);
5165
5166 return this->visitExpr(E, DestroyToplevelScope);
5167}
5168
5169template <class Emitter>
5171
5172 auto R = this->visitVarDecl(VD, VD->getInit(), /*Toplevel=*/true);
5173
5174 if (R.notCreated())
5175 return R;
5176
5177 if (R)
5178 return true;
5179
5180 if (!R && Context::shouldBeGloballyIndexed(VD)) {
5181 if (auto GlobalIndex = P.getGlobal(VD)) {
5182 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
5183 auto &GD = GlobalBlock->getBlockDesc<GlobalInlineDescriptor>();
5184
5186 GlobalBlock->invokeDtor();
5187 }
5188 }
5189
5190 return R;
5191}
5192
5193/// Toplevel visitDeclAndReturn().
5194/// We get here from evaluateAsInitializer().
5195/// We need to evaluate the initializer and return its value.
5196template <class Emitter>
5198 bool ConstantContext) {
5199 // We only create variables if we're evaluating in a constant context.
5200 // Otherwise, just evaluate the initializer and return it.
5201 if (!ConstantContext) {
5202 DeclScope<Emitter> LS(this, VD);
5203 if (!this->visit(Init))
5204 return false;
5205 return this->emitRet(classify(Init).value_or(PT_Ptr), VD) &&
5206 LS.destroyLocals() && this->emitCheckAllocations(VD);
5207 }
5208
5209 LocalScope<Emitter> VDScope(this);
5210 if (!this->visitVarDecl(VD, Init, /*Toplevel=*/true))
5211 return false;
5212
5213 OptPrimType VarT = classify(VD->getType());
5215 auto GlobalIndex = P.getGlobal(VD);
5216 assert(GlobalIndex); // visitVarDecl() didn't return false.
5217 if (VarT) {
5218 if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD))
5219 return false;
5220 } else {
5221 if (!this->emitGetPtrGlobal(*GlobalIndex, VD))
5222 return false;
5223 }
5224 } else {
5225 auto Local = Locals.find(VD);
5226 assert(Local != Locals.end()); // Same here.
5227 if (VarT) {
5228 if (!this->emitGetLocal(*VarT, Local->second.Offset, VD))
5229 return false;
5230 } else {
5231 if (!this->emitGetPtrLocal(Local->second.Offset, VD))
5232 return false;
5233 }
5234 }
5235
5236 // Return the value.
5237 if (!this->emitRet(VarT.value_or(PT_Ptr), VD)) {
5238 // If the Ret above failed and this is a global variable, mark it as
5239 // uninitialized, even everything else succeeded.
5241 auto GlobalIndex = P.getGlobal(VD);
5242 assert(GlobalIndex);
5243 Block *GlobalBlock = P.getGlobal(*GlobalIndex);
5244 auto &GD = GlobalBlock->getBlockDesc<GlobalInlineDescriptor>();
5245
5247 GlobalBlock->invokeDtor();
5248 }
5249 return false;
5250 }
5251
5252 return VDScope.destroyLocals() && this->emitCheckAllocations(VD);
5253}
5254
5255template <class Emitter>
5257 const Expr *Init,
5258 bool Toplevel) {
5259 QualType VarTy = VD->getType();
5260 // We don't know what to do with these, so just return false.
5261 if (VarTy.isNull())
5262 return false;
5263
5264 // This case is EvalEmitter-only. If we won't create any instructions for the
5265 // initializer anyway, don't bother creating the variable in the first place.
5266 if (!this->isActive())
5268
5269 OptPrimType VarT = classify(VD->getType());
5270
5271 if (Init && Init->isValueDependent())
5272 return false;
5273
5275 auto checkDecl = [&]() -> bool {
5276 bool NeedsOp = !Toplevel && VD->isLocalVarDecl() && VD->isStaticLocal();
5277 return !NeedsOp || this->emitCheckDecl(VD, VD);
5278 };
5279
5281 UnsignedOrNone GlobalIndex = P.getGlobal(VD);
5282 if (GlobalIndex) {
5283 // The global was previously created but the initializer failed.
5284 if (!P.getGlobal(*GlobalIndex)->isInitialized())
5285 return false;
5286 // We've already seen and initialized this global.
5287 if (P.isGlobalInitialized(*GlobalIndex))
5288 return checkDecl();
5289 // The previous attempt at initialization might've been unsuccessful,
5290 // so let's try this one.
5291 } else if ((GlobalIndex =
5292 P.createGlobal(VD, Init, VariablesAreConstexprUnknown))) {
5293 } else {
5294 return false;
5295 }
5296 if (!Init)
5297 return true;
5298
5299 if (!checkDecl())
5300 return false;
5301
5302 if (VarT) {
5303 if (!this->visit(Init))
5304 return false;
5305
5306 return this->emitInitGlobal(*VarT, *GlobalIndex, VD);
5307 }
5308
5309 if (!this->emitGetPtrGlobal(*GlobalIndex, Init))
5310 return false;
5311
5312 if (!this->emitStartInit(Init))
5313 return false;
5314
5315 if (!visitInitializer(Init))
5316 return false;
5317
5318 if (!this->emitEndInit(Init))
5319 return false;
5320
5321 return this->emitFinishInitGlobal(Init);
5322 }
5323 // Local variables.
5325
5326 if (VarT) {
5327 unsigned Offset = this->allocateLocalPrimitive(
5328 VD, *VarT, VarTy.isConstQualified(), VarTy.isVolatileQualified(),
5330
5331 if (!Init || Init->getType()->isVoidType())
5332 return true;
5333
5334 // If this is a toplevel declaration, create a scope for the
5335 // initializer.
5336 if (Toplevel) {
5338 if (!this->visit(Init))
5339 return false;
5340 return this->emitSetLocal(*VarT, Offset, VD) && Scope.destroyLocals();
5341 }
5342 if (!this->visit(Init))
5343 return false;
5344
5345 if (VarTy->isReferenceType()) {
5346 // [C++26][decl.ref]
5347 // The object designated by such a glvalue can be outside its lifetime
5348 // Because a null pointer value or a pointer past the end of an object
5349 // does not point to an object, a reference in a well-defined program
5350 // cannot refer to such things;
5351 assert(classifyPrim(VarTy) == PT_Ptr);
5352 if (!this->emitCheckRefInit(Init))
5353 return false;
5354 }
5355
5356 return this->emitSetLocal(*VarT, Offset, VD);
5357 }
5358 // Local composite variables.
5359 if (UnsignedOrNone Offset =
5360 this->allocateLocal(VD, VarTy, ScopeKind::Block)) {
5361 if (!Init)
5362 return true;
5363
5364 if (!this->emitGetPtrLocal(*Offset, Init))
5365 return false;
5366
5367 return visitInitializerPop(Init);
5368 }
5369 return false;
5370}
5371
5372template <class Emitter>
5374 assert(!canClassify(VD->getType()));
5375
5377 // Create a local variable to use as the instance.
5378 QualType Ty = VD->getType();
5379 Descriptor *D =
5380 P.createDescriptor(VD, Ty.getTypePtr(), Descriptor::InlineDescMD,
5381 /*IsConst=*/Ty.isConstQualified(),
5382 /*IsTemporary=*/false, /*IsMutable=*/false,
5383 /*IsVolatile=*/Ty.isVolatileQualified(), nullptr);
5384 if (!D)
5385 return false;
5386
5387 // FIXME: Would be nice if we didn't allocate the descriptor at all in this
5388 // case.
5389 if (D->hasTrivialDtor())
5390 return true;
5391
5392 Scope::Local Local = this->createLocal(D);
5393 Locals.insert({VD, Local});
5394 VarScope->addForScopeKind(Local, ScopeKind::Block);
5395
5396 if (!this->emitGetPtrLocal(Local.Offset, VD))
5397 return false;
5398
5399 if (!this->visitAPValueInitializer(Value, VD, Ty))
5400 return false;
5401
5402 return this->emitDestructionPop(D, VD);
5403}
5404
5406public:
5408 explicit ParamFinder() {}
5409
5410 bool VisitDeclRefExpr(const DeclRefExpr *E) override {
5411 if (const auto *P = dyn_cast<ParmVarDecl>(E->getDecl()))
5412 FoundParams.insert(P);
5413 return true;
5414 }
5415};
5416
5417/// Evaluate the \p Condition as if it was in the body of \p Callee.
5418/// Specifically, all the parameters of the callee are available to use
5419/// for the condition, and their values are given by \p Args (and \p This).
5420///
5421// Since this is a somewhat niche feature, we're abusing a few other mechanisms
5422// to implement this.
5423//
5424// We don't create an actual function frame but instead register the parameters
5425// as local variables.
5426//
5427// So we evaluate something like:
5428//
5429// bool thisfunc() {
5430// auto Arg0 = Args[0];
5431// ...
5432// return Condition;
5433// }
5434//
5435template <class Emitter>
5438 const Expr *This,
5439 const Expr *Condition) {
5440 // Instead of evaluating all parameters and trying to ignore failure,
5441 // we collect all the parameters used in the condition and only evaluate
5442 // those. Note that we still ignore failure in the loop below because the
5443 // failure might be inconsequential in the end,
5444 // e.g. in the case of `true || x`.
5445 ParamFinder PF;
5447
5448 LocalScope<Emitter> ArgScope(this);
5449 for (const ParmVarDecl *PVD : PF.FoundParams) {
5450 unsigned ParamIndex = 0;
5451 for (const ParmVarDecl *P : Callee->parameters()) {
5452 if (P == PVD)
5453 break;
5454 ++ParamIndex;
5455 }
5456
5457 const Expr *Arg = Args[ParamIndex];
5458 const ParmVarDecl *Param = Callee->getParamDecl(ParamIndex);
5459 if (OptPrimType ParamT = classify(Param->getType())) {
5460 unsigned ArgOffset =
5461 allocateLocalPrimitive(Param, *ParamT, /*IsConst=*/true);
5462 if (!this->visit(Arg))
5463 continue;
5464 if (!this->emitSetLocal(*ParamT, ArgOffset, Arg))
5465 return false;
5466 } else {
5467 UnsignedOrNone ArgOffset = this->allocateLocal(Param, Param->getType());
5468 if (!ArgOffset)
5469 return false;
5470 if (!this->emitGetPtrLocal(*ArgOffset, Arg))
5471 return false;
5472 if (!this->visitInitializerPop(Arg))
5473 continue;
5474 }
5475 }
5476
5477 if (This) {
5478 // We abuse the init stack for this and tell it to use
5479 // either a local variable or another decl for the This pointer.
5480 this->InitStackActive = true;
5481
5482 if (This->getType()->isPointerType()) {
5483 // Nothing to do here, the evaluation will fail if the instance
5484 // pointer is used.
5485 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(This)) {
5486 InitStack.push_back(InitLink::Decl(DRE->getDecl()));
5487 } else {
5488 assert(!canClassify(This->getType()));
5489 UnsignedOrNone ArgOffset = this->allocateLocal(This, This->getType());
5490 if (!ArgOffset)
5491 return false;
5492 if (!this->emitGetPtrLocal(*ArgOffset, This))
5493 return false;
5494 if (!this->visitInitializerPop(This))
5495 return false;
5496 this->InitStack.push_back(InitLink::Temp(*ArgOffset));
5497 }
5498 }
5499
5500 // Destruction of the argument values is part of the callee frame,
5501 // so we simply ignore them here.
5502 this->VarScope = nullptr;
5503
5504 LocalScope<Emitter> RetScope(this);
5505 if (!this->visit(Condition))
5506 return false;
5507 if (!RetScope.destroyLocals())
5508 return false;
5509
5510 // Result of the condition should be on the stack.
5511 return this->emitRet(PT_Bool, Condition);
5512}
5513
5514template <class Emitter>
5516 SourceInfo Info) {
5517 assert(!Val.isIndeterminate() && "Needs to be checked before");
5518 assert(!DiscardResult);
5519 if (Val.isInt())
5520 return this->emitConst(Val.getInt(), ValType, Info);
5521 if (Val.isFloat()) {
5522 APFloat F = Val.getFloat();
5523 return this->emitFloat(F, Info);
5524 }
5525
5526 if (Val.isMemberPointer()) {
5527 if (const ValueDecl *MemberDecl = Val.getMemberPointerDecl()) {
5528 if (!this->emitGetMemberPtr(MemberDecl, Info))
5529 return false;
5530
5531 bool IsDerived = Val.isMemberPointerToDerivedMember();
5532 // Apply the member pointer path.
5533 for (const CXXRecordDecl *PathEntry : Val.getMemberPointerPath()) {
5534 if (!this->emitCopyMemberPtrPath(PathEntry, IsDerived, Info))
5535 return false;
5536 }
5537
5538 return true;
5539 }
5540 return this->emitNullMemberPtr(0, nullptr, Info);
5541 }
5542
5543 if (Val.isLValue()) {
5544 if (Val.isNullPointer())
5545 return this->emitNull(ValType, 0, nullptr, Info);
5546
5549
5550 if (const Expr *BaseExpr = Base.dyn_cast<const Expr *>())
5551 return this->visit(BaseExpr);
5552 if (const auto *VD = Base.dyn_cast<const ValueDecl *>()) {
5553 if (!this->visitDeclRef(VD, Info.asExpr()))
5554 return false;
5555
5556 QualType EntryType = VD->getType();
5557 for (auto &Entry : Path) {
5558 if (EntryType->isArrayType()) {
5559 uint64_t Index = Entry.getAsArrayIndex();
5560 QualType ElemType =
5561 EntryType->getAsArrayTypeUnsafe()->getElementType();
5562 if (!this->emitConst(Index, PT_Uint64, Info))
5563 return false;
5564 if (!this->emitArrayElemPtrPop(PT_Uint64, Info))
5565 return false;
5566 EntryType = ElemType;
5567 } else {
5568 assert(EntryType->isRecordType());
5569 const Record *EntryRecord = getRecord(EntryType);
5570 if (!EntryRecord) {
5571 assert(false);
5572
5573 return false;
5574 }
5575
5576 const Decl *BaseOrMember = Entry.getAsBaseOrMember().getPointer();
5577 if (const auto *FD = dyn_cast<FieldDecl>(BaseOrMember)) {
5578 unsigned EntryOffset = EntryRecord->getField(FD)->Offset;
5579 if (!this->emitGetPtrFieldPop(EntryOffset, Info))
5580 return false;
5581 EntryType = FD->getType();
5582 } else {
5583 const auto *Base = cast<CXXRecordDecl>(BaseOrMember);
5584 unsigned BaseOffset = EntryRecord->getBase(Base)->Offset;
5585 if (!this->emitGetPtrBasePop(BaseOffset, /*NullOK=*/false, Info))
5586 return false;
5587 EntryType = Ctx.getASTContext().getCanonicalTagType(Base);
5588 }
5589 }
5590 }
5591
5592 return true;
5593 }
5594 }
5595
5596 return false;
5597}
5598
5599template <class Emitter>
5601 SourceInfo Info, QualType T) {
5602 if (Val.isStruct()) {
5603 const Record *R = this->getRecord(T);
5604 assert(R);
5605 for (unsigned I = 0, N = Val.getStructNumFields(); I != N; ++I) {
5606 const APValue &F = Val.getStructField(I);
5607 if (F.isIndeterminate())
5608 continue;
5609 const Record::Field *RF = R->getField(I);
5610 QualType FieldType = RF->Decl->getType();
5611
5612 // Fields.
5613 if (OptPrimType PT = classify(FieldType)) {
5614 if (!this->visitAPValue(F, *PT, Info))
5615 return false;
5616 if (!this->emitInitField(*PT, RF->Offset, Info))
5617 return false;
5618 } else {
5619 if (!this->emitGetPtrField(RF->Offset, Info))
5620 return false;
5621 if (!this->visitAPValueInitializer(F, Info, FieldType))
5622 return false;
5623 if (!this->emitFinishInitPop(Info))
5624 return false;
5625 }
5626 }
5627
5628 // Bases.
5629 for (unsigned I = 0, N = Val.getStructNumBases(); I != N; ++I) {
5630 // FIXME: APValue doesn't know about virtual bases.
5631 // We simply assume that if the APValue has more bases than the Record,
5632 // those additional bases must be virtual.
5633 if (I >= R->getNumBases())
5634 break;
5635 const APValue &B = Val.getStructBase(I);
5636 if (B.isIndeterminate())
5637 continue;
5638 const Record::Base *RB = R->getBase(I);
5639 QualType BaseType = Ctx.getASTContext().getCanonicalTagType(RB->Decl);
5640
5641 if (!this->emitGetPtrBase(RB->Offset, Info))
5642 return false;
5643 if (!this->visitAPValueInitializer(B, Info, BaseType))
5644 return false;
5645 if (!this->emitFinishInitPop(Info))
5646 return false;
5647 }
5648
5649 return true;
5650 }
5651 if (Val.isUnion()) {
5652 const FieldDecl *UnionField = Val.getUnionField();
5653 if (!UnionField)
5654 return true;
5655 const Record *R = this->getRecord(T);
5656 assert(R);
5657 const APValue &F = Val.getUnionValue();
5658 if (F.isIndeterminate())
5659 return true;
5660 const Record::Field *RF = R->getField(UnionField);
5661 QualType FieldType = RF->Decl->getType();
5662
5663 if (OptPrimType PT = classify(FieldType)) {
5664 if (!this->visitAPValue(F, *PT, Info))
5665 return false;
5666 if (RF->isBitField())
5667 return this->emitInitBitFieldActivate(*PT, RF->Offset, RF->bitWidth(),
5668 Info);
5669 return this->emitInitFieldActivate(*PT, RF->Offset, Info);
5670 }
5671
5672 if (!this->emitGetPtrField(RF->Offset, Info))
5673 return false;
5674 if (!this->emitActivate(Info))
5675 return false;
5676 if (!this->visitAPValueInitializer(F, Info, FieldType))
5677 return false;
5678 return this->emitPopPtr(Info);
5679 }
5680 if (Val.isArray()) {
5681 unsigned InitializedElems = Val.getArrayInitializedElts();
5682 const auto *ArrType = T->getAsArrayTypeUnsafe();
5683 QualType ElemType = ArrType->getElementType();
5684 OptPrimType ElemT = classify(ElemType);
5685
5686 for (unsigned A = 0, AN = Val.getArraySize(); A != AN; ++A) {
5687 const APValue &Elem = A >= InitializedElems
5688 ? Val.getArrayFiller()
5689 : Val.getArrayInitializedElt(A);
5690 if (Elem.isIndeterminate())
5691 continue;
5692
5693 if (ElemT) {
5694 if (!this->visitAPValue(Elem, *ElemT, Info))
5695 return false;
5696 if (!this->emitInitElem(*ElemT, A, Info))
5697 return false;
5698 } else {
5699 if (!this->emitConstUint32(A, Info))
5700 return false;
5701 if (!this->emitArrayElemPtrUint32(Info))
5702 return false;
5703 if (!this->visitAPValueInitializer(Elem, Info, ElemType))
5704 return false;
5705 if (!this->emitPopPtr(Info))
5706 return false;
5707 }
5708 }
5709 return true;
5710 }
5711 // TODO: Other types.
5712
5713 return false;
5714}
5715
5716template <class Emitter>
5718 unsigned BuiltinID) {
5719 if (BuiltinID == Builtin::BI__builtin_constant_p) {
5720 // Void argument is always invalid and harder to handle later.
5721 if (E->getArg(0)->getType()->isVoidType()) {
5722 if (DiscardResult)
5723 return true;
5724 return this->emitConst(0, E);
5725 }
5726
5727 if (!this->emitStartSpeculation(E))
5728 return false;
5729 LabelTy EndLabel = this->getLabel();
5730 if (!this->speculate(E, EndLabel))
5731 return false;
5732 if (!this->emitEndSpeculation(E))
5733 return false;
5734 this->fallthrough(EndLabel);
5735 if (DiscardResult)
5736 return this->emitPop(classifyPrim(E), E);
5737 return true;
5738 }
5739
5740 // For these, we're expected to ultimately return an APValue pointing
5741 // to the CallExpr. This is needed to get the correct codegen.
5742 if (BuiltinID == Builtin::BI__builtin___CFStringMakeConstantString ||
5743 BuiltinID == Builtin::BI__builtin___NSStringMakeConstantString ||
5744 BuiltinID == Builtin::BI__builtin_ptrauth_sign_constant ||
5745 BuiltinID == Builtin::BI__builtin_function_start) {
5746 if (DiscardResult)
5747 return true;
5748 return this->emitDummyPtr(E, E);
5749 }
5750
5752 OptPrimType ReturnT = classify(E);
5753
5754 // Non-primitive return type. Prepare storage.
5755 if (!Initializing && !ReturnT && !ReturnType->isVoidType()) {
5756 UnsignedOrNone LocalIndex = allocateLocal(E);
5757 if (!LocalIndex)
5758 return false;
5759 if (!this->emitGetPtrLocal(*LocalIndex, E))
5760 return false;
5761 }
5762
5763 // Prepare function arguments including special cases.
5764 switch (BuiltinID) {
5765 case Builtin::BI__builtin_object_size:
5766 case Builtin::BI__builtin_dynamic_object_size: {
5767 assert(E->getNumArgs() == 2);
5768 const Expr *Arg0 = E->getArg(0);
5769 if (Arg0->isGLValue()) {
5770 if (!this->visit(Arg0))
5771 return false;
5772
5773 } else {
5774 if (!this->visitAsLValue(Arg0))
5775 return false;
5776 }
5777 if (!this->visit(E->getArg(1)))
5778 return false;
5779
5780 } break;
5781 case Builtin::BI__assume:
5782 case Builtin::BI__builtin_assume:
5783 // Argument is not evaluated.
5784 break;
5785 case Builtin::BI__atomic_is_lock_free:
5786 case Builtin::BI__atomic_always_lock_free: {
5787 assert(E->getNumArgs() == 2);
5788 if (!this->visit(E->getArg(0)))
5789 return false;
5790 if (!this->visitAsLValue(E->getArg(1)))
5791 return false;
5792 } break;
5793
5794 default:
5795 if (!Context::isUnevaluatedBuiltin(BuiltinID)) {
5796 // Put arguments on the stack.
5797 for (const auto *Arg : E->arguments()) {
5798 if (!this->visit(Arg))
5799 return false;
5800 }
5801 }
5802 }
5803
5804 if (!this->emitCallBI(E, BuiltinID, E))
5805 return false;
5806
5807 if (DiscardResult && !ReturnType->isVoidType())
5808 return this->emitPop(ReturnT.value_or(PT_Ptr), E);
5809
5810 return true;
5811}
5812
5813template <class Emitter>
5815 if (E->containsErrors())
5816 return false;
5817 const FunctionDecl *FuncDecl = E->getDirectCallee();
5818
5819 if (FuncDecl) {
5820 if (unsigned BuiltinID = FuncDecl->getBuiltinID())
5821 return VisitBuiltinCallExpr(E, BuiltinID);
5822
5823 // Calls to replaceable operator new/operator delete.
5825 if (FuncDecl->getDeclName().isAnyOperatorNew())
5826 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_new);
5827 assert(FuncDecl->getDeclName().getCXXOverloadedOperator() == OO_Delete ||
5828 FuncDecl->getDeclName().getCXXOverloadedOperator() ==
5829 OO_Array_Delete);
5830 return VisitBuiltinCallExpr(E, Builtin::BI__builtin_operator_delete);
5831 }
5832
5833 // Explicit calls to trivial destructors
5834 if (const auto *DD = dyn_cast<CXXDestructorDecl>(FuncDecl);
5835 DD && DD->isTrivial()) {
5836 const auto *MemberCall = cast<CXXMemberCallExpr>(E);
5837 if (!this->visit(MemberCall->getImplicitObjectArgument()))
5838 return false;
5839 return this->emitCheckDestruction(E) && this->emitEndLifetime(E) &&
5840 this->emitPopPtr(E);
5841 }
5842 }
5843
5844 LocalScope<Emitter> CallScope(this, ScopeKind::Call);
5845
5846 QualType ReturnType = E->getCallReturnType(Ctx.getASTContext());
5848 bool HasRVO = !ReturnType->isVoidType() && !T;
5849
5850 if (HasRVO) {
5851 if (DiscardResult) {
5852 // If we need to discard the return value but the function returns its
5853 // value via an RVO pointer, we need to create one such pointer just
5854 // for this call.
5855 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
5856 if (!this->emitGetPtrLocal(*LocalIndex, E))
5857 return false;
5858 }
5859 } else {
5860 // We need the result. Prepare a pointer to return or
5861 // dup the current one.
5862 if (!Initializing) {
5863 if (UnsignedOrNone LocalIndex = allocateLocal(E)) {
5864 if (!this->emitGetPtrLocal(*LocalIndex, E))
5865 return false;
5866 }
5867 }
5868 if (!this->emitDupPtr(E))
5869 return false;
5870 }
5871 }
5872
5874
5875 bool IsAssignmentOperatorCall = false;
5876 bool ActivateLHS = false;
5877 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E);
5878 OCE && OCE->isAssignmentOp()) {
5879 // Just like with regular assignments, we need to special-case assignment
5880 // operators here and evaluate the RHS (the second arg) before the LHS (the
5881 // first arg). We fix this by using a Flip op later.
5882 assert(Args.size() == 2);
5883 const CXXRecordDecl *LHSRecord = Args[0]->getType()->getAsCXXRecordDecl();
5884 ActivateLHS = LHSRecord && LHSRecord->hasTrivialDefaultConstructor();
5885 IsAssignmentOperatorCall = true;
5886 std::reverse(Args.begin(), Args.end());
5887 }
5888 // Calling a static operator will still
5889 // pass the instance, but we don't need it.
5890 // Discard it here.
5891 if (isa<CXXOperatorCallExpr>(E)) {
5892 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl);
5893 MD && MD->isStatic()) {
5894 if (!this->discard(E->getArg(0)))
5895 return false;
5896 // Drop first arg.
5897 Args.erase(Args.begin());
5898 }
5899 }
5900
5901 bool Devirtualized = false;
5902 UnsignedOrNone CalleeOffset = std::nullopt;
5903 // Add the (optional, implicit) This pointer.
5904 if (const auto *MC = dyn_cast<CXXMemberCallExpr>(E)) {
5905 if (!FuncDecl && classifyPrim(E->getCallee()) == PT_MemberPtr) {
5906 // If we end up creating a CallPtr op for this, we need the base of the
5907 // member pointer as the instance pointer, and later extract the function
5908 // decl as the function pointer.
5909 const Expr *Callee = E->getCallee();
5910 CalleeOffset =
5911 this->allocateLocalPrimitive(Callee, PT_MemberPtr, /*IsConst=*/true);
5912 if (!this->visit(Callee))
5913 return false;
5914 if (!this->emitSetLocal(PT_MemberPtr, *CalleeOffset, E))
5915 return false;
5916 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
5917 return false;
5918 if (!this->emitGetMemberPtrBase(E))
5919 return false;
5920 } else {
5921 const auto *InstancePtr = MC->getImplicitObjectArgument();
5922 if (isa_and_nonnull<CXXDestructorDecl>(CompilingFunction) ||
5923 isa_and_nonnull<CXXConstructorDecl>(CompilingFunction)) {
5924 const auto *Stripped = stripCheckedDerivedToBaseCasts(InstancePtr);
5925 if (isa<CXXThisExpr>(Stripped)) {
5926 FuncDecl =
5927 cast<CXXMethodDecl>(FuncDecl)->getCorrespondingMethodInClass(
5928 Stripped->getType()->getPointeeType()->getAsCXXRecordDecl());
5929 Devirtualized = true;
5930 if (!this->visit(Stripped))
5931 return false;
5932 } else {
5933 if (!this->visit(InstancePtr))
5934 return false;
5935 }
5936 } else {
5937 if (!this->visit(InstancePtr))
5938 return false;
5939 }
5940 }
5941 } else if (const auto *PD =
5942 dyn_cast<CXXPseudoDestructorExpr>(E->getCallee())) {
5943 if (!this->emitCheckPseudoDtor(E))
5944 return false;
5945 const Expr *Base = PD->getBase();
5946 // E.g. `using T = int; 0.~T();`.
5947 if (OptPrimType BaseT = classify(Base); !BaseT || BaseT != PT_Ptr)
5948 return this->discard(Base);
5949 if (!this->visit(Base))
5950 return false;
5951 return this->emitEndLifetimePop(E);
5952 } else if (!FuncDecl) {
5953 const Expr *Callee = E->getCallee();
5954 CalleeOffset =
5955 this->allocateLocalPrimitive(Callee, PT_Ptr, /*IsConst=*/true);
5956 if (!this->visit(Callee))
5957 return false;
5958 if (!this->emitSetLocal(PT_Ptr, *CalleeOffset, E))
5959 return false;
5960 }
5961
5962 if (!this->visitCallArgs(Args, FuncDecl, ActivateLHS,
5964 return false;
5965
5966 // Undo the argument reversal we did earlier.
5967 if (IsAssignmentOperatorCall) {
5968 assert(Args.size() == 2);
5969 PrimType Arg1T = classify(Args[0]).value_or(PT_Ptr);
5970 PrimType Arg2T = classify(Args[1]).value_or(PT_Ptr);
5971 if (!this->emitFlip(Arg2T, Arg1T, E))
5972 return false;
5973 }
5974
5975 if (FuncDecl) {
5976 const Function *Func = getFunction(FuncDecl);
5977 if (!Func)
5978 return false;
5979
5980 // In error cases, the function may be called with fewer arguments than
5981 // parameters.
5982 if (E->getNumArgs() < Func->getNumWrittenParams())
5983 return false;
5984
5985 assert(HasRVO == Func->hasRVO());
5986
5987 bool HasQualifier = false;
5988 if (const auto *ME = dyn_cast<MemberExpr>(E->getCallee()))
5989 HasQualifier = ME->hasQualifier();
5990
5991 bool IsVirtual = false;
5992 if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl))
5993 IsVirtual = !Devirtualized && MD->isVirtual();
5994
5995 // In any case call the function. The return value will end up on the stack
5996 // and if the function has RVO, we already have the pointer on the stack to
5997 // write the result into.
5998 if (IsVirtual && !HasQualifier) {
5999 uint32_t VarArgSize = 0;
6000 unsigned NumParams =
6001 Func->getNumWrittenParams() +
6002 (isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisParam());
6003 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
6004 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6005
6006 if (!this->emitCallVirt(Func, VarArgSize, E))
6007 return false;
6008 } else if (Func->isVariadic()) {
6009 uint32_t VarArgSize = 0;
6010 unsigned NumParams =
6011 Func->getNumWrittenParams() +
6012 (isa<CXXOperatorCallExpr>(E) && Func->hasImplicitThisParam());
6013 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I)
6014 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6015 if (!this->emitCallVar(Func, VarArgSize, E))
6016 return false;
6017 } else {
6018 if (!this->emitCall(Func, 0, E))
6019 return false;
6020 }
6021 } else {
6022 // Indirect call. Visit the callee, which will leave a FunctionPointer on
6023 // the stack. Cleanup of the returned value if necessary will be done after
6024 // the function call completed.
6025
6026 // Sum the size of all args from the call expr.
6027 uint32_t ArgSize = 0;
6028 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I)
6029 ArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr)));
6030
6031 // Get the callee, either from a member pointer or function pointer saved in
6032 // CalleeOffset.
6033 if (isa<CXXMemberCallExpr>(E) && CalleeOffset) {
6034 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E))
6035 return false;
6036 if (!this->emitGetMemberPtrDecl(E))
6037 return false;
6038 } else {
6039 if (!this->emitGetLocal(PT_Ptr, *CalleeOffset, E))
6040 return false;
6041 }
6042 if (!this->emitCallPtr(ArgSize, E, E))
6043 return false;
6044 }
6045
6046 // Cleanup for discarded return values.
6047 if (DiscardResult && !ReturnType->isVoidType() && T)
6048 return this->emitPop(*T, E) && CallScope.destroyLocals();
6049
6050 return CallScope.destroyLocals();
6051}
6052
6053template <class Emitter>
6055 SourceLocScope<Emitter> SLS(this, E);
6056
6057 return this->delegate(E->getExpr());
6058}
6059
6060template <class Emitter>
6062 SourceLocScope<Emitter> SLS(this, E);
6063
6064 return this->delegate(E->getExpr());
6065}
6066
6067template <class Emitter>
6069 if (DiscardResult)
6070 return true;
6071
6072 return this->emitConstBool(E->getValue(), E);
6073}
6074
6075template <class Emitter>
6077 const CXXNullPtrLiteralExpr *E) {
6078 if (DiscardResult)
6079 return true;
6080
6081 uint64_t Val = Ctx.getASTContext().getTargetNullPointerValue(E->getType());
6082 return this->emitNullPtr(Val, nullptr, E);
6083}
6084
6085template <class Emitter>
6087 if (DiscardResult)
6088 return true;
6089
6090 assert(E->getType()->isIntegerType());
6091
6092 PrimType T = classifyPrim(E->getType());
6093 return this->emitZero(T, E);
6094}
6095
6096template <class Emitter>
6098 if (DiscardResult)
6099 return true;
6100
6101 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
6102 if (this->LambdaThisCapture.Offset > 0) {
6103 if (this->LambdaThisCapture.IsPtr)
6104 return this->emitGetThisFieldPtr(this->LambdaThisCapture.Offset, E);
6105 return this->emitGetPtrThisField(this->LambdaThisCapture.Offset, E);
6106 }
6107 }
6108
6109 // In some circumstances, the 'this' pointer does not actually refer to the
6110 // instance pointer of the current function frame, but e.g. to the declaration
6111 // currently being initialized. Here we emit the necessary instruction(s) for
6112 // this scenario.
6113 if (!InitStackActive || InitStack.empty())
6114 return this->emitThis(E);
6115
6116 // If our init stack is, for example:
6117 // 0 Stack: 3 (decl)
6118 // 1 Stack: 6 (init list)
6119 // 2 Stack: 1 (field)
6120 // 3 Stack: 6 (init list)
6121 // 4 Stack: 1 (field)
6122 //
6123 // We want to find the LAST element in it that's an init list,
6124 // which is marked with the K_InitList marker. The index right
6125 // before that points to an init list. We need to find the
6126 // elements before the K_InitList element that point to a base
6127 // (e.g. a decl or This), optionally followed by field, elem, etc.
6128 // In the example above, we want to emit elements [0..2].
6129 unsigned StartIndex = 0;
6130 unsigned EndIndex = 0;
6131 // Find the init list.
6132 for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) {
6133 if (InitStack[StartIndex].Kind == InitLink::K_DIE) {
6134 EndIndex = StartIndex;
6135 --StartIndex;
6136 break;
6137 }
6138 }
6139
6140 // Walk backwards to find the base.
6141 for (; StartIndex > 0; --StartIndex) {
6142 if (InitStack[StartIndex].Kind == InitLink::K_InitList)
6143 continue;
6144
6145 if (InitStack[StartIndex].Kind != InitLink::K_Field &&
6146 InitStack[StartIndex].Kind != InitLink::K_Elem &&
6147 InitStack[StartIndex].Kind != InitLink::K_DIE)
6148 break;
6149 }
6150
6151 if (StartIndex == 0 && EndIndex == 0)
6152 EndIndex = InitStack.size() - 1;
6153
6154 // NOTE: This could be StartIndex < EndIndex, but we're also abusing the
6155 // InitStack mechanism in visitWithSubstitutions to have the This pointer
6156 // _just_ be a local variable.
6157 assert(StartIndex <= EndIndex);
6158
6159 // Emit the instructions.
6160 for (unsigned I = StartIndex; I != (EndIndex + 1); ++I) {
6161 if (InitStack[I].Kind == InitLink::K_InitList ||
6162 InitStack[I].Kind == InitLink::K_DIE)
6163 continue;
6164 if (!InitStack[I].template emit<Emitter>(this, E))
6165 return false;
6166 }
6167 return true;
6168}
6169
6170template <class Emitter> bool Compiler<Emitter>::visitStmt(const Stmt *S) {
6171 switch (S->getStmtClass()) {
6172 case Stmt::CompoundStmtClass:
6174 case Stmt::DeclStmtClass:
6175 return visitDeclStmt(cast<DeclStmt>(S), /*EvaluateConditionDecl=*/true);
6176 case Stmt::ReturnStmtClass:
6178 case Stmt::IfStmtClass:
6179 return visitIfStmt(cast<IfStmt>(S));
6180 case Stmt::WhileStmtClass:
6182 case Stmt::DoStmtClass:
6183 return visitDoStmt(cast<DoStmt>(S));
6184 case Stmt::ForStmtClass:
6185 return visitForStmt(cast<ForStmt>(S));
6186 case Stmt::CXXForRangeStmtClass:
6188 case Stmt::BreakStmtClass:
6190 case Stmt::ContinueStmtClass:
6192 case Stmt::SwitchStmtClass:
6194 case Stmt::CaseStmtClass:
6195 return visitCaseStmt(cast<CaseStmt>(S));
6196 case Stmt::DefaultStmtClass:
6198 case Stmt::AttributedStmtClass:
6200 case Stmt::CXXTryStmtClass:
6202 case Stmt::NullStmtClass:
6203 return true;
6204 // Always invalid statements.
6205 case Stmt::GCCAsmStmtClass:
6206 case Stmt::MSAsmStmtClass:
6207 case Stmt::GotoStmtClass:
6208 return this->emitInvalid(S);
6209 case Stmt::LabelStmtClass:
6210 return this->visitStmt(cast<LabelStmt>(S)->getSubStmt());
6211 default: {
6212 if (const auto *E = dyn_cast<Expr>(S))
6213 return this->discard(E);
6214 return false;
6215 }
6216 }
6217}
6218
6219template <class Emitter>
6222 for (const auto *InnerStmt : S->body())
6223 if (!visitStmt(InnerStmt))
6224 return false;
6225 return Scope.destroyLocals();
6226}
6227
6228template <class Emitter>
6229bool Compiler<Emitter>::maybeEmitDeferredVarInit(const VarDecl *VD) {
6230 if (auto *DD = dyn_cast_if_present<DecompositionDecl>(VD)) {
6231 for (auto *BD : DD->flat_bindings())
6232 if (auto *KD = BD->getHoldingVar();
6233 KD && !this->visitVarDecl(KD, KD->getInit()))
6234 return false;
6235 }
6236 return true;
6237}
6238
6240 assert(FD);
6241 assert(FD->getParent()->isUnion());
6242 const CXXRecordDecl *CXXRD =
6244 return !CXXRD || CXXRD->hasTrivialDefaultConstructor();
6245}
6246
6247template <class Emitter> bool Compiler<Emitter>::refersToUnion(const Expr *E) {
6248 for (;;) {
6249 if (const auto *ME = dyn_cast<MemberExpr>(E)) {
6250 if (const auto *FD = dyn_cast<FieldDecl>(ME->getMemberDecl());
6251 FD && FD->getParent()->isUnion() && hasTrivialDefaultCtorParent(FD))
6252 return true;
6253 E = ME->getBase();
6254 continue;
6255 }
6256
6257 if (const auto *ASE = dyn_cast<ArraySubscriptExpr>(E)) {
6258 E = ASE->getBase()->IgnoreImplicit();
6259 continue;
6260 }
6261
6262 if (const auto *ICE = dyn_cast<ImplicitCastExpr>(E);
6263 ICE && (ICE->getCastKind() == CK_NoOp ||
6264 ICE->getCastKind() == CK_DerivedToBase ||
6265 ICE->getCastKind() == CK_UncheckedDerivedToBase)) {
6266 E = ICE->getSubExpr();
6267 continue;
6268 }
6269
6270 if (const auto *This = dyn_cast<CXXThisExpr>(E)) {
6271 const auto *ThisRecord =
6272 This->getType()->getPointeeType()->getAsRecordDecl();
6273 if (!ThisRecord->isUnion())
6274 return false;
6275 // Otherwise, always activate if we're in the ctor.
6276 if (const auto *Ctor =
6277 dyn_cast_if_present<CXXConstructorDecl>(CompilingFunction))
6278 return Ctor->getParent() == ThisRecord;
6279 return false;
6280 }
6281
6282 break;
6283 }
6284 return false;
6285}
6286
6287template <class Emitter>
6289 bool EvaluateConditionDecl) {
6290 for (const auto *D : DS->decls()) {
6293 continue;
6294
6295 const auto *VD = dyn_cast<VarDecl>(D);
6296 if (!VD)
6297 return false;
6298 if (!this->visitVarDecl(VD, VD->getInit()))
6299 return false;
6300
6301 // Register decomposition decl holding vars.
6302 if (EvaluateConditionDecl && !this->maybeEmitDeferredVarInit(VD))
6303 return false;
6304 }
6305
6306 return true;
6307}
6308
6309template <class Emitter>
6311 if (this->InStmtExpr)
6312 return this->emitUnsupported(RS);
6313
6314 if (const Expr *RE = RS->getRetValue()) {
6315 LocalScope<Emitter> RetScope(this);
6316 if (ReturnType) {
6317 // Primitive types are simply returned.
6318 if (!this->visit(RE))
6319 return false;
6320 this->emitCleanup();
6321 return this->emitRet(*ReturnType, RS);
6322 }
6323
6324 if (RE->getType()->isVoidType()) {
6325 if (!this->visit(RE))
6326 return false;
6327 } else {
6328 if (RE->containsErrors())
6329 return false;
6330
6332 // RVO - construct the value in the return location.
6333 if (!this->emitRVOPtr(RE))
6334 return false;
6335 if (!this->visitInitializerPop(RE))
6336 return false;
6337
6338 this->emitCleanup();
6339 return this->emitRetVoid(RS);
6340 }
6341 }
6342
6343 // Void return.
6344 this->emitCleanup();
6345 return this->emitRetVoid(RS);
6346}
6347
6348template <class Emitter> bool Compiler<Emitter>::visitIfStmt(const IfStmt *IS) {
6349 LocalScope<Emitter> IfScope(this);
6350
6351 auto visitChildStmt = [&](const Stmt *S) -> bool {
6352 LocalScope<Emitter> SScope(this);
6353 if (!visitStmt(S))
6354 return false;
6355 return SScope.destroyLocals();
6356 };
6357
6358 if (auto *CondInit = IS->getInit()) {
6359 if (!visitStmt(CondInit))
6360 return false;
6361 }
6362
6363 if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt()) {
6364 if (!visitDeclStmt(CondDecl))
6365 return false;
6366 }
6367
6368 // Save ourselves compiling some code and the jumps, etc. if the condition is
6369 // stataically known to be either true or false. We could look at more cases
6370 // here, but I think all the ones that actually happen are using a
6371 // ConstantExpr.
6372 if (std::optional<bool> BoolValue = getBoolValue(IS->getCond())) {
6373 if (*BoolValue)
6374 return visitChildStmt(IS->getThen());
6375 if (const Stmt *Else = IS->getElse())
6376 return visitChildStmt(Else);
6377 return true;
6378 }
6379
6380 // Otherwise, compile the condition.
6381 if (IS->isNonNegatedConsteval()) {
6382 if (!this->emitIsConstantContext(IS))
6383 return false;
6384 } else if (IS->isNegatedConsteval()) {
6385 if (!this->emitIsConstantContext(IS))
6386 return false;
6387 if (!this->emitInv(IS))
6388 return false;
6389 } else {
6391 if (!this->visitBool(IS->getCond()))
6392 return false;
6393 if (!CondScope.destroyLocals())
6394 return false;
6395 }
6396
6397 if (!this->maybeEmitDeferredVarInit(IS->getConditionVariable()))
6398 return false;
6399
6400 if (const Stmt *Else = IS->getElse()) {
6401 LabelTy LabelElse = this->getLabel();
6402 LabelTy LabelEnd = this->getLabel();
6403 if (!this->jumpFalse(LabelElse, IS))
6404 return false;
6405 if (!visitChildStmt(IS->getThen()))
6406 return false;
6407 if (!this->jump(LabelEnd, IS))
6408 return false;
6409 this->emitLabel(LabelElse);
6410 if (!visitChildStmt(Else))
6411 return false;
6412 this->emitLabel(LabelEnd);
6413 } else {
6414 LabelTy LabelEnd = this->getLabel();
6415 if (!this->jumpFalse(LabelEnd, IS))
6416 return false;
6417 if (!visitChildStmt(IS->getThen()))
6418 return false;
6419 this->emitLabel(LabelEnd);
6420 }
6421
6422 if (!IfScope.destroyLocals())
6423 return false;
6424
6425 return true;
6426}
6427
6428template <class Emitter>
6430 const Expr *Cond = S->getCond();
6431 const Stmt *Body = S->getBody();
6432
6433 LabelTy CondLabel = this->getLabel(); // Label before the condition.
6434 LabelTy EndLabel = this->getLabel(); // Label after the loop.
6435 LocalScope<Emitter> WholeLoopScope(this);
6436 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
6437
6438 this->fallthrough(CondLabel);
6439 this->emitLabel(CondLabel);
6440
6441 // Start of the loop body {
6442 LocalScope<Emitter> CondScope(this);
6443
6444 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
6445 if (!visitDeclStmt(CondDecl))
6446 return false;
6447 }
6448
6449 if (!this->visitBool(Cond))
6450 return false;
6451
6452 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
6453 return false;
6454
6455 if (!this->jumpFalse(EndLabel, S))
6456 return false;
6457
6458 if (!this->visitStmt(Body))
6459 return false;
6460
6461 if (!CondScope.destroyLocals())
6462 return false;
6463 // } End of loop body.
6464
6465 if (!this->jump(CondLabel, S))
6466 return false;
6467 this->fallthrough(EndLabel);
6468 this->emitLabel(EndLabel);
6469
6470 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
6471}
6472
6473template <class Emitter> bool Compiler<Emitter>::visitDoStmt(const DoStmt *S) {
6474 const Expr *Cond = S->getCond();
6475 const Stmt *Body = S->getBody();
6476
6477 LabelTy StartLabel = this->getLabel();
6478 LabelTy EndLabel = this->getLabel();
6479 LabelTy CondLabel = this->getLabel();
6480 LocalScope<Emitter> WholeLoopScope(this);
6481 LoopScope<Emitter> LS(this, S, EndLabel, CondLabel);
6482
6483 this->fallthrough(StartLabel);
6484 this->emitLabel(StartLabel);
6485
6486 {
6487 LocalScope<Emitter> CondScope(this);
6488 if (!this->visitStmt(Body))
6489 return false;
6490 this->fallthrough(CondLabel);
6491 this->emitLabel(CondLabel);
6492 if (!this->visitBool(Cond))
6493 return false;
6494
6495 if (!CondScope.destroyLocals())
6496 return false;
6497 }
6498 if (!this->jumpTrue(StartLabel, S))
6499 return false;
6500
6501 this->fallthrough(EndLabel);
6502 this->emitLabel(EndLabel);
6503 return WholeLoopScope.destroyLocals();
6504}
6505
6506template <class Emitter>
6508 // for (Init; Cond; Inc) { Body }
6509 const Stmt *Init = S->getInit();
6510 const Expr *Cond = S->getCond();
6511 const Expr *Inc = S->getInc();
6512 const Stmt *Body = S->getBody();
6513
6514 LabelTy EndLabel = this->getLabel();
6515 LabelTy CondLabel = this->getLabel();
6516 LabelTy IncLabel = this->getLabel();
6517
6518 LocalScope<Emitter> WholeLoopScope(this);
6519 if (Init && !this->visitStmt(Init))
6520 return false;
6521
6522 // Start of the loop body {
6523 this->fallthrough(CondLabel);
6524 this->emitLabel(CondLabel);
6525
6526 LocalScope<Emitter> CondScope(this);
6527 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
6528 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) {
6529 if (!visitDeclStmt(CondDecl))
6530 return false;
6531 }
6532
6533 if (Cond) {
6534 if (!this->visitBool(Cond))
6535 return false;
6536 if (!this->jumpFalse(EndLabel, S))
6537 return false;
6538 }
6539 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
6540 return false;
6541
6542 if (Body && !this->visitStmt(Body))
6543 return false;
6544
6545 this->fallthrough(IncLabel);
6546 this->emitLabel(IncLabel);
6547 if (Inc && !this->discard(Inc))
6548 return false;
6549
6550 if (!CondScope.destroyLocals())
6551 return false;
6552 if (!this->jump(CondLabel, S))
6553 return false;
6554 // } End of loop body.
6555
6556 this->emitLabel(EndLabel);
6557 // If we jumped out of the loop above, we still need to clean up the condition
6558 // scope.
6559 return CondScope.destroyLocals() && WholeLoopScope.destroyLocals();
6560}
6561
6562template <class Emitter>
6564 const Stmt *Init = S->getInit();
6565 const Expr *Cond = S->getCond();
6566 const Expr *Inc = S->getInc();
6567 const Stmt *Body = S->getBody();
6568 const Stmt *BeginStmt = S->getBeginStmt();
6569 const Stmt *RangeStmt = S->getRangeStmt();
6570 const Stmt *EndStmt = S->getEndStmt();
6571
6572 LabelTy EndLabel = this->getLabel();
6573 LabelTy CondLabel = this->getLabel();
6574 LabelTy IncLabel = this->getLabel();
6575 LocalScope<Emitter> WholeLoopScope(this);
6576 LoopScope<Emitter> LS(this, S, EndLabel, IncLabel);
6577
6578 // Emit declarations needed in the loop.
6579 if (Init && !this->visitStmt(Init))
6580 return false;
6581 if (!this->visitStmt(RangeStmt))
6582 return false;
6583 if (!this->visitStmt(BeginStmt))
6584 return false;
6585 if (!this->visitStmt(EndStmt))
6586 return false;
6587
6588 // Now the condition as well as the loop variable assignment.
6589 this->fallthrough(CondLabel);
6590 this->emitLabel(CondLabel);
6591 if (!this->visitBool(Cond))
6592 return false;
6593 if (!this->jumpFalse(EndLabel, S))
6594 return false;
6595
6596 if (!this->visitDeclStmt(S->getLoopVarStmt(), /*EvaluateConditionDecl=*/true))
6597 return false;
6598
6599 // Body.
6600 {
6601 if (!this->visitStmt(Body))
6602 return false;
6603
6604 this->fallthrough(IncLabel);
6605 this->emitLabel(IncLabel);
6606 if (!this->discard(Inc))
6607 return false;
6608 }
6609
6610 if (!this->jump(CondLabel, S))
6611 return false;
6612
6613 this->fallthrough(EndLabel);
6614 this->emitLabel(EndLabel);
6615 return WholeLoopScope.destroyLocals();
6616}
6617
6618template <class Emitter>
6620 if (LabelInfoStack.empty())
6621 return false;
6622
6623 OptLabelTy TargetLabel = std::nullopt;
6624 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
6625 const VariableScope<Emitter> *BreakScope = nullptr;
6626
6627 if (!TargetLoop) {
6628 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
6629 if (LI.BreakLabel) {
6630 TargetLabel = *LI.BreakLabel;
6631 BreakScope = LI.BreakOrContinueScope;
6632 break;
6633 }
6634 }
6635 } else {
6636 for (auto LI : LabelInfoStack) {
6637 if (LI.Name == TargetLoop) {
6638 TargetLabel = *LI.BreakLabel;
6639 BreakScope = LI.BreakOrContinueScope;
6640 break;
6641 }
6642 }
6643 }
6644
6645 // Faulty break statement (e.g. label redefined or named loops disabled).
6646 if (!TargetLabel)
6647 return false;
6648
6649 for (VariableScope<Emitter> *C = this->VarScope; C != BreakScope;
6650 C = C->getParent()) {
6651 if (!C->destroyLocals())
6652 return false;
6653 }
6654
6655 return this->jump(*TargetLabel, S);
6656}
6657
6658template <class Emitter>
6660 if (LabelInfoStack.empty())
6661 return false;
6662
6663 OptLabelTy TargetLabel = std::nullopt;
6664 const Stmt *TargetLoop = S->getNamedLoopOrSwitch();
6665 const VariableScope<Emitter> *ContinueScope = nullptr;
6666
6667 if (!TargetLoop) {
6668 for (const auto &LI : llvm::reverse(LabelInfoStack)) {
6669 if (LI.ContinueLabel) {
6670 TargetLabel = *LI.ContinueLabel;
6671 ContinueScope = LI.BreakOrContinueScope;
6672 break;
6673 }
6674 }
6675 } else {
6676 for (auto LI : LabelInfoStack) {
6677 if (LI.Name == TargetLoop) {
6678 TargetLabel = *LI.ContinueLabel;
6679 ContinueScope = LI.BreakOrContinueScope;
6680 break;
6681 }
6682 }
6683 }
6684 assert(TargetLabel);
6685
6686 for (VariableScope<Emitter> *C = VarScope; C != ContinueScope;
6687 C = C->getParent()) {
6688 if (!C->destroyLocals())
6689 return false;
6690 }
6691
6692 return this->jump(*TargetLabel, S);
6693}
6694
6695template <class Emitter>
6697 const Expr *Cond = S->getCond();
6698 if (Cond->containsErrors())
6699 return false;
6700
6701 PrimType CondT = this->classifyPrim(Cond->getType());
6702 LocalScope<Emitter> LS(this);
6703 llvm::SaveAndRestore StmtExprSAR(this->SwitchInStmtExpr, this->InStmtExpr);
6704
6705 LabelTy EndLabel = this->getLabel();
6706 UnsignedOrNone DefaultLabel = std::nullopt;
6707 unsigned CondVar =
6708 this->allocateLocalPrimitive(Cond, CondT, /*IsConst=*/true);
6709
6710 if (const auto *CondInit = S->getInit())
6711 if (!visitStmt(CondInit))
6712 return false;
6713
6714 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt())
6715 if (!visitDeclStmt(CondDecl))
6716 return false;
6717
6718 // Initialize condition variable.
6719 if (!this->visit(Cond))
6720 return false;
6721 if (!this->emitSetLocal(CondT, CondVar, S))
6722 return false;
6723
6724 if (!this->maybeEmitDeferredVarInit(S->getConditionVariable()))
6725 return false;
6726
6728 // Create labels and comparison ops for all case statements.
6729 for (const SwitchCase *SC = S->getSwitchCaseList(); SC;
6730 SC = SC->getNextSwitchCase()) {
6731 if (const auto *CS = dyn_cast<CaseStmt>(SC)) {
6732 CaseLabels[SC] = this->getLabel();
6733
6734 if (CS->caseStmtIsGNURange()) {
6735 LabelTy EndOfRangeCheck = this->getLabel();
6736 const Expr *Low = CS->getLHS();
6737 const Expr *High = CS->getRHS();
6738 if (Low->isValueDependent() || High->isValueDependent())
6739 return false;
6740
6741 if (!this->emitGetLocal(CondT, CondVar, CS))
6742 return false;
6743 if (!this->visit(Low))
6744 return false;
6745 PrimType LT = this->classifyPrim(Low->getType());
6746 if (!this->emitGE(LT, S))
6747 return false;
6748 if (!this->jumpFalse(EndOfRangeCheck, S))
6749 return false;
6750
6751 if (!this->emitGetLocal(CondT, CondVar, CS))
6752 return false;
6753 if (!this->visit(High))
6754 return false;
6755 PrimType HT = this->classifyPrim(High->getType());
6756 if (!this->emitLE(HT, S))
6757 return false;
6758 if (!this->jumpTrue(CaseLabels[CS], S))
6759 return false;
6760 this->emitLabel(EndOfRangeCheck);
6761 continue;
6762 }
6763
6764 const Expr *Value = CS->getLHS();
6765 if (Value->isValueDependent())
6766 return false;
6767 PrimType ValueT = this->classifyPrim(Value->getType());
6768
6769 // Compare the case statement's value to the switch condition.
6770 if (!this->emitGetLocal(CondT, CondVar, CS))
6771 return false;
6772 if (!this->visit(Value))
6773 return false;
6774
6775 // Compare and jump to the case label.
6776 if (!this->emitEQ(ValueT, S))
6777 return false;
6778 if (!this->jumpTrue(CaseLabels[CS], S))
6779 return false;
6780 } else {
6781 assert(!DefaultLabel);
6782 DefaultLabel = this->getLabel();
6783 }
6784 }
6785
6786 // If none of the conditions above were true, fall through to the default
6787 // statement or jump after the switch statement.
6788 if (DefaultLabel) {
6789 if (!this->jump(*DefaultLabel, S))
6790 return false;
6791 } else {
6792 if (!this->jump(EndLabel, S))
6793 return false;
6794 }
6795
6796 SwitchScope<Emitter> SS(this, S, std::move(CaseLabels), EndLabel,
6797 DefaultLabel);
6798 if (!this->visitStmt(S->getBody()))
6799 return false;
6800 this->fallthrough(EndLabel);
6801 this->emitLabel(EndLabel);
6802
6803 return LS.destroyLocals();
6804}
6805
6806template <class Emitter>
6808 this->fallthrough(CaseLabels[S]);
6809 this->emitLabel(CaseLabels[S]);
6810
6811 // We can't jump from an outer switch statement to a case label
6812 // that's inside a StmtExpr.
6813 if (this->InStmtExpr && !this->SwitchInStmtExpr)
6814 return this->emitUnsupported(S);
6815
6816 return this->visitStmt(S->getSubStmt());
6817}
6818
6819template <class Emitter>
6821 if (LabelInfoStack.empty())
6822 return false;
6823
6824 LabelTy DefaultLabel;
6825 for (const LabelInfo &LI : llvm::reverse(LabelInfoStack)) {
6826 if (LI.DefaultLabel) {
6827 DefaultLabel = *LI.DefaultLabel;
6828 break;
6829 }
6830 }
6831
6832 this->emitLabel(DefaultLabel);
6833 return this->visitStmt(S->getSubStmt());
6834}
6835
6836template <class Emitter>
6838 const Stmt *SubStmt = S->getSubStmt();
6839
6840 bool IsMSVCConstexprAttr = isa<ReturnStmt>(SubStmt) &&
6842
6843 if (IsMSVCConstexprAttr && !this->emitPushMSVCCE(S))
6844 return false;
6845
6846 if (this->Ctx.getLangOpts().CXXAssumptions &&
6847 !this->Ctx.getLangOpts().MSVCCompat) {
6848 for (const Attr *A : S->getAttrs()) {
6849 auto *AA = dyn_cast<CXXAssumeAttr>(A);
6850 if (!AA)
6851 continue;
6852
6853 assert(isa<NullStmt>(SubStmt));
6854
6855 const Expr *Assumption = AA->getAssumption();
6856 if (Assumption->isValueDependent())
6857 return false;
6858
6859 if (Assumption->HasSideEffects(this->Ctx.getASTContext()))
6860 continue;
6861
6862 // Evaluate assumption.
6863 if (!this->visitBool(Assumption))
6864 return false;
6865
6866 if (!this->emitAssume(Assumption))
6867 return false;
6868 }
6869 }
6870
6871 // Ignore other attributes.
6872 if (!this->visitStmt(SubStmt))
6873 return false;
6874
6875 if (IsMSVCConstexprAttr)
6876 return this->emitPopMSVCCE(S);
6877 return true;
6878}
6879
6880template <class Emitter>
6882 // Ignore all handlers.
6883 return this->visitStmt(S->getTryBlock());
6884}
6885
6886template <class Emitter>
6887bool Compiler<Emitter>::emitLambdaStaticInvokerBody(const CXXMethodDecl *MD) {
6888 assert(MD->isLambdaStaticInvoker());
6889 assert(MD->hasBody());
6890 assert(cast<CompoundStmt>(MD->getBody())->body_empty());
6891
6892 const CXXRecordDecl *ClosureClass = MD->getParent();
6893 const FunctionDecl *LambdaCallOp;
6894 assert(ClosureClass->captures().empty());
6895 if (ClosureClass->isGenericLambda()) {
6896 LambdaCallOp = ClosureClass->getLambdaCallOperator();
6897 assert(MD->isFunctionTemplateSpecialization() &&
6898 "A generic lambda's static-invoker function must be a "
6899 "template specialization");
6901 FunctionTemplateDecl *CallOpTemplate =
6902 LambdaCallOp->getDescribedFunctionTemplate();
6903 void *InsertPos = nullptr;
6904 const FunctionDecl *CorrespondingCallOpSpecialization =
6905 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos);
6906 assert(CorrespondingCallOpSpecialization);
6907 LambdaCallOp = CorrespondingCallOpSpecialization;
6908 } else {
6909 LambdaCallOp = ClosureClass->getLambdaCallOperator();
6910 }
6911 assert(ClosureClass->captures().empty());
6912 const Function *Func = this->getFunction(LambdaCallOp);
6913 if (!Func)
6914 return false;
6915 assert(Func->hasThisPointer());
6916 assert(Func->getNumParams() == (MD->getNumParams() + 1 + Func->hasRVO()));
6917
6918 if (Func->hasRVO()) {
6919 if (!this->emitRVOPtr(MD))
6920 return false;
6921 }
6922
6923 // The lambda call operator needs an instance pointer, but we don't have
6924 // one here, and we don't need one either because the lambda cannot have
6925 // any captures, as verified above. Emit a null pointer. This is then
6926 // special-cased when interpreting to not emit any misleading diagnostics.
6927 if (!this->emitNullPtr(0, nullptr, MD))
6928 return false;
6929
6930 // Forward all arguments from the static invoker to the lambda call operator.
6931 for (const ParmVarDecl *PVD : MD->parameters()) {
6932 auto It = this->Params.find(PVD);
6933 assert(It != this->Params.end());
6934
6935 // We do the lvalue-to-rvalue conversion manually here, so no need
6936 // to care about references.
6937 PrimType ParamType = this->classify(PVD->getType()).value_or(PT_Ptr);
6938 if (!this->emitGetParam(ParamType, It->second.Index, MD))
6939 return false;
6940 }
6941
6942 if (!this->emitCall(Func, 0, LambdaCallOp))
6943 return false;
6944
6945 this->emitCleanup();
6946 if (ReturnType)
6947 return this->emitRet(*ReturnType, MD);
6948
6949 // Nothing to do, since we emitted the RVO pointer above.
6950 return this->emitRetVoid(MD);
6951}
6952
6953template <class Emitter>
6954bool Compiler<Emitter>::checkLiteralType(const Expr *E) {
6955 if (Ctx.getLangOpts().CPlusPlus23)
6956 return true;
6957
6958 if (!E->isPRValue() || E->getType()->isLiteralType(Ctx.getASTContext()))
6959 return true;
6960
6961 return this->emitCheckLiteralType(E->getType().getTypePtr(), E);
6962}
6963
6965 const Expr *InitExpr = Init->getInit();
6966
6967 if (!Init->isWritten() && !Init->isInClassMemberInitializer() &&
6968 !isa<CXXConstructExpr>(InitExpr))
6969 return true;
6970
6971 if (const auto *CE = dyn_cast<CXXConstructExpr>(InitExpr)) {
6972 const CXXConstructorDecl *Ctor = CE->getConstructor();
6973 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() &&
6974 Ctor->isTrivial())
6975 return true;
6976 }
6977
6978 return false;
6979}
6980
6981template <class Emitter>
6982bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) {
6983 assert(!ReturnType);
6984
6985 // Only start the lifetime of the instance pointer.
6986 if (!this->emitStartThisLifetime1(Ctor))
6987 return false;
6988
6989 auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset,
6990 const Expr *InitExpr,
6991 bool Activate = false) -> bool {
6992 // We don't know what to do with these, so just return false.
6993 if (InitExpr->getType().isNull())
6994 return false;
6995
6996 if (OptPrimType T = this->classify(InitExpr)) {
6997 if (Activate && !this->emitActivateThisField(FieldOffset, InitExpr))
6998 return false;
6999
7000 if (!this->visit(InitExpr))
7001 return false;
7002
7003 if (F->isBitField())
7004 return this->emitInitThisBitField(*T, FieldOffset, F->bitWidth(),
7005 InitExpr);
7006 return this->emitInitThisField(*T, FieldOffset, InitExpr);
7007 }
7008 // Non-primitive case. Get a pointer to the field-to-initialize
7009 // on the stack and call visitInitialzer() for it.
7010 InitLinkScope<Emitter> FieldScope(this, InitLink::Field(F->Offset));
7011 if (!this->emitGetPtrThisField(FieldOffset, InitExpr))
7012 return false;
7013
7014 if (Activate && !this->emitActivate(InitExpr))
7015 return false;
7016
7017 return this->visitInitializerPop(InitExpr);
7018 };
7019
7020 const RecordDecl *RD = Ctor->getParent();
7021 const Record *R = this->getRecord(RD);
7022 if (!R)
7023 return false;
7024 bool IsUnion = R->isUnion();
7025
7026 // Default union copy and move ctors are special.
7027 if (IsUnion && Ctor->isCopyOrMoveConstructor() && Ctor->isDefaulted()) {
7029
7030 // No special case for NumFields == 0 here, so the Memcpy op
7031 // below also does its checks in those cases.
7032
7033 assert(cast<CompoundStmt>(Ctor->getBody())->body_empty());
7034 if (!this->emitThis(Ctor))
7035 return false;
7036
7037 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, Ctor))
7038 return false;
7039
7040 return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) &&
7041 this->emitRetVoid(Ctor);
7042 }
7043
7044 unsigned FieldInits = 0;
7046 for (const auto *Init : Ctor->inits()) {
7047 // Scope needed for the initializers.
7048 LocalScope<Emitter> Scope(this, ScopeKind::FullExpression);
7049
7050 const Expr *InitExpr = Init->getInit();
7051 if (const FieldDecl *Member = Init->getMember()) {
7052 const Record::Field *F = R->getField(Member);
7053
7056 if (!emitFieldInitializer(F, F->Offset, InitExpr, IsUnion))
7057 return false;
7058 ++FieldInits;
7059 } else if (const Type *Base = Init->getBaseClass()) {
7060 const auto *BaseDecl = Base->getAsCXXRecordDecl();
7061 assert(BaseDecl);
7062
7063 if (Init->isBaseVirtual()) {
7064 assert(R->getVirtualBase(BaseDecl));
7065 if (!this->emitGetPtrThisVirtBase(BaseDecl, InitExpr))
7066 return false;
7067
7068 } else {
7069 // Base class initializer.
7070 // Get This Base and call initializer on it.
7071 const Record::Base *B = R->getBase(BaseDecl);
7072 assert(B);
7073 if (!this->emitGetPtrThisBase(B->Offset, InitExpr))
7074 return false;
7075 }
7076
7077 if (!this->visitInitializerPop(InitExpr))
7078 return false;
7079 } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) {
7082 unsigned ChainSize = IFD->getChainingSize();
7083 assert(ChainSize >= 2);
7084
7085 unsigned NestedFieldOffset = 0;
7086 const Record::Field *NestedField = nullptr;
7087 for (unsigned I = 0; I != ChainSize; ++I) {
7088 const auto *FD = cast<FieldDecl>(IFD->chain()[I]);
7089 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7090 assert(FieldRecord);
7091
7092 NestedField = FieldRecord->getField(FD);
7093 assert(NestedField);
7094 IsUnion = IsUnion || FieldRecord->isUnion();
7095
7096 NestedFieldOffset += NestedField->Offset;
7097
7098 // Add a new InitChainLink for the record, but not for the final field.
7099 if (I != ChainSize - 1)
7100 InitStack.push_back(InitLink::Field(NestedField->Offset));
7101 }
7102 assert(NestedField);
7103
7105 if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr,
7106 IsUnion))
7107 return false;
7108
7109 // Mark all chain links as initialized.
7110 unsigned InitFieldOffset = 0;
7111 for (const NamedDecl *ND : IFD->chain().drop_back()) {
7112 const auto *FD = cast<FieldDecl>(ND);
7113 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent());
7114 assert(FieldRecord);
7115 NestedField = FieldRecord->getField(FD);
7116 InitFieldOffset += NestedField->Offset;
7117 assert(NestedField);
7118 if (!this->emitGetPtrThisField(InitFieldOffset, InitExpr))
7119 return false;
7120 if (!this->emitFinishInitPop(InitExpr))
7121 return false;
7122 }
7123
7124 InitStack.pop_back_n(ChainSize - 1);
7125
7126 } else {
7127 assert(Init->isDelegatingInitializer());
7128 if (!this->emitThis(InitExpr))
7129 return false;
7130 if (!this->visitInitializerPop(Init->getInit()))
7131 return false;
7132 }
7133
7134 if (!Scope.destroyLocals())
7135 return false;
7136 }
7137
7138 if (FieldInits != R->getNumFields()) {
7139 assert(FieldInits < R->getNumFields());
7140 // Start the lifetime of all members.
7141 if (!this->emitStartThisLifetime(Ctor))
7142 return false;
7143 }
7144
7145 if (const Stmt *Body = Ctor->getBody()) {
7146 // Only emit the CtorCheck op for non-empty CompoundStmt bodies.
7147 // For non-CompoundStmts, always assume they are non-empty and emit it.
7148 if (const auto *CS = dyn_cast<CompoundStmt>(Body)) {
7149 if (!CS->body_empty() && !this->emitCtorCheck(SourceInfo{}))
7150 return false;
7151 } else {
7152 if (!this->emitCtorCheck(SourceInfo{}))
7153 return false;
7154 }
7155
7156 if (!visitStmt(Body))
7157 return false;
7158 }
7159
7160 return this->emitRetVoid(SourceInfo{});
7161}
7162
7163template <class Emitter>
7164bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) {
7165 const RecordDecl *RD = Dtor->getParent();
7166 const Record *R = this->getRecord(RD);
7167 if (!R)
7168 return false;
7169
7170 if (!Dtor->isTrivial() && Dtor->getBody()) {
7171 if (!this->visitStmt(Dtor->getBody()))
7172 return false;
7173 }
7174
7175 if (!this->emitThis(Dtor))
7176 return false;
7177
7178 if (!this->emitCheckDestruction(Dtor))
7179 return false;
7180
7181 assert(R);
7182 if (!R->isUnion()) {
7183
7185 // First, destroy all fields.
7186 for (const Record::Field &Field : llvm::reverse(R->fields())) {
7187 const Descriptor *D = Field.Desc;
7188 if (D->hasTrivialDtor())
7189 continue;
7190 if (!this->emitGetPtrField(Field.Offset, SourceInfo{}))
7191 return false;
7192 if (!this->emitDestructionPop(D, SourceInfo{}))
7193 return false;
7194 }
7195 }
7196
7197 for (const Record::Base &Base : llvm::reverse(R->bases())) {
7198 if (Base.R->hasTrivialDtor())
7199 continue;
7200 if (!this->emitGetPtrBase(Base.Offset, SourceInfo{}))
7201 return false;
7202 if (!this->emitRecordDestructionPop(Base.R, {}))
7203 return false;
7204 }
7205
7206 if (!this->emitMarkDestroyed(Dtor))
7207 return false;
7208
7209 // FIXME: Virtual bases.
7210 return this->emitPopPtr(Dtor) && this->emitRetVoid(Dtor);
7211}
7212
7213template <class Emitter>
7214bool Compiler<Emitter>::compileUnionAssignmentOperator(
7215 const CXXMethodDecl *MD) {
7216 if (!this->emitThis(MD))
7217 return false;
7218
7219 if (!this->emitGetParam(PT_Ptr, /*ParamIndex=*/0, MD))
7220 return false;
7221
7222 return this->emitMemcpy(MD) && this->emitRet(PT_Ptr, MD);
7223}
7224
7225template <class Emitter>
7227 if (F->getReturnType()->isDependentType())
7228 return false;
7229
7230 // Classify the return type.
7231 ReturnType = this->classify(F->getReturnType());
7232
7233 this->CompilingFunction = F;
7234
7235 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F))
7236 return this->compileConstructor(Ctor);
7237 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F))
7238 return this->compileDestructor(Dtor);
7239
7240 // Emit custom code if this is a lambda static invoker.
7241 if (const auto *MD = dyn_cast<CXXMethodDecl>(F)) {
7242 const RecordDecl *RD = MD->getParent();
7243
7244 if (RD->isUnion() &&
7246 return this->compileUnionAssignmentOperator(MD);
7247
7248 if (MD->isLambdaStaticInvoker())
7249 return this->emitLambdaStaticInvokerBody(MD);
7250 }
7251
7252 // Regular functions.
7253 if (const auto *Body = F->getBody())
7254 if (!visitStmt(Body))
7255 return false;
7256
7257 // Emit a guard return to protect against a code path missing one.
7258 if (F->getReturnType()->isVoidType())
7259 return this->emitRetVoid(SourceInfo{});
7260 return this->emitNoRet(SourceInfo{});
7261}
7262
7263static uint32_t getBitWidth(const Expr *E) {
7264 assert(E->refersToBitField());
7265 const auto *ME = cast<MemberExpr>(E);
7266 const auto *FD = cast<FieldDecl>(ME->getMemberDecl());
7267 return FD->getBitWidthValue();
7268}
7269
7270template <class Emitter>
7272 if (E->containsErrors())
7273 return false;
7274
7275 const Expr *SubExpr = E->getSubExpr();
7276 if (SubExpr->getType()->isAnyComplexType())
7277 return this->VisitComplexUnaryOperator(E);
7278 if (SubExpr->getType()->isVectorType())
7279 return this->VisitVectorUnaryOperator(E);
7280 if (SubExpr->getType()->isFixedPointType())
7281 return this->VisitFixedPointUnaryOperator(E);
7282 OptPrimType T = classify(SubExpr->getType());
7283
7284 switch (E->getOpcode()) {
7285 case UO_PostInc: { // x++
7286 if (!Ctx.getLangOpts().CPlusPlus14)
7287 return this->emitInvalid(E);
7288 if (!T)
7289 return this->emitError(E);
7290
7291 if (!this->visit(SubExpr))
7292 return false;
7293
7294 if (T == PT_Ptr) {
7295 if (!this->emitIncPtr(E))
7296 return false;
7297
7298 return DiscardResult ? this->emitPopPtr(E) : true;
7299 }
7300
7301 if (T == PT_Float)
7302 return DiscardResult ? this->emitIncfPop(getFPOptions(E), E)
7303 : this->emitIncf(getFPOptions(E), E);
7304
7305 if (SubExpr->refersToBitField())
7306 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
7307 getBitWidth(SubExpr), E)
7308 : this->emitIncBitfield(*T, E->canOverflow(),
7309 getBitWidth(SubExpr), E);
7310
7311 return DiscardResult ? this->emitIncPop(*T, E->canOverflow(), E)
7312 : this->emitInc(*T, E->canOverflow(), E);
7313 }
7314 case UO_PostDec: { // x--
7315 if (!Ctx.getLangOpts().CPlusPlus14)
7316 return this->emitInvalid(E);
7317 if (!T)
7318 return this->emitError(E);
7319
7320 if (!this->visit(SubExpr))
7321 return false;
7322
7323 if (T == PT_Ptr) {
7324 if (!this->emitDecPtr(E))
7325 return false;
7326
7327 return DiscardResult ? this->emitPopPtr(E) : true;
7328 }
7329
7330 if (T == PT_Float)
7331 return DiscardResult ? this->emitDecfPop(getFPOptions(E), E)
7332 : this->emitDecf(getFPOptions(E), E);
7333
7334 if (SubExpr->refersToBitField()) {
7335 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
7336 getBitWidth(SubExpr), E)
7337 : this->emitDecBitfield(*T, E->canOverflow(),
7338 getBitWidth(SubExpr), E);
7339 }
7340
7341 return DiscardResult ? this->emitDecPop(*T, E->canOverflow(), E)
7342 : this->emitDec(*T, E->canOverflow(), E);
7343 }
7344 case UO_PreInc: { // ++x
7345 if (!Ctx.getLangOpts().CPlusPlus14)
7346 return this->emitInvalid(E);
7347 if (!T)
7348 return this->emitError(E);
7349
7350 if (!this->visit(SubExpr))
7351 return false;
7352
7353 if (T == PT_Ptr) {
7354 if (!this->emitLoadPtr(E))
7355 return false;
7356 if (!this->emitConstUint8(1, E))
7357 return false;
7358 if (!this->emitAddOffsetUint8(E))
7359 return false;
7360 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
7361 }
7362
7363 // Post-inc and pre-inc are the same if the value is to be discarded.
7364 if (DiscardResult) {
7365 if (T == PT_Float)
7366 return this->emitIncfPop(getFPOptions(E), E);
7367 if (SubExpr->refersToBitField())
7368 return DiscardResult ? this->emitIncPopBitfield(*T, E->canOverflow(),
7369 getBitWidth(SubExpr), E)
7370 : this->emitIncBitfield(*T, E->canOverflow(),
7371 getBitWidth(SubExpr), E);
7372 return this->emitIncPop(*T, E->canOverflow(), E);
7373 }
7374
7375 if (T == PT_Float) {
7376 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
7377 if (!this->emitLoadFloat(E))
7378 return false;
7379 APFloat F(TargetSemantics, 1);
7380 if (!this->emitFloat(F, E))
7381 return false;
7382
7383 if (!this->emitAddf(getFPOptions(E), E))
7384 return false;
7385 if (!this->emitStoreFloat(E))
7386 return false;
7387 } else if (SubExpr->refersToBitField()) {
7388 assert(isIntegerOrBoolType(*T));
7389 if (!this->emitPreIncBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
7390 E))
7391 return false;
7392 } else {
7393 assert(isIntegerOrBoolType(*T));
7394 if (!this->emitPreInc(*T, E->canOverflow(), E))
7395 return false;
7396 }
7397 return E->isGLValue() || this->emitLoadPop(*T, E);
7398 }
7399 case UO_PreDec: { // --x
7400 if (!Ctx.getLangOpts().CPlusPlus14)
7401 return this->emitInvalid(E);
7402 if (!T)
7403 return this->emitError(E);
7404
7405 if (!this->visit(SubExpr))
7406 return false;
7407
7408 if (T == PT_Ptr) {
7409 if (!this->emitLoadPtr(E))
7410 return false;
7411 if (!this->emitConstUint8(1, E))
7412 return false;
7413 if (!this->emitSubOffsetUint8(E))
7414 return false;
7415 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E);
7416 }
7417
7418 // Post-dec and pre-dec are the same if the value is to be discarded.
7419 if (DiscardResult) {
7420 if (T == PT_Float)
7421 return this->emitDecfPop(getFPOptions(E), E);
7422 if (SubExpr->refersToBitField())
7423 return DiscardResult ? this->emitDecPopBitfield(*T, E->canOverflow(),
7424 getBitWidth(SubExpr), E)
7425 : this->emitDecBitfield(*T, E->canOverflow(),
7426 getBitWidth(SubExpr), E);
7427 return this->emitDecPop(*T, E->canOverflow(), E);
7428 }
7429
7430 if (T == PT_Float) {
7431 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType());
7432 if (!this->emitLoadFloat(E))
7433 return false;
7434 APFloat F(TargetSemantics, 1);
7435 if (!this->emitFloat(F, E))
7436 return false;
7437
7438 if (!this->emitSubf(getFPOptions(E), E))
7439 return false;
7440 if (!this->emitStoreFloat(E))
7441 return false;
7442 } else if (SubExpr->refersToBitField()) {
7443 assert(isIntegerOrBoolType(*T));
7444 if (!this->emitPreDecBitfield(*T, E->canOverflow(), getBitWidth(SubExpr),
7445 E))
7446 return false;
7447 } else {
7448 assert(isIntegerOrBoolType(*T));
7449 if (!this->emitPreDec(*T, E->canOverflow(), E))
7450 return false;
7451 }
7452 return E->isGLValue() || this->emitLoadPop(*T, E);
7453 }
7454 case UO_LNot: // !x
7455 if (!T)
7456 return this->emitError(E);
7457
7458 if (DiscardResult)
7459 return this->discard(SubExpr);
7460
7461 if (!this->visitBool(SubExpr))
7462 return false;
7463
7464 if (!this->emitInv(E))
7465 return false;
7466
7467 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
7468 return this->emitCast(PT_Bool, ET, E);
7469 return true;
7470 case UO_Minus: // -x
7471 if (!T)
7472 return this->emitError(E);
7473
7474 if (!this->visit(SubExpr))
7475 return false;
7476 return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E);
7477 case UO_Plus: // +x
7478 if (!T)
7479 return this->emitError(E);
7480
7481 if (!this->visit(SubExpr)) // noop
7482 return false;
7483 return DiscardResult ? this->emitPop(*T, E) : true;
7484 case UO_AddrOf: // &x
7485 if (E->getType()->isMemberPointerType()) {
7486 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a
7487 // member can be formed.
7488 if (DiscardResult)
7489 return true;
7490 return this->emitGetMemberPtr(cast<DeclRefExpr>(SubExpr)->getDecl(), E);
7491 }
7492 // [C11 6.5.3.2p3]: if the operand of '&' is the result of a unary '*'
7493 // operator, neither operator is evaluated and the result is as if both
7494 // were omitted. So '&*q' is just 'q' with no dereference; delegate to the
7495 // pointer operand directly instead of to the '*' (which would emit a null
7496 // check), so that e.g. '&*(int *)0' is not rejected.
7497 if (!Ctx.getLangOpts().CPlusPlus) {
7498 const Expr *Sub = SubExpr->IgnoreParens();
7499 if (const auto *Deref = dyn_cast<UnaryOperator>(Sub);
7500 Deref && Deref->getOpcode() == UO_Deref)
7501 return this->delegate(Deref->getSubExpr());
7502 }
7503 // We should already have a pointer when we get here.
7504 return this->delegate(SubExpr);
7505 case UO_Deref: // *x
7506 if (DiscardResult)
7507 return this->discard(SubExpr);
7508
7509 if (!this->visit(SubExpr))
7510 return false;
7511
7512 if (!SubExpr->getType()->isFunctionPointerType() && !this->emitCheckNull(E))
7513 return false;
7514
7515 if (classifyPrim(SubExpr) == PT_Ptr)
7516 return this->emitNarrowPtr(E);
7517 return true;
7518
7519 case UO_Not: // ~x
7520 if (!T)
7521 return this->emitError(E);
7522
7523 if (!this->visit(SubExpr))
7524 return false;
7525 return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E);
7526 case UO_Real: // __real x
7527 if (!T)
7528 return false;
7529 return this->delegate(SubExpr);
7530 case UO_Imag: { // __imag x
7531 if (!T)
7532 return false;
7533 if (!this->discard(SubExpr))
7534 return false;
7535 return DiscardResult
7536 ? true
7537 : this->visitZeroInitializer(*T, SubExpr->getType(), SubExpr);
7538 }
7539 case UO_Extension:
7540 return this->delegate(SubExpr);
7541 case UO_Coawait:
7542 assert(false && "Unhandled opcode");
7543 }
7544
7545 return false;
7546}
7547
7548template <class Emitter>
7550 const Expr *SubExpr = E->getSubExpr();
7551 assert(SubExpr->getType()->isAnyComplexType());
7552
7553 if (DiscardResult)
7554 return this->discard(SubExpr);
7555
7556 OptPrimType ResT = classify(E);
7557 auto prepareResult = [=]() -> bool {
7558 if (!ResT && !Initializing) {
7559 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
7560 if (!LocalIndex)
7561 return false;
7562 return this->emitGetPtrLocal(*LocalIndex, E);
7563 }
7564
7565 return true;
7566 };
7567
7568 // The offset of the temporary, if we created one.
7569 unsigned SubExprOffset = ~0u;
7570 auto createTemp = [=, &SubExprOffset]() -> bool {
7571 SubExprOffset =
7572 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
7573 if (!this->visit(SubExpr))
7574 return false;
7575 return this->emitSetLocal(PT_Ptr, SubExprOffset, E);
7576 };
7577
7578 PrimType ElemT = classifyComplexElementType(SubExpr->getType());
7579 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
7580 if (!this->emitGetLocal(PT_Ptr, Offset, E))
7581 return false;
7582 return this->emitArrayElemPop(ElemT, Index, E);
7583 };
7584
7585 switch (E->getOpcode()) {
7586 case UO_Minus: // -x
7587 if (!prepareResult())
7588 return false;
7589 if (!createTemp())
7590 return false;
7591 for (unsigned I = 0; I != 2; ++I) {
7592 if (!getElem(SubExprOffset, I))
7593 return false;
7594 if (!this->emitNeg(ElemT, E))
7595 return false;
7596 if (!this->emitInitElem(ElemT, I, E))
7597 return false;
7598 }
7599 break;
7600
7601 case UO_Plus: // +x
7602 case UO_AddrOf: // &x
7603 case UO_Deref: // *x
7604 return this->delegate(SubExpr);
7605
7606 case UO_LNot:
7607 if (!this->visit(SubExpr))
7608 return false;
7609 if (!this->emitComplexBoolCast(SubExpr))
7610 return false;
7611 if (!this->emitInv(E))
7612 return false;
7613 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool)
7614 return this->emitCast(PT_Bool, ET, E);
7615 return true;
7616
7617 case UO_Real:
7618 return this->emitComplexReal(SubExpr);
7619
7620 case UO_Imag:
7621 if (!this->visit(SubExpr))
7622 return false;
7623
7624 if (SubExpr->isLValue()) {
7625 if (!this->emitConstUint8(1, E))
7626 return false;
7627 return this->emitArrayElemPtrPopUint8(E);
7628 }
7629
7630 // Since our _Complex implementation does not map to a primitive type,
7631 // we sometimes have to do the lvalue-to-rvalue conversion here manually.
7632 return this->emitArrayElemPop(classifyPrim(E->getType()), 1, E);
7633
7634 case UO_Not: // ~x
7635 if (!this->delegate(SubExpr))
7636 return false;
7637 // Negate the imaginary component.
7638 if (!this->emitArrayElem(ElemT, 1, E))
7639 return false;
7640 if (!this->emitNeg(ElemT, E))
7641 return false;
7642 if (!this->emitInitElem(ElemT, 1, E))
7643 return false;
7644 return DiscardResult ? this->emitPopPtr(E) : true;
7645
7646 case UO_Extension:
7647 return this->delegate(SubExpr);
7648
7649 default:
7650 return this->emitInvalid(E);
7651 }
7652
7653 return true;
7654}
7655
7656template <class Emitter>
7658 const Expr *SubExpr = E->getSubExpr();
7659 assert(SubExpr->getType()->isVectorType());
7660
7661 if (DiscardResult)
7662 return this->discard(SubExpr);
7663
7664 auto UnaryOp = E->getOpcode();
7665 if (UnaryOp == UO_Extension)
7666 return this->delegate(SubExpr);
7667
7668 if (UnaryOp != UO_Plus && UnaryOp != UO_Minus && UnaryOp != UO_LNot &&
7669 UnaryOp != UO_Not && UnaryOp != UO_AddrOf)
7670 return this->emitInvalid(E);
7671
7672 // Nothing to do here.
7673 if (UnaryOp == UO_Plus || UnaryOp == UO_AddrOf)
7674 return this->delegate(SubExpr);
7675
7676 if (!Initializing) {
7677 UnsignedOrNone LocalIndex = allocateLocal(SubExpr);
7678 if (!LocalIndex)
7679 return false;
7680 if (!this->emitGetPtrLocal(*LocalIndex, E))
7681 return false;
7682 }
7683
7684 // The offset of the temporary, if we created one.
7685 unsigned SubExprOffset =
7686 this->allocateLocalPrimitive(SubExpr, PT_Ptr, /*IsConst=*/true);
7687 if (!this->visit(SubExpr))
7688 return false;
7689 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E))
7690 return false;
7691
7692 const auto *VecTy = SubExpr->getType()->getAs<VectorType>();
7693 PrimType ElemT = classifyVectorElementType(SubExpr->getType());
7694 auto getElem = [=](unsigned Offset, unsigned Index) -> bool {
7695 if (!this->emitGetLocal(PT_Ptr, Offset, E))
7696 return false;
7697 return this->emitArrayElemPop(ElemT, Index, E);
7698 };
7699
7700 switch (UnaryOp) {
7701 case UO_Minus:
7702 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
7703 if (!getElem(SubExprOffset, I))
7704 return false;
7705 if (!this->emitNeg(ElemT, E))
7706 return false;
7707 if (!this->emitInitElem(ElemT, I, E))
7708 return false;
7709 }
7710 break;
7711 case UO_LNot: { // !x
7712 // In C++, the logic operators !, &&, || are available for vectors. !v is
7713 // equivalent to v == 0.
7714 //
7715 // The result of the comparison is a vector of the same width and number of
7716 // elements as the comparison operands with a signed integral element type.
7717 //
7718 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html
7719 QualType ResultVecTy = E->getType();
7720 PrimType ResultVecElemT =
7721 classifyPrim(ResultVecTy->getAs<VectorType>()->getElementType());
7722 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
7723 if (!getElem(SubExprOffset, I))
7724 return false;
7725 // operator ! on vectors returns -1 for 'truth', so negate it.
7726 if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E))
7727 return false;
7728 if (!this->emitInv(E))
7729 return false;
7730 if (!this->emitPrimCast(PT_Bool, ElemT, VecTy->getElementType(), E))
7731 return false;
7732 if (!this->emitNeg(ElemT, E))
7733 return false;
7734 if (ElemT != ResultVecElemT &&
7735 !this->emitPrimCast(ElemT, ResultVecElemT, ResultVecTy, E))
7736 return false;
7737 if (!this->emitInitElem(ResultVecElemT, I, E))
7738 return false;
7739 }
7740 break;
7741 }
7742 case UO_Not: // ~x
7743 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) {
7744 if (!getElem(SubExprOffset, I))
7745 return false;
7746 if (ElemT == PT_Bool) {
7747 if (!this->emitInv(E))
7748 return false;
7749 } else {
7750 if (!this->emitComp(ElemT, E))
7751 return false;
7752 }
7753 if (!this->emitInitElem(ElemT, I, E))
7754 return false;
7755 }
7756 break;
7757 default:
7758 llvm_unreachable("Unsupported unary operators should be handled up front");
7759 }
7760 return true;
7761}
7762
7763template <class Emitter>
7765 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) {
7766 if (DiscardResult)
7767 return true;
7768 return this->emitConst(ECD->getInitVal(), E);
7769 }
7770 if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) {
7771 if (DiscardResult)
7772 return true;
7773 const Function *F = getFunction(FuncDecl);
7774 return F && this->emitGetFnPtr(F, E);
7775 }
7776 if (const auto *TPOD = dyn_cast<TemplateParamObjectDecl>(D)) {
7777 if (DiscardResult)
7778 return true;
7779
7780 if (UnsignedOrNone Index = P.getOrCreateGlobal(D)) {
7781 if (OptPrimType T = classify(D->getType())) {
7782 if (!this->visitAPValue(TPOD->getValue(), *T, E))
7783 return false;
7784 return this->emitInitGlobal(*T, *Index, E);
7785 }
7786
7787 if (!this->emitGetPtrGlobal(*Index, E))
7788 return false;
7789 if (!this->visitAPValueInitializer(TPOD->getValue(), E, TPOD->getType()))
7790 return false;
7791 return this->emitFinishInit(E);
7792 }
7793 return false;
7794 }
7795
7796 // References are implemented via pointers, so when we see a DeclRefExpr
7797 // pointing to a reference, we need to get its value directly (i.e. the
7798 // pointer to the actual value) instead of a pointer to the pointer to the
7799 // value.
7800 QualType DeclType = D->getType();
7801 bool IsReference = DeclType->isReferenceType();
7802
7803 auto maybePopPtr = [&]() -> bool {
7804 if (DiscardResult)
7805 return this->emitPopPtr(E);
7806 return true;
7807 };
7808
7809 // Function parameters.
7810 // Note that it's important to check them first since we might have a local
7811 // variable created for a ParmVarDecl as well.
7812 if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) {
7813 if (DiscardResult)
7814 return true;
7815
7816 if (Ctx.getLangOpts().CPlusPlus && !Ctx.getLangOpts().CPlusPlus11 &&
7817 !DeclType->isIntegralOrEnumerationType()) {
7818 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
7819 /*InitializerFailed=*/false, E);
7820 }
7821 if (auto It = this->Params.find(PVD); It != this->Params.end()) {
7822 if (IsReference || !It->second.IsPtr)
7823 return this->emitGetParam(classifyPrim(E), It->second.Index, E);
7824
7825 return this->emitGetPtrParam(It->second.Index, E);
7826 }
7827
7828 if (!Ctx.getLangOpts().CPlusPlus23 && IsReference && !Locals.contains(D))
7829 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
7830 /*InitializerFailed=*/false, E);
7831 }
7832
7833 // Local variables.
7834 if (auto It = Locals.find(D); It != Locals.end()) {
7835 const unsigned Offset = It->second.Offset;
7836 if (IsReference) {
7837 assert(classifyPrim(E) == PT_Ptr);
7838 return this->emitGetRefLocal(Offset, E) && maybePopPtr();
7839 }
7840 return this->emitGetPtrLocal(Offset, E) && maybePopPtr();
7841 }
7842 // Global variables.
7843 if (auto GlobalIndex = P.getGlobal(D)) {
7844 if (IsReference) {
7845 if (!Ctx.getLangOpts().CPlusPlus11)
7846 return this->emitGetGlobal(classifyPrim(E), *GlobalIndex, E);
7847 if (!Ctx.getLangOpts().CPlusPlus23)
7848 return this->emitGetGlobalUnchecked(classifyPrim(E), *GlobalIndex, E);
7849
7850 return this->emitGetRefGlobal(*GlobalIndex, E) && maybePopPtr();
7851 }
7852
7853 return this->emitGetPtrGlobal(*GlobalIndex, E) && maybePopPtr();
7854 }
7855
7856 // In case we need to re-visit a declaration.
7857 auto revisit = [&](const VarDecl *VD,
7858 bool IsConstexprUnknown = true) -> bool {
7860 IsConstexprUnknown);
7861 if (!this->emitPushCC(VD->hasConstantInitialization(), E))
7862 return false;
7863 auto VarState = this->visitDecl(VD);
7864
7865 if (!this->emitPopCC(E))
7866 return false;
7867
7868 if (VarState.notCreated())
7869 return true;
7870 if (!VarState)
7871 return false;
7872 // Retry.
7873 return this->visitDeclRef(D, E);
7874 };
7875
7876 if constexpr (!std::is_same_v<Emitter, EvalEmitter>) {
7877 // Lambda captures.
7878 if (auto It = this->LambdaCaptures.find(D);
7879 It != this->LambdaCaptures.end()) {
7880 auto [Offset, IsPtr] = It->second;
7881
7882 if (IsPtr)
7883 return this->emitGetThisFieldPtr(Offset, E) && maybePopPtr();
7884 return this->emitGetPtrThisField(Offset, E) && maybePopPtr();
7885 }
7886 }
7887
7888 if (const auto *DRE = dyn_cast<DeclRefExpr>(E);
7889 DRE && DRE->refersToEnclosingVariableOrCapture()) {
7890 if (const auto *VD = dyn_cast<VarDecl>(D); VD && VD->isInitCapture())
7891 return revisit(VD);
7892 }
7893
7894 if (const auto *BD = dyn_cast<BindingDecl>(D))
7895 return this->delegate(BD->getBinding());
7896
7897 // Avoid infinite recursion.
7898 if (D == InitializingDecl) {
7899 if (DiscardResult)
7900 return true;
7901 return this->emitDummyPtr(D, E);
7902 }
7903
7904 // Try to lazily visit (or emit dummy pointers for) declarations
7905 // we haven't seen yet.
7906 const auto *VD = dyn_cast<VarDecl>(D);
7907 if (!VD)
7908 return this->emitError(E);
7909
7910 // For C.
7911 if (!Ctx.getLangOpts().CPlusPlus) {
7912 if (VD->getInit() && !VD->getInit()->isValueDependent() &&
7913 DeclType.isConstant(Ctx.getASTContext()) && !VD->isWeak() &&
7914 VD->evaluateValue())
7915 return revisit(VD, /*IsConstexprUnknown=*/false);
7916
7917 if (DiscardResult)
7918 return true;
7919 return this->emitDummyPtr(D, E);
7920 }
7921
7922 // ... and C++.
7923 const auto typeShouldBeVisited = [&](QualType T) -> bool {
7924 if (T.isConstant(Ctx.getASTContext()))
7925 return true;
7926 return T->isReferenceType();
7927 };
7928
7929 if ((VD->hasGlobalStorage() || VD->isStaticDataMember()) &&
7930 typeShouldBeVisited(DeclType)) {
7931 if (const Expr *Init = VD->getAnyInitializer();
7932 Init && !Init->isValueDependent()) {
7933 // Whether or not the evaluation is successul doesn't really matter
7934 // here -- we will create a global variable in any case, and that
7935 // will have the state of initializer evaluation attached.
7937 (void)Init->EvaluateAsInitializer(Ctx.getASTContext(), VD, Result, true);
7938 return this->visitDeclRef(D, E);
7939 }
7940 return revisit(VD, !VD->isConstexpr() && DeclType->isReferenceType());
7941 }
7942
7943 // FIXME: The evaluateValue() check here is a little ridiculous, since
7944 // it will ultimately call into Context::evaluateAsInitializer(). In
7945 // other words, we're evaluating the initializer, just to know if we can
7946 // evaluate the initializer.
7947 if (VD->isLocalVarDecl() && typeShouldBeVisited(DeclType) && VD->getInit() &&
7948 !VD->getInit()->isValueDependent()) {
7949 if (VD->evaluateValue()) {
7950 bool IsConstexprUnknown = !DeclType.isConstant(Ctx.getASTContext()) &&
7951 !DeclType->isReferenceType();
7952 // Revisit the variable declaration, but make sure it's associated with a
7953 // different evaluation, so e.g. mutable reads don't work on it.
7954 EvalIDScope _(Ctx);
7955 return revisit(VD, IsConstexprUnknown);
7956 } else if (Ctx.getLangOpts().CPlusPlus23 && IsReference)
7957 return revisit(VD, /*IsConstexprUnknown=*/true);
7958
7959 if (IsReference)
7960 return this->emitInvalidDeclRef(cast<DeclRefExpr>(E),
7961 /*InitializerFailed=*/true, E);
7962 }
7963
7964 if (DiscardResult)
7965 return true;
7966 return this->emitDummyPtr(
7967 D, E, Ctx.getLangOpts().CPlusPlus23 && DeclType->isReferenceType());
7968}
7969
7970template <class Emitter>
7972 const auto *D = E->getDecl();
7973 return this->visitDeclRef(D, E);
7974}
7975
7976template <class Emitter>
7978 const DesignatedInitUpdateExpr *E) {
7979 if (!this->visitInitializer(E->getBase()))
7980 return false;
7981 return this->visitInitializer(E->getUpdater());
7982}
7983
7984template <class Emitter> bool Compiler<Emitter>::emitCleanup() {
7985 for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent()) {
7986 if (!C->destroyLocals())
7987 return false;
7988 }
7989 return true;
7990}
7991
7992template <class Emitter>
7993unsigned Compiler<Emitter>::collectBaseOffset(const QualType BaseType,
7994 const QualType DerivedType) {
7995 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * {
7996 if (const auto *R = Ty->getPointeeCXXRecordDecl())
7997 return R;
7998 return Ty->getAsCXXRecordDecl();
7999 };
8000 const CXXRecordDecl *BaseDecl = extractRecordDecl(BaseType);
8001 const CXXRecordDecl *DerivedDecl = extractRecordDecl(DerivedType);
8002
8003 return Ctx.collectBaseOffset(BaseDecl, DerivedDecl);
8004}
8005
8006/// Emit casts from a PrimType to another PrimType.
8007template <class Emitter>
8008bool Compiler<Emitter>::emitPrimCast(PrimType FromT, PrimType ToT,
8009 QualType ToQT, const Expr *E) {
8010
8011 if (FromT == PT_Float) {
8012 // Floating to floating.
8013 if (ToT == PT_Float) {
8014 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8015 return this->emitCastFP(ToSem, getRoundingMode(E), E);
8016 }
8017
8018 if (ToT == PT_IntAP)
8019 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(ToQT),
8020 getFPOptions(E), E);
8021 if (ToT == PT_IntAPS)
8022 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(ToQT),
8023 getFPOptions(E), E);
8024
8025 // Float to integral.
8026 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8027 return this->emitCastFloatingIntegral(ToT, getFPOptions(E), E);
8028 }
8029
8030 if (isIntegerOrBoolType(FromT) || FromT == PT_Bool) {
8031 if (ToT == PT_IntAP)
8032 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8033 if (ToT == PT_IntAPS)
8034 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8035
8036 // Integral to integral.
8037 if (isIntegerOrBoolType(ToT) || ToT == PT_Bool)
8038 return FromT != ToT ? this->emitCast(FromT, ToT, E) : true;
8039
8040 if (ToT == PT_Float) {
8041 // Integral to floating.
8042 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT);
8043 return this->emitCastIntegralFloating(FromT, ToSem, getFPOptions(E), E);
8044 }
8045 }
8046
8047 return false;
8048}
8049
8050template <class Emitter>
8051bool Compiler<Emitter>::emitIntegralCast(PrimType FromT, PrimType ToT,
8052 QualType ToQT, const Expr *E) {
8053 assert(FromT != ToT);
8054
8055 if (ToT == PT_IntAP)
8056 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E);
8057 if (ToT == PT_IntAPS)
8058 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E);
8059
8060 return this->emitCast(FromT, ToT, E);
8061}
8062
8063/// Emits __real(SubExpr)
8064template <class Emitter>
8065bool Compiler<Emitter>::emitComplexReal(const Expr *SubExpr) {
8066 assert(SubExpr->getType()->isAnyComplexType());
8067
8068 if (DiscardResult)
8069 return this->discard(SubExpr);
8070
8071 if (!this->visit(SubExpr))
8072 return false;
8073 if (SubExpr->isLValue()) {
8074 if (!this->emitConstUint8(0, SubExpr))
8075 return false;
8076 return this->emitArrayElemPtrPopUint8(SubExpr);
8077 }
8078
8079 // Rvalue, load the actual element.
8080 return this->emitArrayElemPop(classifyComplexElementType(SubExpr->getType()),
8081 0, SubExpr);
8082}
8083
8084template <class Emitter>
8085bool Compiler<Emitter>::emitComplexBoolCast(const Expr *E) {
8086 assert(!DiscardResult);
8087 PrimType ElemT = classifyComplexElementType(E->getType());
8088 // We emit the expression (__real(E) != 0 || __imag(E) != 0)
8089 // for us, that means (bool)E[0] || (bool)E[1]
8090 if (!this->emitArrayElem(ElemT, 0, E))
8091 return false;
8092 if (ElemT == PT_Float) {
8093 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8094 return false;
8095 } else {
8096 if (!this->emitCast(ElemT, PT_Bool, E))
8097 return false;
8098 }
8099
8100 // We now have the bool value of E[0] on the stack.
8101 LabelTy LabelTrue = this->getLabel();
8102 if (!this->jumpTrue(LabelTrue, E))
8103 return false;
8104
8105 if (!this->emitArrayElemPop(ElemT, 1, E))
8106 return false;
8107 if (ElemT == PT_Float) {
8108 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E))
8109 return false;
8110 } else {
8111 if (!this->emitCast(ElemT, PT_Bool, E))
8112 return false;
8113 }
8114 // Leave the boolean value of E[1] on the stack.
8115 LabelTy EndLabel = this->getLabel();
8116 this->jump(EndLabel, E);
8117
8118 this->emitLabel(LabelTrue);
8119 if (!this->emitPopPtr(E))
8120 return false;
8121 if (!this->emitConstBool(true, E))
8122 return false;
8123
8124 this->fallthrough(EndLabel);
8125 this->emitLabel(EndLabel);
8126
8127 return true;
8128}
8129
8130template <class Emitter>
8131bool Compiler<Emitter>::emitComplexComparison(const Expr *LHS, const Expr *RHS,
8132 const BinaryOperator *E) {
8133 assert(E->isComparisonOp());
8134 assert(!Initializing);
8135 if (DiscardResult)
8136 return this->discard(LHS) && this->discard(RHS);
8137
8138 PrimType ElemT;
8139 bool LHSIsComplex;
8140 unsigned LHSOffset;
8141 if (LHS->getType()->isAnyComplexType()) {
8142 LHSIsComplex = true;
8143 ElemT = classifyComplexElementType(LHS->getType());
8144 LHSOffset = allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true);
8145 if (!this->visit(LHS))
8146 return false;
8147 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E))
8148 return false;
8149 } else {
8150 LHSIsComplex = false;
8151 PrimType LHST = classifyPrim(LHS->getType());
8152 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, /*IsConst=*/true);
8153 if (!this->visit(LHS))
8154 return false;
8155 if (!this->emitSetLocal(LHST, LHSOffset, E))
8156 return false;
8157 }
8158
8159 bool RHSIsComplex;
8160 unsigned RHSOffset;
8161 if (RHS->getType()->isAnyComplexType()) {
8162 RHSIsComplex = true;
8163 ElemT = classifyComplexElementType(RHS->getType());
8164 RHSOffset = allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true);
8165 if (!this->visit(RHS))
8166 return false;
8167 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E))
8168 return false;
8169 } else {
8170 RHSIsComplex = false;
8171 PrimType RHST = classifyPrim(RHS->getType());
8172 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, /*IsConst=*/true);
8173 if (!this->visit(RHS))
8174 return false;
8175 if (!this->emitSetLocal(RHST, RHSOffset, E))
8176 return false;
8177 }
8178
8179 auto getElem = [&](unsigned LocalOffset, unsigned Index,
8180 bool IsComplex) -> bool {
8181 if (IsComplex) {
8182 if (!this->emitGetLocal(PT_Ptr, LocalOffset, E))
8183 return false;
8184 return this->emitArrayElemPop(ElemT, Index, E);
8185 }
8186 return this->emitGetLocal(ElemT, LocalOffset, E);
8187 };
8188
8189 for (unsigned I = 0; I != 2; ++I) {
8190 // Get both values.
8191 if (!getElem(LHSOffset, I, LHSIsComplex))
8192 return false;
8193 if (!getElem(RHSOffset, I, RHSIsComplex))
8194 return false;
8195 // And compare them.
8196 if (!this->emitEQ(ElemT, E))
8197 return false;
8198
8199 if (!this->emitCastBoolUint8(E))
8200 return false;
8201 }
8202
8203 // We now have two bool values on the stack. Compare those.
8204 if (!this->emitAddUint8(E))
8205 return false;
8206 if (!this->emitConstUint8(2, E))
8207 return false;
8208
8209 if (E->getOpcode() == BO_EQ) {
8210 if (!this->emitEQUint8(E))
8211 return false;
8212 } else if (E->getOpcode() == BO_NE) {
8213 if (!this->emitNEUint8(E))
8214 return false;
8215 } else
8216 return false;
8217
8218 // In C, this returns an int.
8219 if (PrimType ResT = classifyPrim(E->getType()); ResT != PT_Bool)
8220 return this->emitCast(PT_Bool, ResT, E);
8221 return true;
8222}
8223
8224/// When calling this, we have a pointer of the local-to-destroy
8225/// on the stack.
8226/// Emit destruction of record types (or arrays of record types).
8227template <class Emitter>
8228bool Compiler<Emitter>::emitRecordDestructionPop(const Record *R,
8229 SourceInfo Loc) {
8230 assert(R);
8231 assert(!R->hasTrivialDtor());
8232 const CXXDestructorDecl *Dtor = R->getDestructor();
8233 assert(Dtor);
8234 const Function *DtorFunc = getFunction(Dtor);
8235 if (!DtorFunc)
8236 return false;
8237 assert(DtorFunc->hasThisPointer());
8238 assert(DtorFunc->getNumParams() == 1);
8239 return this->emitCall(DtorFunc, 0, Loc);
8240}
8241/// When calling this, we have a pointer of the local-to-destroy
8242/// on the stack.
8243/// Emit destruction of record types (or arrays of record types).
8244template <class Emitter>
8245bool Compiler<Emitter>::emitDestructionPop(const Descriptor *Desc,
8246 SourceInfo Loc) {
8247 assert(Desc);
8248 assert(!Desc->hasTrivialDtor());
8249
8250 // Arrays.
8251 if (Desc->isArray()) {
8252 const Descriptor *ElemDesc = Desc->ElemDesc;
8253 assert(ElemDesc);
8254
8255 unsigned N = Desc->getNumElems();
8256 if (N == 0)
8257 return this->emitPopPtr(Loc);
8258
8259 for (ssize_t I = N - 1; I >= 1; --I) {
8260 if (!this->emitConstUint64(I, Loc))
8261 return false;
8262 if (!this->emitArrayElemPtrUint64(Loc))
8263 return false;
8264 if (!this->emitDestructionPop(ElemDesc, Loc))
8265 return false;
8266 }
8267 // Last iteration, removes the instance pointer from the stack.
8268 if (!this->emitConstUint64(0, Loc))
8269 return false;
8270 if (!this->emitArrayElemPtrPopUint64(Loc))
8271 return false;
8272 return this->emitDestructionPop(ElemDesc, Loc);
8273 }
8274
8275 assert(Desc->ElemRecord);
8276 assert(!Desc->ElemRecord->hasTrivialDtor());
8277 return this->emitRecordDestructionPop(Desc->ElemRecord, Loc);
8278}
8279
8280/// Create a dummy pointer for the given decl (or expr) and
8281/// push a pointer to it on the stack.
8282template <class Emitter>
8283bool Compiler<Emitter>::emitDummyPtr(const DeclTy &D, const Expr *E, bool CU) {
8284 assert(!DiscardResult && "Should've been checked before");
8285 unsigned DummyID = P.getOrCreateDummy(D, CU);
8286
8287 if (!this->emitGetPtrGlobal(DummyID, E))
8288 return false;
8289 if (E->getType()->isVoidType())
8290 return true;
8291
8292 // Convert the dummy pointer to another pointer type if we have to.
8293 if (PrimType PT = classifyPrim(E); PT != PT_Ptr) {
8294 if (isPtrType(PT))
8295 return this->emitDecayPtr(PT_Ptr, PT, E);
8296 return false;
8297 }
8298 return true;
8299}
8300
8301template <class Emitter>
8302bool Compiler<Emitter>::emitFloat(const APFloat &F, SourceInfo Info) {
8303 if (Floating::singleWord(F.getSemantics()))
8304 return this->emitConstFloat(Floating(F), Info);
8305
8306 APInt I = F.bitcastToAPInt();
8307 return this->emitConstFloat(
8308 Floating(const_cast<uint64_t *>(I.getRawData()),
8309 llvm::APFloatBase::SemanticsToEnum(F.getSemantics())),
8310 Info);
8311}
8312
8313// This function is constexpr if and only if To, From, and the types of
8314// all subobjects of To and From are types T such that...
8315// (3.1) - is_union_v<T> is false;
8316// (3.2) - is_pointer_v<T> is false;
8317// (3.3) - is_member_pointer_v<T> is false;
8318// (3.4) - is_volatile_v<T> is false; and
8319// (3.5) - T has no non-static data members of reference type
8320template <class Emitter>
8321bool Compiler<Emitter>::emitBuiltinBitCast(const CastExpr *E) {
8322 const Expr *SubExpr = E->getSubExpr();
8323 QualType FromType = SubExpr->getType();
8324 QualType ToType = E->getType();
8325 OptPrimType ToT = classify(ToType);
8326
8327 assert(!ToType->isReferenceType());
8328
8329 // Prepare storage for the result in case we discard.
8330 if (DiscardResult && !Initializing && !ToT) {
8331 UnsignedOrNone LocalIndex = allocateLocal(E);
8332 if (!LocalIndex)
8333 return false;
8334 if (!this->emitGetPtrLocal(*LocalIndex, E))
8335 return false;
8336 }
8337
8338 // Get a pointer to the value-to-cast on the stack.
8339 // For CK_LValueToRValueBitCast, this is always an lvalue and
8340 // we later assume it to be one (i.e. a PT_Ptr). However,
8341 // we call this function for other utility methods where
8342 // a bitcast might be useful, so convert it to a PT_Ptr in that case.
8343 if (SubExpr->isGLValue() || FromType->isVectorType()) {
8344 if (!this->visit(SubExpr))
8345 return false;
8346 } else if (OptPrimType FromT = classify(SubExpr)) {
8347 unsigned TempOffset =
8348 allocateLocalPrimitive(SubExpr, *FromT, /*IsConst=*/true);
8349 if (!this->visit(SubExpr))
8350 return false;
8351 if (!this->emitSetLocal(*FromT, TempOffset, E))
8352 return false;
8353 if (!this->emitGetPtrLocal(TempOffset, E))
8354 return false;
8355 } else {
8356 return false;
8357 }
8358
8359 if (!ToT) {
8360 if (!this->emitBitCast(E))
8361 return false;
8362 return DiscardResult ? this->emitPopPtr(E) : true;
8363 }
8364 assert(ToT);
8365
8366 const llvm::fltSemantics *TargetSemantics = nullptr;
8367 if (ToT == PT_Float)
8368 TargetSemantics = &Ctx.getFloatSemantics(ToType);
8369
8370 // Conversion to a primitive type. FromType can be another
8371 // primitive type, or a record/array.
8372 bool ToTypeIsUChar = (ToType->isSpecificBuiltinType(BuiltinType::UChar) ||
8373 ToType->isSpecificBuiltinType(BuiltinType::Char_U));
8374 uint32_t ResultBitWidth = std::max(Ctx.getBitWidth(ToType), 8u);
8375
8376 if (!this->emitBitCastPrim(*ToT, ToTypeIsUChar || ToType->isStdByteType(),
8377 ResultBitWidth, TargetSemantics,
8378 ToType.getTypePtr(), E))
8379 return false;
8380
8381 if (DiscardResult)
8382 return this->emitPop(*ToT, E);
8383
8384 return true;
8385}
8386
8387/// Replicate a scalar value into every scalar element of an aggregate.
8388/// The scalar is stored in a local at \p SrcOffset and a pointer to the
8389/// destination must be on top of the interpreter stack. Each element receives
8390/// the scalar, cast to its own type.
8391template <class Emitter>
8392bool Compiler<Emitter>::emitHLSLAggregateSplat(PrimType SrcT,
8393 unsigned SrcOffset,
8394 QualType DestType,
8395 const Expr *E) {
8396 // Vectors and matrices are treated as flat sequences of elements.
8397 unsigned NumElems = 0;
8398 QualType ElemType;
8399 if (const auto *VT = DestType->getAs<VectorType>()) {
8400 NumElems = VT->getNumElements();
8401 ElemType = VT->getElementType();
8402 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
8403 NumElems = MT->getNumElementsFlattened();
8404 ElemType = MT->getElementType();
8405 }
8406 if (NumElems > 0) {
8407 PrimType ElemT = classifyPrim(ElemType);
8408 for (unsigned I = 0; I != NumElems; ++I) {
8409 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8410 return false;
8411 if (!this->emitPrimCast(SrcT, ElemT, ElemType, E))
8412 return false;
8413 if (!this->emitInitElem(ElemT, I, E))
8414 return false;
8415 }
8416 return true;
8417 }
8418
8419 // Arrays: primitive elements are filled directly; composite elements
8420 // require recursion into each sub-aggregate.
8421 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
8422 const auto *CAT = cast<ConstantArrayType>(AT);
8423 QualType ArrElemType = CAT->getElementType();
8424 unsigned ArrSize = CAT->getZExtSize();
8425
8426 if (OptPrimType ElemT = classify(ArrElemType)) {
8427 for (unsigned I = 0; I != ArrSize; ++I) {
8428 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8429 return false;
8430 if (!this->emitPrimCast(SrcT, *ElemT, ArrElemType, E))
8431 return false;
8432 if (!this->emitInitElem(*ElemT, I, E))
8433 return false;
8434 }
8435 } else {
8436 for (unsigned I = 0; I != ArrSize; ++I) {
8437 if (!this->emitConstUint32(I, E))
8438 return false;
8439 if (!this->emitArrayElemPtrUint32(E))
8440 return false;
8441 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, ArrElemType, E))
8442 return false;
8443 if (!this->emitFinishInitPop(E))
8444 return false;
8445 }
8446 }
8447 return true;
8448 }
8449
8450 // Records: fill base classes first, then named fields in declaration
8451 // order.
8452 if (DestType->isRecordType()) {
8453 const Record *R = getRecord(DestType);
8454 if (!R)
8455 return false;
8456
8457 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
8458 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
8459 const Record::Base *B = R->getBase(BS.getType());
8460 assert(B);
8461 if (!this->emitGetPtrBase(B->Offset, E))
8462 return false;
8463 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, BS.getType(), E))
8464 return false;
8465 if (!this->emitFinishInitPop(E))
8466 return false;
8467 }
8468 }
8469
8470 for (const Record::Field &F : R->fields()) {
8471 if (F.isUnnamedBitField())
8472 continue;
8473
8474 QualType FieldType = F.Decl->getType();
8475 if (OptPrimType FieldT = classify(FieldType)) {
8476 if (!this->emitGetLocal(SrcT, SrcOffset, E))
8477 return false;
8478 if (!this->emitPrimCast(SrcT, *FieldT, FieldType, E))
8479 return false;
8480 if (F.isBitField()) {
8481 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
8482 return false;
8483 } else {
8484 if (!this->emitInitField(*FieldT, F.Offset, E))
8485 return false;
8486 }
8487 } else {
8488 if (!this->emitGetPtrField(F.Offset, E))
8489 return false;
8490 if (!emitHLSLAggregateSplat(SrcT, SrcOffset, FieldType, E))
8491 return false;
8492 if (!this->emitPopPtr(E))
8493 return false;
8494 }
8495 }
8496 return true;
8497 }
8498
8499 return false;
8500}
8501
8502/// Return the total number of scalar elements in a type. This is used
8503/// to cap how many source elements are extracted during an elementwise cast,
8504/// so we never flatten more than the destination can hold.
8505template <class Emitter>
8506unsigned Compiler<Emitter>::countHLSLFlatElements(QualType Ty) {
8507 // Vector and matrix types are treated as flat sequences of elements.
8508 if (const auto *VT = Ty->getAs<VectorType>())
8509 return VT->getNumElements();
8510 if (const auto *MT = Ty->getAs<ConstantMatrixType>())
8511 return MT->getNumElementsFlattened();
8512 // Arrays: total count is array size * scalar elements per element.
8513 if (const auto *AT = Ty->getAsArrayTypeUnsafe()) {
8514 const auto *CAT = cast<ConstantArrayType>(AT);
8515 return CAT->getZExtSize() * countHLSLFlatElements(CAT->getElementType());
8516 }
8517 // Records: sum scalar element counts of base classes and named fields.
8518 if (Ty->isRecordType()) {
8519 const Record *R = getRecord(Ty);
8520 if (!R)
8521 return 0;
8522 unsigned Count = 0;
8523 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
8524 for (const CXXBaseSpecifier &BS : CXXRD->bases())
8525 Count += countHLSLFlatElements(BS.getType());
8526 }
8527 for (const Record::Field &F : R->fields()) {
8528 if (F.isUnnamedBitField())
8529 continue;
8530 Count += countHLSLFlatElements(F.Decl->getType());
8531 }
8532 return Count;
8533 }
8534 // Scalar primitive types contribute one element.
8535 if (canClassify(Ty))
8536 return 1;
8537 return 0;
8538}
8539
8540/// Walk a source aggregate and extract every scalar element into its own local
8541/// variable. The results are appended to \p Elements in declaration order,
8542/// stopping once \p MaxElements have been collected. A pointer to the
8543/// source aggregate must be stored in the local at \p SrcOffset.
8544template <class Emitter>
8545bool Compiler<Emitter>::emitHLSLFlattenAggregate(
8546 QualType SrcType, unsigned SrcOffset,
8547 SmallVectorImpl<HLSLFlatElement> &Elements, unsigned MaxElements,
8548 const Expr *E) {
8549
8550 // Save a scalar value from the stack into a new local and record it.
8551 auto saveToLocal = [&](PrimType T) -> bool {
8552 unsigned Offset = allocateLocalPrimitive(E, T, /*IsConst=*/true);
8553 if (!this->emitSetLocal(T, Offset, E))
8554 return false;
8555 Elements.push_back({Offset, T});
8556 return true;
8557 };
8558
8559 // Save a pointer from the stack into a new local for later use.
8560 auto savePtrToLocal = [&]() -> UnsignedOrNone {
8561 unsigned Offset = allocateLocalPrimitive(E, PT_Ptr, /*IsConst=*/true);
8562 if (!this->emitSetLocal(PT_Ptr, Offset, E))
8563 return std::nullopt;
8564 return Offset;
8565 };
8566
8567 // Vectors and matrices are flat sequences of elements.
8568 unsigned NumElems = 0;
8569 QualType ElemType;
8570 if (const auto *VT = SrcType->getAs<VectorType>()) {
8571 NumElems = VT->getNumElements();
8572 ElemType = VT->getElementType();
8573 } else if (const auto *MT = SrcType->getAs<ConstantMatrixType>()) {
8574 NumElems = MT->getNumElementsFlattened();
8575 ElemType = MT->getElementType();
8576 }
8577 if (NumElems > 0) {
8578 PrimType ElemT = classifyPrim(ElemType);
8579 for (unsigned I = 0; I != NumElems && Elements.size() < MaxElements; ++I) {
8580 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
8581 return false;
8582 if (!this->emitArrayElemPop(ElemT, I, E))
8583 return false;
8584 if (!saveToLocal(ElemT))
8585 return false;
8586 }
8587 return true;
8588 }
8589
8590 // Arrays: primitive elements are extracted directly; composite elements
8591 // require recursion into each sub-aggregate.
8592 if (const auto *AT = SrcType->getAsArrayTypeUnsafe()) {
8593 const auto *CAT = cast<ConstantArrayType>(AT);
8594 QualType ArrElemType = CAT->getElementType();
8595 unsigned ArrSize = CAT->getZExtSize();
8596
8597 if (OptPrimType ElemT = classify(ArrElemType)) {
8598 for (unsigned I = 0; I != ArrSize && Elements.size() < MaxElements; ++I) {
8599 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
8600 return false;
8601 if (!this->emitArrayElemPop(*ElemT, I, E))
8602 return false;
8603 if (!saveToLocal(*ElemT))
8604 return false;
8605 }
8606 } else {
8607 for (unsigned I = 0; I != ArrSize && Elements.size() < MaxElements; ++I) {
8608 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
8609 return false;
8610 if (!this->emitConstUint32(I, E))
8611 return false;
8612 if (!this->emitArrayElemPtrPopUint32(E))
8613 return false;
8614 UnsignedOrNone ElemPtrOffset = savePtrToLocal();
8615 if (!ElemPtrOffset)
8616 return false;
8617 if (!emitHLSLFlattenAggregate(ArrElemType, *ElemPtrOffset, Elements,
8618 MaxElements, E))
8619 return false;
8620 }
8621 }
8622 return true;
8623 }
8624
8625 // Records: base classes come first, then named fields in declaration
8626 // order.
8627 if (SrcType->isRecordType()) {
8628 const Record *R = getRecord(SrcType);
8629 if (!R)
8630 return false;
8631
8632 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
8633 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
8634 if (Elements.size() >= MaxElements)
8635 break;
8636 const Record::Base *B = R->getBase(BS.getType());
8637 assert(B);
8638 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
8639 return false;
8640 if (!this->emitGetPtrBasePop(B->Offset, /*NullOK=*/false, E))
8641 return false;
8642 UnsignedOrNone BasePtrOffset = savePtrToLocal();
8643 if (!BasePtrOffset)
8644 return false;
8645 if (!emitHLSLFlattenAggregate(BS.getType(), *BasePtrOffset, Elements,
8646 MaxElements, E))
8647 return false;
8648 }
8649 }
8650
8651 for (const Record::Field &F : R->fields()) {
8652 if (Elements.size() >= MaxElements)
8653 break;
8654 if (F.isUnnamedBitField())
8655 continue;
8656
8657 QualType FieldType = F.Decl->getType();
8658 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E))
8659 return false;
8660 if (!this->emitGetPtrFieldPop(F.Offset, E))
8661 return false;
8662
8663 if (OptPrimType FieldT = classify(FieldType)) {
8664 if (!this->emitLoadPop(*FieldT, E))
8665 return false;
8666 if (!saveToLocal(*FieldT))
8667 return false;
8668 } else {
8669 UnsignedOrNone FieldPtrOffset = savePtrToLocal();
8670 if (!FieldPtrOffset)
8671 return false;
8672 if (!emitHLSLFlattenAggregate(FieldType, *FieldPtrOffset, Elements,
8673 MaxElements, E))
8674 return false;
8675 }
8676 }
8677 return true;
8678 }
8679
8680 return false;
8681}
8682
8683/// Populate an HLSL aggregate from a flat list of previously extracted source
8684/// elements, casting each to the corresponding destination element type.
8685/// \p ElemIdx tracks the current position in \p Elements and is advanced as
8686/// elements are consumed. A pointer to the destination must be on top of the
8687/// interpreter stack.
8688template <class Emitter>
8689bool Compiler<Emitter>::emitHLSLConstructAggregate(
8690 QualType DestType, ArrayRef<HLSLFlatElement> Elements, unsigned &ElemIdx,
8691 const Expr *E) {
8692
8693 // Consume the next source element, cast it, and leave it on the stack.
8694 auto loadAndCast = [&](PrimType DestT, QualType DestQT) -> bool {
8695 const auto &Src = Elements[ElemIdx++];
8696 if (!this->emitGetLocal(Src.Type, Src.LocalOffset, E))
8697 return false;
8698 return this->emitPrimCast(Src.Type, DestT, DestQT, E);
8699 };
8700
8701 // Vectors and matrices are flat sequences of elements.
8702 unsigned NumElems = 0;
8703 QualType ElemType;
8704 if (const auto *VT = DestType->getAs<VectorType>()) {
8705 NumElems = VT->getNumElements();
8706 ElemType = VT->getElementType();
8707 } else if (const auto *MT = DestType->getAs<ConstantMatrixType>()) {
8708 NumElems = MT->getNumElementsFlattened();
8709 ElemType = MT->getElementType();
8710 }
8711 if (NumElems > 0) {
8712 PrimType DestElemT = classifyPrim(ElemType);
8713 for (unsigned I = 0; I != NumElems; ++I) {
8714 if (!loadAndCast(DestElemT, ElemType))
8715 return false;
8716 if (!this->emitInitElem(DestElemT, I, E))
8717 return false;
8718 }
8719 return true;
8720 }
8721
8722 // Arrays: primitive elements are filled directly; composite elements
8723 // require recursion into each sub-aggregate.
8724 if (const auto *AT = DestType->getAsArrayTypeUnsafe()) {
8725 const auto *CAT = cast<ConstantArrayType>(AT);
8726 QualType ArrElemType = CAT->getElementType();
8727 unsigned ArrSize = CAT->getZExtSize();
8728
8729 if (OptPrimType ElemT = classify(ArrElemType)) {
8730 for (unsigned I = 0; I != ArrSize; ++I) {
8731 if (!loadAndCast(*ElemT, ArrElemType))
8732 return false;
8733 if (!this->emitInitElem(*ElemT, I, E))
8734 return false;
8735 }
8736 } else {
8737 for (unsigned I = 0; I != ArrSize; ++I) {
8738 if (!this->emitConstUint32(I, E))
8739 return false;
8740 if (!this->emitArrayElemPtrUint32(E))
8741 return false;
8742 if (!emitHLSLConstructAggregate(ArrElemType, Elements, ElemIdx, E))
8743 return false;
8744 if (!this->emitFinishInitPop(E))
8745 return false;
8746 }
8747 }
8748 return true;
8749 }
8750
8751 // Records: base classes come first, then named fields in declaration
8752 // order.
8753 if (DestType->isRecordType()) {
8754 const Record *R = getRecord(DestType);
8755 if (!R)
8756 return false;
8757
8758 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(R->getDecl())) {
8759 for (const CXXBaseSpecifier &BS : CXXRD->bases()) {
8760 const Record::Base *B = R->getBase(BS.getType());
8761 assert(B);
8762 if (!this->emitGetPtrBase(B->Offset, E))
8763 return false;
8764 if (!emitHLSLConstructAggregate(BS.getType(), Elements, ElemIdx, E))
8765 return false;
8766 if (!this->emitFinishInitPop(E))
8767 return false;
8768 }
8769 }
8770
8771 for (const Record::Field &F : R->fields()) {
8772 if (F.isUnnamedBitField())
8773 continue;
8774
8775 QualType FieldType = F.Decl->getType();
8776 if (OptPrimType FieldT = classify(FieldType)) {
8777 if (!loadAndCast(*FieldT, FieldType))
8778 return false;
8779 if (F.isBitField()) {
8780 if (!this->emitInitBitField(*FieldT, F.Offset, F.bitWidth(), E))
8781 return false;
8782 } else {
8783 if (!this->emitInitField(*FieldT, F.Offset, E))
8784 return false;
8785 }
8786 } else {
8787 if (!this->emitGetPtrField(F.Offset, E))
8788 return false;
8789 if (!emitHLSLConstructAggregate(FieldType, Elements, ElemIdx, E))
8790 return false;
8791 if (!this->emitPopPtr(E))
8792 return false;
8793 }
8794 }
8795 return true;
8796 }
8797
8798 return false;
8799}
8800
8801namespace clang {
8802namespace interp {
8803
8804template class Compiler<ByteCodeEmitter>;
8805template class Compiler<EvalEmitter>;
8806
8807} // namespace interp
8808} // namespace clang
#define V(N, I)
static void emit(Program &P, llvm::SmallVectorImpl< std::byte > &Code, const T &Val, bool &Success)
Helper to write bytecode and bail out if 32-bit offsets become invalid.
static void emitCleanup(CIRGenFunction &cgf, cir::CleanupScopeOp cleanupScope, EHScopeStack::Cleanup *cleanup, EHScopeStack::Cleanup::Flags flags, Address activeFlag)
static uint32_t getBitWidth(const Expr *E)
#define EMIT_ARITH_OP(OP)
static CharUnits AlignOfType(QualType T, const ASTContext &ASTCtx, UnaryExprOrTypeTrait Kind)
static const Expr * stripDerivedToBaseCasts(const Expr *E)
static const Expr * stripCheckedDerivedToBaseCasts(const Expr *E)
static bool hasTrivialDefaultCtorParent(const FieldDecl *FD)
static bool initNeedsOverridenLoc(const CXXCtorInitializer *Init)
llvm::APSInt APSInt
Definition Compiler.cpp:25
Result
Implement __builtin_bit_cast and related operations.
llvm::SmallPtrSet< const ParmVarDecl *, 1 > FoundParams
bool VisitDeclRefExpr(const DeclRefExpr *E) override
a trap message and trap category.
llvm::APInt getValue() const
APValue - This class implements a discriminated union of [uninitialized] [APSInt] [APFloat],...
Definition APValue.h:122
const LValueBase getLValueBase() const
Definition APValue.cpp:1001
APValue & getArrayInitializedElt(unsigned I)
Definition APValue.h:626
ArrayRef< LValuePathEntry > getLValuePath() const
Definition APValue.cpp:1021
APSInt & getInt()
Definition APValue.h:508
APValue & getStructField(unsigned i)
Definition APValue.h:667
const FieldDecl * getUnionField() const
Definition APValue.h:679
unsigned getStructNumFields() const
Definition APValue.h:658
bool isArray() const
Definition APValue.h:493
bool isMemberPointerToDerivedMember() const
Definition APValue.cpp:1091
unsigned getArrayInitializedElts() const
Definition APValue.h:645
bool isFloat() const
Definition APValue.h:486
unsigned getStructNumBases() const
Definition APValue.h:654
const ValueDecl * getMemberPointerDecl() const
Definition APValue.cpp:1084
APValue & getUnionValue()
Definition APValue.h:683
APValue & getArrayFiller()
Definition APValue.h:637
bool isLValue() const
Definition APValue.h:490
bool isIndeterminate() const
Definition APValue.h:482
ArrayRef< const CXXRecordDecl * > getMemberPointerPath() const
Definition APValue.cpp:1098
bool isMemberPointer() const
Definition APValue.h:496
bool isInt() const
Definition APValue.h:485
unsigned getArraySize() const
Definition APValue.h:649
bool isUnion() const
Definition APValue.h:495
@ None
There is no such object (it's outside its lifetime).
Definition APValue.h:129
bool isStruct() const
Definition APValue.h:494
bool isNullPointer() const
Definition APValue.cpp:1037
APFloat & getFloat()
Definition APValue.h:522
APValue & getStructBase(unsigned i)
Definition APValue.h:662
Holds long-lived AST nodes (such as types and decls) that can be referred to throughout the semantic ...
Definition ASTContext.h:223
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
unsigned getPreferredTypeAlign(QualType T) const
Return the "preferred" alignment of the specified type T for the current target, in bits.
const LangOptions & getLangOpts() const
Definition ASTContext.h:959
unsigned getOpenMPDefaultSimdAlign(QualType T) const
Get default simd alignment of the specified complete type in bits.
TypeInfoChars getTypeInfoDataSizeInChars(QualType T) const
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
llvm::FixedPointSemantics getFixedPointSemantics(QualType Ty) const
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4359
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4537
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4543
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4549
AddrLabelExpr - The GNU address of label extension, representing &&label.
Definition Expr.h:4556
Represents the index of the current element of an array being initialized by an ArrayInitLoopExpr.
Definition Expr.h:6024
Represents a loop initializing the elements of an array.
Definition Expr.h:5971
llvm::APInt getArraySize() const
Definition Expr.h:5993
OpaqueValueExpr * getCommonExpr() const
Get the common subexpression shared by all initializations (the source array).
Definition Expr.h:5986
Expr * getSubExpr() const
Get the initializer to use for each array element.
Definition Expr.h:5991
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2727
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2756
An Embarcadero array type trait, as used in the implementation of __array_rank and __array_extent.
Definition ExprCXX.h:3000
uint64_t getValue() const
Definition ExprCXX.h:3048
Represents an array type, per C99 6.7.5.2 - Array Declarators.
Definition TypeBase.h:3786
QualType getElementType() const
Definition TypeBase.h:3798
Attr - This represents one attribute.
Definition Attr.h:46
Represents an attribute applied to a statement.
Definition Stmt.h:2213
Stmt * getSubStmt()
Definition Stmt.h:2249
ArrayRef< const Attr * > getAttrs() const
Definition Stmt.h:2245
Represents a C++ declaration that introduces decls from somewhere else.
Definition DeclCXX.h:3514
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4044
static bool isLogicalOp(Opcode Opc)
Definition Expr.h:4177
Expr * getLHS() const
Definition Expr.h:4094
static bool isComparisonOp(Opcode Opc)
Definition Expr.h:4144
static bool isShiftOp(Opcode Opc)
Definition Expr.h:4132
static bool isCommaOp(Opcode Opc)
Definition Expr.h:4147
static Opcode getOpForCompoundAssignment(Opcode Opc)
Definition Expr.h:4191
Expr * getRHS() const
Definition Expr.h:4096
static bool isPtrMemOp(Opcode Opc)
predicates to categorize the respective opcodes.
Definition Expr.h:4121
static bool isAssignmentOp(Opcode Opc)
Definition Expr.h:4180
static bool isCompoundAssignmentOp(Opcode Opc)
Definition Expr.h:4185
Opcode getOpcode() const
Definition Expr.h:4089
static bool isBitwiseOp(Opcode Opc)
Definition Expr.h:4135
BlockExpr - Adaptor class for mixing a BlockDecl with expressions.
Definition Expr.h:6675
BreakStmt - This represents a break.
Definition Stmt.h:3145
Represents a C++2a __builtin_bit_cast(T, v) expression.
Definition ExprCXX.h:5472
Represents a base class of a C++ class.
Definition DeclCXX.h:146
Represents binding an expression to a temporary.
Definition ExprCXX.h:1497
const Expr * getSubExpr() const
Definition ExprCXX.h:1519
A boolean literal, per ([C++ lex.bool] Boolean literals).
Definition ExprCXX.h:727
bool getValue() const
Definition ExprCXX.h:744
Represents a call to a C++ constructor.
Definition ExprCXX.h:1552
bool isElidable() const
Whether this construction is elidable.
Definition ExprCXX.h:1621
Expr * getArg(unsigned Arg)
Return the specified argument.
Definition ExprCXX.h:1695
arg_range arguments()
Definition ExprCXX.h:1676
bool requiresZeroInitialization() const
Whether this construction first requires zero-initialization before the initializer is called.
Definition ExprCXX.h:1654
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will (ultimately) call.
Definition ExprCXX.h:1615
unsigned getNumArgs() const
Return the number of arguments to the constructor call.
Definition ExprCXX.h:1692
Represents a C++ constructor within a class.
Definition DeclCXX.h:2633
bool isCopyOrMoveConstructor(unsigned &TypeQuals) const
Determine whether this is a copy or move constructor.
Definition DeclCXX.cpp:3067
Represents a C++ base or member initializer.
Definition DeclCXX.h:2398
A default argument (C++ [dcl.fct.default]).
Definition ExprCXX.h:1274
A use of a default initializer in a constructor or in aggregate initialization.
Definition ExprCXX.h:1381
Expr * getExpr()
Get the initialization expression that will be used.
Definition ExprCXX.cpp:1112
Represents a delete expression for memory deallocation and destructor calls, e.g.
Definition ExprCXX.h:2630
FunctionDecl * getOperatorDelete() const
Definition ExprCXX.h:2669
bool isArrayForm() const
Definition ExprCXX.h:2656
bool isGlobalDelete() const
Definition ExprCXX.h:2655
Represents a C++ destructor within a class.
Definition DeclCXX.h:2895
A C++ dynamic_cast expression (C++ [expr.dynamic.cast]).
Definition ExprCXX.h:485
CXXForRangeStmt - This represents C++0x [stmt.ranged]'s ranged for statement, represented as 'for (ra...
Definition StmtCXX.h:135
DeclStmt * getBeginStmt()
Definition StmtCXX.h:163
DeclStmt * getLoopVarStmt()
Definition StmtCXX.h:169
DeclStmt * getEndStmt()
Definition StmtCXX.h:166
DeclStmt * getRangeStmt()
Definition StmtCXX.h:162
Represents a call to an inherited base class constructor from an inheriting constructor.
Definition ExprCXX.h:1755
CXXConstructorDecl * getConstructor() const
Get the constructor that this expression will call.
Definition ExprCXX.h:1792
Represents a static or instance method of a struct/union/class.
Definition DeclCXX.h:2145
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition DeclCXX.h:2284
bool isMoveAssignmentOperator() const
Determine whether this is a move assignment operator.
Definition DeclCXX.cpp:2749
bool isCopyAssignmentOperator() const
Determine whether this is a copy-assignment operator, regardless of whether it was declared implicitl...
Definition DeclCXX.cpp:2728
bool isLambdaStaticInvoker() const
Determine whether this is a lambda closure type's static member function that is used for the result ...
Definition DeclCXX.cpp:2893
Represents a new-expression for memory allocation and constructor calls, e.g: "new CXXNewExpr(foo)".
Definition ExprCXX.h:2359
bool isArray() const
Definition ExprCXX.h:2468
QualType getAllocatedType() const
Definition ExprCXX.h:2438
std::optional< Expr * > getArraySize()
This might return std::nullopt even if isArray() returns true, since there might not be an array size...
Definition ExprCXX.h:2473
Expr * getPlacementArg(unsigned I)
Definition ExprCXX.h:2507
unsigned getNumPlacementArgs() const
Definition ExprCXX.h:2498
FunctionDecl * getOperatorNew() const
Definition ExprCXX.h:2463
Expr * getInitializer()
The initializer of this new-expression.
Definition ExprCXX.h:2537
Represents a C++11 noexcept expression (C++ [expr.unary.noexcept]).
Definition ExprCXX.h:4309
bool getValue() const
Definition ExprCXX.h:4332
The null pointer literal (C++11 [lex.nullptr])
Definition ExprCXX.h:772
Represents a list-initialization with parenthesis.
Definition ExprCXX.h:5141
MutableArrayRef< Expr * > getInitExprs()
Definition ExprCXX.h:5181
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasTrivialDefaultConstructor() const
Determine whether this class has a trivial default constructor (C++11 [class.ctor]p5).
Definition DeclCXX.h:1251
bool isGenericLambda() const
Determine whether this class describes a generic lambda function object (i.e.
Definition DeclCXX.cpp:1679
capture_const_range captures() const
Definition DeclCXX.h:1102
CXXMethodDecl * getLambdaCallOperator() const
Retrieve the lambda call operator of the closure type if this is a closure type.
Definition DeclCXX.cpp:1742
A C++ reinterpret_cast expression (C++ [expr.reinterpret.cast]).
Definition ExprCXX.h:530
A rewritten comparison expression that was originally written using operator syntax.
Definition ExprCXX.h:290
Expr * getSemanticForm()
Get an equivalent semantic form for this expression.
Definition ExprCXX.h:308
An expression "T()" which creates an rvalue of a non-class type T.
Definition ExprCXX.h:2200
Implicit construction of a std::initializer_list<T> object from an array temporary within list-initia...
Definition ExprCXX.h:804
Represents the this expression in C++.
Definition ExprCXX.h:1158
A C++ throw-expression (C++ [except.throw]).
Definition ExprCXX.h:1212
const Expr * getSubExpr() const
Definition ExprCXX.h:1232
CXXTryStmt - A C++ try block, including all handlers.
Definition StmtCXX.h:69
CompoundStmt * getTryBlock()
Definition StmtCXX.h:100
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:852
bool isTypeOperand() const
Definition ExprCXX.h:888
QualType getTypeOperand(const ASTContext &Context) const
Retrieves the type operand of this typeid() expression after various required adjustments (removing r...
Definition ExprCXX.cpp:166
Expr * getExprOperand() const
Definition ExprCXX.h:899
bool isPotentiallyEvaluated() const
Determine whether this typeid has a type operand which is potentially evaluated, per C++11 [expr....
Definition ExprCXX.cpp:134
A Microsoft C++ __uuidof expression, which gets the _GUID that corresponds to the supplied type or ex...
Definition ExprCXX.h:1072
MSGuidDecl * getGuidDecl() const
Definition ExprCXX.h:1118
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:2949
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3153
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3132
Expr * getCallee()
Definition Expr.h:3096
unsigned getNumArgs() const
getNumArgs - Return the number of actual arguments to this call.
Definition Expr.h:3140
Expr ** getArgs()
Retrieve the call arguments.
Definition Expr.h:3143
arg_range arguments()
Definition Expr.h:3201
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1609
CaseStmt - Represent a case statement.
Definition Stmt.h:1930
Stmt * getSubStmt()
Definition Stmt.h:2043
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3682
path_iterator path_begin()
Definition Expr.h:3752
CastKind getCastKind() const
Definition Expr.h:3726
llvm::iterator_range< path_iterator > path()
Path through the class hierarchy taken by casts between base and derived classes (see implementation ...
Definition Expr.h:3769
const FieldDecl * getTargetUnionField() const
Definition Expr.h:3776
path_iterator path_end()
Definition Expr.h:3753
Expr * getSubExpr()
Definition Expr.h:3732
CharUnits - This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
QuantityType getQuantity() const
getQuantity - Get the raw integer representation of this quantity.
Definition CharUnits.h:185
static CharUnits One()
One - Construct a CharUnits quantity of one.
Definition CharUnits.h:58
unsigned getValue() const
Definition Expr.h:1635
ChooseExpr - GNU builtin-in function __builtin_choose_expr.
Definition Expr.h:4854
Expr * getChosenSubExpr() const
getChosenSubExpr - Return the subexpression chosen according to the condition.
Definition Expr.h:4890
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3339
QualType getElementType() const
Definition TypeBase.h:3349
CompoundAssignOperator - For compound assignments (e.g.
Definition Expr.h:4306
QualType getComputationLHSType() const
Definition Expr.h:4340
QualType getComputationResultType() const
Definition Expr.h:4343
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3611
bool isFileScope() const
Definition Expr.h:3643
const Expr * getInitializer() const
Definition Expr.h:3639
CompoundStmt - This represents a group of statements like { stmt stmt }.
Definition Stmt.h:1750
body_range body()
Definition Stmt.h:1813
Stmt * body_back()
Definition Stmt.h:1818
Represents the specialization of a concept - evaluates to a prvalue of type bool.
bool isSatisfied() const
Whether or not the concept with the given arguments was satisfied when the expression was created.
Represents the canonical version of C arrays with a specified constant size.
Definition TypeBase.h:3824
uint64_t getZExtSize() const
Return the size zero-extended as a uint64_t.
Definition TypeBase.h:3900
ConstantExpr - An expression that occurs in a constant context and optionally the result of evaluatin...
Definition Expr.h:1088
APValue getAPValueResult() const
Definition Expr.cpp:419
bool hasAPValueResult() const
Definition Expr.h:1163
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4451
ContinueStmt - This represents a continue.
Definition Stmt.h:3129
ConvertVectorExpr - Clang builtin function __builtin_convertvector This AST node provides support for...
Definition Expr.h:4725
Expr * getSrcExpr() const
getSrcExpr - Return the Expr to be converted.
Definition Expr.h:4815
DeclContext * getParent()
getParent - Returns the containing DeclContext.
Definition DeclBase.h:2126
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1276
ValueDecl * getDecl()
Definition Expr.h:1344
DeclStmt - Adaptor class for mixing declarations with statements and expressions.
Definition Stmt.h:1641
decl_range decls()
Definition Stmt.h:1689
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
bool isInvalidDecl() const
Definition DeclBase.h:596
bool hasAttr() const
Definition DeclBase.h:585
OverloadedOperatorKind getCXXOverloadedOperator() const
If this name is the name of an overloadable operator in C++ (e.g., operator+), retrieve the kind of o...
Stmt * getSubStmt()
Definition Stmt.h:2091
InitListExpr * getUpdater() const
Definition Expr.h:5939
DoStmt - This represents a 'do/while' stmt.
Definition Stmt.h:2842
Stmt * getBody()
Definition Stmt.h:2867
Expr * getCond()
Definition Stmt.h:2860
virtual bool TraverseStmt(MaybeConst< Stmt > *S)
Recursively visit a statement or expression, by dispatching to Traverse*() based on the argument's dy...
const Expr * getBase() const
Definition Expr.h:6584
Represents a reference to emded data.
Definition Expr.h:5132
ChildElementIter< false > begin()
Definition Expr.h:5238
Represents an expression – generally a full-expression – that introduces cleanups to be run at the en...
Definition ExprCXX.h:3661
This represents one expression.
Definition Expr.h:112
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:85
bool isGLValue() const
Definition Expr.h:287
bool isValueDependent() const
Determines whether the value of this expression depends on.
Definition Expr.h:177
Expr * IgnoreImplicit() LLVM_READONLY
Skip past any implicit AST nodes which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3087
bool containsErrors() const
Whether this expression contains subexpressions which had errors.
Definition Expr.h:246
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3095
bool isPRValue() const
Definition Expr.h:285
bool isLValue() const
isLValue - True if this expression is an "l-value" according to the rules of the current language.
Definition Expr.h:284
bool HasSideEffects(const ASTContext &Ctx, bool IncludePossibleEffects=true) const
HasSideEffects - This routine returns true for all those expressions which have any effect other than...
Definition Expr.cpp:3697
bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const
Determine whether the result of this expression is a temporary object of the given class type.
Definition Expr.cpp:3262
bool refersToBitField() const
Returns true if this expression is a gl-value that potentially refers to a bit-field.
Definition Expr.h:479
QualType getType() const
Definition Expr.h:144
An expression trait intrinsic.
Definition ExprCXX.h:3073
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6613
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4558
Represents a member of a struct/union/class.
Definition Decl.h:3191
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3427
llvm::APInt getValue() const
Returns an internal integer representation of the literal.
Definition Expr.h:1581
llvm::APFloat getValue() const
Definition Expr.h:1672
ForStmt - This represents a 'for (init;cond;inc)' stmt.
Definition Stmt.h:2898
Stmt * getInit()
Definition Stmt.h:2913
VarDecl * getConditionVariable() const
Retrieve the variable declared in this "for" statement, if any.
Definition Stmt.cpp:1120
Stmt * getBody()
Definition Stmt.h:2942
Expr * getInc()
Definition Stmt.h:2941
Expr * getCond()
Definition Stmt.h:2940
DeclStmt * getConditionVariableDeclStmt()
If this ForStmt has a condition variable, return the faux DeclStmt associated with the creation of th...
Definition Stmt.h:2928
const Expr * getSubExpr() const
Definition Expr.h:1068
Represents a function declaration or definition.
Definition Decl.h:2027
const ParmVarDecl * getParamDecl(unsigned i) const
Definition Decl.h:2824
Stmt * getBody(const FunctionDecl *&Definition) const
Retrieve the body (definition) of the function.
Definition Decl.cpp:3256
bool isFunctionTemplateSpecialization() const
Determine whether this function is a function template specialization.
Definition Decl.cpp:4182
FunctionTemplateDecl * getDescribedFunctionTemplate() const
Retrieves the function template that is described by this function declaration.
Definition Decl.cpp:4170
unsigned getBuiltinID(bool ConsiderWrapperFunctions=false) const
Returns a value indicating whether this function corresponds to a builtin function.
Definition Decl.cpp:3739
QualType getReturnType() const
Definition Decl.h:2872
ArrayRef< ParmVarDecl * > parameters() const
Definition Decl.h:2801
bool isTrivial() const
Whether this function is "trivial" in some specialized C++ senses.
Definition Decl.h:2404
const TemplateArgumentList * getTemplateSpecializationArgs() const
Retrieve the template arguments used to produce this function template specialization from the primar...
Definition Decl.cpp:4306
bool isUsableAsGlobalAllocationFunctionInConstantEvaluation(UnsignedOrNone *AlignmentParam=nullptr, bool *IsNothrow=nullptr) const
Determines whether this function is one of the replaceable global allocation functions described in i...
Definition Decl.cpp:3403
bool isDefaulted() const
Whether this function is defaulted.
Definition Decl.h:2412
unsigned getNumParams() const
Return the number of parameters this function must have based on its FunctionType.
Definition Decl.cpp:3803
bool hasBody(const FunctionDecl *&Definition) const
Returns true if the function has a body.
Definition Decl.cpp:3176
Declaration of a template function.
FunctionDecl * findSpecialization(ArrayRef< TemplateArgument > Args, void *&InsertPos)
Return the specialization with the provided arguments if it exists, otherwise return the insertion po...
GNUNullExpr - Implements the GNU __null extension, which is a name for a null pointer constant that h...
Definition Expr.h:4929
Represents a C11 generic selection.
Definition Expr.h:6185
Expr * getResultExpr()
Return the result expression of this controlling expression.
Definition Expr.h:6471
IfStmt - This represents an if/then/else.
Definition Stmt.h:2269
Stmt * getThen()
Definition Stmt.h:2358
Stmt * getInit()
Definition Stmt.h:2419
bool isNonNegatedConsteval() const
Definition Stmt.h:2454
Expr * getCond()
Definition Stmt.h:2346
bool isNegatedConsteval() const
Definition Stmt.h:2458
Stmt * getElse()
Definition Stmt.h:2367
DeclStmt * getConditionVariableDeclStmt()
If this IfStmt has a condition variable, return the faux DeclStmt associated with the creation of tha...
Definition Stmt.h:2402
VarDecl * getConditionVariable()
Retrieve the variable declared in this "if" statement, if any.
Definition Stmt.cpp:1068
ImaginaryLiteral - We support imaginary integer and floating point literals, like "1....
Definition Expr.h:1737
const Expr * getSubExpr() const
Definition Expr.h:1749
Represents an implicitly-generated value initialization of an object of a given type.
Definition Expr.h:6060
Represents a field injected from an anonymous union/struct into the parent scope.
Definition Decl.h:3498
Describes an C or C++ initializer list.
Definition Expr.h:5305
Expr * getArrayFiller()
If this initializer list initializes an array with more elements than there are initializers in the l...
Definition Expr.h:5408
ArrayRef< Expr * > inits() const
Definition Expr.h:5358
A C++ lambda expression, which produces a function object (of unspecified type) that can be invoked l...
Definition ExprCXX.h:1972
capture_init_iterator capture_init_begin()
Retrieve the first initialization argument for this lambda expression (which initializes the first ca...
Definition ExprCXX.h:2098
CXXRecordDecl * getLambdaClass() const
Retrieve the class that corresponds to the lambda.
Definition ExprCXX.cpp:1407
bool isCompatibleWith(ClangABI Version) const
Implicit declaration of a temporary that was materialized by a MaterializeTemporaryExpr and lifetime-...
Definition DeclCXX.h:3326
const Stmt * getNamedLoopOrSwitch() const
If this is a named break/continue, get the loop or switch statement that this targets.
Definition Stmt.cpp:1535
A global _GUID constant.
Definition DeclCXX.h:4416
APValue & getAsAPValue() const
Get the value of this MSGuidDecl as an APValue.
Definition DeclCXX.cpp:3862
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4920
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4945
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4937
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:4970
LifetimeExtendedTemporaryDecl * getLifetimeExtendedTemporaryDecl()
Definition ExprCXX.h:4960
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3370
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3453
Expr * getBase() const
Definition Expr.h:3447
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3717
This represents a decl that may have a name.
Definition Decl.h:274
DeclarationName getDeclName() const
Get the actual, stored name of the declaration, which may be a special name.
Definition Decl.h:340
Represents a C++ namespace alias.
Definition DeclCXX.h:3219
ObjCArrayLiteral - used for objective-c array containers; as in: @["Hello", NSApp,...
Definition ExprObjC.h:220
ObjCBoolLiteralExpr - Objective-C Boolean Literal.
Definition ExprObjC.h:119
ObjCBoxedExpr - used for generalized expression boxing.
Definition ExprObjC.h:159
ObjCDictionaryLiteral - AST node to represent objective-c dictionary literals; as in:"name" : NSUserN...
Definition ExprObjC.h:342
ObjCEncodeExpr, used for @encode in Objective-C.
Definition ExprObjC.h:441
QualType getEncodedType() const
Definition ExprObjC.h:460
SourceLocation getAtLoc() const
Definition ExprObjC.h:455
bool isExpressibleAsConstantInitializer() const
Definition ExprObjC.h:68
ObjCStringLiteral, used for Objective-C string literals i.e.
Definition ExprObjC.h:84
OffsetOfExpr - [C99 7.17] - This represents an expression of the form offsetof(record-type,...
Definition Expr.h:2533
Expr * getIndexExpr(unsigned Idx)
Definition Expr.h:2592
const OffsetOfNode & getComponent(unsigned Idx) const
Definition Expr.h:2580
unsigned getNumComponents() const
Definition Expr.h:2588
Helper class for OffsetOfExpr.
Definition Expr.h:2427
unsigned getArrayExprIndex() const
For an array element node, returns the index into the array of expressions.
Definition Expr.h:2485
@ Array
An index into an array.
Definition Expr.h:2432
Kind getKind() const
Determine what kind of offsetof node this is.
Definition Expr.h:2481
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1184
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1234
Expr * getSelectedExpr() const
Definition ExprCXX.h:4639
ParenExpr - This represents a parenthesized expression, e.g.
Definition Expr.h:2188
const Expr * getSubExpr() const
Definition Expr.h:2205
Represents a parameter to a function.
Definition Decl.h:1817
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3392
QualType getPointeeType() const
Definition TypeBase.h:3402
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2011
StringLiteral * getFunctionName()
Definition Expr.h:2055
PseudoObjectExpr - An expression which accesses a pseudo-object l-value.
Definition Expr.h:6807
Expr * getResultExpr()
Return the result-bearing expression, or null if there is none.
Definition Expr.h:6855
ArrayRef< Expr * > semantics()
Definition Expr.h:6879
A (possibly-)qualified type.
Definition TypeBase.h:937
bool isVolatileQualified() const
Determine whether this type is volatile-qualified.
Definition TypeBase.h:8531
QualType withConst() const
Definition TypeBase.h:1174
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1004
const Type * getTypePtr() const
Retrieves a pointer to the underlying (unqualified) type.
Definition TypeBase.h:8447
bool isConstant(const ASTContext &Ctx) const
Definition TypeBase.h:1097
bool isConstQualified() const
Determine whether this type is const-qualified.
Definition TypeBase.h:8520
Represents a struct/union/class.
Definition Decl.h:4356
Frontend produces RecoveryExprs on semantic errors that prevent creating other well-formed expression...
Definition Expr.h:7506
Base for LValueReferenceType and RValueReferenceType.
Definition TypeBase.h:3637
C++2a [expr.prim.req]: A requires-expression provides a concise way to express requirements on templa...
bool isSatisfied() const
Whether or not the requires clause is satisfied.
ReturnStmt - This represents a return, optionally of an expression: return; return 4;.
Definition Stmt.h:3170
Expr * getRetValue()
Definition Stmt.h:3197
SourceLocation getLocation() const
Definition Expr.h:2161
std::string ComputeName(ASTContext &Context) const
Definition Expr.cpp:593
Scope - A scope is a transient data structure that is used while parsing the program.
Definition Scope.h:41
ShuffleVectorExpr - clang-specific builtin-in function __builtin_shufflevector.
Definition Expr.h:4649
llvm::APSInt getShuffleMaskIdx(unsigned N) const
Definition Expr.h:4701
unsigned getNumSubExprs() const
getNumSubExprs - Return the size of the SubExprs array.
Definition Expr.h:4682
Expr * getExpr(unsigned Index)
getExpr - Return the Expr at the specified index.
Definition Expr.h:4688
Represents an expression that computes the length of a parameter pack.
Definition ExprCXX.h:4441
unsigned getPackLength() const
Retrieve the length of the parameter pack.
Definition ExprCXX.h:4515
Represents a function call to one of __builtin_LINE(), __builtin_COLUMN(), __builtin_FUNCTION(),...
Definition Expr.h:5023
APValue EvaluateInContext(const ASTContext &Ctx, const Expr *DefaultExpr) const
Return the result of evaluating this SourceLocExpr in the specified (and possibly null) default argum...
Definition Expr.cpp:2289
Represents a C++11 static_assert declaration.
Definition DeclCXX.h:4154
StmtExpr - This is the GNU Statement Expression extension: ({int X=4; X;}).
Definition Expr.h:4601
CompoundStmt * getSubStmt()
Definition Expr.h:4618
Stmt - This represents one statement.
Definition Stmt.h:86
StmtClass getStmtClass() const
Definition Stmt.h:1503
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1805
unsigned getLength() const
Definition Expr.h:1915
static StringLiteral * Create(const ASTContext &Ctx, StringRef Str, StringLiteralKind Kind, bool Pascal, QualType Ty, ArrayRef< SourceLocation > Locs)
This is the "fully general" constructor that allows representation of strings formed from one or more...
Definition Expr.cpp:1194
uint32_t getCodeUnit(size_t i) const
Definition Expr.h:1888
unsigned getCharByteWidth() const
Definition Expr.h:1916
Represents a reference to a non-type template parameter that has been substituted with a template arg...
Definition ExprCXX.h:4664
const SwitchCase * getNextSwitchCase() const
Definition Stmt.h:1903
SwitchStmt - This represents a 'switch' stmt.
Definition Stmt.h:2519
Expr * getCond()
Definition Stmt.h:2582
Stmt * getBody()
Definition Stmt.h:2594
VarDecl * getConditionVariable()
Retrieve the variable declared in this "switch" statement, if any.
Definition Stmt.cpp:1186
Stmt * getInit()
Definition Stmt.h:2599
SwitchCase * getSwitchCaseList()
Definition Stmt.h:2650
DeclStmt * getConditionVariableDeclStmt()
If this SwitchStmt has a condition variable, return the faux DeclStmt associated with the creation of...
Definition Stmt.h:2633
Represents the declaration of a struct/union/class/enum.
Definition Decl.h:3748
bool isCompleteDefinition() const
Return true if this decl has its body fully specified.
Definition Decl.h:3849
bool isUnion() const
Definition Decl.h:3959
A template argument list.
ArrayRef< TemplateArgument > asArray() const
Produce this as an array ref.
A type trait used in the implementation of various C++11 and Library TR1 trait templates.
Definition ExprCXX.h:2900
bool getBoolValue() const
Definition ExprCXX.h:2951
const APValue & getAPValue() const
Definition ExprCXX.h:2956
bool isStoredAsBoolean() const
Definition ExprCXX.h:2947
The base class of the type hierarchy.
Definition TypeBase.h:1875
bool isVoidType() const
Definition TypeBase.h:9050
bool isBooleanType() const
Definition TypeBase.h:9187
bool isLiteralType(const ASTContext &Ctx) const
Return true if this is a literal type (C++11 [basic.types]p10)
Definition Type.cpp:3117
bool isIncompleteArrayType() const
Definition TypeBase.h:8791
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isNothrowT() const
Definition Type.cpp:3301
RecordDecl * getAsRecordDecl() const
Retrieves the RecordDecl this type refers to.
Definition Type.h:41
bool isVoidPointerType() const
Definition Type.cpp:749
bool isConstantSizeType() const
Return true if this is not a variable sized type, according to the rules of C99 6....
Definition Type.cpp:2521
bool isArrayType() const
Definition TypeBase.h:8783
bool isFunctionPointerType() const
Definition TypeBase.h:8751
bool isConstantMatrixType() const
Definition TypeBase.h:8851
bool isPointerType() const
Definition TypeBase.h:8684
bool isIntegerType() const
isIntegerType() does not include complex integers (a GCC extension).
Definition TypeBase.h:9094
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9344
bool isReferenceType() const
Definition TypeBase.h:8708
bool isEnumeralType() const
Definition TypeBase.h:8815
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:789
bool isIntegralOrEnumerationType() const
Determine whether this type is an integral or enumeration type.
Definition TypeBase.h:9172
bool isSpecificBuiltinType(unsigned K) const
Test for a particular builtin type.
Definition TypeBase.h:9019
bool isDependentType() const
Whether this type is a dependent type, meaning that its definition somehow depends on a template para...
Definition TypeBase.h:2846
bool isAnyComplexType() const
Definition TypeBase.h:8819
bool isFixedPointType() const
Return true if this is a fixed point type according to ISO/IEC JTC1 SC22 WG14 N1169.
Definition TypeBase.h:9110
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9230
bool isMemberPointerType() const
Definition TypeBase.h:8765
bool isAtomicType() const
Definition TypeBase.h:8876
EnumDecl * castAsEnumDecl() const
Definition Type.h:59
bool isStdByteType() const
Definition Type.cpp:3320
const ArrayType * getAsArrayTypeUnsafe() const
A variant of getAs<> for array types which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9330
bool isPointerOrReferenceType() const
Definition TypeBase.h:8688
bool isFunctionType() const
Definition TypeBase.h:8680
bool isVectorType() const
Definition TypeBase.h:8823
bool isRealFloatingType() const
Floating point categories.
Definition Type.cpp:2409
const T * getAsCanonical() const
If this type is canonically the specified type, return its canonical type cast to that specified type...
Definition TypeBase.h:2985
bool isFloatingType() const
Definition Type.cpp:2393
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9277
bool isRecordType() const
Definition TypeBase.h:8811
bool isSizelessVectorType() const
Returns true for all scalable vector types.
Definition Type.cpp:2667
Base class for declarations which introduce a typedef-name.
Definition Decl.h:3593
UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated) expression operand.
Definition Expr.h:2631
QualType getArgumentType() const
Definition Expr.h:2674
QualType getTypeOfArgument() const
Gets the argument type, or the type of the argument expression, whichever is appropriate.
Definition Expr.h:2700
UnaryExprOrTypeTrait getKind() const
Definition Expr.h:2663
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2250
Expr * getSubExpr() const
Definition Expr.h:2291
Opcode getOpcode() const
Definition Expr.h:2286
bool canOverflow() const
Returns true if the unary operator can cause an overflow.
Definition Expr.h:2304
Represents C++ using-directive.
Definition DeclCXX.h:3114
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:712
QualType getType() const
Definition Decl.h:723
bool isWeak() const
Determine whether this symbol is weakly-imported, or declared with the weak or weak-ref attr.
Definition Decl.cpp:5578
QualType getType() const
Definition Value.cpp:238
Represents a variable declaration or definition.
Definition Decl.h:932
bool isConstexpr() const
Whether this variable is (C++11) constexpr.
Definition Decl.h:1591
bool isInitCapture() const
Whether this variable is the implicit variable for a lambda init-capture.
Definition Decl.h:1600
bool isStaticDataMember() const
Determines whether this is a static data member.
Definition Decl.h:1304
bool hasGlobalStorage() const
Returns true for all variables that do not have local storage.
Definition Decl.h:1247
bool hasConstantInitialization() const
Determine whether this variable has constant initialization.
Definition Decl.cpp:2630
bool isStaticLocal() const
Returns true if a variable with function scope is a static local variable.
Definition Decl.h:1214
const Expr * getInit() const
Definition Decl.h:1389
const APValue * evaluateValue() const
Attempt to evaluate the value of the initializer attached to this declaration, and produce notes expl...
Definition Decl.cpp:2554
bool isLocalVarDecl() const
Returns true for local variable declarations other than parameters.
Definition Decl.h:1274
const Expr * getAnyInitializer() const
Get the initializer for this variable, no matter which declaration it is attached to.
Definition Decl.h:1379
Represents a GCC generic vector type.
Definition TypeBase.h:4239
unsigned getNumElements() const
Definition TypeBase.h:4254
QualType getElementType() const
Definition TypeBase.h:4253
WhileStmt - This represents a 'while' stmt.
Definition Stmt.h:2707
Expr * getCond()
Definition Stmt.h:2759
DeclStmt * getConditionVariableDeclStmt()
If this WhileStmt has a condition variable, return the faux DeclStmt associated with the creation of ...
Definition Stmt.h:2795
VarDecl * getConditionVariable()
Retrieve the variable declared in this "while" statement, if any.
Definition Stmt.cpp:1247
Stmt * getBody()
Definition Stmt.h:2771
A memory block, either on the stack or in the heap.
Definition InterpBlock.h:44
void invokeDtor()
Invokes the Destructor.
Compilation context for expressions.
Definition Compiler.h:112
llvm::SmallVector< InitLink > InitStack
Definition Compiler.h:495
bool VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E)
bool VisitCXXDeleteExpr(const CXXDeleteExpr *E)
bool VisitOffsetOfExpr(const OffsetOfExpr *E)
bool visitContinueStmt(const ContinueStmt *S)
bool VisitCharacterLiteral(const CharacterLiteral *E)
bool visitArrayElemInit(unsigned ElemIndex, const Expr *Init, OptPrimType InitT)
Pointer to the array(not the element!) must be on the stack when calling this.
UnsignedOrNone allocateLocal(DeclTy &&Decl, QualType Ty=QualType(), ScopeKind=ScopeKind::Block)
Allocates a space storing a local given its type.
bool VisitCXXParenListInitExpr(const CXXParenListInitExpr *E)
bool VisitConceptSpecializationExpr(const ConceptSpecializationExpr *E)
bool visitInitializerPop(const Expr *E)
Similar, but will also pop the pointer.
bool VisitCompoundLiteralExpr(const CompoundLiteralExpr *E)
bool visitBool(const Expr *E)
Visits an expression and converts it to a boolean.
bool VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
PrimType classifyPrim(QualType Ty) const
Classifies a known primitive type.
Definition Compiler.h:288
bool VisitTypeTraitExpr(const TypeTraitExpr *E)
bool VisitLambdaExpr(const LambdaExpr *E)
bool VisitMemberExpr(const MemberExpr *E)
llvm::DenseMap< const OpaqueValueExpr *, unsigned > OpaqueExprs
OpaqueValueExpr to location mapping.
Definition Compiler.h:470
bool VisitBinaryOperator(const BinaryOperator *E)
bool visitAttributedStmt(const AttributedStmt *S)
bool VisitPackIndexingExpr(const PackIndexingExpr *E)
bool VisitArraySubscriptExpr(const ArraySubscriptExpr *E)
bool VisitCallExpr(const CallExpr *E)
std::optional< uint64_t > ArrayIndex
Current argument index. Needed to emit ArrayInitIndexExpr.
Definition Compiler.h:476
bool VisitPseudoObjectExpr(const PseudoObjectExpr *E)
bool VisitCXXReinterpretCastExpr(const CXXReinterpretCastExpr *E)
const Function * getFunction(const FunctionDecl *FD)
Returns a function for the given FunctionDecl.
bool VisitFixedPointBinOp(const BinaryOperator *E)
bool VisitCastExpr(const CastExpr *E)
Definition Compiler.cpp:201
bool VisitObjCEncodeExpr(const ObjCEncodeExpr *E)
bool VisitFixedPointUnaryOperator(const UnaryOperator *E)
unsigned allocateLocalPrimitive(DeclTy &&Decl, PrimType Ty, bool IsConst, bool IsVolatile=false, ScopeKind SC=ScopeKind::Block)
Creates a local primitive value.
bool VisitComplexUnaryOperator(const UnaryOperator *E)
llvm::DenseMap< const SwitchCase *, LabelTy > CaseMap
Definition Compiler.h:118
bool VisitBlockExpr(const BlockExpr *E)
bool VisitCXXScalarValueInitExpr(const CXXScalarValueInitExpr *E)
bool VisitLogicalBinOp(const BinaryOperator *E)
bool visitCompoundStmt(const CompoundStmt *S)
Context & Ctx
Current compilation context.
Definition Compiler.h:135
bool visitDeclRef(const ValueDecl *D, const Expr *E)
Visit the given decl as if we have a reference to it.
bool visitBreakStmt(const BreakStmt *S)
bool visitExpr(const Expr *E, bool DestroyToplevelScope) override
bool visitForStmt(const ForStmt *S)
bool VisitDeclRefExpr(const DeclRefExpr *E)
bool VisitOpaqueValueExpr(const OpaqueValueExpr *E)
bool VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E)
bool visitAPValue(const APValue &Val, PrimType ValType, SourceInfo Info)
Visit an APValue.
bool VisitStmtExpr(const StmtExpr *E)
bool VisitBuiltinBitCastExpr(const BuiltinBitCastExpr *E)
Definition Compiler.cpp:983
bool VisitFixedPointLiteral(const FixedPointLiteral *E)
const FunctionDecl * CompilingFunction
Definition Compiler.h:506
bool VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E)
VarCreationState visitVarDecl(const VarDecl *VD, const Expr *Init, bool Toplevel=false)
Creates and initializes a variable from the given decl.
VariableScope< Emitter > * VarScope
Current scope.
Definition Compiler.h:473
bool visitDeclAndReturn(const VarDecl *VD, const Expr *Init, bool ConstantContext) override
Toplevel visitDeclAndReturn().
bool VisitCXXNewExpr(const CXXNewExpr *E)
const ValueDecl * InitializingDecl
Definition Compiler.h:493
bool VisitCompoundAssignOperator(const CompoundAssignOperator *E)
bool visit(const Expr *E) override
Evaluates an expression and places the result on the stack.
bool delegate(const Expr *E)
Just pass evaluation on to E.
bool visitLValueExpr(const Expr *E, bool DestroyToplevelScope) override
bool discard(const Expr *E)
Evaluates an expression for side effects and discards the result.
bool VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
CaseMap CaseLabels
Switch case mapping.
Definition Compiler.h:502
bool visitAPValueInitializer(const APValue &Val, SourceInfo Info, QualType T)
Record * getRecord(QualType Ty)
Returns a record from a record or pointer type.
const RecordType * getRecordTy(QualType Ty)
Returns a record type from a record or pointer type.
bool VisitCXXStdInitializerListExpr(const CXXStdInitializerListExpr *E)
bool visitInitList(ArrayRef< const Expr * > Inits, const Expr *ArrayFiller, const Expr *E)
bool VisitSizeOfPackExpr(const SizeOfPackExpr *E)
bool VisitPredefinedExpr(const PredefinedExpr *E)
bool VisitSourceLocExpr(const SourceLocExpr *E)
bool visitDeclStmt(const DeclStmt *DS, bool EvaluateConditionDecl=false)
bool emitCleanup()
Emits scope cleanup instructions.
bool VisitExtVectorElementExpr(const ExtVectorElementExpr *E)
bool VisitObjCStringLiteral(const ObjCStringLiteral *E)
bool VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E)
bool visitInitializer(const Expr *E)
Compiles an initializer.
bool visitDtorCall(const VarDecl *VD, const APValue &Value) override
const Expr * SourceLocDefaultExpr
DefaultInit- or DefaultArgExpr, needed for SourceLocExpr.
Definition Compiler.h:479
bool VisitObjCArrayLiteral(const ObjCArrayLiteral *E)
UnsignedOrNone OptLabelTy
Definition Compiler.h:117
bool VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *E)
bool VisitPointerArithBinOp(const BinaryOperator *E)
Perform addition/subtraction of a pointer and an integer or subtraction of two pointers.
bool visitCallArgs(ArrayRef< const Expr * > Args, const FunctionDecl *FuncDecl, bool Activate, bool IsOperatorCall)
bool VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E)
bool visitDefaultStmt(const DefaultStmt *S)
bool VisitObjCDictionaryLiteral(const ObjCDictionaryLiteral *E)
bool visitWithSubstitutions(const FunctionDecl *Callee, ArrayRef< const Expr * > Args, const Expr *This, const Expr *Condition) override
Evaluate the Condition as if it was in the body of Callee.
typename Emitter::LabelTy LabelTy
Definition Compiler.h:115
VarCreationState visitDecl(const VarDecl *VD)
bool VisitCXXDynamicCastExpr(const CXXDynamicCastExpr *E)
bool visitStmt(const Stmt *S)
bool VisitExpressionTraitExpr(const ExpressionTraitExpr *E)
bool VisitVectorUnaryOperator(const UnaryOperator *E)
bool VisitCXXConstructExpr(const CXXConstructExpr *E)
bool VisitCXXNullPtrLiteralExpr(const CXXNullPtrLiteralExpr *E)
bool VisitObjCBoxedExpr(const ObjCBoxedExpr *E)
bool VisitDesignatedInitUpdateExpr(const DesignatedInitUpdateExpr *E)
bool VisitCXXInheritedCtorInitExpr(const CXXInheritedCtorInitExpr *E)
bool VisitRecoveryExpr(const RecoveryExpr *E)
bool VisitRequiresExpr(const RequiresExpr *E)
bool Initializing
Flag inidicating if we're initializing an already created variable.
Definition Compiler.h:492
bool visitReturnStmt(const ReturnStmt *RS)
bool VisitCXXThrowExpr(const CXXThrowExpr *E)
bool VisitSubstNonTypeTemplateParmExpr(const SubstNonTypeTemplateParmExpr *E)
bool VisitChooseExpr(const ChooseExpr *E)
bool visitFunc(const FunctionDecl *F) override
bool visitCXXForRangeStmt(const CXXForRangeStmt *S)
bool visitCaseStmt(const CaseStmt *S)
bool VisitComplexBinOp(const BinaryOperator *E)
llvm::DenseMap< const ValueDecl *, Scope::Local > Locals
Variable to storage mapping.
Definition Compiler.h:467
bool VisitAbstractConditionalOperator(const AbstractConditionalOperator *E)
bool VisitCXXTypeidExpr(const CXXTypeidExpr *E)
UnsignedOrNone allocateTemporary(const Expr *E)
bool VisitBuiltinCallExpr(const CallExpr *E, unsigned BuiltinID)
bool VisitImplicitValueInitExpr(const ImplicitValueInitExpr *E)
bool VisitCXXRewrittenBinaryOperator(const CXXRewrittenBinaryOperator *E)
OptPrimType ReturnType
Type of the expression returned by the function.
Definition Compiler.h:499
bool VisitUnaryOperator(const UnaryOperator *E)
bool VisitFloatCompoundAssignOperator(const CompoundAssignOperator *E)
OptPrimType classify(const Expr *E) const
Definition Compiler.h:282
llvm::SmallVector< LabelInfo > LabelInfoStack
Stack of label information for loops and switch statements.
Definition Compiler.h:504
bool VisitGenericSelectionExpr(const GenericSelectionExpr *E)
bool visitDoStmt(const DoStmt *S)
bool VisitIntegerLiteral(const IntegerLiteral *E)
Definition Compiler.cpp:988
bool VisitInitListExpr(const InitListExpr *E)
bool VisitVectorBinOp(const BinaryOperator *E)
bool VisitStringLiteral(const StringLiteral *E)
bool VisitParenExpr(const ParenExpr *E)
bool VisitCXXNoexceptExpr(const CXXNoexceptExpr *E)
bool VisitShuffleVectorExpr(const ShuffleVectorExpr *E)
bool VisitPointerCompoundAssignOperator(const CompoundAssignOperator *E)
bool DiscardResult
Flag indicating if return value is to be discarded.
Definition Compiler.h:482
bool VisitEmbedExpr(const EmbedExpr *E)
bool VisitConvertVectorExpr(const ConvertVectorExpr *E)
bool VisitCXXThisExpr(const CXXThisExpr *E)
bool VisitConstantExpr(const ConstantExpr *E)
bool VisitUnaryExprOrTypeTraitExpr(const UnaryExprOrTypeTraitExpr *E)
bool visitSwitchStmt(const SwitchStmt *S)
bool VisitCXXUuidofExpr(const CXXUuidofExpr *E)
bool VisitExprWithCleanups(const ExprWithCleanups *E)
bool visitAsLValue(const Expr *E)
bool visitWhileStmt(const WhileStmt *S)
bool visitIfStmt(const IfStmt *IS)
bool VisitAddrLabelExpr(const AddrLabelExpr *E)
bool canClassify(const Expr *E) const
Definition Compiler.h:284
bool VisitFloatingLiteral(const FloatingLiteral *E)
Definition Compiler.cpp:996
Program & P
Program to link to.
Definition Compiler.h:137
bool VisitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *E)
bool VisitGNUNullExpr(const GNUNullExpr *E)
bool VisitImaginaryLiteral(const ImaginaryLiteral *E)
bool VisitSYCLUniqueStableNameExpr(const SYCLUniqueStableNameExpr *E)
bool visitCXXTryStmt(const CXXTryStmt *S)
static bool isUnevaluatedBuiltin(unsigned ID)
Unevaluated builtins don't get their arguments put on the stack automatically.
Definition Context.cpp:779
static bool shouldBeGloballyIndexed(const ValueDecl *VD)
Returns whether we should create a global variable for the given ValueDecl.
Definition Context.h:165
Scope used to handle temporaries in toplevel variable declarations.
Definition Compiler.cpp:41
DeclScope(Compiler< Emitter > *Ctx, const ValueDecl *VD)
Definition Compiler.cpp:43
Wrapper around fixed point types.
Definition FixedPoint.h:23
static FixedPoint zero(llvm::FixedPointSemantics Sem)
Definition FixedPoint.h:36
If a Floating is constructed from Memory, it DOES NOT OWN THAT MEMORY.
Definition Floating.h:35
bool singleWord() const
Definition Floating.h:107
Bytecode function.
Definition Function.h:99
bool hasThisPointer() const
Definition Function.h:226
bool hasRVO() const
Checks if the first argument is a RVO pointer.
Definition Function.h:156
When generating code for e.g.
Definition Compiler.cpp:176
LocOverrideScope(Compiler< Emitter > *Ctx, SourceInfo NewValue, bool Enabled=true)
Definition Compiler.cpp:178
Generic scope for local variables.
Definition Compiler.h:571
bool destroyLocals(const Expr *E=nullptr) override
Explicit destruction of local variables.
Definition Compiler.h:584
LocalScope(Compiler< Emitter > *Ctx, ScopeKind Kind=ScopeKind::Block)
Definition Compiler.h:573
Sets the context for break/continue statements.
Definition Compiler.cpp:115
typename Compiler< Emitter >::LabelTy LabelTy
Definition Compiler.cpp:117
typename Compiler< Emitter >::OptLabelTy OptLabelTy
Definition Compiler.cpp:118
typename Compiler< Emitter >::LabelInfo LabelInfo
Definition Compiler.cpp:119
LoopScope(Compiler< Emitter > *Ctx, const Stmt *Name, LabelTy BreakLabel, LabelTy ContinueLabel)
Definition Compiler.cpp:121
PrimType value_or(PrimType PT) const
Definition PrimType.h:88
Scope used to handle initialization methods.
Definition Compiler.cpp:61
OptionScope(Compiler< Emitter > *Ctx, bool NewDiscardResult, bool NewInitializing, bool NewToLValue)
Root constructor, compiling or discarding primitives.
Definition Compiler.cpp:64
Context to manage declaration lifetimes.
Definition Program.h:148
Structure/Class descriptor.
Definition Record.h:25
bool isUnion() const
Checks if the record is a union.
Definition Record.h:69
const Field * getField(unsigned I) const
Definition Record.h:95
const Base * getBase(unsigned I) const
Definition Record.h:107
bool hasTrivialDtor() const
Returns true for anonymous unions and records with no destructor or for those with a trivial destruct...
Definition Record.cpp:45
Describes a scope block.
Definition Function.h:36
Describes the statement/declaration an opcode was generated from.
Definition Source.h:74
const Expr * asExpr() const
Definition Source.cpp:35
typename Compiler< Emitter >::LabelTy LabelTy
Definition Compiler.cpp:143
typename Compiler< Emitter >::OptLabelTy OptLabelTy
Definition Compiler.cpp:144
typename Compiler< Emitter >::LabelInfo LabelInfo
Definition Compiler.cpp:146
typename Compiler< Emitter >::CaseMap CaseMap
Definition Compiler.cpp:145
SwitchScope(Compiler< Emitter > *Ctx, const Stmt *Name, CaseMap &&CaseLabels, LabelTy BreakLabel, OptLabelTy DefaultLabel)
Definition Compiler.cpp:148
Scope chain managing the variable lifetimes.
Definition Compiler.h:513
Compiler< Emitter > * Ctx
Compiler instance.
Definition Compiler.h:564
virtual void addLocal(Scope::Local Local)
Definition Compiler.h:524
VariableScope * getParent() const
Definition Compiler.h:554
bool Sub(InterpState &S, CodePtr OpPC)
Definition Interp.h:425
bool LT(InterpState &S, CodePtr OpPC)
Definition Interp.h:1507
static llvm::RoundingMode getRoundingMode(FPOptions FPO)
llvm::PointerUnion< const Decl *, const Expr * > DeclTy
Definition Descriptor.h:29
constexpr bool isSignedType(PrimType T)
Definition PrimType.h:59
bool Div(InterpState &S, CodePtr OpPC)
1) Pops the RHS from the stack.
Definition Interp.h:770
static bool Activate(InterpState &S, CodePtr OpPC)
Definition Interp.h:2265
constexpr bool isPtrType(PrimType T)
Definition PrimType.h:55
constexpr size_t align(size_t Size)
Aligns a size to the pointer alignment.
Definition PrimType.h:201
bool This(InterpState &S, CodePtr OpPC)
Definition Interp.h:3172
bool InitScope(InterpState &S, CodePtr OpPC, uint32_t I)
Definition Interp.h:2773
constexpr bool isIntegerOrBoolType(PrimType T)
Definition PrimType.h:52
llvm::APFloat APFloat
Definition Floating.h:27
static void discard(InterpStack &Stk, PrimType T)
llvm::APInt APInt
Definition FixedPoint.h:19
bool LE(InterpState &S, CodePtr OpPC)
Definition Interp.h:1514
PrimType
Enumeration of the primitive types of the VM.
Definition PrimType.h:34
static std::optional< bool > getBoolValue(const Expr *E)
Definition Compiler.cpp:30
bool Init(InterpState &S, CodePtr OpPC)
Definition Interp.h:2382
bool Mul(InterpState &S, CodePtr OpPC)
Definition Interp.h:479
size_t primSize(PrimType Type)
Returns the size of a primitive type in bytes.
Definition PrimType.cpp:24
bool Inc(InterpState &S, CodePtr OpPC, bool CanOverflow)
1) Pops a pointer from the stack 2) Load the value from the pointer 3) Writes the value increased by ...
Definition Interp.h:964
bool Add(InterpState &S, CodePtr OpPC)
Definition Interp.h:396
llvm::BitVector collectNonNullArgs(const FunctionDecl *F, ArrayRef< const Expr * > Args)
llvm::APSInt APSInt
Definition FixedPoint.h:20
The JSON file list parser is used to communicate input to InstallAPI.
bool isa(CodeGen::Address addr)
Definition Address.h:330
bool hasSpecificAttr(const Container &container)
@ Success
Annotation was successful.
Definition Parser.h:65
DynamicRecursiveASTVisitorBase< true > ConstDynamicRecursiveASTVisitor
Expr * Cond
};
UnaryExprOrTypeTrait
Names for the "expression or type" traits.
Definition TypeTraits.h:51
@ SD_Static
Static storage duration.
Definition Specifiers.h:344
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:341
@ Result
The result type of a method or function.
Definition TypeBase.h:905
OptionalUnsigned< unsigned > UnsignedOrNone
U cast(CodeGen::Address addr)
Definition Address.h:327
int const char * function
Definition c++config.h:31
__packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 __packed_splat2 __packed_splat4 __packed_splat2 __packed_splat8 __packed_splat4 uint32_t
#define true
Definition stdbool.h:25
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:652
A quantity in bits.
Describes a memory block created by an allocation site.
Definition Descriptor.h:123
unsigned getNumElems() const
Returns the number of elements stored in the block.
Definition Descriptor.h:260
bool isPrimitive() const
Checks if the descriptor is of a primitive.
Definition Descriptor.h:274
QualType getElemQualType() const
bool hasTrivialDtor() const
Whether variables of this descriptor need their destructor called or not.
bool isCompositeArray() const
Checks if the descriptor is of an array of composites.
Definition Descriptor.h:267
QualType getType() const
const Descriptor *const ElemDesc
Descriptor of the array element.
Definition Descriptor.h:156
static constexpr MetadataSize InlineDescMD
Definition Descriptor.h:145
bool isPrimitiveArray() const
Checks if the descriptor is of an array of primitives.
Definition Descriptor.h:265
PrimType getPrimType() const
Definition Descriptor.h:242
bool isRecord() const
Checks if the descriptor is of a record.
Definition Descriptor.h:279
const Record *const ElemRecord
Pointer to the record, if block contains records.
Definition Descriptor.h:154
bool isArray() const
Checks if the descriptor is of an array.
Definition Descriptor.h:277
Descriptor used for global variables.
Definition Descriptor.h:50
Information about a local's storage.
Definition Function.h:39
State encapsulating if a the variable creation has been successful, unsuccessful, or no variable has ...
Definition Compiler.h:97
static VarCreationState NotCreated()
Definition Compiler.h:101