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