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