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