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