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