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 "Floating.h" 13 #include "Function.h" 14 #include "InterpShared.h" 15 #include "PrimType.h" 16 #include "Program.h" 17 #include "clang/AST/Attr.h" 18 19 using namespace clang; 20 using namespace clang::interp; 21 22 using APSInt = llvm::APSInt; 23 24 namespace clang { 25 namespace interp { 26 27 /// Scope used to handle temporaries in toplevel variable declarations. 28 template <class Emitter> class DeclScope final : public LocalScope<Emitter> { 29 public: 30 DeclScope(Compiler<Emitter> *Ctx, const ValueDecl *VD) 31 : LocalScope<Emitter>(Ctx, VD), Scope(Ctx->P, VD), 32 OldInitializingDecl(Ctx->InitializingDecl) { 33 Ctx->InitializingDecl = VD; 34 Ctx->InitStack.push_back(InitLink::Decl(VD)); 35 } 36 37 void addExtended(const Scope::Local &Local) override { 38 return this->addLocal(Local); 39 } 40 41 ~DeclScope() { 42 this->Ctx->InitializingDecl = OldInitializingDecl; 43 this->Ctx->InitStack.pop_back(); 44 } 45 46 private: 47 Program::DeclScope Scope; 48 const ValueDecl *OldInitializingDecl; 49 }; 50 51 /// Scope used to handle initialization methods. 52 template <class Emitter> class OptionScope final { 53 public: 54 /// Root constructor, compiling or discarding primitives. 55 OptionScope(Compiler<Emitter> *Ctx, bool NewDiscardResult, 56 bool NewInitializing) 57 : Ctx(Ctx), OldDiscardResult(Ctx->DiscardResult), 58 OldInitializing(Ctx->Initializing) { 59 Ctx->DiscardResult = NewDiscardResult; 60 Ctx->Initializing = NewInitializing; 61 } 62 63 ~OptionScope() { 64 Ctx->DiscardResult = OldDiscardResult; 65 Ctx->Initializing = OldInitializing; 66 } 67 68 private: 69 /// Parent context. 70 Compiler<Emitter> *Ctx; 71 /// Old discard flag to restore. 72 bool OldDiscardResult; 73 bool OldInitializing; 74 }; 75 76 template <class Emitter> 77 bool InitLink::emit(Compiler<Emitter> *Ctx, const Expr *E) const { 78 switch (Kind) { 79 case K_This: 80 return Ctx->emitThis(E); 81 case K_Field: 82 // We're assuming there's a base pointer on the stack already. 83 return Ctx->emitGetPtrFieldPop(Offset, E); 84 case K_Temp: 85 return Ctx->emitGetPtrLocal(Offset, E); 86 case K_Decl: 87 return Ctx->visitDeclRef(D, E); 88 case K_Elem: 89 if (!Ctx->emitConstUint32(Offset, E)) 90 return false; 91 return Ctx->emitArrayElemPtrPopUint32(E); 92 default: 93 llvm_unreachable("Unhandled InitLink kind"); 94 } 95 return true; 96 } 97 98 /// Scope managing label targets. 99 template <class Emitter> class LabelScope { 100 public: 101 virtual ~LabelScope() {} 102 103 protected: 104 LabelScope(Compiler<Emitter> *Ctx) : Ctx(Ctx) {} 105 /// Compiler instance. 106 Compiler<Emitter> *Ctx; 107 }; 108 109 /// Sets the context for break/continue statements. 110 template <class Emitter> class LoopScope final : public LabelScope<Emitter> { 111 public: 112 using LabelTy = typename Compiler<Emitter>::LabelTy; 113 using OptLabelTy = typename Compiler<Emitter>::OptLabelTy; 114 115 LoopScope(Compiler<Emitter> *Ctx, LabelTy BreakLabel, LabelTy ContinueLabel) 116 : LabelScope<Emitter>(Ctx), OldBreakLabel(Ctx->BreakLabel), 117 OldContinueLabel(Ctx->ContinueLabel) { 118 this->Ctx->BreakLabel = BreakLabel; 119 this->Ctx->ContinueLabel = ContinueLabel; 120 } 121 122 ~LoopScope() { 123 this->Ctx->BreakLabel = OldBreakLabel; 124 this->Ctx->ContinueLabel = OldContinueLabel; 125 } 126 127 private: 128 OptLabelTy OldBreakLabel; 129 OptLabelTy OldContinueLabel; 130 }; 131 132 // Sets the context for a switch scope, mapping labels. 133 template <class Emitter> class SwitchScope final : public LabelScope<Emitter> { 134 public: 135 using LabelTy = typename Compiler<Emitter>::LabelTy; 136 using OptLabelTy = typename Compiler<Emitter>::OptLabelTy; 137 using CaseMap = typename Compiler<Emitter>::CaseMap; 138 139 SwitchScope(Compiler<Emitter> *Ctx, CaseMap &&CaseLabels, LabelTy BreakLabel, 140 OptLabelTy DefaultLabel) 141 : LabelScope<Emitter>(Ctx), OldBreakLabel(Ctx->BreakLabel), 142 OldDefaultLabel(this->Ctx->DefaultLabel), 143 OldCaseLabels(std::move(this->Ctx->CaseLabels)) { 144 this->Ctx->BreakLabel = BreakLabel; 145 this->Ctx->DefaultLabel = DefaultLabel; 146 this->Ctx->CaseLabels = std::move(CaseLabels); 147 } 148 149 ~SwitchScope() { 150 this->Ctx->BreakLabel = OldBreakLabel; 151 this->Ctx->DefaultLabel = OldDefaultLabel; 152 this->Ctx->CaseLabels = std::move(OldCaseLabels); 153 } 154 155 private: 156 OptLabelTy OldBreakLabel; 157 OptLabelTy OldDefaultLabel; 158 CaseMap OldCaseLabels; 159 }; 160 161 template <class Emitter> class StmtExprScope final { 162 public: 163 StmtExprScope(Compiler<Emitter> *Ctx) : Ctx(Ctx), OldFlag(Ctx->InStmtExpr) { 164 Ctx->InStmtExpr = true; 165 } 166 167 ~StmtExprScope() { Ctx->InStmtExpr = OldFlag; } 168 169 private: 170 Compiler<Emitter> *Ctx; 171 bool OldFlag; 172 }; 173 174 } // namespace interp 175 } // namespace clang 176 177 template <class Emitter> 178 bool Compiler<Emitter>::VisitCastExpr(const CastExpr *CE) { 179 const Expr *SubExpr = CE->getSubExpr(); 180 switch (CE->getCastKind()) { 181 182 case CK_LValueToRValue: { 183 if (DiscardResult) 184 return this->discard(SubExpr); 185 186 std::optional<PrimType> SubExprT = classify(SubExpr->getType()); 187 // Prepare storage for the result. 188 if (!Initializing && !SubExprT) { 189 std::optional<unsigned> LocalIndex = allocateLocal(SubExpr); 190 if (!LocalIndex) 191 return false; 192 if (!this->emitGetPtrLocal(*LocalIndex, CE)) 193 return false; 194 } 195 196 if (!this->visit(SubExpr)) 197 return false; 198 199 if (SubExprT) 200 return this->emitLoadPop(*SubExprT, CE); 201 202 // If the subexpr type is not primitive, we need to perform a copy here. 203 // This happens for example in C when dereferencing a pointer of struct 204 // type. 205 return this->emitMemcpy(CE); 206 } 207 208 case CK_DerivedToBaseMemberPointer: { 209 assert(classifyPrim(CE->getType()) == PT_MemberPtr); 210 assert(classifyPrim(SubExpr->getType()) == PT_MemberPtr); 211 const auto *FromMP = SubExpr->getType()->getAs<MemberPointerType>(); 212 const auto *ToMP = CE->getType()->getAs<MemberPointerType>(); 213 214 unsigned DerivedOffset = collectBaseOffset(QualType(ToMP->getClass(), 0), 215 QualType(FromMP->getClass(), 0)); 216 217 if (!this->delegate(SubExpr)) 218 return false; 219 220 return this->emitGetMemberPtrBasePop(DerivedOffset, CE); 221 } 222 223 case CK_BaseToDerivedMemberPointer: { 224 assert(classifyPrim(CE) == PT_MemberPtr); 225 assert(classifyPrim(SubExpr) == PT_MemberPtr); 226 const auto *FromMP = SubExpr->getType()->getAs<MemberPointerType>(); 227 const auto *ToMP = CE->getType()->getAs<MemberPointerType>(); 228 229 unsigned DerivedOffset = collectBaseOffset(QualType(FromMP->getClass(), 0), 230 QualType(ToMP->getClass(), 0)); 231 232 if (!this->delegate(SubExpr)) 233 return false; 234 return this->emitGetMemberPtrBasePop(-DerivedOffset, CE); 235 } 236 237 case CK_UncheckedDerivedToBase: 238 case CK_DerivedToBase: { 239 if (!this->delegate(SubExpr)) 240 return false; 241 242 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * { 243 if (const auto *PT = dyn_cast<PointerType>(Ty)) 244 return PT->getPointeeType()->getAsCXXRecordDecl(); 245 return Ty->getAsCXXRecordDecl(); 246 }; 247 248 // FIXME: We can express a series of non-virtual casts as a single 249 // GetPtrBasePop op. 250 QualType CurType = SubExpr->getType(); 251 for (const CXXBaseSpecifier *B : CE->path()) { 252 if (B->isVirtual()) { 253 if (!this->emitGetPtrVirtBasePop(extractRecordDecl(B->getType()), CE)) 254 return false; 255 CurType = B->getType(); 256 } else { 257 unsigned DerivedOffset = collectBaseOffset(B->getType(), CurType); 258 if (!this->emitGetPtrBasePop(DerivedOffset, CE)) 259 return false; 260 CurType = B->getType(); 261 } 262 } 263 264 return true; 265 } 266 267 case CK_BaseToDerived: { 268 if (!this->delegate(SubExpr)) 269 return false; 270 271 unsigned DerivedOffset = 272 collectBaseOffset(SubExpr->getType(), CE->getType()); 273 274 return this->emitGetPtrDerivedPop(DerivedOffset, CE); 275 } 276 277 case CK_FloatingCast: { 278 // HLSL uses CK_FloatingCast to cast between vectors. 279 if (!SubExpr->getType()->isFloatingType() || 280 !CE->getType()->isFloatingType()) 281 return false; 282 if (DiscardResult) 283 return this->discard(SubExpr); 284 if (!this->visit(SubExpr)) 285 return false; 286 const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType()); 287 return this->emitCastFP(TargetSemantics, getRoundingMode(CE), CE); 288 } 289 290 case CK_IntegralToFloating: { 291 if (DiscardResult) 292 return this->discard(SubExpr); 293 std::optional<PrimType> FromT = classify(SubExpr->getType()); 294 if (!FromT) 295 return false; 296 297 if (!this->visit(SubExpr)) 298 return false; 299 300 const auto *TargetSemantics = &Ctx.getFloatSemantics(CE->getType()); 301 return this->emitCastIntegralFloating(*FromT, TargetSemantics, 302 getFPOptions(CE), CE); 303 } 304 305 case CK_FloatingToBoolean: 306 case CK_FloatingToIntegral: { 307 if (DiscardResult) 308 return this->discard(SubExpr); 309 310 std::optional<PrimType> ToT = classify(CE->getType()); 311 312 if (!ToT) 313 return false; 314 315 if (!this->visit(SubExpr)) 316 return false; 317 318 if (ToT == PT_IntAP) 319 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(CE->getType()), 320 getFPOptions(CE), CE); 321 if (ToT == PT_IntAPS) 322 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(CE->getType()), 323 getFPOptions(CE), CE); 324 325 return this->emitCastFloatingIntegral(*ToT, getFPOptions(CE), CE); 326 } 327 328 case CK_NullToPointer: 329 case CK_NullToMemberPointer: { 330 if (!this->discard(SubExpr)) 331 return false; 332 if (DiscardResult) 333 return true; 334 335 const Descriptor *Desc = nullptr; 336 const QualType PointeeType = CE->getType()->getPointeeType(); 337 if (!PointeeType.isNull()) { 338 if (std::optional<PrimType> T = classify(PointeeType)) 339 Desc = P.createDescriptor(SubExpr, *T); 340 else 341 Desc = P.createDescriptor(SubExpr, PointeeType.getTypePtr(), 342 std::nullopt, true, false, 343 /*IsMutable=*/false, nullptr); 344 } 345 return this->emitNull(classifyPrim(CE->getType()), Desc, CE); 346 } 347 348 case CK_PointerToIntegral: { 349 if (DiscardResult) 350 return this->discard(SubExpr); 351 352 if (!this->visit(SubExpr)) 353 return false; 354 355 // If SubExpr doesn't result in a pointer, make it one. 356 if (PrimType FromT = classifyPrim(SubExpr->getType()); FromT != PT_Ptr) { 357 assert(isPtrType(FromT)); 358 if (!this->emitDecayPtr(FromT, PT_Ptr, CE)) 359 return false; 360 } 361 362 PrimType T = classifyPrim(CE->getType()); 363 if (T == PT_IntAP) 364 return this->emitCastPointerIntegralAP(Ctx.getBitWidth(CE->getType()), 365 CE); 366 if (T == PT_IntAPS) 367 return this->emitCastPointerIntegralAPS(Ctx.getBitWidth(CE->getType()), 368 CE); 369 return this->emitCastPointerIntegral(T, CE); 370 } 371 372 case CK_ArrayToPointerDecay: { 373 if (!this->visit(SubExpr)) 374 return false; 375 if (!this->emitArrayDecay(CE)) 376 return false; 377 if (DiscardResult) 378 return this->emitPopPtr(CE); 379 return true; 380 } 381 382 case CK_IntegralToPointer: { 383 QualType IntType = SubExpr->getType(); 384 assert(IntType->isIntegralOrEnumerationType()); 385 if (!this->visit(SubExpr)) 386 return false; 387 // FIXME: I think the discard is wrong since the int->ptr cast might cause a 388 // diagnostic. 389 PrimType T = classifyPrim(IntType); 390 if (DiscardResult) 391 return this->emitPop(T, CE); 392 393 QualType PtrType = CE->getType(); 394 const Descriptor *Desc; 395 if (std::optional<PrimType> T = classify(PtrType->getPointeeType())) 396 Desc = P.createDescriptor(SubExpr, *T); 397 else if (PtrType->getPointeeType()->isVoidType()) 398 Desc = nullptr; 399 else 400 Desc = P.createDescriptor(CE, PtrType->getPointeeType().getTypePtr(), 401 Descriptor::InlineDescMD, true, false, 402 /*IsMutable=*/false, nullptr); 403 404 if (!this->emitGetIntPtr(T, Desc, CE)) 405 return false; 406 407 PrimType DestPtrT = classifyPrim(PtrType); 408 if (DestPtrT == PT_Ptr) 409 return true; 410 411 // In case we're converting the integer to a non-Pointer. 412 return this->emitDecayPtr(PT_Ptr, DestPtrT, CE); 413 } 414 415 case CK_AtomicToNonAtomic: 416 case CK_ConstructorConversion: 417 case CK_FunctionToPointerDecay: 418 case CK_NonAtomicToAtomic: 419 case CK_NoOp: 420 case CK_UserDefinedConversion: 421 case CK_AddressSpaceConversion: 422 return this->delegate(SubExpr); 423 424 case CK_BitCast: { 425 // Reject bitcasts to atomic types. 426 if (CE->getType()->isAtomicType()) { 427 if (!this->discard(SubExpr)) 428 return false; 429 return this->emitInvalidCast(CastKind::Reinterpret, /*Fatal=*/true, CE); 430 } 431 432 if (DiscardResult) 433 return this->discard(SubExpr); 434 435 QualType SubExprTy = SubExpr->getType(); 436 std::optional<PrimType> FromT = classify(SubExprTy); 437 std::optional<PrimType> ToT = classify(CE->getType()); 438 if (!FromT || !ToT) 439 return false; 440 441 assert(isPtrType(*FromT)); 442 assert(isPtrType(*ToT)); 443 if (FromT == ToT) { 444 if (CE->getType()->isVoidPointerType()) 445 return this->delegate(SubExpr); 446 447 if (!this->visit(SubExpr)) 448 return false; 449 if (FromT == PT_Ptr) 450 return this->emitPtrPtrCast(SubExprTy->isVoidPointerType(), CE); 451 return true; 452 } 453 454 if (!this->visit(SubExpr)) 455 return false; 456 return this->emitDecayPtr(*FromT, *ToT, CE); 457 } 458 459 case CK_IntegralToBoolean: 460 case CK_BooleanToSignedIntegral: 461 case CK_IntegralCast: { 462 if (DiscardResult) 463 return this->discard(SubExpr); 464 std::optional<PrimType> FromT = classify(SubExpr->getType()); 465 std::optional<PrimType> ToT = classify(CE->getType()); 466 467 if (!FromT || !ToT) 468 return false; 469 470 if (!this->visit(SubExpr)) 471 return false; 472 473 // Possibly diagnose casts to enum types if the target type does not 474 // have a fixed size. 475 if (Ctx.getLangOpts().CPlusPlus && CE->getType()->isEnumeralType()) { 476 if (const auto *ET = CE->getType().getCanonicalType()->getAs<EnumType>(); 477 ET && !ET->getDecl()->isFixed()) { 478 if (!this->emitCheckEnumValue(*FromT, ET->getDecl(), CE)) 479 return false; 480 } 481 } 482 483 auto maybeNegate = [&]() -> bool { 484 if (CE->getCastKind() == CK_BooleanToSignedIntegral) 485 return this->emitNeg(*ToT, CE); 486 return true; 487 }; 488 489 if (ToT == PT_IntAP) 490 return this->emitCastAP(*FromT, Ctx.getBitWidth(CE->getType()), CE) && 491 maybeNegate(); 492 if (ToT == PT_IntAPS) 493 return this->emitCastAPS(*FromT, Ctx.getBitWidth(CE->getType()), CE) && 494 maybeNegate(); 495 496 if (FromT == ToT) 497 return true; 498 if (!this->emitCast(*FromT, *ToT, CE)) 499 return false; 500 501 return maybeNegate(); 502 } 503 504 case CK_PointerToBoolean: 505 case CK_MemberPointerToBoolean: { 506 PrimType PtrT = classifyPrim(SubExpr->getType()); 507 508 if (!this->visit(SubExpr)) 509 return false; 510 return this->emitIsNonNull(PtrT, CE); 511 } 512 513 case CK_IntegralComplexToBoolean: 514 case CK_FloatingComplexToBoolean: { 515 if (DiscardResult) 516 return this->discard(SubExpr); 517 if (!this->visit(SubExpr)) 518 return false; 519 return this->emitComplexBoolCast(SubExpr); 520 } 521 522 case CK_IntegralComplexToReal: 523 case CK_FloatingComplexToReal: 524 return this->emitComplexReal(SubExpr); 525 526 case CK_IntegralRealToComplex: 527 case CK_FloatingRealToComplex: { 528 // We're creating a complex value here, so we need to 529 // allocate storage for it. 530 if (!Initializing) { 531 unsigned LocalIndex = allocateTemporary(CE); 532 if (!this->emitGetPtrLocal(LocalIndex, CE)) 533 return false; 534 } 535 536 // Init the complex value to {SubExpr, 0}. 537 if (!this->visitArrayElemInit(0, SubExpr)) 538 return false; 539 // Zero-init the second element. 540 PrimType T = classifyPrim(SubExpr->getType()); 541 if (!this->visitZeroInitializer(T, SubExpr->getType(), SubExpr)) 542 return false; 543 return this->emitInitElem(T, 1, SubExpr); 544 } 545 546 case CK_IntegralComplexCast: 547 case CK_FloatingComplexCast: 548 case CK_IntegralComplexToFloatingComplex: 549 case CK_FloatingComplexToIntegralComplex: { 550 assert(CE->getType()->isAnyComplexType()); 551 assert(SubExpr->getType()->isAnyComplexType()); 552 if (DiscardResult) 553 return this->discard(SubExpr); 554 555 if (!Initializing) { 556 std::optional<unsigned> LocalIndex = allocateLocal(CE); 557 if (!LocalIndex) 558 return false; 559 if (!this->emitGetPtrLocal(*LocalIndex, CE)) 560 return false; 561 } 562 563 // Location for the SubExpr. 564 // Since SubExpr is of complex type, visiting it results in a pointer 565 // anyway, so we just create a temporary pointer variable. 566 unsigned SubExprOffset = allocateLocalPrimitive( 567 SubExpr, PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false); 568 if (!this->visit(SubExpr)) 569 return false; 570 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, CE)) 571 return false; 572 573 PrimType SourceElemT = classifyComplexElementType(SubExpr->getType()); 574 QualType DestElemType = 575 CE->getType()->getAs<ComplexType>()->getElementType(); 576 PrimType DestElemT = classifyPrim(DestElemType); 577 // Cast both elements individually. 578 for (unsigned I = 0; I != 2; ++I) { 579 if (!this->emitGetLocal(PT_Ptr, SubExprOffset, CE)) 580 return false; 581 if (!this->emitArrayElemPop(SourceElemT, I, CE)) 582 return false; 583 584 // Do the cast. 585 if (!this->emitPrimCast(SourceElemT, DestElemT, DestElemType, CE)) 586 return false; 587 588 // Save the value. 589 if (!this->emitInitElem(DestElemT, I, CE)) 590 return false; 591 } 592 return true; 593 } 594 595 case CK_VectorSplat: { 596 assert(!classify(CE->getType())); 597 assert(classify(SubExpr->getType())); 598 assert(CE->getType()->isVectorType()); 599 600 if (DiscardResult) 601 return this->discard(SubExpr); 602 603 if (!Initializing) { 604 std::optional<unsigned> LocalIndex = allocateLocal(CE); 605 if (!LocalIndex) 606 return false; 607 if (!this->emitGetPtrLocal(*LocalIndex, CE)) 608 return false; 609 } 610 611 const auto *VT = CE->getType()->getAs<VectorType>(); 612 PrimType ElemT = classifyPrim(SubExpr->getType()); 613 unsigned ElemOffset = allocateLocalPrimitive( 614 SubExpr, ElemT, /*IsConst=*/true, /*IsExtended=*/false); 615 616 // Prepare a local variable for the scalar value. 617 if (!this->visit(SubExpr)) 618 return false; 619 if (classifyPrim(SubExpr) == PT_Ptr && !this->emitLoadPop(ElemT, CE)) 620 return false; 621 622 if (!this->emitSetLocal(ElemT, ElemOffset, CE)) 623 return false; 624 625 for (unsigned I = 0; I != VT->getNumElements(); ++I) { 626 if (!this->emitGetLocal(ElemT, ElemOffset, CE)) 627 return false; 628 if (!this->emitInitElem(ElemT, I, CE)) 629 return false; 630 } 631 632 return true; 633 } 634 635 case CK_ToVoid: 636 return discard(SubExpr); 637 638 default: 639 return this->emitInvalid(CE); 640 } 641 llvm_unreachable("Unhandled clang::CastKind enum"); 642 } 643 644 template <class Emitter> 645 bool Compiler<Emitter>::VisitIntegerLiteral(const IntegerLiteral *LE) { 646 if (DiscardResult) 647 return true; 648 649 return this->emitConst(LE->getValue(), LE); 650 } 651 652 template <class Emitter> 653 bool Compiler<Emitter>::VisitFloatingLiteral(const FloatingLiteral *E) { 654 if (DiscardResult) 655 return true; 656 657 return this->emitConstFloat(E->getValue(), E); 658 } 659 660 template <class Emitter> 661 bool Compiler<Emitter>::VisitImaginaryLiteral(const ImaginaryLiteral *E) { 662 assert(E->getType()->isAnyComplexType()); 663 if (DiscardResult) 664 return true; 665 666 if (!Initializing) { 667 unsigned LocalIndex = allocateTemporary(E); 668 if (!this->emitGetPtrLocal(LocalIndex, E)) 669 return false; 670 } 671 672 const Expr *SubExpr = E->getSubExpr(); 673 PrimType SubExprT = classifyPrim(SubExpr->getType()); 674 675 if (!this->visitZeroInitializer(SubExprT, SubExpr->getType(), SubExpr)) 676 return false; 677 if (!this->emitInitElem(SubExprT, 0, SubExpr)) 678 return false; 679 return this->visitArrayElemInit(1, SubExpr); 680 } 681 682 template <class Emitter> 683 bool Compiler<Emitter>::VisitParenExpr(const ParenExpr *E) { 684 return this->delegate(E->getSubExpr()); 685 } 686 687 template <class Emitter> 688 bool Compiler<Emitter>::VisitBinaryOperator(const BinaryOperator *BO) { 689 // Need short-circuiting for these. 690 if (BO->getType()->isVectorType()) 691 return this->VisitVectorBinOp(BO); 692 if (BO->isLogicalOp()) 693 return this->VisitLogicalBinOp(BO); 694 695 const Expr *LHS = BO->getLHS(); 696 const Expr *RHS = BO->getRHS(); 697 698 // Handle comma operators. Just discard the LHS 699 // and delegate to RHS. 700 if (BO->isCommaOp()) { 701 if (!this->discard(LHS)) 702 return false; 703 if (RHS->getType()->isVoidType()) 704 return this->discard(RHS); 705 706 return this->delegate(RHS); 707 } 708 709 if (BO->getType()->isAnyComplexType()) 710 return this->VisitComplexBinOp(BO); 711 if ((LHS->getType()->isAnyComplexType() || 712 RHS->getType()->isAnyComplexType()) && 713 BO->isComparisonOp()) 714 return this->emitComplexComparison(LHS, RHS, BO); 715 716 if (BO->isPtrMemOp()) { 717 if (!this->visit(LHS)) 718 return false; 719 720 if (!this->visit(RHS)) 721 return false; 722 723 if (!this->emitToMemberPtr(BO)) 724 return false; 725 726 if (classifyPrim(BO) == PT_MemberPtr) 727 return true; 728 729 if (!this->emitCastMemberPtrPtr(BO)) 730 return false; 731 return DiscardResult ? this->emitPopPtr(BO) : true; 732 } 733 734 // Typecheck the args. 735 std::optional<PrimType> LT = classify(LHS); 736 std::optional<PrimType> RT = classify(RHS); 737 std::optional<PrimType> T = classify(BO->getType()); 738 739 // Special case for C++'s three-way/spaceship operator <=>, which 740 // returns a std::{strong,weak,partial}_ordering (which is a class, so doesn't 741 // have a PrimType). 742 if (!T && BO->getOpcode() == BO_Cmp) { 743 if (DiscardResult) 744 return true; 745 const ComparisonCategoryInfo *CmpInfo = 746 Ctx.getASTContext().CompCategories.lookupInfoForType(BO->getType()); 747 assert(CmpInfo); 748 749 // We need a temporary variable holding our return value. 750 if (!Initializing) { 751 std::optional<unsigned> ResultIndex = this->allocateLocal(BO); 752 if (!this->emitGetPtrLocal(*ResultIndex, BO)) 753 return false; 754 } 755 756 if (!visit(LHS) || !visit(RHS)) 757 return false; 758 759 return this->emitCMP3(*LT, CmpInfo, BO); 760 } 761 762 if (!LT || !RT || !T) 763 return false; 764 765 // Pointer arithmetic special case. 766 if (BO->getOpcode() == BO_Add || BO->getOpcode() == BO_Sub) { 767 if (isPtrType(*T) || (isPtrType(*LT) && isPtrType(*RT))) 768 return this->VisitPointerArithBinOp(BO); 769 } 770 771 // Assignmentes require us to evalute the RHS first. 772 if (BO->getOpcode() == BO_Assign) { 773 if (!visit(RHS) || !visit(LHS)) 774 return false; 775 if (!this->emitFlip(*LT, *RT, BO)) 776 return false; 777 } else { 778 if (!visit(LHS) || !visit(RHS)) 779 return false; 780 } 781 782 // For languages such as C, cast the result of one 783 // of our comparision opcodes to T (which is usually int). 784 auto MaybeCastToBool = [this, T, BO](bool Result) { 785 if (!Result) 786 return false; 787 if (DiscardResult) 788 return this->emitPop(*T, BO); 789 if (T != PT_Bool) 790 return this->emitCast(PT_Bool, *T, BO); 791 return true; 792 }; 793 794 auto Discard = [this, T, BO](bool Result) { 795 if (!Result) 796 return false; 797 return DiscardResult ? this->emitPop(*T, BO) : true; 798 }; 799 800 switch (BO->getOpcode()) { 801 case BO_EQ: 802 return MaybeCastToBool(this->emitEQ(*LT, BO)); 803 case BO_NE: 804 return MaybeCastToBool(this->emitNE(*LT, BO)); 805 case BO_LT: 806 return MaybeCastToBool(this->emitLT(*LT, BO)); 807 case BO_LE: 808 return MaybeCastToBool(this->emitLE(*LT, BO)); 809 case BO_GT: 810 return MaybeCastToBool(this->emitGT(*LT, BO)); 811 case BO_GE: 812 return MaybeCastToBool(this->emitGE(*LT, BO)); 813 case BO_Sub: 814 if (BO->getType()->isFloatingType()) 815 return Discard(this->emitSubf(getFPOptions(BO), BO)); 816 return Discard(this->emitSub(*T, BO)); 817 case BO_Add: 818 if (BO->getType()->isFloatingType()) 819 return Discard(this->emitAddf(getFPOptions(BO), BO)); 820 return Discard(this->emitAdd(*T, BO)); 821 case BO_Mul: 822 if (BO->getType()->isFloatingType()) 823 return Discard(this->emitMulf(getFPOptions(BO), BO)); 824 return Discard(this->emitMul(*T, BO)); 825 case BO_Rem: 826 return Discard(this->emitRem(*T, BO)); 827 case BO_Div: 828 if (BO->getType()->isFloatingType()) 829 return Discard(this->emitDivf(getFPOptions(BO), BO)); 830 return Discard(this->emitDiv(*T, BO)); 831 case BO_Assign: 832 if (DiscardResult) 833 return LHS->refersToBitField() ? this->emitStoreBitFieldPop(*T, BO) 834 : this->emitStorePop(*T, BO); 835 if (LHS->refersToBitField()) { 836 if (!this->emitStoreBitField(*T, BO)) 837 return false; 838 } else { 839 if (!this->emitStore(*T, BO)) 840 return false; 841 } 842 // Assignments aren't necessarily lvalues in C. 843 // Load from them in that case. 844 if (!BO->isLValue()) 845 return this->emitLoadPop(*T, BO); 846 return true; 847 case BO_And: 848 return Discard(this->emitBitAnd(*T, BO)); 849 case BO_Or: 850 return Discard(this->emitBitOr(*T, BO)); 851 case BO_Shl: 852 return Discard(this->emitShl(*LT, *RT, BO)); 853 case BO_Shr: 854 return Discard(this->emitShr(*LT, *RT, BO)); 855 case BO_Xor: 856 return Discard(this->emitBitXor(*T, BO)); 857 case BO_LOr: 858 case BO_LAnd: 859 llvm_unreachable("Already handled earlier"); 860 default: 861 return false; 862 } 863 864 llvm_unreachable("Unhandled binary op"); 865 } 866 867 /// Perform addition/subtraction of a pointer and an integer or 868 /// subtraction of two pointers. 869 template <class Emitter> 870 bool Compiler<Emitter>::VisitPointerArithBinOp(const BinaryOperator *E) { 871 BinaryOperatorKind Op = E->getOpcode(); 872 const Expr *LHS = E->getLHS(); 873 const Expr *RHS = E->getRHS(); 874 875 if ((Op != BO_Add && Op != BO_Sub) || 876 (!LHS->getType()->isPointerType() && !RHS->getType()->isPointerType())) 877 return false; 878 879 std::optional<PrimType> LT = classify(LHS); 880 std::optional<PrimType> RT = classify(RHS); 881 882 if (!LT || !RT) 883 return false; 884 885 // Visit the given pointer expression and optionally convert to a PT_Ptr. 886 auto visitAsPointer = [&](const Expr *E, PrimType T) -> bool { 887 if (!this->visit(E)) 888 return false; 889 if (T != PT_Ptr) 890 return this->emitDecayPtr(T, PT_Ptr, E); 891 return true; 892 }; 893 894 if (LHS->getType()->isPointerType() && RHS->getType()->isPointerType()) { 895 if (Op != BO_Sub) 896 return false; 897 898 assert(E->getType()->isIntegerType()); 899 if (!visitAsPointer(RHS, *RT) || !visitAsPointer(LHS, *LT)) 900 return false; 901 902 return this->emitSubPtr(classifyPrim(E->getType()), E); 903 } 904 905 PrimType OffsetType; 906 if (LHS->getType()->isIntegerType()) { 907 if (!visitAsPointer(RHS, *RT)) 908 return false; 909 if (!this->visit(LHS)) 910 return false; 911 OffsetType = *LT; 912 } else if (RHS->getType()->isIntegerType()) { 913 if (!visitAsPointer(LHS, *LT)) 914 return false; 915 if (!this->visit(RHS)) 916 return false; 917 OffsetType = *RT; 918 } else { 919 return false; 920 } 921 922 // Do the operation and optionally transform to 923 // result pointer type. 924 if (Op == BO_Add) { 925 if (!this->emitAddOffset(OffsetType, E)) 926 return false; 927 928 if (classifyPrim(E) != PT_Ptr) 929 return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E); 930 return true; 931 } else if (Op == BO_Sub) { 932 if (!this->emitSubOffset(OffsetType, E)) 933 return false; 934 935 if (classifyPrim(E) != PT_Ptr) 936 return this->emitDecayPtr(PT_Ptr, classifyPrim(E), E); 937 return true; 938 } 939 940 return false; 941 } 942 943 template <class Emitter> 944 bool Compiler<Emitter>::VisitLogicalBinOp(const BinaryOperator *E) { 945 assert(E->isLogicalOp()); 946 BinaryOperatorKind Op = E->getOpcode(); 947 const Expr *LHS = E->getLHS(); 948 const Expr *RHS = E->getRHS(); 949 std::optional<PrimType> T = classify(E->getType()); 950 951 if (Op == BO_LOr) { 952 // Logical OR. Visit LHS and only evaluate RHS if LHS was FALSE. 953 LabelTy LabelTrue = this->getLabel(); 954 LabelTy LabelEnd = this->getLabel(); 955 956 if (!this->visitBool(LHS)) 957 return false; 958 if (!this->jumpTrue(LabelTrue)) 959 return false; 960 961 if (!this->visitBool(RHS)) 962 return false; 963 if (!this->jump(LabelEnd)) 964 return false; 965 966 this->emitLabel(LabelTrue); 967 this->emitConstBool(true, E); 968 this->fallthrough(LabelEnd); 969 this->emitLabel(LabelEnd); 970 971 } else { 972 assert(Op == BO_LAnd); 973 // Logical AND. 974 // Visit LHS. Only visit RHS if LHS was TRUE. 975 LabelTy LabelFalse = this->getLabel(); 976 LabelTy LabelEnd = this->getLabel(); 977 978 if (!this->visitBool(LHS)) 979 return false; 980 if (!this->jumpFalse(LabelFalse)) 981 return false; 982 983 if (!this->visitBool(RHS)) 984 return false; 985 if (!this->jump(LabelEnd)) 986 return false; 987 988 this->emitLabel(LabelFalse); 989 this->emitConstBool(false, E); 990 this->fallthrough(LabelEnd); 991 this->emitLabel(LabelEnd); 992 } 993 994 if (DiscardResult) 995 return this->emitPopBool(E); 996 997 // For C, cast back to integer type. 998 assert(T); 999 if (T != PT_Bool) 1000 return this->emitCast(PT_Bool, *T, E); 1001 return true; 1002 } 1003 1004 template <class Emitter> 1005 bool Compiler<Emitter>::VisitComplexBinOp(const BinaryOperator *E) { 1006 // Prepare storage for result. 1007 if (!Initializing) { 1008 unsigned LocalIndex = allocateTemporary(E); 1009 if (!this->emitGetPtrLocal(LocalIndex, E)) 1010 return false; 1011 } 1012 1013 // Both LHS and RHS might _not_ be of complex type, but one of them 1014 // needs to be. 1015 const Expr *LHS = E->getLHS(); 1016 const Expr *RHS = E->getRHS(); 1017 1018 PrimType ResultElemT = this->classifyComplexElementType(E->getType()); 1019 unsigned ResultOffset = ~0u; 1020 if (!DiscardResult) 1021 ResultOffset = this->allocateLocalPrimitive(E, PT_Ptr, true, false); 1022 1023 // Save result pointer in ResultOffset 1024 if (!this->DiscardResult) { 1025 if (!this->emitDupPtr(E)) 1026 return false; 1027 if (!this->emitSetLocal(PT_Ptr, ResultOffset, E)) 1028 return false; 1029 } 1030 QualType LHSType = LHS->getType(); 1031 if (const auto *AT = LHSType->getAs<AtomicType>()) 1032 LHSType = AT->getValueType(); 1033 QualType RHSType = RHS->getType(); 1034 if (const auto *AT = RHSType->getAs<AtomicType>()) 1035 RHSType = AT->getValueType(); 1036 1037 bool LHSIsComplex = LHSType->isAnyComplexType(); 1038 unsigned LHSOffset; 1039 bool RHSIsComplex = RHSType->isAnyComplexType(); 1040 1041 // For ComplexComplex Mul, we have special ops to make their implementation 1042 // easier. 1043 BinaryOperatorKind Op = E->getOpcode(); 1044 if (Op == BO_Mul && LHSIsComplex && RHSIsComplex) { 1045 assert(classifyPrim(LHSType->getAs<ComplexType>()->getElementType()) == 1046 classifyPrim(RHSType->getAs<ComplexType>()->getElementType())); 1047 PrimType ElemT = 1048 classifyPrim(LHSType->getAs<ComplexType>()->getElementType()); 1049 if (!this->visit(LHS)) 1050 return false; 1051 if (!this->visit(RHS)) 1052 return false; 1053 return this->emitMulc(ElemT, E); 1054 } 1055 1056 if (Op == BO_Div && RHSIsComplex) { 1057 QualType ElemQT = RHSType->getAs<ComplexType>()->getElementType(); 1058 PrimType ElemT = classifyPrim(ElemQT); 1059 // If the LHS is not complex, we still need to do the full complex 1060 // division, so just stub create a complex value and stub it out with 1061 // the LHS and a zero. 1062 1063 if (!LHSIsComplex) { 1064 // This is using the RHS type for the fake-complex LHS. 1065 LHSOffset = allocateTemporary(RHS); 1066 1067 if (!this->emitGetPtrLocal(LHSOffset, E)) 1068 return false; 1069 1070 if (!this->visit(LHS)) 1071 return false; 1072 // real is LHS 1073 if (!this->emitInitElem(ElemT, 0, E)) 1074 return false; 1075 // imag is zero 1076 if (!this->visitZeroInitializer(ElemT, ElemQT, E)) 1077 return false; 1078 if (!this->emitInitElem(ElemT, 1, E)) 1079 return false; 1080 } else { 1081 if (!this->visit(LHS)) 1082 return false; 1083 } 1084 1085 if (!this->visit(RHS)) 1086 return false; 1087 return this->emitDivc(ElemT, E); 1088 } 1089 1090 // Evaluate LHS and save value to LHSOffset. 1091 if (LHSType->isAnyComplexType()) { 1092 LHSOffset = this->allocateLocalPrimitive(LHS, PT_Ptr, true, false); 1093 if (!this->visit(LHS)) 1094 return false; 1095 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E)) 1096 return false; 1097 } else { 1098 PrimType LHST = classifyPrim(LHSType); 1099 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, true, false); 1100 if (!this->visit(LHS)) 1101 return false; 1102 if (!this->emitSetLocal(LHST, LHSOffset, E)) 1103 return false; 1104 } 1105 1106 // Same with RHS. 1107 unsigned RHSOffset; 1108 if (RHSType->isAnyComplexType()) { 1109 RHSOffset = this->allocateLocalPrimitive(RHS, PT_Ptr, true, false); 1110 if (!this->visit(RHS)) 1111 return false; 1112 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E)) 1113 return false; 1114 } else { 1115 PrimType RHST = classifyPrim(RHSType); 1116 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, true, false); 1117 if (!this->visit(RHS)) 1118 return false; 1119 if (!this->emitSetLocal(RHST, RHSOffset, E)) 1120 return false; 1121 } 1122 1123 // For both LHS and RHS, either load the value from the complex pointer, or 1124 // directly from the local variable. For index 1 (i.e. the imaginary part), 1125 // just load 0 and do the operation anyway. 1126 auto loadComplexValue = [this](bool IsComplex, bool LoadZero, 1127 unsigned ElemIndex, unsigned Offset, 1128 const Expr *E) -> bool { 1129 if (IsComplex) { 1130 if (!this->emitGetLocal(PT_Ptr, Offset, E)) 1131 return false; 1132 return this->emitArrayElemPop(classifyComplexElementType(E->getType()), 1133 ElemIndex, E); 1134 } 1135 if (ElemIndex == 0 || !LoadZero) 1136 return this->emitGetLocal(classifyPrim(E->getType()), Offset, E); 1137 return this->visitZeroInitializer(classifyPrim(E->getType()), E->getType(), 1138 E); 1139 }; 1140 1141 // Now we can get pointers to the LHS and RHS from the offsets above. 1142 for (unsigned ElemIndex = 0; ElemIndex != 2; ++ElemIndex) { 1143 // Result pointer for the store later. 1144 if (!this->DiscardResult) { 1145 if (!this->emitGetLocal(PT_Ptr, ResultOffset, E)) 1146 return false; 1147 } 1148 1149 // The actual operation. 1150 switch (Op) { 1151 case BO_Add: 1152 if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS)) 1153 return false; 1154 1155 if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS)) 1156 return false; 1157 if (ResultElemT == PT_Float) { 1158 if (!this->emitAddf(getFPOptions(E), E)) 1159 return false; 1160 } else { 1161 if (!this->emitAdd(ResultElemT, E)) 1162 return false; 1163 } 1164 break; 1165 case BO_Sub: 1166 if (!loadComplexValue(LHSIsComplex, true, ElemIndex, LHSOffset, LHS)) 1167 return false; 1168 1169 if (!loadComplexValue(RHSIsComplex, true, ElemIndex, RHSOffset, RHS)) 1170 return false; 1171 if (ResultElemT == PT_Float) { 1172 if (!this->emitSubf(getFPOptions(E), E)) 1173 return false; 1174 } else { 1175 if (!this->emitSub(ResultElemT, E)) 1176 return false; 1177 } 1178 break; 1179 case BO_Mul: 1180 if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS)) 1181 return false; 1182 1183 if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS)) 1184 return false; 1185 1186 if (ResultElemT == PT_Float) { 1187 if (!this->emitMulf(getFPOptions(E), E)) 1188 return false; 1189 } else { 1190 if (!this->emitMul(ResultElemT, E)) 1191 return false; 1192 } 1193 break; 1194 case BO_Div: 1195 assert(!RHSIsComplex); 1196 if (!loadComplexValue(LHSIsComplex, false, ElemIndex, LHSOffset, LHS)) 1197 return false; 1198 1199 if (!loadComplexValue(RHSIsComplex, false, ElemIndex, RHSOffset, RHS)) 1200 return false; 1201 1202 if (ResultElemT == PT_Float) { 1203 if (!this->emitDivf(getFPOptions(E), E)) 1204 return false; 1205 } else { 1206 if (!this->emitDiv(ResultElemT, E)) 1207 return false; 1208 } 1209 break; 1210 1211 default: 1212 return false; 1213 } 1214 1215 if (!this->DiscardResult) { 1216 // Initialize array element with the value we just computed. 1217 if (!this->emitInitElemPop(ResultElemT, ElemIndex, E)) 1218 return false; 1219 } else { 1220 if (!this->emitPop(ResultElemT, E)) 1221 return false; 1222 } 1223 } 1224 return true; 1225 } 1226 1227 template <class Emitter> 1228 bool Compiler<Emitter>::VisitVectorBinOp(const BinaryOperator *E) { 1229 assert(E->getType()->isVectorType()); 1230 assert(E->getLHS()->getType()->isVectorType()); 1231 assert(E->getRHS()->getType()->isVectorType()); 1232 1233 // FIXME: Current only support comparison binary operator, add support for 1234 // other binary operator. 1235 if (!E->isComparisonOp()) 1236 return this->emitInvalid(E); 1237 // Prepare storage for result. 1238 if (!Initializing) { 1239 unsigned LocalIndex = allocateTemporary(E); 1240 if (!this->emitGetPtrLocal(LocalIndex, E)) 1241 return false; 1242 } 1243 1244 const Expr *LHS = E->getLHS(); 1245 const Expr *RHS = E->getRHS(); 1246 const auto *VecTy = E->getType()->getAs<VectorType>(); 1247 1248 // The LHS and RHS of a comparison operator must have the same type. So we 1249 // just use LHS vector element type here. 1250 PrimType ElemT = this->classifyVectorElementType(LHS->getType()); 1251 PrimType ResultElemT = this->classifyVectorElementType(E->getType()); 1252 1253 // Evaluate LHS and save value to LHSOffset. 1254 unsigned LHSOffset = this->allocateLocalPrimitive(LHS, PT_Ptr, true, false); 1255 if (!this->visit(LHS)) 1256 return false; 1257 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E)) 1258 return false; 1259 1260 // Evaluate RHS and save value to RHSOffset. 1261 unsigned RHSOffset = this->allocateLocalPrimitive(RHS, PT_Ptr, true, false); 1262 if (!this->visit(RHS)) 1263 return false; 1264 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E)) 1265 return false; 1266 1267 auto getElem = [=](unsigned Offset, unsigned Index) { 1268 if (!this->emitGetLocal(PT_Ptr, Offset, E)) 1269 return false; 1270 return this->emitArrayElemPop(ElemT, Index, E); 1271 }; 1272 1273 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) { 1274 if (!getElem(LHSOffset, I)) 1275 return false; 1276 if (!getElem(RHSOffset, I)) 1277 return false; 1278 switch (E->getOpcode()) { 1279 case BO_EQ: 1280 if (!this->emitEQ(ElemT, E)) 1281 return false; 1282 break; 1283 case BO_NE: 1284 if (!this->emitNE(ElemT, E)) 1285 return false; 1286 break; 1287 case BO_LE: 1288 if (!this->emitLE(ElemT, E)) 1289 return false; 1290 break; 1291 case BO_LT: 1292 if (!this->emitLT(ElemT, E)) 1293 return false; 1294 break; 1295 case BO_GE: 1296 if (!this->emitGE(ElemT, E)) 1297 return false; 1298 break; 1299 case BO_GT: 1300 if (!this->emitGT(ElemT, E)) 1301 return false; 1302 break; 1303 default: 1304 llvm_unreachable("Unsupported binary operator"); 1305 } 1306 1307 // The result of the comparison is a vector of the same width and number 1308 // of elements as the comparison operands with a signed integral element 1309 // type. 1310 // 1311 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html 1312 if (E->isComparisonOp()) { 1313 if (!this->emitPrimCast(PT_Bool, ResultElemT, VecTy->getElementType(), E)) 1314 return false; 1315 if (!this->emitNeg(ResultElemT, E)) 1316 return false; 1317 } 1318 1319 // Initialize array element with the value we just computed. 1320 if (!this->emitInitElem(ResultElemT, I, E)) 1321 return false; 1322 } 1323 return true; 1324 } 1325 1326 template <class Emitter> 1327 bool Compiler<Emitter>::VisitImplicitValueInitExpr( 1328 const ImplicitValueInitExpr *E) { 1329 QualType QT = E->getType(); 1330 1331 if (std::optional<PrimType> T = classify(QT)) 1332 return this->visitZeroInitializer(*T, QT, E); 1333 1334 if (QT->isRecordType()) { 1335 const RecordDecl *RD = QT->getAsRecordDecl(); 1336 assert(RD); 1337 if (RD->isInvalidDecl()) 1338 return false; 1339 1340 if (const auto *CXXRD = dyn_cast<CXXRecordDecl>(RD); 1341 CXXRD && CXXRD->getNumVBases() > 0) { 1342 // TODO: Diagnose. 1343 return false; 1344 } 1345 1346 const Record *R = getRecord(QT); 1347 if (!R) 1348 return false; 1349 1350 assert(Initializing); 1351 return this->visitZeroRecordInitializer(R, E); 1352 } 1353 1354 if (QT->isIncompleteArrayType()) 1355 return true; 1356 1357 if (QT->isArrayType()) { 1358 const ArrayType *AT = QT->getAsArrayTypeUnsafe(); 1359 assert(AT); 1360 const auto *CAT = cast<ConstantArrayType>(AT); 1361 size_t NumElems = CAT->getZExtSize(); 1362 PrimType ElemT = classifyPrim(CAT->getElementType()); 1363 1364 for (size_t I = 0; I != NumElems; ++I) { 1365 if (!this->visitZeroInitializer(ElemT, CAT->getElementType(), E)) 1366 return false; 1367 if (!this->emitInitElem(ElemT, I, E)) 1368 return false; 1369 } 1370 1371 return true; 1372 } 1373 1374 if (const auto *ComplexTy = E->getType()->getAs<ComplexType>()) { 1375 assert(Initializing); 1376 QualType ElemQT = ComplexTy->getElementType(); 1377 PrimType ElemT = classifyPrim(ElemQT); 1378 for (unsigned I = 0; I < 2; ++I) { 1379 if (!this->visitZeroInitializer(ElemT, ElemQT, E)) 1380 return false; 1381 if (!this->emitInitElem(ElemT, I, E)) 1382 return false; 1383 } 1384 return true; 1385 } 1386 1387 if (const auto *VecT = E->getType()->getAs<VectorType>()) { 1388 unsigned NumVecElements = VecT->getNumElements(); 1389 QualType ElemQT = VecT->getElementType(); 1390 PrimType ElemT = classifyPrim(ElemQT); 1391 1392 for (unsigned I = 0; I < NumVecElements; ++I) { 1393 if (!this->visitZeroInitializer(ElemT, ElemQT, E)) 1394 return false; 1395 if (!this->emitInitElem(ElemT, I, E)) 1396 return false; 1397 } 1398 return true; 1399 } 1400 1401 return false; 1402 } 1403 1404 template <class Emitter> 1405 bool Compiler<Emitter>::VisitArraySubscriptExpr(const ArraySubscriptExpr *E) { 1406 const Expr *LHS = E->getLHS(); 1407 const Expr *RHS = E->getRHS(); 1408 const Expr *Index = E->getIdx(); 1409 1410 if (DiscardResult) 1411 return this->discard(LHS) && this->discard(RHS); 1412 1413 // C++17's rules require us to evaluate the LHS first, regardless of which 1414 // side is the base. 1415 bool Success = true; 1416 for (const Expr *SubExpr : {LHS, RHS}) { 1417 if (!this->visit(SubExpr)) 1418 Success = false; 1419 } 1420 1421 if (!Success) 1422 return false; 1423 1424 PrimType IndexT = classifyPrim(Index->getType()); 1425 // If the index is first, we need to change that. 1426 if (LHS == Index) { 1427 if (!this->emitFlip(PT_Ptr, IndexT, E)) 1428 return false; 1429 } 1430 1431 return this->emitArrayElemPtrPop(IndexT, E); 1432 } 1433 1434 template <class Emitter> 1435 bool Compiler<Emitter>::visitInitList(ArrayRef<const Expr *> Inits, 1436 const Expr *ArrayFiller, const Expr *E) { 1437 QualType QT = E->getType(); 1438 if (const auto *AT = QT->getAs<AtomicType>()) 1439 QT = AT->getValueType(); 1440 1441 if (QT->isVoidType()) { 1442 if (Inits.size() == 0) 1443 return true; 1444 return this->emitInvalid(E); 1445 } 1446 1447 // Handle discarding first. 1448 if (DiscardResult) { 1449 for (const Expr *Init : Inits) { 1450 if (!this->discard(Init)) 1451 return false; 1452 } 1453 return true; 1454 } 1455 1456 // Primitive values. 1457 if (std::optional<PrimType> T = classify(QT)) { 1458 assert(!DiscardResult); 1459 if (Inits.size() == 0) 1460 return this->visitZeroInitializer(*T, QT, E); 1461 assert(Inits.size() == 1); 1462 return this->delegate(Inits[0]); 1463 } 1464 1465 if (QT->isRecordType()) { 1466 const Record *R = getRecord(QT); 1467 1468 if (Inits.size() == 1 && E->getType() == Inits[0]->getType()) 1469 return this->delegate(Inits[0]); 1470 1471 auto initPrimitiveField = [=](const Record::Field *FieldToInit, 1472 const Expr *Init, PrimType T) -> bool { 1473 InitStackScope<Emitter> ISS(this, isa<CXXDefaultInitExpr>(Init)); 1474 if (!this->visit(Init)) 1475 return false; 1476 1477 if (FieldToInit->isBitField()) 1478 return this->emitInitBitField(T, FieldToInit, E); 1479 return this->emitInitField(T, FieldToInit->Offset, E); 1480 }; 1481 1482 auto initCompositeField = [=](const Record::Field *FieldToInit, 1483 const Expr *Init) -> bool { 1484 InitStackScope<Emitter> ISS(this, isa<CXXDefaultInitExpr>(Init)); 1485 InitLinkScope<Emitter> ILS(this, InitLink::Field(FieldToInit->Offset)); 1486 // Non-primitive case. Get a pointer to the field-to-initialize 1487 // on the stack and recurse into visitInitializer(). 1488 if (!this->emitGetPtrField(FieldToInit->Offset, Init)) 1489 return false; 1490 if (!this->visitInitializer(Init)) 1491 return false; 1492 return this->emitPopPtr(E); 1493 }; 1494 1495 if (R->isUnion()) { 1496 if (Inits.size() == 0) { 1497 if (!this->visitZeroRecordInitializer(R, E)) 1498 return false; 1499 } else { 1500 const Expr *Init = Inits[0]; 1501 const FieldDecl *FToInit = nullptr; 1502 if (const auto *ILE = dyn_cast<InitListExpr>(E)) 1503 FToInit = ILE->getInitializedFieldInUnion(); 1504 else 1505 FToInit = cast<CXXParenListInitExpr>(E)->getInitializedFieldInUnion(); 1506 1507 const Record::Field *FieldToInit = R->getField(FToInit); 1508 if (std::optional<PrimType> T = classify(Init)) { 1509 if (!initPrimitiveField(FieldToInit, Init, *T)) 1510 return false; 1511 } else { 1512 if (!initCompositeField(FieldToInit, Init)) 1513 return false; 1514 } 1515 } 1516 return this->emitFinishInit(E); 1517 } 1518 1519 assert(!R->isUnion()); 1520 unsigned InitIndex = 0; 1521 for (const Expr *Init : Inits) { 1522 // Skip unnamed bitfields. 1523 while (InitIndex < R->getNumFields() && 1524 R->getField(InitIndex)->Decl->isUnnamedBitField()) 1525 ++InitIndex; 1526 1527 if (std::optional<PrimType> T = classify(Init)) { 1528 const Record::Field *FieldToInit = R->getField(InitIndex); 1529 if (!initPrimitiveField(FieldToInit, Init, *T)) 1530 return false; 1531 ++InitIndex; 1532 } else { 1533 // Initializer for a direct base class. 1534 if (const Record::Base *B = R->getBase(Init->getType())) { 1535 if (!this->emitGetPtrBase(B->Offset, Init)) 1536 return false; 1537 1538 if (!this->visitInitializer(Init)) 1539 return false; 1540 1541 if (!this->emitFinishInitPop(E)) 1542 return false; 1543 // Base initializers don't increase InitIndex, since they don't count 1544 // into the Record's fields. 1545 } else { 1546 const Record::Field *FieldToInit = R->getField(InitIndex); 1547 if (!initCompositeField(FieldToInit, Init)) 1548 return false; 1549 ++InitIndex; 1550 } 1551 } 1552 } 1553 return this->emitFinishInit(E); 1554 } 1555 1556 if (QT->isArrayType()) { 1557 if (Inits.size() == 1 && QT == Inits[0]->getType()) 1558 return this->delegate(Inits[0]); 1559 1560 unsigned ElementIndex = 0; 1561 for (const Expr *Init : Inits) { 1562 if (const auto *EmbedS = 1563 dyn_cast<EmbedExpr>(Init->IgnoreParenImpCasts())) { 1564 PrimType TargetT = classifyPrim(Init->getType()); 1565 1566 auto Eval = [&](const Expr *Init, unsigned ElemIndex) { 1567 PrimType InitT = classifyPrim(Init->getType()); 1568 if (!this->visit(Init)) 1569 return false; 1570 if (InitT != TargetT) { 1571 if (!this->emitCast(InitT, TargetT, E)) 1572 return false; 1573 } 1574 return this->emitInitElem(TargetT, ElemIndex, Init); 1575 }; 1576 if (!EmbedS->doForEachDataElement(Eval, ElementIndex)) 1577 return false; 1578 } else { 1579 if (!this->visitArrayElemInit(ElementIndex, Init)) 1580 return false; 1581 ++ElementIndex; 1582 } 1583 } 1584 1585 // Expand the filler expression. 1586 // FIXME: This should go away. 1587 if (ArrayFiller) { 1588 const ConstantArrayType *CAT = 1589 Ctx.getASTContext().getAsConstantArrayType(QT); 1590 uint64_t NumElems = CAT->getZExtSize(); 1591 1592 for (; ElementIndex != NumElems; ++ElementIndex) { 1593 if (!this->visitArrayElemInit(ElementIndex, ArrayFiller)) 1594 return false; 1595 } 1596 } 1597 1598 return this->emitFinishInit(E); 1599 } 1600 1601 if (const auto *ComplexTy = QT->getAs<ComplexType>()) { 1602 unsigned NumInits = Inits.size(); 1603 1604 if (NumInits == 1) 1605 return this->delegate(Inits[0]); 1606 1607 QualType ElemQT = ComplexTy->getElementType(); 1608 PrimType ElemT = classifyPrim(ElemQT); 1609 if (NumInits == 0) { 1610 // Zero-initialize both elements. 1611 for (unsigned I = 0; I < 2; ++I) { 1612 if (!this->visitZeroInitializer(ElemT, ElemQT, E)) 1613 return false; 1614 if (!this->emitInitElem(ElemT, I, E)) 1615 return false; 1616 } 1617 } else if (NumInits == 2) { 1618 unsigned InitIndex = 0; 1619 for (const Expr *Init : Inits) { 1620 if (!this->visit(Init)) 1621 return false; 1622 1623 if (!this->emitInitElem(ElemT, InitIndex, E)) 1624 return false; 1625 ++InitIndex; 1626 } 1627 } 1628 return true; 1629 } 1630 1631 if (const auto *VecT = QT->getAs<VectorType>()) { 1632 unsigned NumVecElements = VecT->getNumElements(); 1633 assert(NumVecElements >= Inits.size()); 1634 1635 QualType ElemQT = VecT->getElementType(); 1636 PrimType ElemT = classifyPrim(ElemQT); 1637 1638 // All initializer elements. 1639 unsigned InitIndex = 0; 1640 for (const Expr *Init : Inits) { 1641 if (!this->visit(Init)) 1642 return false; 1643 1644 // If the initializer is of vector type itself, we have to deconstruct 1645 // that and initialize all the target fields from the initializer fields. 1646 if (const auto *InitVecT = Init->getType()->getAs<VectorType>()) { 1647 if (!this->emitCopyArray(ElemT, 0, InitIndex, 1648 InitVecT->getNumElements(), E)) 1649 return false; 1650 InitIndex += InitVecT->getNumElements(); 1651 } else { 1652 if (!this->emitInitElem(ElemT, InitIndex, E)) 1653 return false; 1654 ++InitIndex; 1655 } 1656 } 1657 1658 assert(InitIndex <= NumVecElements); 1659 1660 // Fill the rest with zeroes. 1661 for (; InitIndex != NumVecElements; ++InitIndex) { 1662 if (!this->visitZeroInitializer(ElemT, ElemQT, E)) 1663 return false; 1664 if (!this->emitInitElem(ElemT, InitIndex, E)) 1665 return false; 1666 } 1667 return true; 1668 } 1669 1670 return false; 1671 } 1672 1673 /// Pointer to the array(not the element!) must be on the stack when calling 1674 /// this. 1675 template <class Emitter> 1676 bool Compiler<Emitter>::visitArrayElemInit(unsigned ElemIndex, 1677 const Expr *Init) { 1678 if (std::optional<PrimType> T = classify(Init->getType())) { 1679 // Visit the primitive element like normal. 1680 if (!this->visit(Init)) 1681 return false; 1682 return this->emitInitElem(*T, ElemIndex, Init); 1683 } 1684 1685 InitLinkScope<Emitter> ILS(this, InitLink::Elem(ElemIndex)); 1686 // Advance the pointer currently on the stack to the given 1687 // dimension. 1688 if (!this->emitConstUint32(ElemIndex, Init)) 1689 return false; 1690 if (!this->emitArrayElemPtrUint32(Init)) 1691 return false; 1692 if (!this->visitInitializer(Init)) 1693 return false; 1694 return this->emitFinishInitPop(Init); 1695 } 1696 1697 template <class Emitter> 1698 bool Compiler<Emitter>::VisitInitListExpr(const InitListExpr *E) { 1699 return this->visitInitList(E->inits(), E->getArrayFiller(), E); 1700 } 1701 1702 template <class Emitter> 1703 bool Compiler<Emitter>::VisitCXXParenListInitExpr( 1704 const CXXParenListInitExpr *E) { 1705 return this->visitInitList(E->getInitExprs(), E->getArrayFiller(), E); 1706 } 1707 1708 template <class Emitter> 1709 bool Compiler<Emitter>::VisitSubstNonTypeTemplateParmExpr( 1710 const SubstNonTypeTemplateParmExpr *E) { 1711 return this->delegate(E->getReplacement()); 1712 } 1713 1714 template <class Emitter> 1715 bool Compiler<Emitter>::VisitConstantExpr(const ConstantExpr *E) { 1716 std::optional<PrimType> T = classify(E->getType()); 1717 if (T && E->hasAPValueResult()) { 1718 // Try to emit the APValue directly, without visiting the subexpr. 1719 // This will only fail if we can't emit the APValue, so won't emit any 1720 // diagnostics or any double values. 1721 if (DiscardResult) 1722 return true; 1723 1724 if (this->visitAPValue(E->getAPValueResult(), *T, E)) 1725 return true; 1726 } 1727 return this->delegate(E->getSubExpr()); 1728 } 1729 1730 template <class Emitter> 1731 bool Compiler<Emitter>::VisitEmbedExpr(const EmbedExpr *E) { 1732 auto It = E->begin(); 1733 return this->visit(*It); 1734 } 1735 1736 static CharUnits AlignOfType(QualType T, const ASTContext &ASTCtx, 1737 UnaryExprOrTypeTrait Kind) { 1738 bool AlignOfReturnsPreferred = 1739 ASTCtx.getLangOpts().getClangABICompat() <= LangOptions::ClangABI::Ver7; 1740 1741 // C++ [expr.alignof]p3: 1742 // When alignof is applied to a reference type, the result is the 1743 // alignment of the referenced type. 1744 if (const auto *Ref = T->getAs<ReferenceType>()) 1745 T = Ref->getPointeeType(); 1746 1747 if (T.getQualifiers().hasUnaligned()) 1748 return CharUnits::One(); 1749 1750 // __alignof is defined to return the preferred alignment. 1751 // Before 8, clang returned the preferred alignment for alignof and 1752 // _Alignof as well. 1753 if (Kind == UETT_PreferredAlignOf || AlignOfReturnsPreferred) 1754 return ASTCtx.toCharUnitsFromBits(ASTCtx.getPreferredTypeAlign(T)); 1755 1756 return ASTCtx.getTypeAlignInChars(T); 1757 } 1758 1759 template <class Emitter> 1760 bool Compiler<Emitter>::VisitUnaryExprOrTypeTraitExpr( 1761 const UnaryExprOrTypeTraitExpr *E) { 1762 UnaryExprOrTypeTrait Kind = E->getKind(); 1763 const ASTContext &ASTCtx = Ctx.getASTContext(); 1764 1765 if (Kind == UETT_SizeOf || Kind == UETT_DataSizeOf) { 1766 QualType ArgType = E->getTypeOfArgument(); 1767 1768 // C++ [expr.sizeof]p2: "When applied to a reference or a reference type, 1769 // the result is the size of the referenced type." 1770 if (const auto *Ref = ArgType->getAs<ReferenceType>()) 1771 ArgType = Ref->getPointeeType(); 1772 1773 CharUnits Size; 1774 if (ArgType->isVoidType() || ArgType->isFunctionType()) 1775 Size = CharUnits::One(); 1776 else { 1777 if (ArgType->isDependentType() || !ArgType->isConstantSizeType()) 1778 return false; 1779 1780 if (Kind == UETT_SizeOf) 1781 Size = ASTCtx.getTypeSizeInChars(ArgType); 1782 else 1783 Size = ASTCtx.getTypeInfoDataSizeInChars(ArgType).Width; 1784 } 1785 1786 if (DiscardResult) 1787 return true; 1788 1789 return this->emitConst(Size.getQuantity(), E); 1790 } 1791 1792 if (Kind == UETT_AlignOf || Kind == UETT_PreferredAlignOf) { 1793 CharUnits Size; 1794 1795 if (E->isArgumentType()) { 1796 QualType ArgType = E->getTypeOfArgument(); 1797 1798 Size = AlignOfType(ArgType, ASTCtx, Kind); 1799 } else { 1800 // Argument is an expression, not a type. 1801 const Expr *Arg = E->getArgumentExpr()->IgnoreParens(); 1802 1803 // The kinds of expressions that we have special-case logic here for 1804 // should be kept up to date with the special checks for those 1805 // expressions in Sema. 1806 1807 // alignof decl is always accepted, even if it doesn't make sense: we 1808 // default to 1 in those cases. 1809 if (const auto *DRE = dyn_cast<DeclRefExpr>(Arg)) 1810 Size = ASTCtx.getDeclAlign(DRE->getDecl(), 1811 /*RefAsPointee*/ true); 1812 else if (const auto *ME = dyn_cast<MemberExpr>(Arg)) 1813 Size = ASTCtx.getDeclAlign(ME->getMemberDecl(), 1814 /*RefAsPointee*/ true); 1815 else 1816 Size = AlignOfType(Arg->getType(), ASTCtx, Kind); 1817 } 1818 1819 if (DiscardResult) 1820 return true; 1821 1822 return this->emitConst(Size.getQuantity(), E); 1823 } 1824 1825 if (Kind == UETT_VectorElements) { 1826 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>()) 1827 return this->emitConst(VT->getNumElements(), E); 1828 assert(E->getTypeOfArgument()->isSizelessVectorType()); 1829 return this->emitSizelessVectorElementSize(E); 1830 } 1831 1832 if (Kind == UETT_VecStep) { 1833 if (const auto *VT = E->getTypeOfArgument()->getAs<VectorType>()) { 1834 unsigned N = VT->getNumElements(); 1835 1836 // The vec_step built-in functions that take a 3-component 1837 // vector return 4. (OpenCL 1.1 spec 6.11.12) 1838 if (N == 3) 1839 N = 4; 1840 1841 return this->emitConst(N, E); 1842 } 1843 return this->emitConst(1, E); 1844 } 1845 1846 return false; 1847 } 1848 1849 template <class Emitter> 1850 bool Compiler<Emitter>::VisitMemberExpr(const MemberExpr *E) { 1851 // 'Base.Member' 1852 const Expr *Base = E->getBase(); 1853 const ValueDecl *Member = E->getMemberDecl(); 1854 1855 if (DiscardResult) 1856 return this->discard(Base); 1857 1858 // MemberExprs are almost always lvalues, in which case we don't need to 1859 // do the load. But sometimes they aren't. 1860 const auto maybeLoadValue = [&]() -> bool { 1861 if (E->isGLValue()) 1862 return true; 1863 if (std::optional<PrimType> T = classify(E)) 1864 return this->emitLoadPop(*T, E); 1865 return false; 1866 }; 1867 1868 if (const auto *VD = dyn_cast<VarDecl>(Member)) { 1869 // I am almost confident in saying that a var decl must be static 1870 // and therefore registered as a global variable. But this will probably 1871 // turn out to be wrong some time in the future, as always. 1872 if (auto GlobalIndex = P.getGlobal(VD)) 1873 return this->emitGetPtrGlobal(*GlobalIndex, E) && maybeLoadValue(); 1874 return false; 1875 } 1876 1877 if (!isa<FieldDecl>(Member)) { 1878 if (!this->discard(Base) && !this->emitSideEffect(E)) 1879 return false; 1880 1881 return this->visitDeclRef(Member, E); 1882 } 1883 1884 if (Initializing) { 1885 if (!this->delegate(Base)) 1886 return false; 1887 } else { 1888 if (!this->visit(Base)) 1889 return false; 1890 } 1891 1892 // Base above gives us a pointer on the stack. 1893 const auto *FD = cast<FieldDecl>(Member); 1894 const RecordDecl *RD = FD->getParent(); 1895 const Record *R = getRecord(RD); 1896 if (!R) 1897 return false; 1898 const Record::Field *F = R->getField(FD); 1899 // Leave a pointer to the field on the stack. 1900 if (F->Decl->getType()->isReferenceType()) 1901 return this->emitGetFieldPop(PT_Ptr, F->Offset, E) && maybeLoadValue(); 1902 return this->emitGetPtrFieldPop(F->Offset, E) && maybeLoadValue(); 1903 } 1904 1905 template <class Emitter> 1906 bool Compiler<Emitter>::VisitArrayInitIndexExpr(const ArrayInitIndexExpr *E) { 1907 // ArrayIndex might not be set if a ArrayInitIndexExpr is being evaluated 1908 // stand-alone, e.g. via EvaluateAsInt(). 1909 if (!ArrayIndex) 1910 return false; 1911 return this->emitConst(*ArrayIndex, E); 1912 } 1913 1914 template <class Emitter> 1915 bool Compiler<Emitter>::VisitArrayInitLoopExpr(const ArrayInitLoopExpr *E) { 1916 assert(Initializing); 1917 assert(!DiscardResult); 1918 1919 // We visit the common opaque expression here once so we have its value 1920 // cached. 1921 if (!this->discard(E->getCommonExpr())) 1922 return false; 1923 1924 // TODO: This compiles to quite a lot of bytecode if the array is larger. 1925 // Investigate compiling this to a loop. 1926 const Expr *SubExpr = E->getSubExpr(); 1927 size_t Size = E->getArraySize().getZExtValue(); 1928 1929 // So, every iteration, we execute an assignment here 1930 // where the LHS is on the stack (the target array) 1931 // and the RHS is our SubExpr. 1932 for (size_t I = 0; I != Size; ++I) { 1933 ArrayIndexScope<Emitter> IndexScope(this, I); 1934 BlockScope<Emitter> BS(this); 1935 1936 if (!this->visitArrayElemInit(I, SubExpr)) 1937 return false; 1938 if (!BS.destroyLocals()) 1939 return false; 1940 } 1941 return true; 1942 } 1943 1944 template <class Emitter> 1945 bool Compiler<Emitter>::VisitOpaqueValueExpr(const OpaqueValueExpr *E) { 1946 const Expr *SourceExpr = E->getSourceExpr(); 1947 if (!SourceExpr) 1948 return false; 1949 1950 if (Initializing) 1951 return this->visitInitializer(SourceExpr); 1952 1953 PrimType SubExprT = classify(SourceExpr).value_or(PT_Ptr); 1954 if (auto It = OpaqueExprs.find(E); It != OpaqueExprs.end()) 1955 return this->emitGetLocal(SubExprT, It->second, E); 1956 1957 if (!this->visit(SourceExpr)) 1958 return false; 1959 1960 // At this point we either have the evaluated source expression or a pointer 1961 // to an object on the stack. We want to create a local variable that stores 1962 // this value. 1963 unsigned LocalIndex = allocateLocalPrimitive(E, SubExprT, /*IsConst=*/true); 1964 if (!this->emitSetLocal(SubExprT, LocalIndex, E)) 1965 return false; 1966 1967 // Here the local variable is created but the value is removed from the stack, 1968 // so we put it back if the caller needs it. 1969 if (!DiscardResult) { 1970 if (!this->emitGetLocal(SubExprT, LocalIndex, E)) 1971 return false; 1972 } 1973 1974 // This is cleaned up when the local variable is destroyed. 1975 OpaqueExprs.insert({E, LocalIndex}); 1976 1977 return true; 1978 } 1979 1980 template <class Emitter> 1981 bool Compiler<Emitter>::VisitAbstractConditionalOperator( 1982 const AbstractConditionalOperator *E) { 1983 const Expr *Condition = E->getCond(); 1984 const Expr *TrueExpr = E->getTrueExpr(); 1985 const Expr *FalseExpr = E->getFalseExpr(); 1986 1987 LabelTy LabelEnd = this->getLabel(); // Label after the operator. 1988 LabelTy LabelFalse = this->getLabel(); // Label for the false expr. 1989 1990 if (!this->visitBool(Condition)) 1991 return false; 1992 1993 if (!this->jumpFalse(LabelFalse)) 1994 return false; 1995 1996 { 1997 LocalScope<Emitter> S(this); 1998 if (!this->delegate(TrueExpr)) 1999 return false; 2000 if (!S.destroyLocals()) 2001 return false; 2002 } 2003 2004 if (!this->jump(LabelEnd)) 2005 return false; 2006 2007 this->emitLabel(LabelFalse); 2008 2009 { 2010 LocalScope<Emitter> S(this); 2011 if (!this->delegate(FalseExpr)) 2012 return false; 2013 if (!S.destroyLocals()) 2014 return false; 2015 } 2016 2017 this->fallthrough(LabelEnd); 2018 this->emitLabel(LabelEnd); 2019 2020 return true; 2021 } 2022 2023 template <class Emitter> 2024 bool Compiler<Emitter>::VisitStringLiteral(const StringLiteral *E) { 2025 if (DiscardResult) 2026 return true; 2027 2028 if (!Initializing) { 2029 unsigned StringIndex = P.createGlobalString(E); 2030 return this->emitGetPtrGlobal(StringIndex, E); 2031 } 2032 2033 // We are initializing an array on the stack. 2034 const ConstantArrayType *CAT = 2035 Ctx.getASTContext().getAsConstantArrayType(E->getType()); 2036 assert(CAT && "a string literal that's not a constant array?"); 2037 2038 // If the initializer string is too long, a diagnostic has already been 2039 // emitted. Read only the array length from the string literal. 2040 unsigned ArraySize = CAT->getZExtSize(); 2041 unsigned N = std::min(ArraySize, E->getLength()); 2042 size_t CharWidth = E->getCharByteWidth(); 2043 2044 for (unsigned I = 0; I != N; ++I) { 2045 uint32_t CodeUnit = E->getCodeUnit(I); 2046 2047 if (CharWidth == 1) { 2048 this->emitConstSint8(CodeUnit, E); 2049 this->emitInitElemSint8(I, E); 2050 } else if (CharWidth == 2) { 2051 this->emitConstUint16(CodeUnit, E); 2052 this->emitInitElemUint16(I, E); 2053 } else if (CharWidth == 4) { 2054 this->emitConstUint32(CodeUnit, E); 2055 this->emitInitElemUint32(I, E); 2056 } else { 2057 llvm_unreachable("unsupported character width"); 2058 } 2059 } 2060 2061 // Fill up the rest of the char array with NUL bytes. 2062 for (unsigned I = N; I != ArraySize; ++I) { 2063 if (CharWidth == 1) { 2064 this->emitConstSint8(0, E); 2065 this->emitInitElemSint8(I, E); 2066 } else if (CharWidth == 2) { 2067 this->emitConstUint16(0, E); 2068 this->emitInitElemUint16(I, E); 2069 } else if (CharWidth == 4) { 2070 this->emitConstUint32(0, E); 2071 this->emitInitElemUint32(I, E); 2072 } else { 2073 llvm_unreachable("unsupported character width"); 2074 } 2075 } 2076 2077 return true; 2078 } 2079 2080 template <class Emitter> 2081 bool Compiler<Emitter>::VisitObjCStringLiteral(const ObjCStringLiteral *E) { 2082 return this->delegate(E->getString()); 2083 } 2084 2085 template <class Emitter> 2086 bool Compiler<Emitter>::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { 2087 auto &A = Ctx.getASTContext(); 2088 std::string Str; 2089 A.getObjCEncodingForType(E->getEncodedType(), Str); 2090 StringLiteral *SL = 2091 StringLiteral::Create(A, Str, StringLiteralKind::Ordinary, 2092 /*Pascal=*/false, E->getType(), E->getAtLoc()); 2093 return this->delegate(SL); 2094 } 2095 2096 template <class Emitter> 2097 bool Compiler<Emitter>::VisitSYCLUniqueStableNameExpr( 2098 const SYCLUniqueStableNameExpr *E) { 2099 if (DiscardResult) 2100 return true; 2101 2102 assert(!Initializing); 2103 2104 auto &A = Ctx.getASTContext(); 2105 std::string ResultStr = E->ComputeName(A); 2106 2107 QualType CharTy = A.CharTy.withConst(); 2108 APInt Size(A.getTypeSize(A.getSizeType()), ResultStr.size() + 1); 2109 QualType ArrayTy = A.getConstantArrayType(CharTy, Size, nullptr, 2110 ArraySizeModifier::Normal, 0); 2111 2112 StringLiteral *SL = 2113 StringLiteral::Create(A, ResultStr, StringLiteralKind::Ordinary, 2114 /*Pascal=*/false, ArrayTy, E->getLocation()); 2115 2116 unsigned StringIndex = P.createGlobalString(SL); 2117 return this->emitGetPtrGlobal(StringIndex, E); 2118 } 2119 2120 template <class Emitter> 2121 bool Compiler<Emitter>::VisitCharacterLiteral(const CharacterLiteral *E) { 2122 if (DiscardResult) 2123 return true; 2124 return this->emitConst(E->getValue(), E); 2125 } 2126 2127 template <class Emitter> 2128 bool Compiler<Emitter>::VisitFloatCompoundAssignOperator( 2129 const CompoundAssignOperator *E) { 2130 2131 const Expr *LHS = E->getLHS(); 2132 const Expr *RHS = E->getRHS(); 2133 QualType LHSType = LHS->getType(); 2134 QualType LHSComputationType = E->getComputationLHSType(); 2135 QualType ResultType = E->getComputationResultType(); 2136 std::optional<PrimType> LT = classify(LHSComputationType); 2137 std::optional<PrimType> RT = classify(ResultType); 2138 2139 assert(ResultType->isFloatingType()); 2140 2141 if (!LT || !RT) 2142 return false; 2143 2144 PrimType LHST = classifyPrim(LHSType); 2145 2146 // C++17 onwards require that we evaluate the RHS first. 2147 // Compute RHS and save it in a temporary variable so we can 2148 // load it again later. 2149 if (!visit(RHS)) 2150 return false; 2151 2152 unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true); 2153 if (!this->emitSetLocal(*RT, TempOffset, E)) 2154 return false; 2155 2156 // First, visit LHS. 2157 if (!visit(LHS)) 2158 return false; 2159 if (!this->emitLoad(LHST, E)) 2160 return false; 2161 2162 // If necessary, convert LHS to its computation type. 2163 if (!this->emitPrimCast(LHST, classifyPrim(LHSComputationType), 2164 LHSComputationType, E)) 2165 return false; 2166 2167 // Now load RHS. 2168 if (!this->emitGetLocal(*RT, TempOffset, E)) 2169 return false; 2170 2171 switch (E->getOpcode()) { 2172 case BO_AddAssign: 2173 if (!this->emitAddf(getFPOptions(E), E)) 2174 return false; 2175 break; 2176 case BO_SubAssign: 2177 if (!this->emitSubf(getFPOptions(E), E)) 2178 return false; 2179 break; 2180 case BO_MulAssign: 2181 if (!this->emitMulf(getFPOptions(E), E)) 2182 return false; 2183 break; 2184 case BO_DivAssign: 2185 if (!this->emitDivf(getFPOptions(E), E)) 2186 return false; 2187 break; 2188 default: 2189 return false; 2190 } 2191 2192 if (!this->emitPrimCast(classifyPrim(ResultType), LHST, LHS->getType(), E)) 2193 return false; 2194 2195 if (DiscardResult) 2196 return this->emitStorePop(LHST, E); 2197 return this->emitStore(LHST, E); 2198 } 2199 2200 template <class Emitter> 2201 bool Compiler<Emitter>::VisitPointerCompoundAssignOperator( 2202 const CompoundAssignOperator *E) { 2203 BinaryOperatorKind Op = E->getOpcode(); 2204 const Expr *LHS = E->getLHS(); 2205 const Expr *RHS = E->getRHS(); 2206 std::optional<PrimType> LT = classify(LHS->getType()); 2207 std::optional<PrimType> RT = classify(RHS->getType()); 2208 2209 if (Op != BO_AddAssign && Op != BO_SubAssign) 2210 return false; 2211 2212 if (!LT || !RT) 2213 return false; 2214 2215 if (!visit(LHS)) 2216 return false; 2217 2218 if (!this->emitLoad(*LT, LHS)) 2219 return false; 2220 2221 if (!visit(RHS)) 2222 return false; 2223 2224 if (Op == BO_AddAssign) { 2225 if (!this->emitAddOffset(*RT, E)) 2226 return false; 2227 } else { 2228 if (!this->emitSubOffset(*RT, E)) 2229 return false; 2230 } 2231 2232 if (DiscardResult) 2233 return this->emitStorePopPtr(E); 2234 return this->emitStorePtr(E); 2235 } 2236 2237 template <class Emitter> 2238 bool Compiler<Emitter>::VisitCompoundAssignOperator( 2239 const CompoundAssignOperator *E) { 2240 2241 const Expr *LHS = E->getLHS(); 2242 const Expr *RHS = E->getRHS(); 2243 std::optional<PrimType> LHSComputationT = 2244 classify(E->getComputationLHSType()); 2245 std::optional<PrimType> LT = classify(LHS->getType()); 2246 std::optional<PrimType> RT = classify(RHS->getType()); 2247 std::optional<PrimType> ResultT = classify(E->getType()); 2248 2249 if (!Ctx.getLangOpts().CPlusPlus14) 2250 return this->visit(RHS) && this->visit(LHS) && this->emitError(E); 2251 2252 if (!LT || !RT || !ResultT || !LHSComputationT) 2253 return false; 2254 2255 // Handle floating point operations separately here, since they 2256 // require special care. 2257 2258 if (ResultT == PT_Float || RT == PT_Float) 2259 return VisitFloatCompoundAssignOperator(E); 2260 2261 if (E->getType()->isPointerType()) 2262 return VisitPointerCompoundAssignOperator(E); 2263 2264 assert(!E->getType()->isPointerType() && "Handled above"); 2265 assert(!E->getType()->isFloatingType() && "Handled above"); 2266 2267 // C++17 onwards require that we evaluate the RHS first. 2268 // Compute RHS and save it in a temporary variable so we can 2269 // load it again later. 2270 // FIXME: Compound assignments are unsequenced in C, so we might 2271 // have to figure out how to reject them. 2272 if (!visit(RHS)) 2273 return false; 2274 2275 unsigned TempOffset = this->allocateLocalPrimitive(E, *RT, /*IsConst=*/true); 2276 2277 if (!this->emitSetLocal(*RT, TempOffset, E)) 2278 return false; 2279 2280 // Get LHS pointer, load its value and cast it to the 2281 // computation type if necessary. 2282 if (!visit(LHS)) 2283 return false; 2284 if (!this->emitLoad(*LT, E)) 2285 return false; 2286 if (LT != LHSComputationT) { 2287 if (!this->emitCast(*LT, *LHSComputationT, E)) 2288 return false; 2289 } 2290 2291 // Get the RHS value on the stack. 2292 if (!this->emitGetLocal(*RT, TempOffset, E)) 2293 return false; 2294 2295 // Perform operation. 2296 switch (E->getOpcode()) { 2297 case BO_AddAssign: 2298 if (!this->emitAdd(*LHSComputationT, E)) 2299 return false; 2300 break; 2301 case BO_SubAssign: 2302 if (!this->emitSub(*LHSComputationT, E)) 2303 return false; 2304 break; 2305 case BO_MulAssign: 2306 if (!this->emitMul(*LHSComputationT, E)) 2307 return false; 2308 break; 2309 case BO_DivAssign: 2310 if (!this->emitDiv(*LHSComputationT, E)) 2311 return false; 2312 break; 2313 case BO_RemAssign: 2314 if (!this->emitRem(*LHSComputationT, E)) 2315 return false; 2316 break; 2317 case BO_ShlAssign: 2318 if (!this->emitShl(*LHSComputationT, *RT, E)) 2319 return false; 2320 break; 2321 case BO_ShrAssign: 2322 if (!this->emitShr(*LHSComputationT, *RT, E)) 2323 return false; 2324 break; 2325 case BO_AndAssign: 2326 if (!this->emitBitAnd(*LHSComputationT, E)) 2327 return false; 2328 break; 2329 case BO_XorAssign: 2330 if (!this->emitBitXor(*LHSComputationT, E)) 2331 return false; 2332 break; 2333 case BO_OrAssign: 2334 if (!this->emitBitOr(*LHSComputationT, E)) 2335 return false; 2336 break; 2337 default: 2338 llvm_unreachable("Unimplemented compound assign operator"); 2339 } 2340 2341 // And now cast from LHSComputationT to ResultT. 2342 if (ResultT != LHSComputationT) { 2343 if (!this->emitCast(*LHSComputationT, *ResultT, E)) 2344 return false; 2345 } 2346 2347 // And store the result in LHS. 2348 if (DiscardResult) { 2349 if (LHS->refersToBitField()) 2350 return this->emitStoreBitFieldPop(*ResultT, E); 2351 return this->emitStorePop(*ResultT, E); 2352 } 2353 if (LHS->refersToBitField()) 2354 return this->emitStoreBitField(*ResultT, E); 2355 return this->emitStore(*ResultT, E); 2356 } 2357 2358 template <class Emitter> 2359 bool Compiler<Emitter>::VisitExprWithCleanups(const ExprWithCleanups *E) { 2360 LocalScope<Emitter> ES(this); 2361 const Expr *SubExpr = E->getSubExpr(); 2362 2363 return this->delegate(SubExpr) && ES.destroyLocals(E); 2364 } 2365 2366 template <class Emitter> 2367 bool Compiler<Emitter>::VisitMaterializeTemporaryExpr( 2368 const MaterializeTemporaryExpr *E) { 2369 const Expr *SubExpr = E->getSubExpr(); 2370 2371 if (Initializing) { 2372 // We already have a value, just initialize that. 2373 return this->delegate(SubExpr); 2374 } 2375 // If we don't end up using the materialized temporary anyway, don't 2376 // bother creating it. 2377 if (DiscardResult) 2378 return this->discard(SubExpr); 2379 2380 // When we're initializing a global variable *or* the storage duration of 2381 // the temporary is explicitly static, create a global variable. 2382 std::optional<PrimType> SubExprT = classify(SubExpr); 2383 bool IsStatic = E->getStorageDuration() == SD_Static; 2384 if (IsStatic) { 2385 std::optional<unsigned> GlobalIndex = P.createGlobal(E); 2386 if (!GlobalIndex) 2387 return false; 2388 2389 const LifetimeExtendedTemporaryDecl *TempDecl = 2390 E->getLifetimeExtendedTemporaryDecl(); 2391 if (IsStatic) 2392 assert(TempDecl); 2393 2394 if (SubExprT) { 2395 if (!this->visit(SubExpr)) 2396 return false; 2397 if (IsStatic) { 2398 if (!this->emitInitGlobalTemp(*SubExprT, *GlobalIndex, TempDecl, E)) 2399 return false; 2400 } else { 2401 if (!this->emitInitGlobal(*SubExprT, *GlobalIndex, E)) 2402 return false; 2403 } 2404 return this->emitGetPtrGlobal(*GlobalIndex, E); 2405 } 2406 2407 // Non-primitive values. 2408 if (!this->emitGetPtrGlobal(*GlobalIndex, E)) 2409 return false; 2410 if (!this->visitInitializer(SubExpr)) 2411 return false; 2412 if (IsStatic) 2413 return this->emitInitGlobalTempComp(TempDecl, E); 2414 return true; 2415 } 2416 2417 // For everyhing else, use local variables. 2418 if (SubExprT) { 2419 unsigned LocalIndex = allocateLocalPrimitive(E, *SubExprT, /*IsConst=*/true, 2420 /*IsExtended=*/true); 2421 if (!this->visit(SubExpr)) 2422 return false; 2423 if (!this->emitSetLocal(*SubExprT, LocalIndex, E)) 2424 return false; 2425 return this->emitGetPtrLocal(LocalIndex, E); 2426 } else { 2427 const Expr *Inner = E->getSubExpr()->skipRValueSubobjectAdjustments(); 2428 if (std::optional<unsigned> LocalIndex = 2429 allocateLocal(Inner, E->getExtendingDecl())) { 2430 InitLinkScope<Emitter> ILS(this, InitLink::Temp(*LocalIndex)); 2431 if (!this->emitGetPtrLocal(*LocalIndex, E)) 2432 return false; 2433 return this->visitInitializer(SubExpr); 2434 } 2435 } 2436 return false; 2437 } 2438 2439 template <class Emitter> 2440 bool Compiler<Emitter>::VisitCXXBindTemporaryExpr( 2441 const CXXBindTemporaryExpr *E) { 2442 return this->delegate(E->getSubExpr()); 2443 } 2444 2445 template <class Emitter> 2446 bool Compiler<Emitter>::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 2447 const Expr *Init = E->getInitializer(); 2448 if (DiscardResult) 2449 return this->discard(Init); 2450 2451 if (Initializing) { 2452 // We already have a value, just initialize that. 2453 return this->visitInitializer(Init) && this->emitFinishInit(E); 2454 } 2455 2456 std::optional<PrimType> T = classify(E->getType()); 2457 if (E->isFileScope()) { 2458 // Avoid creating a variable if this is a primitive RValue anyway. 2459 if (T && !E->isLValue()) 2460 return this->delegate(Init); 2461 2462 if (std::optional<unsigned> GlobalIndex = P.createGlobal(E)) { 2463 if (!this->emitGetPtrGlobal(*GlobalIndex, E)) 2464 return false; 2465 2466 if (T) { 2467 if (!this->visit(Init)) 2468 return false; 2469 return this->emitInitGlobal(*T, *GlobalIndex, E); 2470 } 2471 2472 return this->visitInitializer(Init) && this->emitFinishInit(E); 2473 } 2474 2475 return false; 2476 } 2477 2478 // Otherwise, use a local variable. 2479 if (T && !E->isLValue()) { 2480 // For primitive types, we just visit the initializer. 2481 return this->delegate(Init); 2482 } else { 2483 unsigned LocalIndex; 2484 2485 if (T) 2486 LocalIndex = this->allocateLocalPrimitive(Init, *T, false, false); 2487 else if (std::optional<unsigned> MaybeIndex = this->allocateLocal(Init)) 2488 LocalIndex = *MaybeIndex; 2489 else 2490 return false; 2491 2492 if (!this->emitGetPtrLocal(LocalIndex, E)) 2493 return false; 2494 2495 if (T) { 2496 if (!this->visit(Init)) { 2497 return false; 2498 } 2499 return this->emitInit(*T, E); 2500 } else { 2501 if (!this->visitInitializer(Init) || !this->emitFinishInit(E)) 2502 return false; 2503 } 2504 return true; 2505 } 2506 2507 return false; 2508 } 2509 2510 template <class Emitter> 2511 bool Compiler<Emitter>::VisitTypeTraitExpr(const TypeTraitExpr *E) { 2512 if (DiscardResult) 2513 return true; 2514 if (E->getType()->isBooleanType()) 2515 return this->emitConstBool(E->getValue(), E); 2516 return this->emitConst(E->getValue(), E); 2517 } 2518 2519 template <class Emitter> 2520 bool Compiler<Emitter>::VisitArrayTypeTraitExpr(const ArrayTypeTraitExpr *E) { 2521 if (DiscardResult) 2522 return true; 2523 return this->emitConst(E->getValue(), E); 2524 } 2525 2526 template <class Emitter> 2527 bool Compiler<Emitter>::VisitLambdaExpr(const LambdaExpr *E) { 2528 if (DiscardResult) 2529 return true; 2530 2531 assert(Initializing); 2532 const Record *R = P.getOrCreateRecord(E->getLambdaClass()); 2533 2534 auto *CaptureInitIt = E->capture_init_begin(); 2535 // Initialize all fields (which represent lambda captures) of the 2536 // record with their initializers. 2537 for (const Record::Field &F : R->fields()) { 2538 const Expr *Init = *CaptureInitIt; 2539 ++CaptureInitIt; 2540 2541 if (!Init) 2542 continue; 2543 2544 if (std::optional<PrimType> T = classify(Init)) { 2545 if (!this->visit(Init)) 2546 return false; 2547 2548 if (!this->emitInitField(*T, F.Offset, E)) 2549 return false; 2550 } else { 2551 if (!this->emitGetPtrField(F.Offset, E)) 2552 return false; 2553 2554 if (!this->visitInitializer(Init)) 2555 return false; 2556 2557 if (!this->emitPopPtr(E)) 2558 return false; 2559 } 2560 } 2561 2562 return true; 2563 } 2564 2565 template <class Emitter> 2566 bool Compiler<Emitter>::VisitPredefinedExpr(const PredefinedExpr *E) { 2567 if (DiscardResult) 2568 return true; 2569 2570 return this->delegate(E->getFunctionName()); 2571 } 2572 2573 template <class Emitter> 2574 bool Compiler<Emitter>::VisitCXXThrowExpr(const CXXThrowExpr *E) { 2575 if (E->getSubExpr() && !this->discard(E->getSubExpr())) 2576 return false; 2577 2578 return this->emitInvalid(E); 2579 } 2580 2581 template <class Emitter> 2582 bool Compiler<Emitter>::VisitCXXReinterpretCastExpr( 2583 const CXXReinterpretCastExpr *E) { 2584 const Expr *SubExpr = E->getSubExpr(); 2585 2586 bool Fatal = false; 2587 std::optional<PrimType> FromT = classify(SubExpr); 2588 std::optional<PrimType> ToT = classify(E); 2589 if (!FromT || !ToT) 2590 Fatal = true; 2591 else 2592 Fatal = (ToT != FromT); 2593 2594 if (!this->emitInvalidCast(CastKind::Reinterpret, Fatal, E)) 2595 return false; 2596 2597 return this->delegate(SubExpr); 2598 } 2599 2600 template <class Emitter> 2601 bool Compiler<Emitter>::VisitCXXNoexceptExpr(const CXXNoexceptExpr *E) { 2602 assert(E->getType()->isBooleanType()); 2603 2604 if (DiscardResult) 2605 return true; 2606 return this->emitConstBool(E->getValue(), E); 2607 } 2608 2609 template <class Emitter> 2610 bool Compiler<Emitter>::VisitCXXConstructExpr(const CXXConstructExpr *E) { 2611 QualType T = E->getType(); 2612 assert(!classify(T)); 2613 2614 if (T->isRecordType()) { 2615 const CXXConstructorDecl *Ctor = E->getConstructor(); 2616 2617 // Trivial copy/move constructor. Avoid copy. 2618 if (Ctor->isDefaulted() && Ctor->isCopyOrMoveConstructor() && 2619 Ctor->isTrivial() && 2620 E->getArg(0)->isTemporaryObject(Ctx.getASTContext(), 2621 T->getAsCXXRecordDecl())) 2622 return this->visitInitializer(E->getArg(0)); 2623 2624 // If we're discarding a construct expression, we still need 2625 // to allocate a variable and call the constructor and destructor. 2626 if (DiscardResult) { 2627 if (Ctor->isTrivial()) 2628 return true; 2629 assert(!Initializing); 2630 std::optional<unsigned> LocalIndex = allocateLocal(E); 2631 2632 if (!LocalIndex) 2633 return false; 2634 2635 if (!this->emitGetPtrLocal(*LocalIndex, E)) 2636 return false; 2637 } 2638 2639 // Zero initialization. 2640 if (E->requiresZeroInitialization()) { 2641 const Record *R = getRecord(E->getType()); 2642 2643 if (!this->visitZeroRecordInitializer(R, E)) 2644 return false; 2645 2646 // If the constructor is trivial anyway, we're done. 2647 if (Ctor->isTrivial()) 2648 return true; 2649 } 2650 2651 const Function *Func = getFunction(Ctor); 2652 2653 if (!Func) 2654 return false; 2655 2656 assert(Func->hasThisPointer()); 2657 assert(!Func->hasRVO()); 2658 2659 // The This pointer is already on the stack because this is an initializer, 2660 // but we need to dup() so the call() below has its own copy. 2661 if (!this->emitDupPtr(E)) 2662 return false; 2663 2664 // Constructor arguments. 2665 for (const auto *Arg : E->arguments()) { 2666 if (!this->visit(Arg)) 2667 return false; 2668 } 2669 2670 if (Func->isVariadic()) { 2671 uint32_t VarArgSize = 0; 2672 unsigned NumParams = Func->getNumWrittenParams(); 2673 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) { 2674 VarArgSize += 2675 align(primSize(classify(E->getArg(I)->getType()).value_or(PT_Ptr))); 2676 } 2677 if (!this->emitCallVar(Func, VarArgSize, E)) 2678 return false; 2679 } else { 2680 if (!this->emitCall(Func, 0, E)) { 2681 // When discarding, we don't need the result anyway, so clean up 2682 // the instance dup we did earlier in case surrounding code wants 2683 // to keep evaluating. 2684 if (DiscardResult) 2685 (void)this->emitPopPtr(E); 2686 return false; 2687 } 2688 } 2689 2690 if (DiscardResult) 2691 return this->emitPopPtr(E); 2692 return this->emitFinishInit(E); 2693 } 2694 2695 if (T->isArrayType()) { 2696 const ConstantArrayType *CAT = 2697 Ctx.getASTContext().getAsConstantArrayType(E->getType()); 2698 if (!CAT) 2699 return false; 2700 2701 size_t NumElems = CAT->getZExtSize(); 2702 const Function *Func = getFunction(E->getConstructor()); 2703 if (!Func || !Func->isConstexpr()) 2704 return false; 2705 2706 // FIXME(perf): We're calling the constructor once per array element here, 2707 // in the old intepreter we had a special-case for trivial constructors. 2708 for (size_t I = 0; I != NumElems; ++I) { 2709 if (!this->emitConstUint64(I, E)) 2710 return false; 2711 if (!this->emitArrayElemPtrUint64(E)) 2712 return false; 2713 2714 // Constructor arguments. 2715 for (const auto *Arg : E->arguments()) { 2716 if (!this->visit(Arg)) 2717 return false; 2718 } 2719 2720 if (!this->emitCall(Func, 0, E)) 2721 return false; 2722 } 2723 return true; 2724 } 2725 2726 return false; 2727 } 2728 2729 template <class Emitter> 2730 bool Compiler<Emitter>::VisitSourceLocExpr(const SourceLocExpr *E) { 2731 if (DiscardResult) 2732 return true; 2733 2734 const APValue Val = 2735 E->EvaluateInContext(Ctx.getASTContext(), SourceLocDefaultExpr); 2736 2737 // Things like __builtin_LINE(). 2738 if (E->getType()->isIntegerType()) { 2739 assert(Val.isInt()); 2740 const APSInt &I = Val.getInt(); 2741 return this->emitConst(I, E); 2742 } 2743 // Otherwise, the APValue is an LValue, with only one element. 2744 // Theoretically, we don't need the APValue at all of course. 2745 assert(E->getType()->isPointerType()); 2746 assert(Val.isLValue()); 2747 const APValue::LValueBase &Base = Val.getLValueBase(); 2748 if (const Expr *LValueExpr = Base.dyn_cast<const Expr *>()) 2749 return this->visit(LValueExpr); 2750 2751 // Otherwise, we have a decl (which is the case for 2752 // __builtin_source_location). 2753 assert(Base.is<const ValueDecl *>()); 2754 assert(Val.getLValuePath().size() == 0); 2755 const auto *BaseDecl = Base.dyn_cast<const ValueDecl *>(); 2756 assert(BaseDecl); 2757 2758 auto *UGCD = cast<UnnamedGlobalConstantDecl>(BaseDecl); 2759 2760 std::optional<unsigned> GlobalIndex = P.getOrCreateGlobal(UGCD); 2761 if (!GlobalIndex) 2762 return false; 2763 2764 if (!this->emitGetPtrGlobal(*GlobalIndex, E)) 2765 return false; 2766 2767 const Record *R = getRecord(E->getType()); 2768 const APValue &V = UGCD->getValue(); 2769 for (unsigned I = 0, N = R->getNumFields(); I != N; ++I) { 2770 const Record::Field *F = R->getField(I); 2771 const APValue &FieldValue = V.getStructField(I); 2772 2773 PrimType FieldT = classifyPrim(F->Decl->getType()); 2774 2775 if (!this->visitAPValue(FieldValue, FieldT, E)) 2776 return false; 2777 if (!this->emitInitField(FieldT, F->Offset, E)) 2778 return false; 2779 } 2780 2781 // Leave the pointer to the global on the stack. 2782 return true; 2783 } 2784 2785 template <class Emitter> 2786 bool Compiler<Emitter>::VisitOffsetOfExpr(const OffsetOfExpr *E) { 2787 unsigned N = E->getNumComponents(); 2788 if (N == 0) 2789 return false; 2790 2791 for (unsigned I = 0; I != N; ++I) { 2792 const OffsetOfNode &Node = E->getComponent(I); 2793 if (Node.getKind() == OffsetOfNode::Array) { 2794 const Expr *ArrayIndexExpr = E->getIndexExpr(Node.getArrayExprIndex()); 2795 PrimType IndexT = classifyPrim(ArrayIndexExpr->getType()); 2796 2797 if (DiscardResult) { 2798 if (!this->discard(ArrayIndexExpr)) 2799 return false; 2800 continue; 2801 } 2802 2803 if (!this->visit(ArrayIndexExpr)) 2804 return false; 2805 // Cast to Sint64. 2806 if (IndexT != PT_Sint64) { 2807 if (!this->emitCast(IndexT, PT_Sint64, E)) 2808 return false; 2809 } 2810 } 2811 } 2812 2813 if (DiscardResult) 2814 return true; 2815 2816 PrimType T = classifyPrim(E->getType()); 2817 return this->emitOffsetOf(T, E, E); 2818 } 2819 2820 template <class Emitter> 2821 bool Compiler<Emitter>::VisitCXXScalarValueInitExpr( 2822 const CXXScalarValueInitExpr *E) { 2823 QualType Ty = E->getType(); 2824 2825 if (DiscardResult || Ty->isVoidType()) 2826 return true; 2827 2828 if (std::optional<PrimType> T = classify(Ty)) 2829 return this->visitZeroInitializer(*T, Ty, E); 2830 2831 if (const auto *CT = Ty->getAs<ComplexType>()) { 2832 if (!Initializing) { 2833 std::optional<unsigned> LocalIndex = allocateLocal(E); 2834 if (!LocalIndex) 2835 return false; 2836 if (!this->emitGetPtrLocal(*LocalIndex, E)) 2837 return false; 2838 } 2839 2840 // Initialize both fields to 0. 2841 QualType ElemQT = CT->getElementType(); 2842 PrimType ElemT = classifyPrim(ElemQT); 2843 2844 for (unsigned I = 0; I != 2; ++I) { 2845 if (!this->visitZeroInitializer(ElemT, ElemQT, E)) 2846 return false; 2847 if (!this->emitInitElem(ElemT, I, E)) 2848 return false; 2849 } 2850 return true; 2851 } 2852 2853 if (const auto *VT = Ty->getAs<VectorType>()) { 2854 // FIXME: Code duplication with the _Complex case above. 2855 if (!Initializing) { 2856 std::optional<unsigned> LocalIndex = allocateLocal(E); 2857 if (!LocalIndex) 2858 return false; 2859 if (!this->emitGetPtrLocal(*LocalIndex, E)) 2860 return false; 2861 } 2862 2863 // Initialize all fields to 0. 2864 QualType ElemQT = VT->getElementType(); 2865 PrimType ElemT = classifyPrim(ElemQT); 2866 2867 for (unsigned I = 0, N = VT->getNumElements(); I != N; ++I) { 2868 if (!this->visitZeroInitializer(ElemT, ElemQT, E)) 2869 return false; 2870 if (!this->emitInitElem(ElemT, I, E)) 2871 return false; 2872 } 2873 return true; 2874 } 2875 2876 return false; 2877 } 2878 2879 template <class Emitter> 2880 bool Compiler<Emitter>::VisitSizeOfPackExpr(const SizeOfPackExpr *E) { 2881 return this->emitConst(E->getPackLength(), E); 2882 } 2883 2884 template <class Emitter> 2885 bool Compiler<Emitter>::VisitGenericSelectionExpr( 2886 const GenericSelectionExpr *E) { 2887 return this->delegate(E->getResultExpr()); 2888 } 2889 2890 template <class Emitter> 2891 bool Compiler<Emitter>::VisitChooseExpr(const ChooseExpr *E) { 2892 return this->delegate(E->getChosenSubExpr()); 2893 } 2894 2895 template <class Emitter> 2896 bool Compiler<Emitter>::VisitObjCBoolLiteralExpr(const ObjCBoolLiteralExpr *E) { 2897 if (DiscardResult) 2898 return true; 2899 2900 return this->emitConst(E->getValue(), E); 2901 } 2902 2903 template <class Emitter> 2904 bool Compiler<Emitter>::VisitCXXInheritedCtorInitExpr( 2905 const CXXInheritedCtorInitExpr *E) { 2906 const CXXConstructorDecl *Ctor = E->getConstructor(); 2907 assert(!Ctor->isTrivial() && 2908 "Trivial CXXInheritedCtorInitExpr, implement. (possible?)"); 2909 const Function *F = this->getFunction(Ctor); 2910 assert(F); 2911 assert(!F->hasRVO()); 2912 assert(F->hasThisPointer()); 2913 2914 if (!this->emitDupPtr(SourceInfo{})) 2915 return false; 2916 2917 // Forward all arguments of the current function (which should be a 2918 // constructor itself) to the inherited ctor. 2919 // This is necessary because the calling code has pushed the pointer 2920 // of the correct base for us already, but the arguments need 2921 // to come after. 2922 unsigned Offset = align(primSize(PT_Ptr)); // instance pointer. 2923 for (const ParmVarDecl *PD : Ctor->parameters()) { 2924 PrimType PT = this->classify(PD->getType()).value_or(PT_Ptr); 2925 2926 if (!this->emitGetParam(PT, Offset, E)) 2927 return false; 2928 Offset += align(primSize(PT)); 2929 } 2930 2931 return this->emitCall(F, 0, E); 2932 } 2933 2934 template <class Emitter> 2935 bool Compiler<Emitter>::VisitCXXNewExpr(const CXXNewExpr *E) { 2936 assert(classifyPrim(E->getType()) == PT_Ptr); 2937 const Expr *Init = E->getInitializer(); 2938 QualType ElementType = E->getAllocatedType(); 2939 std::optional<PrimType> ElemT = classify(ElementType); 2940 unsigned PlacementArgs = E->getNumPlacementArgs(); 2941 bool IsNoThrow = false; 2942 2943 // FIXME: Better diagnostic. diag::note_constexpr_new_placement 2944 if (PlacementArgs != 0) { 2945 // The only new-placement list we support is of the form (std::nothrow). 2946 // 2947 // FIXME: There is no restriction on this, but it's not clear that any 2948 // other form makes any sense. We get here for cases such as: 2949 // 2950 // new (std::align_val_t{N}) X(int) 2951 // 2952 // (which should presumably be valid only if N is a multiple of 2953 // alignof(int), and in any case can't be deallocated unless N is 2954 // alignof(X) and X has new-extended alignment). 2955 if (PlacementArgs != 1 || !E->getPlacementArg(0)->getType()->isNothrowT()) 2956 return this->emitInvalid(E); 2957 2958 if (!this->discard(E->getPlacementArg(0))) 2959 return false; 2960 IsNoThrow = true; 2961 } 2962 2963 const Descriptor *Desc; 2964 if (ElemT) { 2965 if (E->isArray()) 2966 Desc = nullptr; // We're not going to use it in this case. 2967 else 2968 Desc = P.createDescriptor(E, *ElemT, Descriptor::InlineDescMD, 2969 /*IsConst=*/false, /*IsTemporary=*/false, 2970 /*IsMutable=*/false); 2971 } else { 2972 Desc = P.createDescriptor( 2973 E, ElementType.getTypePtr(), 2974 E->isArray() ? std::nullopt : Descriptor::InlineDescMD, 2975 /*IsConst=*/false, /*IsTemporary=*/false, /*IsMutable=*/false, Init); 2976 } 2977 2978 if (E->isArray()) { 2979 std::optional<const Expr *> ArraySizeExpr = E->getArraySize(); 2980 if (!ArraySizeExpr) 2981 return false; 2982 2983 const Expr *Stripped = *ArraySizeExpr; 2984 for (; auto *ICE = dyn_cast<ImplicitCastExpr>(Stripped); 2985 Stripped = ICE->getSubExpr()) 2986 if (ICE->getCastKind() != CK_NoOp && 2987 ICE->getCastKind() != CK_IntegralCast) 2988 break; 2989 2990 PrimType SizeT = classifyPrim(Stripped->getType()); 2991 2992 if (!this->visit(Stripped)) 2993 return false; 2994 2995 if (ElemT) { 2996 // N primitive elements. 2997 if (!this->emitAllocN(SizeT, *ElemT, E, IsNoThrow, E)) 2998 return false; 2999 } else { 3000 // N Composite elements. 3001 if (!this->emitAllocCN(SizeT, Desc, IsNoThrow, E)) 3002 return false; 3003 } 3004 3005 if (Init && !this->visitInitializer(Init)) 3006 return false; 3007 3008 } else { 3009 // Allocate just one element. 3010 if (!this->emitAlloc(Desc, E)) 3011 return false; 3012 3013 if (Init) { 3014 if (ElemT) { 3015 if (!this->visit(Init)) 3016 return false; 3017 3018 if (!this->emitInit(*ElemT, E)) 3019 return false; 3020 } else { 3021 // Composite. 3022 if (!this->visitInitializer(Init)) 3023 return false; 3024 } 3025 } 3026 } 3027 3028 if (DiscardResult) 3029 return this->emitPopPtr(E); 3030 3031 return true; 3032 } 3033 3034 template <class Emitter> 3035 bool Compiler<Emitter>::VisitCXXDeleteExpr(const CXXDeleteExpr *E) { 3036 const Expr *Arg = E->getArgument(); 3037 3038 // Arg must be an lvalue. 3039 if (!this->visit(Arg)) 3040 return false; 3041 3042 return this->emitFree(E->isArrayForm(), E); 3043 } 3044 3045 template <class Emitter> 3046 bool Compiler<Emitter>::VisitBlockExpr(const BlockExpr *E) { 3047 const Function *Func = nullptr; 3048 if (auto F = Compiler<ByteCodeEmitter>(Ctx, P).compileObjCBlock(E)) 3049 Func = F; 3050 3051 if (!Func) 3052 return false; 3053 return this->emitGetFnPtr(Func, E); 3054 } 3055 3056 template <class Emitter> 3057 bool Compiler<Emitter>::VisitExpressionTraitExpr(const ExpressionTraitExpr *E) { 3058 assert(Ctx.getLangOpts().CPlusPlus); 3059 return this->emitConstBool(E->getValue(), E); 3060 } 3061 3062 template <class Emitter> 3063 bool Compiler<Emitter>::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 3064 if (DiscardResult) 3065 return true; 3066 assert(!Initializing); 3067 3068 const MSGuidDecl *GuidDecl = E->getGuidDecl(); 3069 const RecordDecl *RD = GuidDecl->getType()->getAsRecordDecl(); 3070 assert(RD); 3071 // If the definiton of the result type is incomplete, just return a dummy. 3072 // If (and when) that is read from, we will fail, but not now. 3073 if (!RD->isCompleteDefinition()) { 3074 if (std::optional<unsigned> I = P.getOrCreateDummy(GuidDecl)) 3075 return this->emitGetPtrGlobal(*I, E); 3076 return false; 3077 } 3078 3079 std::optional<unsigned> GlobalIndex = P.getOrCreateGlobal(GuidDecl); 3080 if (!GlobalIndex) 3081 return false; 3082 if (!this->emitGetPtrGlobal(*GlobalIndex, E)) 3083 return false; 3084 3085 assert(this->getRecord(E->getType())); 3086 3087 const APValue &V = GuidDecl->getAsAPValue(); 3088 if (V.getKind() == APValue::None) 3089 return true; 3090 3091 assert(V.isStruct()); 3092 assert(V.getStructNumBases() == 0); 3093 if (!this->visitAPValueInitializer(V, E)) 3094 return false; 3095 3096 return this->emitFinishInit(E); 3097 } 3098 3099 template <class Emitter> 3100 bool Compiler<Emitter>::VisitRequiresExpr(const RequiresExpr *E) { 3101 assert(classifyPrim(E->getType()) == PT_Bool); 3102 if (DiscardResult) 3103 return true; 3104 return this->emitConstBool(E->isSatisfied(), E); 3105 } 3106 3107 template <class Emitter> 3108 bool Compiler<Emitter>::VisitConceptSpecializationExpr( 3109 const ConceptSpecializationExpr *E) { 3110 assert(classifyPrim(E->getType()) == PT_Bool); 3111 if (DiscardResult) 3112 return true; 3113 return this->emitConstBool(E->isSatisfied(), E); 3114 } 3115 3116 template <class Emitter> 3117 bool Compiler<Emitter>::VisitCXXRewrittenBinaryOperator( 3118 const CXXRewrittenBinaryOperator *E) { 3119 return this->delegate(E->getSemanticForm()); 3120 } 3121 3122 template <class Emitter> 3123 bool Compiler<Emitter>::VisitPseudoObjectExpr(const PseudoObjectExpr *E) { 3124 3125 for (const Expr *SemE : E->semantics()) { 3126 if (auto *OVE = dyn_cast<OpaqueValueExpr>(SemE)) { 3127 if (SemE == E->getResultExpr()) 3128 return false; 3129 3130 if (OVE->isUnique()) 3131 continue; 3132 3133 if (!this->discard(OVE)) 3134 return false; 3135 } else if (SemE == E->getResultExpr()) { 3136 if (!this->delegate(SemE)) 3137 return false; 3138 } else { 3139 if (!this->discard(SemE)) 3140 return false; 3141 } 3142 } 3143 return true; 3144 } 3145 3146 template <class Emitter> 3147 bool Compiler<Emitter>::VisitPackIndexingExpr(const PackIndexingExpr *E) { 3148 return this->delegate(E->getSelectedExpr()); 3149 } 3150 3151 template <class Emitter> 3152 bool Compiler<Emitter>::VisitRecoveryExpr(const RecoveryExpr *E) { 3153 return this->emitError(E); 3154 } 3155 3156 template <class Emitter> 3157 bool Compiler<Emitter>::VisitAddrLabelExpr(const AddrLabelExpr *E) { 3158 assert(E->getType()->isVoidPointerType()); 3159 3160 unsigned Offset = allocateLocalPrimitive( 3161 E->getLabel(), PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false); 3162 3163 return this->emitGetLocal(PT_Ptr, Offset, E); 3164 } 3165 3166 template <class Emitter> 3167 bool Compiler<Emitter>::VisitConvertVectorExpr(const ConvertVectorExpr *E) { 3168 assert(Initializing); 3169 const auto *VT = E->getType()->castAs<VectorType>(); 3170 QualType ElemType = VT->getElementType(); 3171 PrimType ElemT = classifyPrim(ElemType); 3172 const Expr *Src = E->getSrcExpr(); 3173 PrimType SrcElemT = 3174 classifyPrim(Src->getType()->castAs<VectorType>()->getElementType()); 3175 3176 unsigned SrcOffset = this->allocateLocalPrimitive(Src, PT_Ptr, true, false); 3177 if (!this->visit(Src)) 3178 return false; 3179 if (!this->emitSetLocal(PT_Ptr, SrcOffset, E)) 3180 return false; 3181 3182 for (unsigned I = 0; I != VT->getNumElements(); ++I) { 3183 if (!this->emitGetLocal(PT_Ptr, SrcOffset, E)) 3184 return false; 3185 if (!this->emitArrayElemPop(SrcElemT, I, E)) 3186 return false; 3187 if (SrcElemT != ElemT) { 3188 if (!this->emitPrimCast(SrcElemT, ElemT, ElemType, E)) 3189 return false; 3190 } 3191 if (!this->emitInitElem(ElemT, I, E)) 3192 return false; 3193 } 3194 3195 return true; 3196 } 3197 3198 template <class Emitter> 3199 bool Compiler<Emitter>::VisitShuffleVectorExpr(const ShuffleVectorExpr *E) { 3200 assert(Initializing); 3201 assert(E->getNumSubExprs() > 2); 3202 3203 const Expr *Vecs[] = {E->getExpr(0), E->getExpr(1)}; 3204 const VectorType *VT = Vecs[0]->getType()->castAs<VectorType>(); 3205 PrimType ElemT = classifyPrim(VT->getElementType()); 3206 unsigned NumInputElems = VT->getNumElements(); 3207 unsigned NumOutputElems = E->getNumSubExprs() - 2; 3208 assert(NumOutputElems > 0); 3209 3210 // Save both input vectors to a local variable. 3211 unsigned VectorOffsets[2]; 3212 for (unsigned I = 0; I != 2; ++I) { 3213 VectorOffsets[I] = this->allocateLocalPrimitive( 3214 Vecs[I], PT_Ptr, /*IsConst=*/true, /*IsExtended=*/false); 3215 if (!this->visit(Vecs[I])) 3216 return false; 3217 if (!this->emitSetLocal(PT_Ptr, VectorOffsets[I], E)) 3218 return false; 3219 } 3220 for (unsigned I = 0; I != NumOutputElems; ++I) { 3221 APSInt ShuffleIndex = E->getShuffleMaskIdx(Ctx.getASTContext(), I); 3222 if (ShuffleIndex == -1) 3223 return this->emitInvalid(E); // FIXME: Better diagnostic. 3224 3225 assert(ShuffleIndex < (NumInputElems * 2)); 3226 if (!this->emitGetLocal(PT_Ptr, 3227 VectorOffsets[ShuffleIndex >= NumInputElems], E)) 3228 return false; 3229 unsigned InputVectorIndex = ShuffleIndex.getZExtValue() % NumInputElems; 3230 if (!this->emitArrayElemPop(ElemT, InputVectorIndex, E)) 3231 return false; 3232 3233 if (!this->emitInitElem(ElemT, I, E)) 3234 return false; 3235 } 3236 3237 return true; 3238 } 3239 3240 template <class Emitter> 3241 bool Compiler<Emitter>::VisitExtVectorElementExpr( 3242 const ExtVectorElementExpr *E) { 3243 const Expr *Base = E->getBase(); 3244 assert( 3245 Base->getType()->isVectorType() || 3246 Base->getType()->getAs<PointerType>()->getPointeeType()->isVectorType()); 3247 3248 SmallVector<uint32_t, 4> Indices; 3249 E->getEncodedElementAccess(Indices); 3250 3251 if (Indices.size() == 1) { 3252 if (!this->visit(Base)) 3253 return false; 3254 3255 if (E->isGLValue()) { 3256 if (!this->emitConstUint32(Indices[0], E)) 3257 return false; 3258 return this->emitArrayElemPtrPop(PT_Uint32, E); 3259 } 3260 // Else, also load the value. 3261 return this->emitArrayElemPop(classifyPrim(E->getType()), Indices[0], E); 3262 } 3263 3264 // Create a local variable for the base. 3265 unsigned BaseOffset = allocateLocalPrimitive(Base, PT_Ptr, /*IsConst=*/true, 3266 /*IsExtended=*/false); 3267 if (!this->visit(Base)) 3268 return false; 3269 if (!this->emitSetLocal(PT_Ptr, BaseOffset, E)) 3270 return false; 3271 3272 // Now the vector variable for the return value. 3273 if (!Initializing) { 3274 std::optional<unsigned> ResultIndex; 3275 ResultIndex = allocateLocal(E); 3276 if (!ResultIndex) 3277 return false; 3278 if (!this->emitGetPtrLocal(*ResultIndex, E)) 3279 return false; 3280 } 3281 3282 assert(Indices.size() == E->getType()->getAs<VectorType>()->getNumElements()); 3283 3284 PrimType ElemT = 3285 classifyPrim(E->getType()->getAs<VectorType>()->getElementType()); 3286 uint32_t DstIndex = 0; 3287 for (uint32_t I : Indices) { 3288 if (!this->emitGetLocal(PT_Ptr, BaseOffset, E)) 3289 return false; 3290 if (!this->emitArrayElemPop(ElemT, I, E)) 3291 return false; 3292 if (!this->emitInitElem(ElemT, DstIndex, E)) 3293 return false; 3294 ++DstIndex; 3295 } 3296 3297 // Leave the result pointer on the stack. 3298 assert(!DiscardResult); 3299 return true; 3300 } 3301 3302 template <class Emitter> 3303 bool Compiler<Emitter>::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 3304 const Expr *SubExpr = E->getSubExpr(); 3305 if (!E->isExpressibleAsConstantInitializer()) 3306 return this->discard(SubExpr) && this->emitInvalid(E); 3307 3308 return this->delegate(SubExpr); 3309 } 3310 3311 template <class Emitter> 3312 bool Compiler<Emitter>::VisitCXXStdInitializerListExpr( 3313 const CXXStdInitializerListExpr *E) { 3314 const Expr *SubExpr = E->getSubExpr(); 3315 const ConstantArrayType *ArrayType = 3316 Ctx.getASTContext().getAsConstantArrayType(SubExpr->getType()); 3317 const Record *R = getRecord(E->getType()); 3318 assert(Initializing); 3319 assert(SubExpr->isGLValue()); 3320 3321 if (!this->visit(SubExpr)) 3322 return false; 3323 if (!this->emitInitFieldPtr(R->getField(0u)->Offset, E)) 3324 return false; 3325 3326 PrimType SecondFieldT = classifyPrim(R->getField(1u)->Decl->getType()); 3327 if (isIntegralType(SecondFieldT)) { 3328 if (!this->emitConst(static_cast<APSInt>(ArrayType->getSize()), 3329 SecondFieldT, E)) 3330 return false; 3331 return this->emitInitField(SecondFieldT, R->getField(1u)->Offset, E); 3332 } 3333 assert(SecondFieldT == PT_Ptr); 3334 3335 if (!this->emitGetFieldPtr(R->getField(0u)->Offset, E)) 3336 return false; 3337 if (!this->emitConst(static_cast<APSInt>(ArrayType->getSize()), PT_Uint64, E)) 3338 return false; 3339 if (!this->emitArrayElemPtrPop(PT_Uint64, E)) 3340 return false; 3341 return this->emitInitFieldPtr(R->getField(1u)->Offset, E); 3342 } 3343 3344 template <class Emitter> 3345 bool Compiler<Emitter>::VisitStmtExpr(const StmtExpr *E) { 3346 BlockScope<Emitter> BS(this); 3347 StmtExprScope<Emitter> SS(this); 3348 3349 const CompoundStmt *CS = E->getSubStmt(); 3350 const Stmt *Result = CS->getStmtExprResult(); 3351 for (const Stmt *S : CS->body()) { 3352 if (S != Result) { 3353 if (!this->visitStmt(S)) 3354 return false; 3355 continue; 3356 } 3357 3358 assert(S == Result); 3359 if (const Expr *ResultExpr = dyn_cast<Expr>(S)) 3360 return this->delegate(ResultExpr); 3361 return this->emitUnsupported(E); 3362 } 3363 3364 return BS.destroyLocals(); 3365 } 3366 3367 template <class Emitter> bool Compiler<Emitter>::discard(const Expr *E) { 3368 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/true, 3369 /*NewInitializing=*/false); 3370 return this->Visit(E); 3371 } 3372 3373 template <class Emitter> bool Compiler<Emitter>::delegate(const Expr *E) { 3374 // We're basically doing: 3375 // OptionScope<Emitter> Scope(this, DicardResult, Initializing); 3376 // but that's unnecessary of course. 3377 return this->Visit(E); 3378 } 3379 3380 template <class Emitter> bool Compiler<Emitter>::visit(const Expr *E) { 3381 if (E->getType().isNull()) 3382 return false; 3383 3384 if (E->getType()->isVoidType()) 3385 return this->discard(E); 3386 3387 // Create local variable to hold the return value. 3388 if (!E->isGLValue() && !E->getType()->isAnyComplexType() && 3389 !classify(E->getType())) { 3390 std::optional<unsigned> LocalIndex = allocateLocal(E); 3391 if (!LocalIndex) 3392 return false; 3393 3394 if (!this->emitGetPtrLocal(*LocalIndex, E)) 3395 return false; 3396 return this->visitInitializer(E); 3397 } 3398 3399 // Otherwise,we have a primitive return value, produce the value directly 3400 // and push it on the stack. 3401 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false, 3402 /*NewInitializing=*/false); 3403 return this->Visit(E); 3404 } 3405 3406 template <class Emitter> 3407 bool Compiler<Emitter>::visitInitializer(const Expr *E) { 3408 assert(!classify(E->getType())); 3409 3410 if (!this->checkLiteralType(E)) 3411 return false; 3412 3413 OptionScope<Emitter> Scope(this, /*NewDiscardResult=*/false, 3414 /*NewInitializing=*/true); 3415 return this->Visit(E); 3416 } 3417 3418 template <class Emitter> bool Compiler<Emitter>::visitBool(const Expr *E) { 3419 std::optional<PrimType> T = classify(E->getType()); 3420 if (!T) { 3421 // Convert complex values to bool. 3422 if (E->getType()->isAnyComplexType()) { 3423 if (!this->visit(E)) 3424 return false; 3425 return this->emitComplexBoolCast(E); 3426 } 3427 return false; 3428 } 3429 3430 if (!this->visit(E)) 3431 return false; 3432 3433 if (T == PT_Bool) 3434 return true; 3435 3436 // Convert pointers to bool. 3437 if (T == PT_Ptr || T == PT_FnPtr) { 3438 if (!this->emitNull(*T, nullptr, E)) 3439 return false; 3440 return this->emitNE(*T, E); 3441 } 3442 3443 // Or Floats. 3444 if (T == PT_Float) 3445 return this->emitCastFloatingIntegralBool(getFPOptions(E), E); 3446 3447 // Or anything else we can. 3448 return this->emitCast(*T, PT_Bool, E); 3449 } 3450 3451 template <class Emitter> 3452 bool Compiler<Emitter>::visitZeroInitializer(PrimType T, QualType QT, 3453 const Expr *E) { 3454 switch (T) { 3455 case PT_Bool: 3456 return this->emitZeroBool(E); 3457 case PT_Sint8: 3458 return this->emitZeroSint8(E); 3459 case PT_Uint8: 3460 return this->emitZeroUint8(E); 3461 case PT_Sint16: 3462 return this->emitZeroSint16(E); 3463 case PT_Uint16: 3464 return this->emitZeroUint16(E); 3465 case PT_Sint32: 3466 return this->emitZeroSint32(E); 3467 case PT_Uint32: 3468 return this->emitZeroUint32(E); 3469 case PT_Sint64: 3470 return this->emitZeroSint64(E); 3471 case PT_Uint64: 3472 return this->emitZeroUint64(E); 3473 case PT_IntAP: 3474 return this->emitZeroIntAP(Ctx.getBitWidth(QT), E); 3475 case PT_IntAPS: 3476 return this->emitZeroIntAPS(Ctx.getBitWidth(QT), E); 3477 case PT_Ptr: 3478 return this->emitNullPtr(nullptr, E); 3479 case PT_FnPtr: 3480 return this->emitNullFnPtr(nullptr, E); 3481 case PT_MemberPtr: 3482 return this->emitNullMemberPtr(nullptr, E); 3483 case PT_Float: { 3484 return this->emitConstFloat(APFloat::getZero(Ctx.getFloatSemantics(QT)), E); 3485 } 3486 } 3487 llvm_unreachable("unknown primitive type"); 3488 } 3489 3490 template <class Emitter> 3491 bool Compiler<Emitter>::visitZeroRecordInitializer(const Record *R, 3492 const Expr *E) { 3493 assert(E); 3494 assert(R); 3495 // Fields 3496 for (const Record::Field &Field : R->fields()) { 3497 if (Field.Decl->isUnnamedBitField()) 3498 continue; 3499 3500 const Descriptor *D = Field.Desc; 3501 if (D->isPrimitive()) { 3502 QualType QT = D->getType(); 3503 PrimType T = classifyPrim(D->getType()); 3504 if (!this->visitZeroInitializer(T, QT, E)) 3505 return false; 3506 if (!this->emitInitField(T, Field.Offset, E)) 3507 return false; 3508 if (R->isUnion()) 3509 break; 3510 continue; 3511 } 3512 3513 if (!this->emitGetPtrField(Field.Offset, E)) 3514 return false; 3515 3516 if (D->isPrimitiveArray()) { 3517 QualType ET = D->getElemQualType(); 3518 PrimType T = classifyPrim(ET); 3519 for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) { 3520 if (!this->visitZeroInitializer(T, ET, E)) 3521 return false; 3522 if (!this->emitInitElem(T, I, E)) 3523 return false; 3524 } 3525 } else if (D->isCompositeArray()) { 3526 const Record *ElemRecord = D->ElemDesc->ElemRecord; 3527 assert(D->ElemDesc->ElemRecord); 3528 for (uint32_t I = 0, N = D->getNumElems(); I != N; ++I) { 3529 if (!this->emitConstUint32(I, E)) 3530 return false; 3531 if (!this->emitArrayElemPtr(PT_Uint32, E)) 3532 return false; 3533 if (!this->visitZeroRecordInitializer(ElemRecord, E)) 3534 return false; 3535 if (!this->emitPopPtr(E)) 3536 return false; 3537 } 3538 } else if (D->isRecord()) { 3539 if (!this->visitZeroRecordInitializer(D->ElemRecord, E)) 3540 return false; 3541 } else { 3542 assert(false); 3543 } 3544 3545 if (!this->emitFinishInitPop(E)) 3546 return false; 3547 3548 // C++11 [dcl.init]p5: If T is a (possibly cv-qualified) union type, the 3549 // object's first non-static named data member is zero-initialized 3550 if (R->isUnion()) 3551 break; 3552 } 3553 3554 for (const Record::Base &B : R->bases()) { 3555 if (!this->emitGetPtrBase(B.Offset, E)) 3556 return false; 3557 if (!this->visitZeroRecordInitializer(B.R, E)) 3558 return false; 3559 if (!this->emitFinishInitPop(E)) 3560 return false; 3561 } 3562 3563 // FIXME: Virtual bases. 3564 3565 return true; 3566 } 3567 3568 template <class Emitter> 3569 template <typename T> 3570 bool Compiler<Emitter>::emitConst(T Value, PrimType Ty, const Expr *E) { 3571 switch (Ty) { 3572 case PT_Sint8: 3573 return this->emitConstSint8(Value, E); 3574 case PT_Uint8: 3575 return this->emitConstUint8(Value, E); 3576 case PT_Sint16: 3577 return this->emitConstSint16(Value, E); 3578 case PT_Uint16: 3579 return this->emitConstUint16(Value, E); 3580 case PT_Sint32: 3581 return this->emitConstSint32(Value, E); 3582 case PT_Uint32: 3583 return this->emitConstUint32(Value, E); 3584 case PT_Sint64: 3585 return this->emitConstSint64(Value, E); 3586 case PT_Uint64: 3587 return this->emitConstUint64(Value, E); 3588 case PT_Bool: 3589 return this->emitConstBool(Value, E); 3590 case PT_Ptr: 3591 case PT_FnPtr: 3592 case PT_MemberPtr: 3593 case PT_Float: 3594 case PT_IntAP: 3595 case PT_IntAPS: 3596 llvm_unreachable("Invalid integral type"); 3597 break; 3598 } 3599 llvm_unreachable("unknown primitive type"); 3600 } 3601 3602 template <class Emitter> 3603 template <typename T> 3604 bool Compiler<Emitter>::emitConst(T Value, const Expr *E) { 3605 return this->emitConst(Value, classifyPrim(E->getType()), E); 3606 } 3607 3608 template <class Emitter> 3609 bool Compiler<Emitter>::emitConst(const APSInt &Value, PrimType Ty, 3610 const Expr *E) { 3611 if (Ty == PT_IntAPS) 3612 return this->emitConstIntAPS(Value, E); 3613 if (Ty == PT_IntAP) 3614 return this->emitConstIntAP(Value, E); 3615 3616 if (Value.isSigned()) 3617 return this->emitConst(Value.getSExtValue(), Ty, E); 3618 return this->emitConst(Value.getZExtValue(), Ty, E); 3619 } 3620 3621 template <class Emitter> 3622 bool Compiler<Emitter>::emitConst(const APSInt &Value, const Expr *E) { 3623 return this->emitConst(Value, classifyPrim(E->getType()), E); 3624 } 3625 3626 template <class Emitter> 3627 unsigned Compiler<Emitter>::allocateLocalPrimitive(DeclTy &&Src, PrimType Ty, 3628 bool IsConst, 3629 bool IsExtended) { 3630 // Make sure we don't accidentally register the same decl twice. 3631 if (const auto *VD = 3632 dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) { 3633 assert(!P.getGlobal(VD)); 3634 assert(!Locals.contains(VD)); 3635 (void)VD; 3636 } 3637 3638 // FIXME: There are cases where Src.is<Expr*>() is wrong, e.g. 3639 // (int){12} in C. Consider using Expr::isTemporaryObject() instead 3640 // or isa<MaterializeTemporaryExpr>(). 3641 Descriptor *D = P.createDescriptor(Src, Ty, Descriptor::InlineDescMD, IsConst, 3642 Src.is<const Expr *>()); 3643 Scope::Local Local = this->createLocal(D); 3644 if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) 3645 Locals.insert({VD, Local}); 3646 VarScope->add(Local, IsExtended); 3647 return Local.Offset; 3648 } 3649 3650 template <class Emitter> 3651 std::optional<unsigned> 3652 Compiler<Emitter>::allocateLocal(DeclTy &&Src, const ValueDecl *ExtendingDecl) { 3653 // Make sure we don't accidentally register the same decl twice. 3654 if ([[maybe_unused]] const auto *VD = 3655 dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) { 3656 assert(!P.getGlobal(VD)); 3657 assert(!Locals.contains(VD)); 3658 } 3659 3660 QualType Ty; 3661 const ValueDecl *Key = nullptr; 3662 const Expr *Init = nullptr; 3663 bool IsTemporary = false; 3664 if (auto *VD = dyn_cast_if_present<ValueDecl>(Src.dyn_cast<const Decl *>())) { 3665 Key = VD; 3666 Ty = VD->getType(); 3667 3668 if (const auto *VarD = dyn_cast<VarDecl>(VD)) 3669 Init = VarD->getInit(); 3670 } 3671 if (auto *E = Src.dyn_cast<const Expr *>()) { 3672 IsTemporary = true; 3673 Ty = E->getType(); 3674 } 3675 3676 Descriptor *D = P.createDescriptor( 3677 Src, Ty.getTypePtr(), Descriptor::InlineDescMD, Ty.isConstQualified(), 3678 IsTemporary, /*IsMutable=*/false, Init); 3679 if (!D) 3680 return std::nullopt; 3681 3682 Scope::Local Local = this->createLocal(D); 3683 if (Key) 3684 Locals.insert({Key, Local}); 3685 if (ExtendingDecl) 3686 VarScope->addExtended(Local, ExtendingDecl); 3687 else 3688 VarScope->add(Local, false); 3689 return Local.Offset; 3690 } 3691 3692 template <class Emitter> 3693 unsigned Compiler<Emitter>::allocateTemporary(const Expr *E) { 3694 QualType Ty = E->getType(); 3695 assert(!Ty->isRecordType()); 3696 3697 Descriptor *D = P.createDescriptor( 3698 E, Ty.getTypePtr(), Descriptor::InlineDescMD, Ty.isConstQualified(), 3699 /*IsTemporary=*/true, /*IsMutable=*/false, /*Init=*/nullptr); 3700 assert(D); 3701 3702 Scope::Local Local = this->createLocal(D); 3703 VariableScope<Emitter> *S = VarScope; 3704 assert(S); 3705 // Attach to topmost scope. 3706 while (S->getParent()) 3707 S = S->getParent(); 3708 assert(S && !S->getParent()); 3709 S->addLocal(Local); 3710 return Local.Offset; 3711 } 3712 3713 template <class Emitter> 3714 const RecordType *Compiler<Emitter>::getRecordTy(QualType Ty) { 3715 if (const PointerType *PT = dyn_cast<PointerType>(Ty)) 3716 return PT->getPointeeType()->getAs<RecordType>(); 3717 return Ty->getAs<RecordType>(); 3718 } 3719 3720 template <class Emitter> Record *Compiler<Emitter>::getRecord(QualType Ty) { 3721 if (const auto *RecordTy = getRecordTy(Ty)) 3722 return getRecord(RecordTy->getDecl()); 3723 return nullptr; 3724 } 3725 3726 template <class Emitter> 3727 Record *Compiler<Emitter>::getRecord(const RecordDecl *RD) { 3728 return P.getOrCreateRecord(RD); 3729 } 3730 3731 template <class Emitter> 3732 const Function *Compiler<Emitter>::getFunction(const FunctionDecl *FD) { 3733 return Ctx.getOrCreateFunction(FD); 3734 } 3735 3736 template <class Emitter> 3737 bool Compiler<Emitter>::visitExpr(const Expr *E, bool DestroyToplevelScope) { 3738 LocalScope<Emitter> RootScope(this); 3739 3740 auto maybeDestroyLocals = [&]() -> bool { 3741 if (DestroyToplevelScope) 3742 return RootScope.destroyLocals(); 3743 return true; 3744 }; 3745 3746 // Void expressions. 3747 if (E->getType()->isVoidType()) { 3748 if (!visit(E)) 3749 return false; 3750 return this->emitRetVoid(E) && maybeDestroyLocals(); 3751 } 3752 3753 // Expressions with a primitive return type. 3754 if (std::optional<PrimType> T = classify(E)) { 3755 if (!visit(E)) 3756 return false; 3757 3758 return this->emitRet(*T, E) && maybeDestroyLocals(); 3759 } 3760 3761 // Expressions with a composite return type. 3762 // For us, that means everything we don't 3763 // have a PrimType for. 3764 if (std::optional<unsigned> LocalOffset = this->allocateLocal(E)) { 3765 if (!this->emitGetPtrLocal(*LocalOffset, E)) 3766 return false; 3767 3768 if (!visitInitializer(E)) 3769 return false; 3770 3771 if (!this->emitFinishInit(E)) 3772 return false; 3773 // We are destroying the locals AFTER the Ret op. 3774 // The Ret op needs to copy the (alive) values, but the 3775 // destructors may still turn the entire expression invalid. 3776 return this->emitRetValue(E) && maybeDestroyLocals(); 3777 } 3778 3779 (void)maybeDestroyLocals(); 3780 return false; 3781 } 3782 3783 template <class Emitter> 3784 VarCreationState Compiler<Emitter>::visitDecl(const VarDecl *VD) { 3785 3786 auto R = this->visitVarDecl(VD, /*Toplevel=*/true); 3787 3788 if (R.notCreated()) 3789 return R; 3790 3791 if (R) 3792 return true; 3793 3794 if (!R && Context::shouldBeGloballyIndexed(VD)) { 3795 if (auto GlobalIndex = P.getGlobal(VD)) { 3796 Block *GlobalBlock = P.getGlobal(*GlobalIndex); 3797 GlobalInlineDescriptor &GD = 3798 *reinterpret_cast<GlobalInlineDescriptor *>(GlobalBlock->rawData()); 3799 3800 GD.InitState = GlobalInitState::InitializerFailed; 3801 GlobalBlock->invokeDtor(); 3802 } 3803 } 3804 3805 return R; 3806 } 3807 3808 /// Toplevel visitDeclAndReturn(). 3809 /// We get here from evaluateAsInitializer(). 3810 /// We need to evaluate the initializer and return its value. 3811 template <class Emitter> 3812 bool Compiler<Emitter>::visitDeclAndReturn(const VarDecl *VD, 3813 bool ConstantContext) { 3814 std::optional<PrimType> VarT = classify(VD->getType()); 3815 3816 // We only create variables if we're evaluating in a constant context. 3817 // Otherwise, just evaluate the initializer and return it. 3818 if (!ConstantContext) { 3819 DeclScope<Emitter> LS(this, VD); 3820 if (!this->visit(VD->getAnyInitializer())) 3821 return false; 3822 return this->emitRet(VarT.value_or(PT_Ptr), VD) && LS.destroyLocals(); 3823 } 3824 3825 LocalScope<Emitter> VDScope(this, VD); 3826 if (!this->visitVarDecl(VD, /*Toplevel=*/true)) 3827 return false; 3828 3829 if (Context::shouldBeGloballyIndexed(VD)) { 3830 auto GlobalIndex = P.getGlobal(VD); 3831 assert(GlobalIndex); // visitVarDecl() didn't return false. 3832 if (VarT) { 3833 if (!this->emitGetGlobalUnchecked(*VarT, *GlobalIndex, VD)) 3834 return false; 3835 } else { 3836 if (!this->emitGetPtrGlobal(*GlobalIndex, VD)) 3837 return false; 3838 } 3839 } else { 3840 auto Local = Locals.find(VD); 3841 assert(Local != Locals.end()); // Same here. 3842 if (VarT) { 3843 if (!this->emitGetLocal(*VarT, Local->second.Offset, VD)) 3844 return false; 3845 } else { 3846 if (!this->emitGetPtrLocal(Local->second.Offset, VD)) 3847 return false; 3848 } 3849 } 3850 3851 // Return the value. 3852 if (!this->emitRet(VarT.value_or(PT_Ptr), VD)) { 3853 // If the Ret above failed and this is a global variable, mark it as 3854 // uninitialized, even everything else succeeded. 3855 if (Context::shouldBeGloballyIndexed(VD)) { 3856 auto GlobalIndex = P.getGlobal(VD); 3857 assert(GlobalIndex); 3858 Block *GlobalBlock = P.getGlobal(*GlobalIndex); 3859 GlobalInlineDescriptor &GD = 3860 *reinterpret_cast<GlobalInlineDescriptor *>(GlobalBlock->rawData()); 3861 3862 GD.InitState = GlobalInitState::InitializerFailed; 3863 GlobalBlock->invokeDtor(); 3864 } 3865 return false; 3866 } 3867 3868 return VDScope.destroyLocals(); 3869 } 3870 3871 template <class Emitter> 3872 VarCreationState Compiler<Emitter>::visitVarDecl(const VarDecl *VD, 3873 bool Toplevel) { 3874 // We don't know what to do with these, so just return false. 3875 if (VD->getType().isNull()) 3876 return false; 3877 3878 // This case is EvalEmitter-only. If we won't create any instructions for the 3879 // initializer anyway, don't bother creating the variable in the first place. 3880 if (!this->isActive()) 3881 return VarCreationState::NotCreated(); 3882 3883 const Expr *Init = VD->getInit(); 3884 std::optional<PrimType> VarT = classify(VD->getType()); 3885 3886 if (Init && Init->isValueDependent()) 3887 return false; 3888 3889 if (Context::shouldBeGloballyIndexed(VD)) { 3890 auto checkDecl = [&]() -> bool { 3891 bool NeedsOp = !Toplevel && VD->isLocalVarDecl() && VD->isStaticLocal(); 3892 return !NeedsOp || this->emitCheckDecl(VD, VD); 3893 }; 3894 3895 auto initGlobal = [&](unsigned GlobalIndex) -> bool { 3896 assert(Init); 3897 3898 if (VarT) { 3899 if (!this->visit(Init)) 3900 return checkDecl() && false; 3901 3902 return checkDecl() && this->emitInitGlobal(*VarT, GlobalIndex, VD); 3903 } 3904 3905 if (!checkDecl()) 3906 return false; 3907 3908 if (!this->emitGetPtrGlobal(GlobalIndex, Init)) 3909 return false; 3910 3911 if (!visitInitializer(Init)) 3912 return false; 3913 3914 if (!this->emitFinishInit(Init)) 3915 return false; 3916 3917 return this->emitPopPtr(Init); 3918 }; 3919 3920 DeclScope<Emitter> LocalScope(this, VD); 3921 3922 // We've already seen and initialized this global. 3923 if (std::optional<unsigned> GlobalIndex = P.getGlobal(VD)) { 3924 if (P.getPtrGlobal(*GlobalIndex).isInitialized()) 3925 return checkDecl(); 3926 3927 // The previous attempt at initialization might've been unsuccessful, 3928 // so let's try this one. 3929 return Init && checkDecl() && initGlobal(*GlobalIndex); 3930 } 3931 3932 std::optional<unsigned> GlobalIndex = P.createGlobal(VD, Init); 3933 3934 if (!GlobalIndex) 3935 return false; 3936 3937 return !Init || (checkDecl() && initGlobal(*GlobalIndex)); 3938 } else { 3939 InitLinkScope<Emitter> ILS(this, InitLink::Decl(VD)); 3940 3941 if (VarT) { 3942 unsigned Offset = this->allocateLocalPrimitive( 3943 VD, *VarT, VD->getType().isConstQualified()); 3944 if (Init) { 3945 // If this is a toplevel declaration, create a scope for the 3946 // initializer. 3947 if (Toplevel) { 3948 LocalScope<Emitter> Scope(this); 3949 if (!this->visit(Init)) 3950 return false; 3951 return this->emitSetLocal(*VarT, Offset, VD) && Scope.destroyLocals(); 3952 } else { 3953 if (!this->visit(Init)) 3954 return false; 3955 return this->emitSetLocal(*VarT, Offset, VD); 3956 } 3957 } 3958 } else { 3959 if (std::optional<unsigned> Offset = this->allocateLocal(VD)) { 3960 if (!Init) 3961 return true; 3962 3963 if (!this->emitGetPtrLocal(*Offset, Init)) 3964 return false; 3965 3966 if (!visitInitializer(Init)) 3967 return false; 3968 3969 if (!this->emitFinishInit(Init)) 3970 return false; 3971 3972 return this->emitPopPtr(Init); 3973 } 3974 return false; 3975 } 3976 return true; 3977 } 3978 3979 return false; 3980 } 3981 3982 template <class Emitter> 3983 bool Compiler<Emitter>::visitAPValue(const APValue &Val, PrimType ValType, 3984 const Expr *E) { 3985 assert(!DiscardResult); 3986 if (Val.isInt()) 3987 return this->emitConst(Val.getInt(), ValType, E); 3988 else if (Val.isFloat()) 3989 return this->emitConstFloat(Val.getFloat(), E); 3990 3991 if (Val.isLValue()) { 3992 if (Val.isNullPointer()) 3993 return this->emitNull(ValType, nullptr, E); 3994 APValue::LValueBase Base = Val.getLValueBase(); 3995 if (const Expr *BaseExpr = Base.dyn_cast<const Expr *>()) 3996 return this->visit(BaseExpr); 3997 else if (const auto *VD = Base.dyn_cast<const ValueDecl *>()) { 3998 return this->visitDeclRef(VD, E); 3999 } 4000 } else if (Val.isMemberPointer()) { 4001 if (const ValueDecl *MemberDecl = Val.getMemberPointerDecl()) 4002 return this->emitGetMemberPtr(MemberDecl, E); 4003 return this->emitNullMemberPtr(nullptr, E); 4004 } 4005 4006 return false; 4007 } 4008 4009 template <class Emitter> 4010 bool Compiler<Emitter>::visitAPValueInitializer(const APValue &Val, 4011 const Expr *E) { 4012 4013 if (Val.isStruct()) { 4014 const Record *R = this->getRecord(E->getType()); 4015 assert(R); 4016 for (unsigned I = 0, N = Val.getStructNumFields(); I != N; ++I) { 4017 const APValue &F = Val.getStructField(I); 4018 const Record::Field *RF = R->getField(I); 4019 4020 if (F.isInt() || F.isFloat() || F.isLValue() || F.isMemberPointer()) { 4021 PrimType T = classifyPrim(RF->Decl->getType()); 4022 if (!this->visitAPValue(F, T, E)) 4023 return false; 4024 if (!this->emitInitField(T, RF->Offset, E)) 4025 return false; 4026 } else if (F.isArray()) { 4027 assert(RF->Desc->isPrimitiveArray()); 4028 const auto *ArrType = RF->Decl->getType()->getAsArrayTypeUnsafe(); 4029 PrimType ElemT = classifyPrim(ArrType->getElementType()); 4030 assert(ArrType); 4031 4032 if (!this->emitGetPtrField(RF->Offset, E)) 4033 return false; 4034 4035 for (unsigned A = 0, AN = F.getArraySize(); A != AN; ++A) { 4036 if (!this->visitAPValue(F.getArrayInitializedElt(A), ElemT, E)) 4037 return false; 4038 if (!this->emitInitElem(ElemT, A, E)) 4039 return false; 4040 } 4041 4042 if (!this->emitPopPtr(E)) 4043 return false; 4044 } else if (F.isStruct() || F.isUnion()) { 4045 if (!this->emitGetPtrField(RF->Offset, E)) 4046 return false; 4047 if (!this->visitAPValueInitializer(F, E)) 4048 return false; 4049 if (!this->emitPopPtr(E)) 4050 return false; 4051 } else { 4052 assert(false && "I don't think this should be possible"); 4053 } 4054 } 4055 return true; 4056 } else if (Val.isUnion()) { 4057 const FieldDecl *UnionField = Val.getUnionField(); 4058 const Record *R = this->getRecord(UnionField->getParent()); 4059 assert(R); 4060 const APValue &F = Val.getUnionValue(); 4061 const Record::Field *RF = R->getField(UnionField); 4062 PrimType T = classifyPrim(RF->Decl->getType()); 4063 if (!this->visitAPValue(F, T, E)) 4064 return false; 4065 return this->emitInitField(T, RF->Offset, E); 4066 } 4067 // TODO: Other types. 4068 4069 return false; 4070 } 4071 4072 template <class Emitter> 4073 bool Compiler<Emitter>::VisitBuiltinCallExpr(const CallExpr *E) { 4074 const Function *Func = getFunction(E->getDirectCallee()); 4075 if (!Func) 4076 return false; 4077 4078 // For these, we're expected to ultimately return an APValue pointing 4079 // to the CallExpr. This is needed to get the correct codegen. 4080 unsigned Builtin = E->getBuiltinCallee(); 4081 if (Builtin == Builtin::BI__builtin___CFStringMakeConstantString || 4082 Builtin == Builtin::BI__builtin___NSStringMakeConstantString || 4083 Builtin == Builtin::BI__builtin_ptrauth_sign_constant || 4084 Builtin == Builtin::BI__builtin_function_start) { 4085 if (std::optional<unsigned> GlobalOffset = P.createGlobal(E)) { 4086 if (!this->emitGetPtrGlobal(*GlobalOffset, E)) 4087 return false; 4088 4089 if (PrimType PT = classifyPrim(E); PT != PT_Ptr && isPtrType(PT)) 4090 return this->emitDecayPtr(PT_Ptr, PT, E); 4091 return true; 4092 } 4093 return false; 4094 } 4095 4096 QualType ReturnType = E->getType(); 4097 std::optional<PrimType> ReturnT = classify(E); 4098 4099 // Non-primitive return type. Prepare storage. 4100 if (!Initializing && !ReturnT && !ReturnType->isVoidType()) { 4101 std::optional<unsigned> LocalIndex = allocateLocal(E); 4102 if (!LocalIndex) 4103 return false; 4104 if (!this->emitGetPtrLocal(*LocalIndex, E)) 4105 return false; 4106 } 4107 4108 if (!Func->isUnevaluatedBuiltin()) { 4109 // Put arguments on the stack. 4110 for (const auto *Arg : E->arguments()) { 4111 if (!this->visit(Arg)) 4112 return false; 4113 } 4114 } 4115 4116 if (!this->emitCallBI(Func, E, E)) 4117 return false; 4118 4119 if (DiscardResult && !ReturnType->isVoidType()) { 4120 assert(ReturnT); 4121 return this->emitPop(*ReturnT, E); 4122 } 4123 4124 return true; 4125 } 4126 4127 template <class Emitter> 4128 bool Compiler<Emitter>::VisitCallExpr(const CallExpr *E) { 4129 if (E->getBuiltinCallee()) 4130 return VisitBuiltinCallExpr(E); 4131 4132 QualType ReturnType = E->getCallReturnType(Ctx.getASTContext()); 4133 std::optional<PrimType> T = classify(ReturnType); 4134 bool HasRVO = !ReturnType->isVoidType() && !T; 4135 const FunctionDecl *FuncDecl = E->getDirectCallee(); 4136 4137 if (HasRVO) { 4138 if (DiscardResult) { 4139 // If we need to discard the return value but the function returns its 4140 // value via an RVO pointer, we need to create one such pointer just 4141 // for this call. 4142 if (std::optional<unsigned> LocalIndex = allocateLocal(E)) { 4143 if (!this->emitGetPtrLocal(*LocalIndex, E)) 4144 return false; 4145 } 4146 } else { 4147 // We need the result. Prepare a pointer to return or 4148 // dup the current one. 4149 if (!Initializing) { 4150 if (std::optional<unsigned> LocalIndex = allocateLocal(E)) { 4151 if (!this->emitGetPtrLocal(*LocalIndex, E)) 4152 return false; 4153 } 4154 } 4155 if (!this->emitDupPtr(E)) 4156 return false; 4157 } 4158 } 4159 4160 SmallVector<const Expr *, 8> Args( 4161 llvm::ArrayRef(E->getArgs(), E->getNumArgs())); 4162 4163 bool IsAssignmentOperatorCall = false; 4164 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E); 4165 OCE && OCE->isAssignmentOp()) { 4166 // Just like with regular assignments, we need to special-case assignment 4167 // operators here and evaluate the RHS (the second arg) before the LHS (the 4168 // first arg. We fix this by using a Flip op later. 4169 assert(Args.size() == 2); 4170 IsAssignmentOperatorCall = true; 4171 std::reverse(Args.begin(), Args.end()); 4172 } 4173 // Calling a static operator will still 4174 // pass the instance, but we don't need it. 4175 // Discard it here. 4176 if (isa<CXXOperatorCallExpr>(E)) { 4177 if (const auto *MD = dyn_cast_if_present<CXXMethodDecl>(FuncDecl); 4178 MD && MD->isStatic()) { 4179 if (!this->discard(E->getArg(0))) 4180 return false; 4181 // Drop first arg. 4182 Args.erase(Args.begin()); 4183 } 4184 } 4185 4186 std::optional<unsigned> CalleeOffset; 4187 // Add the (optional, implicit) This pointer. 4188 if (const auto *MC = dyn_cast<CXXMemberCallExpr>(E)) { 4189 if (!FuncDecl && classifyPrim(E->getCallee()) == PT_MemberPtr) { 4190 // If we end up creating a CallPtr op for this, we need the base of the 4191 // member pointer as the instance pointer, and later extract the function 4192 // decl as the function pointer. 4193 const Expr *Callee = E->getCallee(); 4194 CalleeOffset = 4195 this->allocateLocalPrimitive(Callee, PT_MemberPtr, true, false); 4196 if (!this->visit(Callee)) 4197 return false; 4198 if (!this->emitSetLocal(PT_MemberPtr, *CalleeOffset, E)) 4199 return false; 4200 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E)) 4201 return false; 4202 if (!this->emitGetMemberPtrBase(E)) 4203 return false; 4204 } else if (!this->visit(MC->getImplicitObjectArgument())) { 4205 return false; 4206 } 4207 } else if (!FuncDecl) { 4208 const Expr *Callee = E->getCallee(); 4209 CalleeOffset = this->allocateLocalPrimitive(Callee, PT_FnPtr, true, false); 4210 if (!this->visit(Callee)) 4211 return false; 4212 if (!this->emitSetLocal(PT_FnPtr, *CalleeOffset, E)) 4213 return false; 4214 } 4215 4216 llvm::BitVector NonNullArgs = collectNonNullArgs(FuncDecl, Args); 4217 // Put arguments on the stack. 4218 unsigned ArgIndex = 0; 4219 for (const auto *Arg : Args) { 4220 if (!this->visit(Arg)) 4221 return false; 4222 4223 // If we know the callee already, check the known parametrs for nullability. 4224 if (FuncDecl && NonNullArgs[ArgIndex]) { 4225 PrimType ArgT = classify(Arg).value_or(PT_Ptr); 4226 if (ArgT == PT_Ptr || ArgT == PT_FnPtr) { 4227 if (!this->emitCheckNonNullArg(ArgT, Arg)) 4228 return false; 4229 } 4230 } 4231 ++ArgIndex; 4232 } 4233 4234 // Undo the argument reversal we did earlier. 4235 if (IsAssignmentOperatorCall) { 4236 assert(Args.size() == 2); 4237 PrimType Arg1T = classify(Args[0]).value_or(PT_Ptr); 4238 PrimType Arg2T = classify(Args[1]).value_or(PT_Ptr); 4239 if (!this->emitFlip(Arg2T, Arg1T, E)) 4240 return false; 4241 } 4242 4243 if (FuncDecl) { 4244 const Function *Func = getFunction(FuncDecl); 4245 if (!Func) 4246 return false; 4247 assert(HasRVO == Func->hasRVO()); 4248 4249 bool HasQualifier = false; 4250 if (const auto *ME = dyn_cast<MemberExpr>(E->getCallee())) 4251 HasQualifier = ME->hasQualifier(); 4252 4253 bool IsVirtual = false; 4254 if (const auto *MD = dyn_cast<CXXMethodDecl>(FuncDecl)) 4255 IsVirtual = MD->isVirtual(); 4256 4257 // In any case call the function. The return value will end up on the stack 4258 // and if the function has RVO, we already have the pointer on the stack to 4259 // write the result into. 4260 if (IsVirtual && !HasQualifier) { 4261 uint32_t VarArgSize = 0; 4262 unsigned NumParams = 4263 Func->getNumWrittenParams() + isa<CXXOperatorCallExpr>(E); 4264 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) 4265 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr))); 4266 4267 if (!this->emitCallVirt(Func, VarArgSize, E)) 4268 return false; 4269 } else if (Func->isVariadic()) { 4270 uint32_t VarArgSize = 0; 4271 unsigned NumParams = 4272 Func->getNumWrittenParams() + isa<CXXOperatorCallExpr>(E); 4273 for (unsigned I = NumParams, N = E->getNumArgs(); I != N; ++I) 4274 VarArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr))); 4275 if (!this->emitCallVar(Func, VarArgSize, E)) 4276 return false; 4277 } else { 4278 if (!this->emitCall(Func, 0, E)) 4279 return false; 4280 } 4281 } else { 4282 // Indirect call. Visit the callee, which will leave a FunctionPointer on 4283 // the stack. Cleanup of the returned value if necessary will be done after 4284 // the function call completed. 4285 4286 // Sum the size of all args from the call expr. 4287 uint32_t ArgSize = 0; 4288 for (unsigned I = 0, N = E->getNumArgs(); I != N; ++I) 4289 ArgSize += align(primSize(classify(E->getArg(I)).value_or(PT_Ptr))); 4290 4291 // Get the callee, either from a member pointer or function pointer saved in 4292 // CalleeOffset. 4293 if (isa<CXXMemberCallExpr>(E) && CalleeOffset) { 4294 if (!this->emitGetLocal(PT_MemberPtr, *CalleeOffset, E)) 4295 return false; 4296 if (!this->emitGetMemberPtrDecl(E)) 4297 return false; 4298 } else { 4299 if (!this->emitGetLocal(PT_FnPtr, *CalleeOffset, E)) 4300 return false; 4301 } 4302 if (!this->emitCallPtr(ArgSize, E, E)) 4303 return false; 4304 } 4305 4306 // Cleanup for discarded return values. 4307 if (DiscardResult && !ReturnType->isVoidType() && T) 4308 return this->emitPop(*T, E); 4309 4310 return true; 4311 } 4312 4313 template <class Emitter> 4314 bool Compiler<Emitter>::VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E) { 4315 SourceLocScope<Emitter> SLS(this, E); 4316 4317 return this->delegate(E->getExpr()); 4318 } 4319 4320 template <class Emitter> 4321 bool Compiler<Emitter>::VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E) { 4322 SourceLocScope<Emitter> SLS(this, E); 4323 4324 const Expr *SubExpr = E->getExpr(); 4325 if (std::optional<PrimType> T = classify(E->getExpr())) 4326 return this->visit(SubExpr); 4327 4328 assert(Initializing); 4329 return this->visitInitializer(SubExpr); 4330 } 4331 4332 template <class Emitter> 4333 bool Compiler<Emitter>::VisitCXXBoolLiteralExpr(const CXXBoolLiteralExpr *E) { 4334 if (DiscardResult) 4335 return true; 4336 4337 return this->emitConstBool(E->getValue(), E); 4338 } 4339 4340 template <class Emitter> 4341 bool Compiler<Emitter>::VisitCXXNullPtrLiteralExpr( 4342 const CXXNullPtrLiteralExpr *E) { 4343 if (DiscardResult) 4344 return true; 4345 4346 return this->emitNullPtr(nullptr, E); 4347 } 4348 4349 template <class Emitter> 4350 bool Compiler<Emitter>::VisitGNUNullExpr(const GNUNullExpr *E) { 4351 if (DiscardResult) 4352 return true; 4353 4354 assert(E->getType()->isIntegerType()); 4355 4356 PrimType T = classifyPrim(E->getType()); 4357 return this->emitZero(T, E); 4358 } 4359 4360 template <class Emitter> 4361 bool Compiler<Emitter>::VisitCXXThisExpr(const CXXThisExpr *E) { 4362 if (DiscardResult) 4363 return true; 4364 4365 if (this->LambdaThisCapture.Offset > 0) { 4366 if (this->LambdaThisCapture.IsPtr) 4367 return this->emitGetThisFieldPtr(this->LambdaThisCapture.Offset, E); 4368 return this->emitGetPtrThisField(this->LambdaThisCapture.Offset, E); 4369 } 4370 4371 // In some circumstances, the 'this' pointer does not actually refer to the 4372 // instance pointer of the current function frame, but e.g. to the declaration 4373 // currently being initialized. Here we emit the necessary instruction(s) for 4374 // this scenario. 4375 if (!InitStackActive || !E->isImplicit()) 4376 return this->emitThis(E); 4377 4378 if (InitStackActive && !InitStack.empty()) { 4379 unsigned StartIndex = 0; 4380 for (StartIndex = InitStack.size() - 1; StartIndex > 0; --StartIndex) { 4381 if (InitStack[StartIndex].Kind != InitLink::K_Field && 4382 InitStack[StartIndex].Kind != InitLink::K_Elem) 4383 break; 4384 } 4385 4386 for (unsigned I = StartIndex, N = InitStack.size(); I != N; ++I) { 4387 if (!InitStack[I].template emit<Emitter>(this, E)) 4388 return false; 4389 } 4390 return true; 4391 } 4392 return this->emitThis(E); 4393 } 4394 4395 template <class Emitter> bool Compiler<Emitter>::visitStmt(const Stmt *S) { 4396 switch (S->getStmtClass()) { 4397 case Stmt::CompoundStmtClass: 4398 return visitCompoundStmt(cast<CompoundStmt>(S)); 4399 case Stmt::DeclStmtClass: 4400 return visitDeclStmt(cast<DeclStmt>(S)); 4401 case Stmt::ReturnStmtClass: 4402 return visitReturnStmt(cast<ReturnStmt>(S)); 4403 case Stmt::IfStmtClass: 4404 return visitIfStmt(cast<IfStmt>(S)); 4405 case Stmt::WhileStmtClass: 4406 return visitWhileStmt(cast<WhileStmt>(S)); 4407 case Stmt::DoStmtClass: 4408 return visitDoStmt(cast<DoStmt>(S)); 4409 case Stmt::ForStmtClass: 4410 return visitForStmt(cast<ForStmt>(S)); 4411 case Stmt::CXXForRangeStmtClass: 4412 return visitCXXForRangeStmt(cast<CXXForRangeStmt>(S)); 4413 case Stmt::BreakStmtClass: 4414 return visitBreakStmt(cast<BreakStmt>(S)); 4415 case Stmt::ContinueStmtClass: 4416 return visitContinueStmt(cast<ContinueStmt>(S)); 4417 case Stmt::SwitchStmtClass: 4418 return visitSwitchStmt(cast<SwitchStmt>(S)); 4419 case Stmt::CaseStmtClass: 4420 return visitCaseStmt(cast<CaseStmt>(S)); 4421 case Stmt::DefaultStmtClass: 4422 return visitDefaultStmt(cast<DefaultStmt>(S)); 4423 case Stmt::AttributedStmtClass: 4424 return visitAttributedStmt(cast<AttributedStmt>(S)); 4425 case Stmt::CXXTryStmtClass: 4426 return visitCXXTryStmt(cast<CXXTryStmt>(S)); 4427 case Stmt::NullStmtClass: 4428 return true; 4429 // Always invalid statements. 4430 case Stmt::GCCAsmStmtClass: 4431 case Stmt::MSAsmStmtClass: 4432 case Stmt::GotoStmtClass: 4433 return this->emitInvalid(S); 4434 case Stmt::LabelStmtClass: 4435 return this->visitStmt(cast<LabelStmt>(S)->getSubStmt()); 4436 default: { 4437 if (const auto *E = dyn_cast<Expr>(S)) 4438 return this->discard(E); 4439 return false; 4440 } 4441 } 4442 } 4443 4444 template <class Emitter> 4445 bool Compiler<Emitter>::visitCompoundStmt(const CompoundStmt *S) { 4446 BlockScope<Emitter> Scope(this); 4447 for (const auto *InnerStmt : S->body()) 4448 if (!visitStmt(InnerStmt)) 4449 return false; 4450 return Scope.destroyLocals(); 4451 } 4452 4453 template <class Emitter> 4454 bool Compiler<Emitter>::visitDeclStmt(const DeclStmt *DS) { 4455 for (const auto *D : DS->decls()) { 4456 if (isa<StaticAssertDecl, TagDecl, TypedefNameDecl, UsingEnumDecl, 4457 FunctionDecl>(D)) 4458 continue; 4459 4460 const auto *VD = dyn_cast<VarDecl>(D); 4461 if (!VD) 4462 return false; 4463 if (!this->visitVarDecl(VD)) 4464 return false; 4465 } 4466 4467 return true; 4468 } 4469 4470 template <class Emitter> 4471 bool Compiler<Emitter>::visitReturnStmt(const ReturnStmt *RS) { 4472 if (this->InStmtExpr) 4473 return this->emitUnsupported(RS); 4474 4475 if (const Expr *RE = RS->getRetValue()) { 4476 LocalScope<Emitter> RetScope(this); 4477 if (ReturnType) { 4478 // Primitive types are simply returned. 4479 if (!this->visit(RE)) 4480 return false; 4481 this->emitCleanup(); 4482 return this->emitRet(*ReturnType, RS); 4483 } else if (RE->getType()->isVoidType()) { 4484 if (!this->visit(RE)) 4485 return false; 4486 } else { 4487 // RVO - construct the value in the return location. 4488 if (!this->emitRVOPtr(RE)) 4489 return false; 4490 if (!this->visitInitializer(RE)) 4491 return false; 4492 if (!this->emitPopPtr(RE)) 4493 return false; 4494 4495 this->emitCleanup(); 4496 return this->emitRetVoid(RS); 4497 } 4498 } 4499 4500 // Void return. 4501 this->emitCleanup(); 4502 return this->emitRetVoid(RS); 4503 } 4504 4505 template <class Emitter> bool Compiler<Emitter>::visitIfStmt(const IfStmt *IS) { 4506 if (auto *CondInit = IS->getInit()) 4507 if (!visitStmt(CondInit)) 4508 return false; 4509 4510 if (const DeclStmt *CondDecl = IS->getConditionVariableDeclStmt()) 4511 if (!visitDeclStmt(CondDecl)) 4512 return false; 4513 4514 // Compile condition. 4515 if (IS->isNonNegatedConsteval()) { 4516 if (!this->emitIsConstantContext(IS)) 4517 return false; 4518 } else if (IS->isNegatedConsteval()) { 4519 if (!this->emitIsConstantContext(IS)) 4520 return false; 4521 if (!this->emitInv(IS)) 4522 return false; 4523 } else { 4524 if (!this->visitBool(IS->getCond())) 4525 return false; 4526 } 4527 4528 if (const Stmt *Else = IS->getElse()) { 4529 LabelTy LabelElse = this->getLabel(); 4530 LabelTy LabelEnd = this->getLabel(); 4531 if (!this->jumpFalse(LabelElse)) 4532 return false; 4533 if (!visitStmt(IS->getThen())) 4534 return false; 4535 if (!this->jump(LabelEnd)) 4536 return false; 4537 this->emitLabel(LabelElse); 4538 if (!visitStmt(Else)) 4539 return false; 4540 this->emitLabel(LabelEnd); 4541 } else { 4542 LabelTy LabelEnd = this->getLabel(); 4543 if (!this->jumpFalse(LabelEnd)) 4544 return false; 4545 if (!visitStmt(IS->getThen())) 4546 return false; 4547 this->emitLabel(LabelEnd); 4548 } 4549 4550 return true; 4551 } 4552 4553 template <class Emitter> 4554 bool Compiler<Emitter>::visitWhileStmt(const WhileStmt *S) { 4555 const Expr *Cond = S->getCond(); 4556 const Stmt *Body = S->getBody(); 4557 4558 LabelTy CondLabel = this->getLabel(); // Label before the condition. 4559 LabelTy EndLabel = this->getLabel(); // Label after the loop. 4560 LoopScope<Emitter> LS(this, EndLabel, CondLabel); 4561 4562 this->fallthrough(CondLabel); 4563 this->emitLabel(CondLabel); 4564 4565 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) 4566 if (!visitDeclStmt(CondDecl)) 4567 return false; 4568 4569 if (!this->visitBool(Cond)) 4570 return false; 4571 if (!this->jumpFalse(EndLabel)) 4572 return false; 4573 4574 if (!this->visitStmt(Body)) 4575 return false; 4576 4577 if (!this->jump(CondLabel)) 4578 return false; 4579 this->fallthrough(EndLabel); 4580 this->emitLabel(EndLabel); 4581 4582 return true; 4583 } 4584 4585 template <class Emitter> bool Compiler<Emitter>::visitDoStmt(const DoStmt *S) { 4586 const Expr *Cond = S->getCond(); 4587 const Stmt *Body = S->getBody(); 4588 4589 LabelTy StartLabel = this->getLabel(); 4590 LabelTy EndLabel = this->getLabel(); 4591 LabelTy CondLabel = this->getLabel(); 4592 LoopScope<Emitter> LS(this, EndLabel, CondLabel); 4593 4594 this->fallthrough(StartLabel); 4595 this->emitLabel(StartLabel); 4596 { 4597 if (!this->visitStmt(Body)) 4598 return false; 4599 this->fallthrough(CondLabel); 4600 this->emitLabel(CondLabel); 4601 if (!this->visitBool(Cond)) 4602 return false; 4603 } 4604 if (!this->jumpTrue(StartLabel)) 4605 return false; 4606 4607 this->fallthrough(EndLabel); 4608 this->emitLabel(EndLabel); 4609 return true; 4610 } 4611 4612 template <class Emitter> 4613 bool Compiler<Emitter>::visitForStmt(const ForStmt *S) { 4614 // for (Init; Cond; Inc) { Body } 4615 const Stmt *Init = S->getInit(); 4616 const Expr *Cond = S->getCond(); 4617 const Expr *Inc = S->getInc(); 4618 const Stmt *Body = S->getBody(); 4619 4620 LabelTy EndLabel = this->getLabel(); 4621 LabelTy CondLabel = this->getLabel(); 4622 LabelTy IncLabel = this->getLabel(); 4623 LoopScope<Emitter> LS(this, EndLabel, IncLabel); 4624 4625 if (Init && !this->visitStmt(Init)) 4626 return false; 4627 4628 this->fallthrough(CondLabel); 4629 this->emitLabel(CondLabel); 4630 4631 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) 4632 if (!visitDeclStmt(CondDecl)) 4633 return false; 4634 4635 if (Cond) { 4636 if (!this->visitBool(Cond)) 4637 return false; 4638 if (!this->jumpFalse(EndLabel)) 4639 return false; 4640 } 4641 4642 { 4643 if (Body && !this->visitStmt(Body)) 4644 return false; 4645 4646 this->fallthrough(IncLabel); 4647 this->emitLabel(IncLabel); 4648 if (Inc && !this->discard(Inc)) 4649 return false; 4650 } 4651 4652 if (!this->jump(CondLabel)) 4653 return false; 4654 this->fallthrough(EndLabel); 4655 this->emitLabel(EndLabel); 4656 return true; 4657 } 4658 4659 template <class Emitter> 4660 bool Compiler<Emitter>::visitCXXForRangeStmt(const CXXForRangeStmt *S) { 4661 const Stmt *Init = S->getInit(); 4662 const Expr *Cond = S->getCond(); 4663 const Expr *Inc = S->getInc(); 4664 const Stmt *Body = S->getBody(); 4665 const Stmt *BeginStmt = S->getBeginStmt(); 4666 const Stmt *RangeStmt = S->getRangeStmt(); 4667 const Stmt *EndStmt = S->getEndStmt(); 4668 const VarDecl *LoopVar = S->getLoopVariable(); 4669 4670 LabelTy EndLabel = this->getLabel(); 4671 LabelTy CondLabel = this->getLabel(); 4672 LabelTy IncLabel = this->getLabel(); 4673 LoopScope<Emitter> LS(this, EndLabel, IncLabel); 4674 4675 // Emit declarations needed in the loop. 4676 if (Init && !this->visitStmt(Init)) 4677 return false; 4678 if (!this->visitStmt(RangeStmt)) 4679 return false; 4680 if (!this->visitStmt(BeginStmt)) 4681 return false; 4682 if (!this->visitStmt(EndStmt)) 4683 return false; 4684 4685 // Now the condition as well as the loop variable assignment. 4686 this->fallthrough(CondLabel); 4687 this->emitLabel(CondLabel); 4688 if (!this->visitBool(Cond)) 4689 return false; 4690 if (!this->jumpFalse(EndLabel)) 4691 return false; 4692 4693 if (!this->visitVarDecl(LoopVar)) 4694 return false; 4695 4696 // Body. 4697 { 4698 if (!this->visitStmt(Body)) 4699 return false; 4700 4701 this->fallthrough(IncLabel); 4702 this->emitLabel(IncLabel); 4703 if (!this->discard(Inc)) 4704 return false; 4705 } 4706 4707 if (!this->jump(CondLabel)) 4708 return false; 4709 4710 this->fallthrough(EndLabel); 4711 this->emitLabel(EndLabel); 4712 return true; 4713 } 4714 4715 template <class Emitter> 4716 bool Compiler<Emitter>::visitBreakStmt(const BreakStmt *S) { 4717 if (!BreakLabel) 4718 return false; 4719 4720 this->emitCleanup(); 4721 return this->jump(*BreakLabel); 4722 } 4723 4724 template <class Emitter> 4725 bool Compiler<Emitter>::visitContinueStmt(const ContinueStmt *S) { 4726 if (!ContinueLabel) 4727 return false; 4728 4729 this->emitCleanup(); 4730 return this->jump(*ContinueLabel); 4731 } 4732 4733 template <class Emitter> 4734 bool Compiler<Emitter>::visitSwitchStmt(const SwitchStmt *S) { 4735 const Expr *Cond = S->getCond(); 4736 PrimType CondT = this->classifyPrim(Cond->getType()); 4737 4738 LabelTy EndLabel = this->getLabel(); 4739 OptLabelTy DefaultLabel = std::nullopt; 4740 unsigned CondVar = this->allocateLocalPrimitive(Cond, CondT, true, false); 4741 4742 if (const auto *CondInit = S->getInit()) 4743 if (!visitStmt(CondInit)) 4744 return false; 4745 4746 if (const DeclStmt *CondDecl = S->getConditionVariableDeclStmt()) 4747 if (!visitDeclStmt(CondDecl)) 4748 return false; 4749 4750 // Initialize condition variable. 4751 if (!this->visit(Cond)) 4752 return false; 4753 if (!this->emitSetLocal(CondT, CondVar, S)) 4754 return false; 4755 4756 CaseMap CaseLabels; 4757 // Create labels and comparison ops for all case statements. 4758 for (const SwitchCase *SC = S->getSwitchCaseList(); SC; 4759 SC = SC->getNextSwitchCase()) { 4760 if (const auto *CS = dyn_cast<CaseStmt>(SC)) { 4761 // FIXME: Implement ranges. 4762 if (CS->caseStmtIsGNURange()) 4763 return false; 4764 CaseLabels[SC] = this->getLabel(); 4765 4766 const Expr *Value = CS->getLHS(); 4767 PrimType ValueT = this->classifyPrim(Value->getType()); 4768 4769 // Compare the case statement's value to the switch condition. 4770 if (!this->emitGetLocal(CondT, CondVar, CS)) 4771 return false; 4772 if (!this->visit(Value)) 4773 return false; 4774 4775 // Compare and jump to the case label. 4776 if (!this->emitEQ(ValueT, S)) 4777 return false; 4778 if (!this->jumpTrue(CaseLabels[CS])) 4779 return false; 4780 } else { 4781 assert(!DefaultLabel); 4782 DefaultLabel = this->getLabel(); 4783 } 4784 } 4785 4786 // If none of the conditions above were true, fall through to the default 4787 // statement or jump after the switch statement. 4788 if (DefaultLabel) { 4789 if (!this->jump(*DefaultLabel)) 4790 return false; 4791 } else { 4792 if (!this->jump(EndLabel)) 4793 return false; 4794 } 4795 4796 SwitchScope<Emitter> SS(this, std::move(CaseLabels), EndLabel, DefaultLabel); 4797 if (!this->visitStmt(S->getBody())) 4798 return false; 4799 this->emitLabel(EndLabel); 4800 return true; 4801 } 4802 4803 template <class Emitter> 4804 bool Compiler<Emitter>::visitCaseStmt(const CaseStmt *S) { 4805 this->emitLabel(CaseLabels[S]); 4806 return this->visitStmt(S->getSubStmt()); 4807 } 4808 4809 template <class Emitter> 4810 bool Compiler<Emitter>::visitDefaultStmt(const DefaultStmt *S) { 4811 this->emitLabel(*DefaultLabel); 4812 return this->visitStmt(S->getSubStmt()); 4813 } 4814 4815 template <class Emitter> 4816 bool Compiler<Emitter>::visitAttributedStmt(const AttributedStmt *S) { 4817 if (this->Ctx.getLangOpts().CXXAssumptions && 4818 !this->Ctx.getLangOpts().MSVCCompat) { 4819 for (const Attr *A : S->getAttrs()) { 4820 auto *AA = dyn_cast<CXXAssumeAttr>(A); 4821 if (!AA) 4822 continue; 4823 4824 assert(isa<NullStmt>(S->getSubStmt())); 4825 4826 const Expr *Assumption = AA->getAssumption(); 4827 if (Assumption->isValueDependent()) 4828 return false; 4829 4830 if (Assumption->HasSideEffects(this->Ctx.getASTContext())) 4831 continue; 4832 4833 // Evaluate assumption. 4834 if (!this->visitBool(Assumption)) 4835 return false; 4836 4837 if (!this->emitAssume(Assumption)) 4838 return false; 4839 } 4840 } 4841 4842 // Ignore other attributes. 4843 return this->visitStmt(S->getSubStmt()); 4844 } 4845 4846 template <class Emitter> 4847 bool Compiler<Emitter>::visitCXXTryStmt(const CXXTryStmt *S) { 4848 // Ignore all handlers. 4849 return this->visitStmt(S->getTryBlock()); 4850 } 4851 4852 template <class Emitter> 4853 bool Compiler<Emitter>::emitLambdaStaticInvokerBody(const CXXMethodDecl *MD) { 4854 assert(MD->isLambdaStaticInvoker()); 4855 assert(MD->hasBody()); 4856 assert(cast<CompoundStmt>(MD->getBody())->body_empty()); 4857 4858 const CXXRecordDecl *ClosureClass = MD->getParent(); 4859 const CXXMethodDecl *LambdaCallOp = ClosureClass->getLambdaCallOperator(); 4860 assert(ClosureClass->captures_begin() == ClosureClass->captures_end()); 4861 const Function *Func = this->getFunction(LambdaCallOp); 4862 if (!Func) 4863 return false; 4864 assert(Func->hasThisPointer()); 4865 assert(Func->getNumParams() == (MD->getNumParams() + 1 + Func->hasRVO())); 4866 4867 if (Func->hasRVO()) { 4868 if (!this->emitRVOPtr(MD)) 4869 return false; 4870 } 4871 4872 // The lambda call operator needs an instance pointer, but we don't have 4873 // one here, and we don't need one either because the lambda cannot have 4874 // any captures, as verified above. Emit a null pointer. This is then 4875 // special-cased when interpreting to not emit any misleading diagnostics. 4876 if (!this->emitNullPtr(nullptr, MD)) 4877 return false; 4878 4879 // Forward all arguments from the static invoker to the lambda call operator. 4880 for (const ParmVarDecl *PVD : MD->parameters()) { 4881 auto It = this->Params.find(PVD); 4882 assert(It != this->Params.end()); 4883 4884 // We do the lvalue-to-rvalue conversion manually here, so no need 4885 // to care about references. 4886 PrimType ParamType = this->classify(PVD->getType()).value_or(PT_Ptr); 4887 if (!this->emitGetParam(ParamType, It->second.Offset, MD)) 4888 return false; 4889 } 4890 4891 if (!this->emitCall(Func, 0, LambdaCallOp)) 4892 return false; 4893 4894 this->emitCleanup(); 4895 if (ReturnType) 4896 return this->emitRet(*ReturnType, MD); 4897 4898 // Nothing to do, since we emitted the RVO pointer above. 4899 return this->emitRetVoid(MD); 4900 } 4901 4902 template <class Emitter> 4903 bool Compiler<Emitter>::checkLiteralType(const Expr *E) { 4904 if (Ctx.getLangOpts().CPlusPlus23) 4905 return true; 4906 4907 if (!E->isPRValue() || E->getType()->isLiteralType(Ctx.getASTContext())) 4908 return true; 4909 4910 return this->emitCheckLiteralType(E->getType().getTypePtr(), E); 4911 } 4912 4913 template <class Emitter> 4914 bool Compiler<Emitter>::compileConstructor(const CXXConstructorDecl *Ctor) { 4915 assert(!ReturnType); 4916 4917 auto emitFieldInitializer = [&](const Record::Field *F, unsigned FieldOffset, 4918 const Expr *InitExpr) -> bool { 4919 // We don't know what to do with these, so just return false. 4920 if (InitExpr->getType().isNull()) 4921 return false; 4922 4923 if (std::optional<PrimType> T = this->classify(InitExpr)) { 4924 if (!this->visit(InitExpr)) 4925 return false; 4926 4927 if (F->isBitField()) 4928 return this->emitInitThisBitField(*T, F, FieldOffset, InitExpr); 4929 return this->emitInitThisField(*T, FieldOffset, InitExpr); 4930 } 4931 // Non-primitive case. Get a pointer to the field-to-initialize 4932 // on the stack and call visitInitialzer() for it. 4933 InitLinkScope<Emitter> FieldScope(this, InitLink::Field(F->Offset)); 4934 if (!this->emitGetPtrThisField(FieldOffset, InitExpr)) 4935 return false; 4936 4937 if (!this->visitInitializer(InitExpr)) 4938 return false; 4939 4940 return this->emitFinishInitPop(InitExpr); 4941 }; 4942 4943 const RecordDecl *RD = Ctor->getParent(); 4944 const Record *R = this->getRecord(RD); 4945 if (!R) 4946 return false; 4947 4948 if (R->isUnion() && Ctor->isCopyOrMoveConstructor()) { 4949 // union copy and move ctors are special. 4950 assert(cast<CompoundStmt>(Ctor->getBody())->body_empty()); 4951 if (!this->emitThis(Ctor)) 4952 return false; 4953 4954 auto PVD = Ctor->getParamDecl(0); 4955 ParamOffset PO = this->Params[PVD]; // Must exist. 4956 4957 if (!this->emitGetParam(PT_Ptr, PO.Offset, Ctor)) 4958 return false; 4959 4960 return this->emitMemcpy(Ctor) && this->emitPopPtr(Ctor) && 4961 this->emitRetVoid(Ctor); 4962 } 4963 4964 InitLinkScope<Emitter> InitScope(this, InitLink::This()); 4965 for (const auto *Init : Ctor->inits()) { 4966 // Scope needed for the initializers. 4967 BlockScope<Emitter> Scope(this); 4968 4969 const Expr *InitExpr = Init->getInit(); 4970 if (const FieldDecl *Member = Init->getMember()) { 4971 const Record::Field *F = R->getField(Member); 4972 4973 if (!emitFieldInitializer(F, F->Offset, InitExpr)) 4974 return false; 4975 } else if (const Type *Base = Init->getBaseClass()) { 4976 const auto *BaseDecl = Base->getAsCXXRecordDecl(); 4977 assert(BaseDecl); 4978 4979 if (Init->isBaseVirtual()) { 4980 assert(R->getVirtualBase(BaseDecl)); 4981 if (!this->emitGetPtrThisVirtBase(BaseDecl, InitExpr)) 4982 return false; 4983 4984 } else { 4985 // Base class initializer. 4986 // Get This Base and call initializer on it. 4987 const Record::Base *B = R->getBase(BaseDecl); 4988 assert(B); 4989 if (!this->emitGetPtrThisBase(B->Offset, InitExpr)) 4990 return false; 4991 } 4992 4993 if (!this->visitInitializer(InitExpr)) 4994 return false; 4995 if (!this->emitFinishInitPop(InitExpr)) 4996 return false; 4997 } else if (const IndirectFieldDecl *IFD = Init->getIndirectMember()) { 4998 assert(IFD->getChainingSize() >= 2); 4999 5000 unsigned NestedFieldOffset = 0; 5001 const Record::Field *NestedField = nullptr; 5002 for (const NamedDecl *ND : IFD->chain()) { 5003 const auto *FD = cast<FieldDecl>(ND); 5004 const Record *FieldRecord = this->P.getOrCreateRecord(FD->getParent()); 5005 assert(FieldRecord); 5006 5007 NestedField = FieldRecord->getField(FD); 5008 assert(NestedField); 5009 5010 NestedFieldOffset += NestedField->Offset; 5011 } 5012 assert(NestedField); 5013 5014 if (!emitFieldInitializer(NestedField, NestedFieldOffset, InitExpr)) 5015 return false; 5016 } else { 5017 assert(Init->isDelegatingInitializer()); 5018 if (!this->emitThis(InitExpr)) 5019 return false; 5020 if (!this->visitInitializer(Init->getInit())) 5021 return false; 5022 if (!this->emitPopPtr(InitExpr)) 5023 return false; 5024 } 5025 5026 if (!Scope.destroyLocals()) 5027 return false; 5028 } 5029 5030 if (const auto *Body = Ctor->getBody()) 5031 if (!visitStmt(Body)) 5032 return false; 5033 5034 return this->emitRetVoid(SourceInfo{}); 5035 } 5036 5037 template <class Emitter> 5038 bool Compiler<Emitter>::compileDestructor(const CXXDestructorDecl *Dtor) { 5039 const RecordDecl *RD = Dtor->getParent(); 5040 const Record *R = this->getRecord(RD); 5041 if (!R) 5042 return false; 5043 5044 if (!Dtor->isTrivial() && Dtor->getBody()) { 5045 if (!this->visitStmt(Dtor->getBody())) 5046 return false; 5047 } 5048 5049 if (!this->emitThis(Dtor)) 5050 return false; 5051 5052 assert(R); 5053 if (!R->isUnion()) { 5054 // First, destroy all fields. 5055 for (const Record::Field &Field : llvm::reverse(R->fields())) { 5056 const Descriptor *D = Field.Desc; 5057 if (!D->isPrimitive() && !D->isPrimitiveArray()) { 5058 if (!this->emitGetPtrField(Field.Offset, SourceInfo{})) 5059 return false; 5060 if (!this->emitDestruction(D)) 5061 return false; 5062 if (!this->emitPopPtr(SourceInfo{})) 5063 return false; 5064 } 5065 } 5066 } 5067 5068 for (const Record::Base &Base : llvm::reverse(R->bases())) { 5069 if (!this->emitGetPtrBase(Base.Offset, SourceInfo{})) 5070 return false; 5071 if (!this->emitRecordDestruction(Base.R)) 5072 return false; 5073 if (!this->emitPopPtr(SourceInfo{})) 5074 return false; 5075 } 5076 5077 // FIXME: Virtual bases. 5078 return this->emitPopPtr(Dtor) && this->emitRetVoid(Dtor); 5079 } 5080 5081 template <class Emitter> 5082 bool Compiler<Emitter>::visitFunc(const FunctionDecl *F) { 5083 // Classify the return type. 5084 ReturnType = this->classify(F->getReturnType()); 5085 5086 if (const auto *Ctor = dyn_cast<CXXConstructorDecl>(F)) 5087 return this->compileConstructor(Ctor); 5088 if (const auto *Dtor = dyn_cast<CXXDestructorDecl>(F)) 5089 return this->compileDestructor(Dtor); 5090 5091 // Emit custom code if this is a lambda static invoker. 5092 if (const auto *MD = dyn_cast<CXXMethodDecl>(F); 5093 MD && MD->isLambdaStaticInvoker()) 5094 return this->emitLambdaStaticInvokerBody(MD); 5095 5096 // Regular functions. 5097 if (const auto *Body = F->getBody()) 5098 if (!visitStmt(Body)) 5099 return false; 5100 5101 // Emit a guard return to protect against a code path missing one. 5102 if (F->getReturnType()->isVoidType()) 5103 return this->emitRetVoid(SourceInfo{}); 5104 return this->emitNoRet(SourceInfo{}); 5105 } 5106 5107 template <class Emitter> 5108 bool Compiler<Emitter>::VisitUnaryOperator(const UnaryOperator *E) { 5109 const Expr *SubExpr = E->getSubExpr(); 5110 if (SubExpr->getType()->isAnyComplexType()) 5111 return this->VisitComplexUnaryOperator(E); 5112 if (SubExpr->getType()->isVectorType()) 5113 return this->VisitVectorUnaryOperator(E); 5114 std::optional<PrimType> T = classify(SubExpr->getType()); 5115 5116 switch (E->getOpcode()) { 5117 case UO_PostInc: { // x++ 5118 if (!Ctx.getLangOpts().CPlusPlus14) 5119 return this->emitInvalid(E); 5120 if (!T) 5121 return this->emitError(E); 5122 5123 if (!this->visit(SubExpr)) 5124 return false; 5125 5126 if (T == PT_Ptr || T == PT_FnPtr) { 5127 if (!this->emitIncPtr(E)) 5128 return false; 5129 5130 return DiscardResult ? this->emitPopPtr(E) : true; 5131 } 5132 5133 if (T == PT_Float) { 5134 return DiscardResult ? this->emitIncfPop(getFPOptions(E), E) 5135 : this->emitIncf(getFPOptions(E), E); 5136 } 5137 5138 return DiscardResult ? this->emitIncPop(*T, E) : this->emitInc(*T, E); 5139 } 5140 case UO_PostDec: { // x-- 5141 if (!Ctx.getLangOpts().CPlusPlus14) 5142 return this->emitInvalid(E); 5143 if (!T) 5144 return this->emitError(E); 5145 5146 if (!this->visit(SubExpr)) 5147 return false; 5148 5149 if (T == PT_Ptr || T == PT_FnPtr) { 5150 if (!this->emitDecPtr(E)) 5151 return false; 5152 5153 return DiscardResult ? this->emitPopPtr(E) : true; 5154 } 5155 5156 if (T == PT_Float) { 5157 return DiscardResult ? this->emitDecfPop(getFPOptions(E), E) 5158 : this->emitDecf(getFPOptions(E), E); 5159 } 5160 5161 return DiscardResult ? this->emitDecPop(*T, E) : this->emitDec(*T, E); 5162 } 5163 case UO_PreInc: { // ++x 5164 if (!Ctx.getLangOpts().CPlusPlus14) 5165 return this->emitInvalid(E); 5166 if (!T) 5167 return this->emitError(E); 5168 5169 if (!this->visit(SubExpr)) 5170 return false; 5171 5172 if (T == PT_Ptr || T == PT_FnPtr) { 5173 if (!this->emitLoadPtr(E)) 5174 return false; 5175 if (!this->emitConstUint8(1, E)) 5176 return false; 5177 if (!this->emitAddOffsetUint8(E)) 5178 return false; 5179 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E); 5180 } 5181 5182 // Post-inc and pre-inc are the same if the value is to be discarded. 5183 if (DiscardResult) { 5184 if (T == PT_Float) 5185 return this->emitIncfPop(getFPOptions(E), E); 5186 return this->emitIncPop(*T, E); 5187 } 5188 5189 if (T == PT_Float) { 5190 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType()); 5191 if (!this->emitLoadFloat(E)) 5192 return false; 5193 if (!this->emitConstFloat(llvm::APFloat(TargetSemantics, 1), E)) 5194 return false; 5195 if (!this->emitAddf(getFPOptions(E), E)) 5196 return false; 5197 if (!this->emitStoreFloat(E)) 5198 return false; 5199 } else { 5200 assert(isIntegralType(*T)); 5201 if (!this->emitLoad(*T, E)) 5202 return false; 5203 if (!this->emitConst(1, E)) 5204 return false; 5205 if (!this->emitAdd(*T, E)) 5206 return false; 5207 if (!this->emitStore(*T, E)) 5208 return false; 5209 } 5210 return E->isGLValue() || this->emitLoadPop(*T, E); 5211 } 5212 case UO_PreDec: { // --x 5213 if (!Ctx.getLangOpts().CPlusPlus14) 5214 return this->emitInvalid(E); 5215 if (!T) 5216 return this->emitError(E); 5217 5218 if (!this->visit(SubExpr)) 5219 return false; 5220 5221 if (T == PT_Ptr || T == PT_FnPtr) { 5222 if (!this->emitLoadPtr(E)) 5223 return false; 5224 if (!this->emitConstUint8(1, E)) 5225 return false; 5226 if (!this->emitSubOffsetUint8(E)) 5227 return false; 5228 return DiscardResult ? this->emitStorePopPtr(E) : this->emitStorePtr(E); 5229 } 5230 5231 // Post-dec and pre-dec are the same if the value is to be discarded. 5232 if (DiscardResult) { 5233 if (T == PT_Float) 5234 return this->emitDecfPop(getFPOptions(E), E); 5235 return this->emitDecPop(*T, E); 5236 } 5237 5238 if (T == PT_Float) { 5239 const auto &TargetSemantics = Ctx.getFloatSemantics(E->getType()); 5240 if (!this->emitLoadFloat(E)) 5241 return false; 5242 if (!this->emitConstFloat(llvm::APFloat(TargetSemantics, 1), E)) 5243 return false; 5244 if (!this->emitSubf(getFPOptions(E), E)) 5245 return false; 5246 if (!this->emitStoreFloat(E)) 5247 return false; 5248 } else { 5249 assert(isIntegralType(*T)); 5250 if (!this->emitLoad(*T, E)) 5251 return false; 5252 if (!this->emitConst(1, E)) 5253 return false; 5254 if (!this->emitSub(*T, E)) 5255 return false; 5256 if (!this->emitStore(*T, E)) 5257 return false; 5258 } 5259 return E->isGLValue() || this->emitLoadPop(*T, E); 5260 } 5261 case UO_LNot: // !x 5262 if (!T) 5263 return this->emitError(E); 5264 5265 if (DiscardResult) 5266 return this->discard(SubExpr); 5267 5268 if (!this->visitBool(SubExpr)) 5269 return false; 5270 5271 if (!this->emitInv(E)) 5272 return false; 5273 5274 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool) 5275 return this->emitCast(PT_Bool, ET, E); 5276 return true; 5277 case UO_Minus: // -x 5278 if (!T) 5279 return this->emitError(E); 5280 5281 if (!this->visit(SubExpr)) 5282 return false; 5283 return DiscardResult ? this->emitPop(*T, E) : this->emitNeg(*T, E); 5284 case UO_Plus: // +x 5285 if (!T) 5286 return this->emitError(E); 5287 5288 if (!this->visit(SubExpr)) // noop 5289 return false; 5290 return DiscardResult ? this->emitPop(*T, E) : true; 5291 case UO_AddrOf: // &x 5292 if (E->getType()->isMemberPointerType()) { 5293 // C++11 [expr.unary.op]p3 has very strict rules on how the address of a 5294 // member can be formed. 5295 return this->emitGetMemberPtr(cast<DeclRefExpr>(SubExpr)->getDecl(), E); 5296 } 5297 // We should already have a pointer when we get here. 5298 return this->delegate(SubExpr); 5299 case UO_Deref: // *x 5300 if (DiscardResult) 5301 return this->discard(SubExpr); 5302 return this->visit(SubExpr); 5303 case UO_Not: // ~x 5304 if (!T) 5305 return this->emitError(E); 5306 5307 if (!this->visit(SubExpr)) 5308 return false; 5309 return DiscardResult ? this->emitPop(*T, E) : this->emitComp(*T, E); 5310 case UO_Real: // __real x 5311 assert(T); 5312 return this->delegate(SubExpr); 5313 case UO_Imag: { // __imag x 5314 assert(T); 5315 if (!this->discard(SubExpr)) 5316 return false; 5317 return this->visitZeroInitializer(*T, SubExpr->getType(), SubExpr); 5318 } 5319 case UO_Extension: 5320 return this->delegate(SubExpr); 5321 case UO_Coawait: 5322 assert(false && "Unhandled opcode"); 5323 } 5324 5325 return false; 5326 } 5327 5328 template <class Emitter> 5329 bool Compiler<Emitter>::VisitComplexUnaryOperator(const UnaryOperator *E) { 5330 const Expr *SubExpr = E->getSubExpr(); 5331 assert(SubExpr->getType()->isAnyComplexType()); 5332 5333 if (DiscardResult) 5334 return this->discard(SubExpr); 5335 5336 std::optional<PrimType> ResT = classify(E); 5337 auto prepareResult = [=]() -> bool { 5338 if (!ResT && !Initializing) { 5339 std::optional<unsigned> LocalIndex = allocateLocal(SubExpr); 5340 if (!LocalIndex) 5341 return false; 5342 return this->emitGetPtrLocal(*LocalIndex, E); 5343 } 5344 5345 return true; 5346 }; 5347 5348 // The offset of the temporary, if we created one. 5349 unsigned SubExprOffset = ~0u; 5350 auto createTemp = [=, &SubExprOffset]() -> bool { 5351 SubExprOffset = this->allocateLocalPrimitive(SubExpr, PT_Ptr, true, false); 5352 if (!this->visit(SubExpr)) 5353 return false; 5354 return this->emitSetLocal(PT_Ptr, SubExprOffset, E); 5355 }; 5356 5357 PrimType ElemT = classifyComplexElementType(SubExpr->getType()); 5358 auto getElem = [=](unsigned Offset, unsigned Index) -> bool { 5359 if (!this->emitGetLocal(PT_Ptr, Offset, E)) 5360 return false; 5361 return this->emitArrayElemPop(ElemT, Index, E); 5362 }; 5363 5364 switch (E->getOpcode()) { 5365 case UO_Minus: 5366 if (!prepareResult()) 5367 return false; 5368 if (!createTemp()) 5369 return false; 5370 for (unsigned I = 0; I != 2; ++I) { 5371 if (!getElem(SubExprOffset, I)) 5372 return false; 5373 if (!this->emitNeg(ElemT, E)) 5374 return false; 5375 if (!this->emitInitElem(ElemT, I, E)) 5376 return false; 5377 } 5378 break; 5379 5380 case UO_Plus: // +x 5381 case UO_AddrOf: // &x 5382 case UO_Deref: // *x 5383 return this->delegate(SubExpr); 5384 5385 case UO_LNot: 5386 if (!this->visit(SubExpr)) 5387 return false; 5388 if (!this->emitComplexBoolCast(SubExpr)) 5389 return false; 5390 if (!this->emitInv(E)) 5391 return false; 5392 if (PrimType ET = classifyPrim(E->getType()); ET != PT_Bool) 5393 return this->emitCast(PT_Bool, ET, E); 5394 return true; 5395 5396 case UO_Real: 5397 return this->emitComplexReal(SubExpr); 5398 5399 case UO_Imag: 5400 if (!this->visit(SubExpr)) 5401 return false; 5402 5403 if (SubExpr->isLValue()) { 5404 if (!this->emitConstUint8(1, E)) 5405 return false; 5406 return this->emitArrayElemPtrPopUint8(E); 5407 } 5408 5409 // Since our _Complex implementation does not map to a primitive type, 5410 // we sometimes have to do the lvalue-to-rvalue conversion here manually. 5411 return this->emitArrayElemPop(classifyPrim(E->getType()), 1, E); 5412 5413 case UO_Not: // ~x 5414 if (!this->visit(SubExpr)) 5415 return false; 5416 // Negate the imaginary component. 5417 if (!this->emitArrayElem(ElemT, 1, E)) 5418 return false; 5419 if (!this->emitNeg(ElemT, E)) 5420 return false; 5421 if (!this->emitInitElem(ElemT, 1, E)) 5422 return false; 5423 return DiscardResult ? this->emitPopPtr(E) : true; 5424 5425 case UO_Extension: 5426 return this->delegate(SubExpr); 5427 5428 default: 5429 return this->emitInvalid(E); 5430 } 5431 5432 return true; 5433 } 5434 5435 template <class Emitter> 5436 bool Compiler<Emitter>::VisitVectorUnaryOperator(const UnaryOperator *E) { 5437 const Expr *SubExpr = E->getSubExpr(); 5438 assert(SubExpr->getType()->isVectorType()); 5439 5440 if (DiscardResult) 5441 return this->discard(SubExpr); 5442 5443 auto UnaryOp = E->getOpcode(); 5444 if (UnaryOp != UO_Plus && UnaryOp != UO_Minus && UnaryOp != UO_LNot && 5445 UnaryOp != UO_Not && UnaryOp != UO_AddrOf) 5446 return this->emitInvalid(E); 5447 5448 // Nothing to do here. 5449 if (UnaryOp == UO_Plus || UnaryOp == UO_AddrOf) 5450 return this->delegate(SubExpr); 5451 5452 if (!Initializing) { 5453 std::optional<unsigned> LocalIndex = allocateLocal(SubExpr); 5454 if (!LocalIndex) 5455 return false; 5456 if (!this->emitGetPtrLocal(*LocalIndex, E)) 5457 return false; 5458 } 5459 5460 // The offset of the temporary, if we created one. 5461 unsigned SubExprOffset = 5462 this->allocateLocalPrimitive(SubExpr, PT_Ptr, true, false); 5463 if (!this->visit(SubExpr)) 5464 return false; 5465 if (!this->emitSetLocal(PT_Ptr, SubExprOffset, E)) 5466 return false; 5467 5468 const auto *VecTy = SubExpr->getType()->getAs<VectorType>(); 5469 PrimType ElemT = classifyVectorElementType(SubExpr->getType()); 5470 auto getElem = [=](unsigned Offset, unsigned Index) -> bool { 5471 if (!this->emitGetLocal(PT_Ptr, Offset, E)) 5472 return false; 5473 return this->emitArrayElemPop(ElemT, Index, E); 5474 }; 5475 5476 switch (UnaryOp) { 5477 case UO_Minus: 5478 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) { 5479 if (!getElem(SubExprOffset, I)) 5480 return false; 5481 if (!this->emitNeg(ElemT, E)) 5482 return false; 5483 if (!this->emitInitElem(ElemT, I, E)) 5484 return false; 5485 } 5486 break; 5487 case UO_LNot: { // !x 5488 // In C++, the logic operators !, &&, || are available for vectors. !v is 5489 // equivalent to v == 0. 5490 // 5491 // The result of the comparison is a vector of the same width and number of 5492 // elements as the comparison operands with a signed integral element type. 5493 // 5494 // https://gcc.gnu.org/onlinedocs/gcc/Vector-Extensions.html 5495 QualType ResultVecTy = E->getType(); 5496 PrimType ResultVecElemT = 5497 classifyPrim(ResultVecTy->getAs<VectorType>()->getElementType()); 5498 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) { 5499 if (!getElem(SubExprOffset, I)) 5500 return false; 5501 // operator ! on vectors returns -1 for 'truth', so negate it. 5502 if (!this->emitPrimCast(ElemT, PT_Bool, Ctx.getASTContext().BoolTy, E)) 5503 return false; 5504 if (!this->emitInv(E)) 5505 return false; 5506 if (!this->emitPrimCast(PT_Bool, ElemT, VecTy->getElementType(), E)) 5507 return false; 5508 if (!this->emitNeg(ElemT, E)) 5509 return false; 5510 if (ElemT != ResultVecElemT && 5511 !this->emitPrimCast(ElemT, ResultVecElemT, ResultVecTy, E)) 5512 return false; 5513 if (!this->emitInitElem(ResultVecElemT, I, E)) 5514 return false; 5515 } 5516 break; 5517 } 5518 case UO_Not: // ~x 5519 for (unsigned I = 0; I != VecTy->getNumElements(); ++I) { 5520 if (!getElem(SubExprOffset, I)) 5521 return false; 5522 if (ElemT == PT_Bool) { 5523 if (!this->emitInv(E)) 5524 return false; 5525 } else { 5526 if (!this->emitComp(ElemT, E)) 5527 return false; 5528 } 5529 if (!this->emitInitElem(ElemT, I, E)) 5530 return false; 5531 } 5532 break; 5533 default: 5534 llvm_unreachable("Unsupported unary operators should be handled up front"); 5535 } 5536 return true; 5537 } 5538 5539 template <class Emitter> 5540 bool Compiler<Emitter>::visitDeclRef(const ValueDecl *D, const Expr *E) { 5541 if (DiscardResult) 5542 return true; 5543 5544 if (const auto *ECD = dyn_cast<EnumConstantDecl>(D)) { 5545 return this->emitConst(ECD->getInitVal(), E); 5546 } else if (const auto *BD = dyn_cast<BindingDecl>(D)) { 5547 return this->visit(BD->getBinding()); 5548 } else if (const auto *FuncDecl = dyn_cast<FunctionDecl>(D)) { 5549 const Function *F = getFunction(FuncDecl); 5550 return F && this->emitGetFnPtr(F, E); 5551 } else if (const auto *TPOD = dyn_cast<TemplateParamObjectDecl>(D)) { 5552 if (std::optional<unsigned> Index = P.getOrCreateGlobal(D)) { 5553 if (!this->emitGetPtrGlobal(*Index, E)) 5554 return false; 5555 if (std::optional<PrimType> T = classify(E->getType())) { 5556 if (!this->visitAPValue(TPOD->getValue(), *T, E)) 5557 return false; 5558 return this->emitInitGlobal(*T, *Index, E); 5559 } 5560 return this->visitAPValueInitializer(TPOD->getValue(), E); 5561 } 5562 return false; 5563 } 5564 5565 // References are implemented via pointers, so when we see a DeclRefExpr 5566 // pointing to a reference, we need to get its value directly (i.e. the 5567 // pointer to the actual value) instead of a pointer to the pointer to the 5568 // value. 5569 bool IsReference = D->getType()->isReferenceType(); 5570 5571 // Check for local/global variables and parameters. 5572 if (auto It = Locals.find(D); It != Locals.end()) { 5573 const unsigned Offset = It->second.Offset; 5574 if (IsReference) 5575 return this->emitGetLocal(PT_Ptr, Offset, E); 5576 return this->emitGetPtrLocal(Offset, E); 5577 } else if (auto GlobalIndex = P.getGlobal(D)) { 5578 if (IsReference) { 5579 if (!Ctx.getLangOpts().CPlusPlus11) 5580 return this->emitGetGlobal(classifyPrim(E), *GlobalIndex, E); 5581 return this->emitGetGlobalUnchecked(classifyPrim(E), *GlobalIndex, E); 5582 } 5583 5584 return this->emitGetPtrGlobal(*GlobalIndex, E); 5585 } else if (const auto *PVD = dyn_cast<ParmVarDecl>(D)) { 5586 if (auto It = this->Params.find(PVD); It != this->Params.end()) { 5587 if (IsReference || !It->second.IsPtr) 5588 return this->emitGetParam(classifyPrim(E), It->second.Offset, E); 5589 5590 return this->emitGetPtrParam(It->second.Offset, E); 5591 } 5592 } 5593 5594 // In case we need to re-visit a declaration. 5595 auto revisit = [&](const VarDecl *VD) -> bool { 5596 auto VarState = this->visitDecl(VD); 5597 5598 if (VarState.notCreated()) 5599 return true; 5600 if (!VarState) 5601 return false; 5602 // Retry. 5603 return this->visitDeclRef(D, E); 5604 }; 5605 5606 // Handle lambda captures. 5607 if (auto It = this->LambdaCaptures.find(D); 5608 It != this->LambdaCaptures.end()) { 5609 auto [Offset, IsPtr] = It->second; 5610 5611 if (IsPtr) 5612 return this->emitGetThisFieldPtr(Offset, E); 5613 return this->emitGetPtrThisField(Offset, E); 5614 } else if (const auto *DRE = dyn_cast<DeclRefExpr>(E); 5615 DRE && DRE->refersToEnclosingVariableOrCapture()) { 5616 if (const auto *VD = dyn_cast<VarDecl>(D); VD && VD->isInitCapture()) 5617 return revisit(VD); 5618 } 5619 5620 if (D != InitializingDecl) { 5621 // Try to lazily visit (or emit dummy pointers for) declarations 5622 // we haven't seen yet. 5623 if (Ctx.getLangOpts().CPlusPlus) { 5624 if (const auto *VD = dyn_cast<VarDecl>(D)) { 5625 const auto typeShouldBeVisited = [&](QualType T) -> bool { 5626 if (T.isConstant(Ctx.getASTContext())) 5627 return true; 5628 if (const auto *RT = T->getAs<ReferenceType>()) 5629 return RT->getPointeeType().isConstQualified(); 5630 return false; 5631 }; 5632 5633 // DecompositionDecls are just proxies for us. 5634 if (isa<DecompositionDecl>(VD)) 5635 return revisit(VD); 5636 5637 if ((VD->hasGlobalStorage() || VD->isStaticDataMember()) && 5638 typeShouldBeVisited(VD->getType())) 5639 return revisit(VD); 5640 5641 // FIXME: The evaluateValue() check here is a little ridiculous, since 5642 // it will ultimately call into Context::evaluateAsInitializer(). In 5643 // other words, we're evaluating the initializer, just to know if we can 5644 // evaluate the initializer. 5645 if (VD->isLocalVarDecl() && typeShouldBeVisited(VD->getType()) && 5646 VD->getInit() && !VD->getInit()->isValueDependent() && 5647 VD->evaluateValue()) 5648 return revisit(VD); 5649 } 5650 } else { 5651 if (const auto *VD = dyn_cast<VarDecl>(D); 5652 VD && VD->getAnyInitializer() && 5653 VD->getType().isConstant(Ctx.getASTContext()) && !VD->isWeak()) 5654 return revisit(VD); 5655 } 5656 } 5657 5658 if (std::optional<unsigned> I = P.getOrCreateDummy(D)) { 5659 if (!this->emitGetPtrGlobal(*I, E)) 5660 return false; 5661 if (E->getType()->isVoidType()) 5662 return true; 5663 // Convert the dummy pointer to another pointer type if we have to. 5664 if (PrimType PT = classifyPrim(E); PT != PT_Ptr) { 5665 if (isPtrType(PT)) 5666 return this->emitDecayPtr(PT_Ptr, PT, E); 5667 return false; 5668 } 5669 return true; 5670 } 5671 5672 if (const auto *DRE = dyn_cast<DeclRefExpr>(E)) 5673 return this->emitInvalidDeclRef(DRE, E); 5674 return false; 5675 } 5676 5677 template <class Emitter> 5678 bool Compiler<Emitter>::VisitDeclRefExpr(const DeclRefExpr *E) { 5679 const auto *D = E->getDecl(); 5680 return this->visitDeclRef(D, E); 5681 } 5682 5683 template <class Emitter> void Compiler<Emitter>::emitCleanup() { 5684 for (VariableScope<Emitter> *C = VarScope; C; C = C->getParent()) 5685 C->emitDestruction(); 5686 } 5687 5688 template <class Emitter> 5689 unsigned Compiler<Emitter>::collectBaseOffset(const QualType BaseType, 5690 const QualType DerivedType) { 5691 const auto extractRecordDecl = [](QualType Ty) -> const CXXRecordDecl * { 5692 if (const auto *R = Ty->getPointeeCXXRecordDecl()) 5693 return R; 5694 return Ty->getAsCXXRecordDecl(); 5695 }; 5696 const CXXRecordDecl *BaseDecl = extractRecordDecl(BaseType); 5697 const CXXRecordDecl *DerivedDecl = extractRecordDecl(DerivedType); 5698 5699 return Ctx.collectBaseOffset(BaseDecl, DerivedDecl); 5700 } 5701 5702 /// Emit casts from a PrimType to another PrimType. 5703 template <class Emitter> 5704 bool Compiler<Emitter>::emitPrimCast(PrimType FromT, PrimType ToT, 5705 QualType ToQT, const Expr *E) { 5706 5707 if (FromT == PT_Float) { 5708 // Floating to floating. 5709 if (ToT == PT_Float) { 5710 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT); 5711 return this->emitCastFP(ToSem, getRoundingMode(E), E); 5712 } 5713 5714 if (ToT == PT_IntAP) 5715 return this->emitCastFloatingIntegralAP(Ctx.getBitWidth(ToQT), 5716 getFPOptions(E), E); 5717 if (ToT == PT_IntAPS) 5718 return this->emitCastFloatingIntegralAPS(Ctx.getBitWidth(ToQT), 5719 getFPOptions(E), E); 5720 5721 // Float to integral. 5722 if (isIntegralType(ToT) || ToT == PT_Bool) 5723 return this->emitCastFloatingIntegral(ToT, getFPOptions(E), E); 5724 } 5725 5726 if (isIntegralType(FromT) || FromT == PT_Bool) { 5727 if (ToT == PT_IntAP) 5728 return this->emitCastAP(FromT, Ctx.getBitWidth(ToQT), E); 5729 if (ToT == PT_IntAPS) 5730 return this->emitCastAPS(FromT, Ctx.getBitWidth(ToQT), E); 5731 5732 // Integral to integral. 5733 if (isIntegralType(ToT) || ToT == PT_Bool) 5734 return FromT != ToT ? this->emitCast(FromT, ToT, E) : true; 5735 5736 if (ToT == PT_Float) { 5737 // Integral to floating. 5738 const llvm::fltSemantics *ToSem = &Ctx.getFloatSemantics(ToQT); 5739 return this->emitCastIntegralFloating(FromT, ToSem, getFPOptions(E), E); 5740 } 5741 } 5742 5743 return false; 5744 } 5745 5746 /// Emits __real(SubExpr) 5747 template <class Emitter> 5748 bool Compiler<Emitter>::emitComplexReal(const Expr *SubExpr) { 5749 assert(SubExpr->getType()->isAnyComplexType()); 5750 5751 if (DiscardResult) 5752 return this->discard(SubExpr); 5753 5754 if (!this->visit(SubExpr)) 5755 return false; 5756 if (SubExpr->isLValue()) { 5757 if (!this->emitConstUint8(0, SubExpr)) 5758 return false; 5759 return this->emitArrayElemPtrPopUint8(SubExpr); 5760 } 5761 5762 // Rvalue, load the actual element. 5763 return this->emitArrayElemPop(classifyComplexElementType(SubExpr->getType()), 5764 0, SubExpr); 5765 } 5766 5767 template <class Emitter> 5768 bool Compiler<Emitter>::emitComplexBoolCast(const Expr *E) { 5769 assert(!DiscardResult); 5770 PrimType ElemT = classifyComplexElementType(E->getType()); 5771 // We emit the expression (__real(E) != 0 || __imag(E) != 0) 5772 // for us, that means (bool)E[0] || (bool)E[1] 5773 if (!this->emitArrayElem(ElemT, 0, E)) 5774 return false; 5775 if (ElemT == PT_Float) { 5776 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E)) 5777 return false; 5778 } else { 5779 if (!this->emitCast(ElemT, PT_Bool, E)) 5780 return false; 5781 } 5782 5783 // We now have the bool value of E[0] on the stack. 5784 LabelTy LabelTrue = this->getLabel(); 5785 if (!this->jumpTrue(LabelTrue)) 5786 return false; 5787 5788 if (!this->emitArrayElemPop(ElemT, 1, E)) 5789 return false; 5790 if (ElemT == PT_Float) { 5791 if (!this->emitCastFloatingIntegral(PT_Bool, getFPOptions(E), E)) 5792 return false; 5793 } else { 5794 if (!this->emitCast(ElemT, PT_Bool, E)) 5795 return false; 5796 } 5797 // Leave the boolean value of E[1] on the stack. 5798 LabelTy EndLabel = this->getLabel(); 5799 this->jump(EndLabel); 5800 5801 this->emitLabel(LabelTrue); 5802 if (!this->emitPopPtr(E)) 5803 return false; 5804 if (!this->emitConstBool(true, E)) 5805 return false; 5806 5807 this->fallthrough(EndLabel); 5808 this->emitLabel(EndLabel); 5809 5810 return true; 5811 } 5812 5813 template <class Emitter> 5814 bool Compiler<Emitter>::emitComplexComparison(const Expr *LHS, const Expr *RHS, 5815 const BinaryOperator *E) { 5816 assert(E->isComparisonOp()); 5817 assert(!Initializing); 5818 assert(!DiscardResult); 5819 5820 PrimType ElemT; 5821 bool LHSIsComplex; 5822 unsigned LHSOffset; 5823 if (LHS->getType()->isAnyComplexType()) { 5824 LHSIsComplex = true; 5825 ElemT = classifyComplexElementType(LHS->getType()); 5826 LHSOffset = allocateLocalPrimitive(LHS, PT_Ptr, /*IsConst=*/true, 5827 /*IsExtended=*/false); 5828 if (!this->visit(LHS)) 5829 return false; 5830 if (!this->emitSetLocal(PT_Ptr, LHSOffset, E)) 5831 return false; 5832 } else { 5833 LHSIsComplex = false; 5834 PrimType LHST = classifyPrim(LHS->getType()); 5835 LHSOffset = this->allocateLocalPrimitive(LHS, LHST, true, false); 5836 if (!this->visit(LHS)) 5837 return false; 5838 if (!this->emitSetLocal(LHST, LHSOffset, E)) 5839 return false; 5840 } 5841 5842 bool RHSIsComplex; 5843 unsigned RHSOffset; 5844 if (RHS->getType()->isAnyComplexType()) { 5845 RHSIsComplex = true; 5846 ElemT = classifyComplexElementType(RHS->getType()); 5847 RHSOffset = allocateLocalPrimitive(RHS, PT_Ptr, /*IsConst=*/true, 5848 /*IsExtended=*/false); 5849 if (!this->visit(RHS)) 5850 return false; 5851 if (!this->emitSetLocal(PT_Ptr, RHSOffset, E)) 5852 return false; 5853 } else { 5854 RHSIsComplex = false; 5855 PrimType RHST = classifyPrim(RHS->getType()); 5856 RHSOffset = this->allocateLocalPrimitive(RHS, RHST, true, false); 5857 if (!this->visit(RHS)) 5858 return false; 5859 if (!this->emitSetLocal(RHST, RHSOffset, E)) 5860 return false; 5861 } 5862 5863 auto getElem = [&](unsigned LocalOffset, unsigned Index, 5864 bool IsComplex) -> bool { 5865 if (IsComplex) { 5866 if (!this->emitGetLocal(PT_Ptr, LocalOffset, E)) 5867 return false; 5868 return this->emitArrayElemPop(ElemT, Index, E); 5869 } 5870 return this->emitGetLocal(ElemT, LocalOffset, E); 5871 }; 5872 5873 for (unsigned I = 0; I != 2; ++I) { 5874 // Get both values. 5875 if (!getElem(LHSOffset, I, LHSIsComplex)) 5876 return false; 5877 if (!getElem(RHSOffset, I, RHSIsComplex)) 5878 return false; 5879 // And compare them. 5880 if (!this->emitEQ(ElemT, E)) 5881 return false; 5882 5883 if (!this->emitCastBoolUint8(E)) 5884 return false; 5885 } 5886 5887 // We now have two bool values on the stack. Compare those. 5888 if (!this->emitAddUint8(E)) 5889 return false; 5890 if (!this->emitConstUint8(2, E)) 5891 return false; 5892 5893 if (E->getOpcode() == BO_EQ) { 5894 if (!this->emitEQUint8(E)) 5895 return false; 5896 } else if (E->getOpcode() == BO_NE) { 5897 if (!this->emitNEUint8(E)) 5898 return false; 5899 } else 5900 return false; 5901 5902 // In C, this returns an int. 5903 if (PrimType ResT = classifyPrim(E->getType()); ResT != PT_Bool) 5904 return this->emitCast(PT_Bool, ResT, E); 5905 return true; 5906 } 5907 5908 /// When calling this, we have a pointer of the local-to-destroy 5909 /// on the stack. 5910 /// Emit destruction of record types (or arrays of record types). 5911 template <class Emitter> 5912 bool Compiler<Emitter>::emitRecordDestruction(const Record *R) { 5913 assert(R); 5914 const CXXDestructorDecl *Dtor = R->getDestructor(); 5915 if (!Dtor || Dtor->isTrivial()) 5916 return true; 5917 5918 assert(Dtor); 5919 const Function *DtorFunc = getFunction(Dtor); 5920 if (!DtorFunc) 5921 return false; 5922 assert(DtorFunc->hasThisPointer()); 5923 assert(DtorFunc->getNumParams() == 1); 5924 if (!this->emitDupPtr(SourceInfo{})) 5925 return false; 5926 return this->emitCall(DtorFunc, 0, SourceInfo{}); 5927 } 5928 /// When calling this, we have a pointer of the local-to-destroy 5929 /// on the stack. 5930 /// Emit destruction of record types (or arrays of record types). 5931 template <class Emitter> 5932 bool Compiler<Emitter>::emitDestruction(const Descriptor *Desc) { 5933 assert(Desc); 5934 assert(!Desc->isPrimitive()); 5935 assert(!Desc->isPrimitiveArray()); 5936 5937 // Arrays. 5938 if (Desc->isArray()) { 5939 const Descriptor *ElemDesc = Desc->ElemDesc; 5940 assert(ElemDesc); 5941 5942 // Don't need to do anything for these. 5943 if (ElemDesc->isPrimitiveArray()) 5944 return true; 5945 5946 // If this is an array of record types, check if we need 5947 // to call the element destructors at all. If not, try 5948 // to save the work. 5949 if (const Record *ElemRecord = ElemDesc->ElemRecord) { 5950 if (const CXXDestructorDecl *Dtor = ElemRecord->getDestructor(); 5951 !Dtor || Dtor->isTrivial()) 5952 return true; 5953 } 5954 5955 for (ssize_t I = Desc->getNumElems() - 1; I >= 0; --I) { 5956 if (!this->emitConstUint64(I, SourceInfo{})) 5957 return false; 5958 if (!this->emitArrayElemPtrUint64(SourceInfo{})) 5959 return false; 5960 if (!this->emitDestruction(ElemDesc)) 5961 return false; 5962 if (!this->emitPopPtr(SourceInfo{})) 5963 return false; 5964 } 5965 return true; 5966 } 5967 5968 assert(Desc->ElemRecord); 5969 return this->emitRecordDestruction(Desc->ElemRecord); 5970 } 5971 5972 namespace clang { 5973 namespace interp { 5974 5975 template class Compiler<ByteCodeEmitter>; 5976 template class Compiler<EvalEmitter>; 5977 5978 } // namespace interp 5979 } // namespace clang 5980