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