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