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