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