1 //===--- CGClass.cpp - Emit LLVM Code for C++ classes -----------*- C++ -*-===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // 10 // This contains code dealing with C++ code generation of classes 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "CGBlocks.h" 15 #include "CGCXXABI.h" 16 #include "CGDebugInfo.h" 17 #include "CGRecordLayout.h" 18 #include "CodeGenFunction.h" 19 #include "clang/AST/CXXInheritance.h" 20 #include "clang/AST/DeclTemplate.h" 21 #include "clang/AST/EvaluatedExprVisitor.h" 22 #include "clang/AST/RecordLayout.h" 23 #include "clang/AST/StmtCXX.h" 24 #include "clang/Basic/TargetBuiltins.h" 25 #include "clang/CodeGen/CGFunctionInfo.h" 26 #include "clang/Frontend/CodeGenOptions.h" 27 #include "llvm/IR/Intrinsics.h" 28 #include "llvm/IR/Metadata.h" 29 #include "llvm/Transforms/Utils/SanitizerStats.h" 30 31 using namespace clang; 32 using namespace CodeGen; 33 34 /// Return the best known alignment for an unknown pointer to a 35 /// particular class. 36 CharUnits CodeGenModule::getClassPointerAlignment(const CXXRecordDecl *RD) { 37 if (!RD->isCompleteDefinition()) 38 return CharUnits::One(); // Hopefully won't be used anywhere. 39 40 auto &layout = getContext().getASTRecordLayout(RD); 41 42 // If the class is final, then we know that the pointer points to an 43 // object of that type and can use the full alignment. 44 if (RD->hasAttr<FinalAttr>()) { 45 return layout.getAlignment(); 46 47 // Otherwise, we have to assume it could be a subclass. 48 } else { 49 return layout.getNonVirtualAlignment(); 50 } 51 } 52 53 /// Return the best known alignment for a pointer to a virtual base, 54 /// given the alignment of a pointer to the derived class. 55 CharUnits CodeGenModule::getVBaseAlignment(CharUnits actualDerivedAlign, 56 const CXXRecordDecl *derivedClass, 57 const CXXRecordDecl *vbaseClass) { 58 // The basic idea here is that an underaligned derived pointer might 59 // indicate an underaligned base pointer. 60 61 assert(vbaseClass->isCompleteDefinition()); 62 auto &baseLayout = getContext().getASTRecordLayout(vbaseClass); 63 CharUnits expectedVBaseAlign = baseLayout.getNonVirtualAlignment(); 64 65 return getDynamicOffsetAlignment(actualDerivedAlign, derivedClass, 66 expectedVBaseAlign); 67 } 68 69 CharUnits 70 CodeGenModule::getDynamicOffsetAlignment(CharUnits actualBaseAlign, 71 const CXXRecordDecl *baseDecl, 72 CharUnits expectedTargetAlign) { 73 // If the base is an incomplete type (which is, alas, possible with 74 // member pointers), be pessimistic. 75 if (!baseDecl->isCompleteDefinition()) 76 return std::min(actualBaseAlign, expectedTargetAlign); 77 78 auto &baseLayout = getContext().getASTRecordLayout(baseDecl); 79 CharUnits expectedBaseAlign = baseLayout.getNonVirtualAlignment(); 80 81 // If the class is properly aligned, assume the target offset is, too. 82 // 83 // This actually isn't necessarily the right thing to do --- if the 84 // class is a complete object, but it's only properly aligned for a 85 // base subobject, then the alignments of things relative to it are 86 // probably off as well. (Note that this requires the alignment of 87 // the target to be greater than the NV alignment of the derived 88 // class.) 89 // 90 // However, our approach to this kind of under-alignment can only 91 // ever be best effort; after all, we're never going to propagate 92 // alignments through variables or parameters. Note, in particular, 93 // that constructing a polymorphic type in an address that's less 94 // than pointer-aligned will generally trap in the constructor, 95 // unless we someday add some sort of attribute to change the 96 // assumed alignment of 'this'. So our goal here is pretty much 97 // just to allow the user to explicitly say that a pointer is 98 // under-aligned and then safely access its fields and vtables. 99 if (actualBaseAlign >= expectedBaseAlign) { 100 return expectedTargetAlign; 101 } 102 103 // Otherwise, we might be offset by an arbitrary multiple of the 104 // actual alignment. The correct adjustment is to take the min of 105 // the two alignments. 106 return std::min(actualBaseAlign, expectedTargetAlign); 107 } 108 109 Address CodeGenFunction::LoadCXXThisAddress() { 110 assert(CurFuncDecl && "loading 'this' without a func declaration?"); 111 assert(isa<CXXMethodDecl>(CurFuncDecl)); 112 113 // Lazily compute CXXThisAlignment. 114 if (CXXThisAlignment.isZero()) { 115 // Just use the best known alignment for the parent. 116 // TODO: if we're currently emitting a complete-object ctor/dtor, 117 // we can always use the complete-object alignment. 118 auto RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent(); 119 CXXThisAlignment = CGM.getClassPointerAlignment(RD); 120 } 121 122 return Address(LoadCXXThis(), CXXThisAlignment); 123 } 124 125 /// Emit the address of a field using a member data pointer. 126 /// 127 /// \param E Only used for emergency diagnostics 128 Address 129 CodeGenFunction::EmitCXXMemberDataPointerAddress(const Expr *E, Address base, 130 llvm::Value *memberPtr, 131 const MemberPointerType *memberPtrType, 132 AlignmentSource *alignSource) { 133 // Ask the ABI to compute the actual address. 134 llvm::Value *ptr = 135 CGM.getCXXABI().EmitMemberDataPointerAddress(*this, E, base, 136 memberPtr, memberPtrType); 137 138 QualType memberType = memberPtrType->getPointeeType(); 139 CharUnits memberAlign = getNaturalTypeAlignment(memberType, alignSource); 140 memberAlign = 141 CGM.getDynamicOffsetAlignment(base.getAlignment(), 142 memberPtrType->getClass()->getAsCXXRecordDecl(), 143 memberAlign); 144 return Address(ptr, memberAlign); 145 } 146 147 CharUnits CodeGenModule::computeNonVirtualBaseClassOffset( 148 const CXXRecordDecl *DerivedClass, CastExpr::path_const_iterator Start, 149 CastExpr::path_const_iterator End) { 150 CharUnits Offset = CharUnits::Zero(); 151 152 const ASTContext &Context = getContext(); 153 const CXXRecordDecl *RD = DerivedClass; 154 155 for (CastExpr::path_const_iterator I = Start; I != End; ++I) { 156 const CXXBaseSpecifier *Base = *I; 157 assert(!Base->isVirtual() && "Should not see virtual bases here!"); 158 159 // Get the layout. 160 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 161 162 const CXXRecordDecl *BaseDecl = 163 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 164 165 // Add the offset. 166 Offset += Layout.getBaseClassOffset(BaseDecl); 167 168 RD = BaseDecl; 169 } 170 171 return Offset; 172 } 173 174 llvm::Constant * 175 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 176 CastExpr::path_const_iterator PathBegin, 177 CastExpr::path_const_iterator PathEnd) { 178 assert(PathBegin != PathEnd && "Base path should not be empty!"); 179 180 CharUnits Offset = 181 computeNonVirtualBaseClassOffset(ClassDecl, PathBegin, PathEnd); 182 if (Offset.isZero()) 183 return nullptr; 184 185 llvm::Type *PtrDiffTy = 186 Types.ConvertType(getContext().getPointerDiffType()); 187 188 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity()); 189 } 190 191 /// Gets the address of a direct base class within a complete object. 192 /// This should only be used for (1) non-virtual bases or (2) virtual bases 193 /// when the type is known to be complete (e.g. in complete destructors). 194 /// 195 /// The object pointed to by 'This' is assumed to be non-null. 196 Address 197 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(Address This, 198 const CXXRecordDecl *Derived, 199 const CXXRecordDecl *Base, 200 bool BaseIsVirtual) { 201 // 'this' must be a pointer (in some address space) to Derived. 202 assert(This.getElementType() == ConvertType(Derived)); 203 204 // Compute the offset of the virtual base. 205 CharUnits Offset; 206 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived); 207 if (BaseIsVirtual) 208 Offset = Layout.getVBaseClassOffset(Base); 209 else 210 Offset = Layout.getBaseClassOffset(Base); 211 212 // Shift and cast down to the base type. 213 // TODO: for complete types, this should be possible with a GEP. 214 Address V = This; 215 if (!Offset.isZero()) { 216 V = Builder.CreateElementBitCast(V, Int8Ty); 217 V = Builder.CreateConstInBoundsByteGEP(V, Offset); 218 } 219 V = Builder.CreateElementBitCast(V, ConvertType(Base)); 220 221 return V; 222 } 223 224 static Address 225 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, Address addr, 226 CharUnits nonVirtualOffset, 227 llvm::Value *virtualOffset, 228 const CXXRecordDecl *derivedClass, 229 const CXXRecordDecl *nearestVBase) { 230 // Assert that we have something to do. 231 assert(!nonVirtualOffset.isZero() || virtualOffset != nullptr); 232 233 // Compute the offset from the static and dynamic components. 234 llvm::Value *baseOffset; 235 if (!nonVirtualOffset.isZero()) { 236 baseOffset = llvm::ConstantInt::get(CGF.PtrDiffTy, 237 nonVirtualOffset.getQuantity()); 238 if (virtualOffset) { 239 baseOffset = CGF.Builder.CreateAdd(virtualOffset, baseOffset); 240 } 241 } else { 242 baseOffset = virtualOffset; 243 } 244 245 // Apply the base offset. 246 llvm::Value *ptr = addr.getPointer(); 247 ptr = CGF.Builder.CreateBitCast(ptr, CGF.Int8PtrTy); 248 ptr = CGF.Builder.CreateInBoundsGEP(ptr, baseOffset, "add.ptr"); 249 250 // If we have a virtual component, the alignment of the result will 251 // be relative only to the known alignment of that vbase. 252 CharUnits alignment; 253 if (virtualOffset) { 254 assert(nearestVBase && "virtual offset without vbase?"); 255 alignment = CGF.CGM.getVBaseAlignment(addr.getAlignment(), 256 derivedClass, nearestVBase); 257 } else { 258 alignment = addr.getAlignment(); 259 } 260 alignment = alignment.alignmentAtOffset(nonVirtualOffset); 261 262 return Address(ptr, alignment); 263 } 264 265 Address CodeGenFunction::GetAddressOfBaseClass( 266 Address Value, const CXXRecordDecl *Derived, 267 CastExpr::path_const_iterator PathBegin, 268 CastExpr::path_const_iterator PathEnd, bool NullCheckValue, 269 SourceLocation Loc) { 270 assert(PathBegin != PathEnd && "Base path should not be empty!"); 271 272 CastExpr::path_const_iterator Start = PathBegin; 273 const CXXRecordDecl *VBase = nullptr; 274 275 // Sema has done some convenient canonicalization here: if the 276 // access path involved any virtual steps, the conversion path will 277 // *start* with a step down to the correct virtual base subobject, 278 // and hence will not require any further steps. 279 if ((*Start)->isVirtual()) { 280 VBase = 281 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl()); 282 ++Start; 283 } 284 285 // Compute the static offset of the ultimate destination within its 286 // allocating subobject (the virtual base, if there is one, or else 287 // the "complete" object that we see). 288 CharUnits NonVirtualOffset = CGM.computeNonVirtualBaseClassOffset( 289 VBase ? VBase : Derived, Start, PathEnd); 290 291 // If there's a virtual step, we can sometimes "devirtualize" it. 292 // For now, that's limited to when the derived type is final. 293 // TODO: "devirtualize" this for accesses to known-complete objects. 294 if (VBase && Derived->hasAttr<FinalAttr>()) { 295 const ASTRecordLayout &layout = getContext().getASTRecordLayout(Derived); 296 CharUnits vBaseOffset = layout.getVBaseClassOffset(VBase); 297 NonVirtualOffset += vBaseOffset; 298 VBase = nullptr; // we no longer have a virtual step 299 } 300 301 // Get the base pointer type. 302 llvm::Type *BasePtrTy = 303 ConvertType((PathEnd[-1])->getType())->getPointerTo(); 304 305 QualType DerivedTy = getContext().getRecordType(Derived); 306 CharUnits DerivedAlign = CGM.getClassPointerAlignment(Derived); 307 308 // If the static offset is zero and we don't have a virtual step, 309 // just do a bitcast; null checks are unnecessary. 310 if (NonVirtualOffset.isZero() && !VBase) { 311 if (sanitizePerformTypeCheck()) { 312 EmitTypeCheck(TCK_Upcast, Loc, Value.getPointer(), 313 DerivedTy, DerivedAlign, !NullCheckValue); 314 } 315 return Builder.CreateBitCast(Value, BasePtrTy); 316 } 317 318 llvm::BasicBlock *origBB = nullptr; 319 llvm::BasicBlock *endBB = nullptr; 320 321 // Skip over the offset (and the vtable load) if we're supposed to 322 // null-check the pointer. 323 if (NullCheckValue) { 324 origBB = Builder.GetInsertBlock(); 325 llvm::BasicBlock *notNullBB = createBasicBlock("cast.notnull"); 326 endBB = createBasicBlock("cast.end"); 327 328 llvm::Value *isNull = Builder.CreateIsNull(Value.getPointer()); 329 Builder.CreateCondBr(isNull, endBB, notNullBB); 330 EmitBlock(notNullBB); 331 } 332 333 if (sanitizePerformTypeCheck()) { 334 EmitTypeCheck(VBase ? TCK_UpcastToVirtualBase : TCK_Upcast, Loc, 335 Value.getPointer(), DerivedTy, DerivedAlign, true); 336 } 337 338 // Compute the virtual offset. 339 llvm::Value *VirtualOffset = nullptr; 340 if (VBase) { 341 VirtualOffset = 342 CGM.getCXXABI().GetVirtualBaseClassOffset(*this, Value, Derived, VBase); 343 } 344 345 // Apply both offsets. 346 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, NonVirtualOffset, 347 VirtualOffset, Derived, VBase); 348 349 // Cast to the destination type. 350 Value = Builder.CreateBitCast(Value, BasePtrTy); 351 352 // Build a phi if we needed a null check. 353 if (NullCheckValue) { 354 llvm::BasicBlock *notNullBB = Builder.GetInsertBlock(); 355 Builder.CreateBr(endBB); 356 EmitBlock(endBB); 357 358 llvm::PHINode *PHI = Builder.CreatePHI(BasePtrTy, 2, "cast.result"); 359 PHI->addIncoming(Value.getPointer(), notNullBB); 360 PHI->addIncoming(llvm::Constant::getNullValue(BasePtrTy), origBB); 361 Value = Address(PHI, Value.getAlignment()); 362 } 363 364 return Value; 365 } 366 367 Address 368 CodeGenFunction::GetAddressOfDerivedClass(Address BaseAddr, 369 const CXXRecordDecl *Derived, 370 CastExpr::path_const_iterator PathBegin, 371 CastExpr::path_const_iterator PathEnd, 372 bool NullCheckValue) { 373 assert(PathBegin != PathEnd && "Base path should not be empty!"); 374 375 QualType DerivedTy = 376 getContext().getCanonicalType(getContext().getTagDeclType(Derived)); 377 llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo(); 378 379 llvm::Value *NonVirtualOffset = 380 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd); 381 382 if (!NonVirtualOffset) { 383 // No offset, we can just cast back. 384 return Builder.CreateBitCast(BaseAddr, DerivedPtrTy); 385 } 386 387 llvm::BasicBlock *CastNull = nullptr; 388 llvm::BasicBlock *CastNotNull = nullptr; 389 llvm::BasicBlock *CastEnd = nullptr; 390 391 if (NullCheckValue) { 392 CastNull = createBasicBlock("cast.null"); 393 CastNotNull = createBasicBlock("cast.notnull"); 394 CastEnd = createBasicBlock("cast.end"); 395 396 llvm::Value *IsNull = Builder.CreateIsNull(BaseAddr.getPointer()); 397 Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 398 EmitBlock(CastNotNull); 399 } 400 401 // Apply the offset. 402 llvm::Value *Value = Builder.CreateBitCast(BaseAddr.getPointer(), Int8PtrTy); 403 Value = Builder.CreateGEP(Value, Builder.CreateNeg(NonVirtualOffset), 404 "sub.ptr"); 405 406 // Just cast. 407 Value = Builder.CreateBitCast(Value, DerivedPtrTy); 408 409 // Produce a PHI if we had a null-check. 410 if (NullCheckValue) { 411 Builder.CreateBr(CastEnd); 412 EmitBlock(CastNull); 413 Builder.CreateBr(CastEnd); 414 EmitBlock(CastEnd); 415 416 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 417 PHI->addIncoming(Value, CastNotNull); 418 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), CastNull); 419 Value = PHI; 420 } 421 422 return Address(Value, CGM.getClassPointerAlignment(Derived)); 423 } 424 425 llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD, 426 bool ForVirtualBase, 427 bool Delegating) { 428 if (!CGM.getCXXABI().NeedsVTTParameter(GD)) { 429 // This constructor/destructor does not need a VTT parameter. 430 return nullptr; 431 } 432 433 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent(); 434 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent(); 435 436 llvm::Value *VTT; 437 438 uint64_t SubVTTIndex; 439 440 if (Delegating) { 441 // If this is a delegating constructor call, just load the VTT. 442 return LoadCXXVTT(); 443 } else if (RD == Base) { 444 // If the record matches the base, this is the complete ctor/dtor 445 // variant calling the base variant in a class with virtual bases. 446 assert(!CGM.getCXXABI().NeedsVTTParameter(CurGD) && 447 "doing no-op VTT offset in base dtor/ctor?"); 448 assert(!ForVirtualBase && "Can't have same class as virtual base!"); 449 SubVTTIndex = 0; 450 } else { 451 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 452 CharUnits BaseOffset = ForVirtualBase ? 453 Layout.getVBaseClassOffset(Base) : 454 Layout.getBaseClassOffset(Base); 455 456 SubVTTIndex = 457 CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset)); 458 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!"); 459 } 460 461 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) { 462 // A VTT parameter was passed to the constructor, use it. 463 VTT = LoadCXXVTT(); 464 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex); 465 } else { 466 // We're the complete constructor, so get the VTT by name. 467 VTT = CGM.getVTables().GetAddrOfVTT(RD); 468 VTT = Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex); 469 } 470 471 return VTT; 472 } 473 474 namespace { 475 /// Call the destructor for a direct base class. 476 struct CallBaseDtor final : EHScopeStack::Cleanup { 477 const CXXRecordDecl *BaseClass; 478 bool BaseIsVirtual; 479 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual) 480 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {} 481 482 void Emit(CodeGenFunction &CGF, Flags flags) override { 483 const CXXRecordDecl *DerivedClass = 484 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent(); 485 486 const CXXDestructorDecl *D = BaseClass->getDestructor(); 487 Address Addr = 488 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThisAddress(), 489 DerivedClass, BaseClass, 490 BaseIsVirtual); 491 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, 492 /*Delegating=*/false, Addr); 493 } 494 }; 495 496 /// A visitor which checks whether an initializer uses 'this' in a 497 /// way which requires the vtable to be properly set. 498 struct DynamicThisUseChecker : ConstEvaluatedExprVisitor<DynamicThisUseChecker> { 499 typedef ConstEvaluatedExprVisitor<DynamicThisUseChecker> super; 500 501 bool UsesThis; 502 503 DynamicThisUseChecker(const ASTContext &C) : super(C), UsesThis(false) {} 504 505 // Black-list all explicit and implicit references to 'this'. 506 // 507 // Do we need to worry about external references to 'this' derived 508 // from arbitrary code? If so, then anything which runs arbitrary 509 // external code might potentially access the vtable. 510 void VisitCXXThisExpr(const CXXThisExpr *E) { UsesThis = true; } 511 }; 512 } // end anonymous namespace 513 514 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) { 515 DynamicThisUseChecker Checker(C); 516 Checker.Visit(Init); 517 return Checker.UsesThis; 518 } 519 520 static void EmitBaseInitializer(CodeGenFunction &CGF, 521 const CXXRecordDecl *ClassDecl, 522 CXXCtorInitializer *BaseInit, 523 CXXCtorType CtorType) { 524 assert(BaseInit->isBaseInitializer() && 525 "Must have base initializer!"); 526 527 Address ThisPtr = CGF.LoadCXXThisAddress(); 528 529 const Type *BaseType = BaseInit->getBaseClass(); 530 CXXRecordDecl *BaseClassDecl = 531 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()); 532 533 bool isBaseVirtual = BaseInit->isBaseVirtual(); 534 535 // The base constructor doesn't construct virtual bases. 536 if (CtorType == Ctor_Base && isBaseVirtual) 537 return; 538 539 // If the initializer for the base (other than the constructor 540 // itself) accesses 'this' in any way, we need to initialize the 541 // vtables. 542 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit())) 543 CGF.InitializeVTablePointers(ClassDecl); 544 545 // We can pretend to be a complete class because it only matters for 546 // virtual bases, and we only do virtual bases for complete ctors. 547 Address V = 548 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl, 549 BaseClassDecl, 550 isBaseVirtual); 551 AggValueSlot AggSlot = 552 AggValueSlot::forAddr(V, Qualifiers(), 553 AggValueSlot::IsDestructed, 554 AggValueSlot::DoesNotNeedGCBarriers, 555 AggValueSlot::IsNotAliased); 556 557 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot); 558 559 if (CGF.CGM.getLangOpts().Exceptions && 560 !BaseClassDecl->hasTrivialDestructor()) 561 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl, 562 isBaseVirtual); 563 } 564 565 static bool isMemcpyEquivalentSpecialMember(const CXXMethodDecl *D) { 566 auto *CD = dyn_cast<CXXConstructorDecl>(D); 567 if (!(CD && CD->isCopyOrMoveConstructor()) && 568 !D->isCopyAssignmentOperator() && !D->isMoveAssignmentOperator()) 569 return false; 570 571 // We can emit a memcpy for a trivial copy or move constructor/assignment. 572 if (D->isTrivial() && !D->getParent()->mayInsertExtraPadding()) 573 return true; 574 575 // We *must* emit a memcpy for a defaulted union copy or move op. 576 if (D->getParent()->isUnion() && D->isDefaulted()) 577 return true; 578 579 return false; 580 } 581 582 static void EmitLValueForAnyFieldInitialization(CodeGenFunction &CGF, 583 CXXCtorInitializer *MemberInit, 584 LValue &LHS) { 585 FieldDecl *Field = MemberInit->getAnyMember(); 586 if (MemberInit->isIndirectMemberInitializer()) { 587 // If we are initializing an anonymous union field, drill down to the field. 588 IndirectFieldDecl *IndirectField = MemberInit->getIndirectMember(); 589 for (const auto *I : IndirectField->chain()) 590 LHS = CGF.EmitLValueForFieldInitialization(LHS, cast<FieldDecl>(I)); 591 } else { 592 LHS = CGF.EmitLValueForFieldInitialization(LHS, Field); 593 } 594 } 595 596 static void EmitMemberInitializer(CodeGenFunction &CGF, 597 const CXXRecordDecl *ClassDecl, 598 CXXCtorInitializer *MemberInit, 599 const CXXConstructorDecl *Constructor, 600 FunctionArgList &Args) { 601 ApplyDebugLocation Loc(CGF, MemberInit->getSourceLocation()); 602 assert(MemberInit->isAnyMemberInitializer() && 603 "Must have member initializer!"); 604 assert(MemberInit->getInit() && "Must have initializer!"); 605 606 // non-static data member initializers. 607 FieldDecl *Field = MemberInit->getAnyMember(); 608 QualType FieldType = Field->getType(); 609 610 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 611 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl); 612 LValue LHS = CGF.MakeNaturalAlignAddrLValue(ThisPtr, RecordTy); 613 614 EmitLValueForAnyFieldInitialization(CGF, MemberInit, LHS); 615 616 // Special case: if we are in a copy or move constructor, and we are copying 617 // an array of PODs or classes with trivial copy constructors, ignore the 618 // AST and perform the copy we know is equivalent. 619 // FIXME: This is hacky at best... if we had a bit more explicit information 620 // in the AST, we could generalize it more easily. 621 const ConstantArrayType *Array 622 = CGF.getContext().getAsConstantArrayType(FieldType); 623 if (Array && Constructor->isDefaulted() && 624 Constructor->isCopyOrMoveConstructor()) { 625 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array); 626 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit()); 627 if (BaseElementTy.isPODType(CGF.getContext()) || 628 (CE && isMemcpyEquivalentSpecialMember(CE->getConstructor()))) { 629 unsigned SrcArgIndex = 630 CGF.CGM.getCXXABI().getSrcArgforCopyCtor(Constructor, Args); 631 llvm::Value *SrcPtr 632 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex])); 633 LValue ThisRHSLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy); 634 LValue Src = CGF.EmitLValueForFieldInitialization(ThisRHSLV, Field); 635 636 // Copy the aggregate. 637 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType, 638 LHS.isVolatileQualified()); 639 // Ensure that we destroy the objects if an exception is thrown later in 640 // the constructor. 641 QualType::DestructionKind dtorKind = FieldType.isDestructedType(); 642 if (CGF.needsEHCleanup(dtorKind)) 643 CGF.pushEHDestroy(dtorKind, LHS.getAddress(), FieldType); 644 return; 645 } 646 } 647 648 CGF.EmitInitializerForField(Field, LHS, MemberInit->getInit()); 649 } 650 651 void CodeGenFunction::EmitInitializerForField(FieldDecl *Field, LValue LHS, 652 Expr *Init) { 653 QualType FieldType = Field->getType(); 654 switch (getEvaluationKind(FieldType)) { 655 case TEK_Scalar: 656 if (LHS.isSimple()) { 657 EmitExprAsInit(Init, Field, LHS, false); 658 } else { 659 RValue RHS = RValue::get(EmitScalarExpr(Init)); 660 EmitStoreThroughLValue(RHS, LHS); 661 } 662 break; 663 case TEK_Complex: 664 EmitComplexExprIntoLValue(Init, LHS, /*isInit*/ true); 665 break; 666 case TEK_Aggregate: { 667 AggValueSlot Slot = 668 AggValueSlot::forLValue(LHS, 669 AggValueSlot::IsDestructed, 670 AggValueSlot::DoesNotNeedGCBarriers, 671 AggValueSlot::IsNotAliased); 672 EmitAggExpr(Init, Slot); 673 break; 674 } 675 } 676 677 // Ensure that we destroy this object if an exception is thrown 678 // later in the constructor. 679 QualType::DestructionKind dtorKind = FieldType.isDestructedType(); 680 if (needsEHCleanup(dtorKind)) 681 pushEHDestroy(dtorKind, LHS.getAddress(), FieldType); 682 } 683 684 /// Checks whether the given constructor is a valid subject for the 685 /// complete-to-base constructor delegation optimization, i.e. 686 /// emitting the complete constructor as a simple call to the base 687 /// constructor. 688 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) { 689 690 // Currently we disable the optimization for classes with virtual 691 // bases because (1) the addresses of parameter variables need to be 692 // consistent across all initializers but (2) the delegate function 693 // call necessarily creates a second copy of the parameter variable. 694 // 695 // The limiting example (purely theoretical AFAIK): 696 // struct A { A(int &c) { c++; } }; 697 // struct B : virtual A { 698 // B(int count) : A(count) { printf("%d\n", count); } 699 // }; 700 // ...although even this example could in principle be emitted as a 701 // delegation since the address of the parameter doesn't escape. 702 if (Ctor->getParent()->getNumVBases()) { 703 // TODO: white-list trivial vbase initializers. This case wouldn't 704 // be subject to the restrictions below. 705 706 // TODO: white-list cases where: 707 // - there are no non-reference parameters to the constructor 708 // - the initializers don't access any non-reference parameters 709 // - the initializers don't take the address of non-reference 710 // parameters 711 // - etc. 712 // If we ever add any of the above cases, remember that: 713 // - function-try-blocks will always blacklist this optimization 714 // - we need to perform the constructor prologue and cleanup in 715 // EmitConstructorBody. 716 717 return false; 718 } 719 720 // We also disable the optimization for variadic functions because 721 // it's impossible to "re-pass" varargs. 722 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic()) 723 return false; 724 725 // FIXME: Decide if we can do a delegation of a delegating constructor. 726 if (Ctor->isDelegatingConstructor()) 727 return false; 728 729 return true; 730 } 731 732 // Emit code in ctor (Prologue==true) or dtor (Prologue==false) 733 // to poison the extra field paddings inserted under 734 // -fsanitize-address-field-padding=1|2. 735 void CodeGenFunction::EmitAsanPrologueOrEpilogue(bool Prologue) { 736 ASTContext &Context = getContext(); 737 const CXXRecordDecl *ClassDecl = 738 Prologue ? cast<CXXConstructorDecl>(CurGD.getDecl())->getParent() 739 : cast<CXXDestructorDecl>(CurGD.getDecl())->getParent(); 740 if (!ClassDecl->mayInsertExtraPadding()) return; 741 742 struct SizeAndOffset { 743 uint64_t Size; 744 uint64_t Offset; 745 }; 746 747 unsigned PtrSize = CGM.getDataLayout().getPointerSizeInBits(); 748 const ASTRecordLayout &Info = Context.getASTRecordLayout(ClassDecl); 749 750 // Populate sizes and offsets of fields. 751 SmallVector<SizeAndOffset, 16> SSV(Info.getFieldCount()); 752 for (unsigned i = 0, e = Info.getFieldCount(); i != e; ++i) 753 SSV[i].Offset = 754 Context.toCharUnitsFromBits(Info.getFieldOffset(i)).getQuantity(); 755 756 size_t NumFields = 0; 757 for (const auto *Field : ClassDecl->fields()) { 758 const FieldDecl *D = Field; 759 std::pair<CharUnits, CharUnits> FieldInfo = 760 Context.getTypeInfoInChars(D->getType()); 761 CharUnits FieldSize = FieldInfo.first; 762 assert(NumFields < SSV.size()); 763 SSV[NumFields].Size = D->isBitField() ? 0 : FieldSize.getQuantity(); 764 NumFields++; 765 } 766 assert(NumFields == SSV.size()); 767 if (SSV.size() <= 1) return; 768 769 // We will insert calls to __asan_* run-time functions. 770 // LLVM AddressSanitizer pass may decide to inline them later. 771 llvm::Type *Args[2] = {IntPtrTy, IntPtrTy}; 772 llvm::FunctionType *FTy = 773 llvm::FunctionType::get(CGM.VoidTy, Args, false); 774 llvm::Constant *F = CGM.CreateRuntimeFunction( 775 FTy, Prologue ? "__asan_poison_intra_object_redzone" 776 : "__asan_unpoison_intra_object_redzone"); 777 778 llvm::Value *ThisPtr = LoadCXXThis(); 779 ThisPtr = Builder.CreatePtrToInt(ThisPtr, IntPtrTy); 780 uint64_t TypeSize = Info.getNonVirtualSize().getQuantity(); 781 // For each field check if it has sufficient padding, 782 // if so (un)poison it with a call. 783 for (size_t i = 0; i < SSV.size(); i++) { 784 uint64_t AsanAlignment = 8; 785 uint64_t NextField = i == SSV.size() - 1 ? TypeSize : SSV[i + 1].Offset; 786 uint64_t PoisonSize = NextField - SSV[i].Offset - SSV[i].Size; 787 uint64_t EndOffset = SSV[i].Offset + SSV[i].Size; 788 if (PoisonSize < AsanAlignment || !SSV[i].Size || 789 (NextField % AsanAlignment) != 0) 790 continue; 791 Builder.CreateCall( 792 F, {Builder.CreateAdd(ThisPtr, Builder.getIntN(PtrSize, EndOffset)), 793 Builder.getIntN(PtrSize, PoisonSize)}); 794 } 795 } 796 797 /// EmitConstructorBody - Emits the body of the current constructor. 798 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) { 799 EmitAsanPrologueOrEpilogue(true); 800 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl()); 801 CXXCtorType CtorType = CurGD.getCtorType(); 802 803 assert((CGM.getTarget().getCXXABI().hasConstructorVariants() || 804 CtorType == Ctor_Complete) && 805 "can only generate complete ctor for this ABI"); 806 807 // Before we go any further, try the complete->base constructor 808 // delegation optimization. 809 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) && 810 CGM.getTarget().getCXXABI().hasConstructorVariants()) { 811 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args, Ctor->getLocEnd()); 812 return; 813 } 814 815 const FunctionDecl *Definition = nullptr; 816 Stmt *Body = Ctor->getBody(Definition); 817 assert(Definition == Ctor && "emitting wrong constructor body"); 818 819 // Enter the function-try-block before the constructor prologue if 820 // applicable. 821 bool IsTryBody = (Body && isa<CXXTryStmt>(Body)); 822 if (IsTryBody) 823 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true); 824 825 incrementProfileCounter(Body); 826 827 RunCleanupsScope RunCleanups(*this); 828 829 // TODO: in restricted cases, we can emit the vbase initializers of 830 // a complete ctor and then delegate to the base ctor. 831 832 // Emit the constructor prologue, i.e. the base and member 833 // initializers. 834 EmitCtorPrologue(Ctor, CtorType, Args); 835 836 // Emit the body of the statement. 837 if (IsTryBody) 838 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock()); 839 else if (Body) 840 EmitStmt(Body); 841 842 // Emit any cleanup blocks associated with the member or base 843 // initializers, which includes (along the exceptional path) the 844 // destructors for those members and bases that were fully 845 // constructed. 846 RunCleanups.ForceCleanup(); 847 848 if (IsTryBody) 849 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true); 850 } 851 852 namespace { 853 /// RAII object to indicate that codegen is copying the value representation 854 /// instead of the object representation. Useful when copying a struct or 855 /// class which has uninitialized members and we're only performing 856 /// lvalue-to-rvalue conversion on the object but not its members. 857 class CopyingValueRepresentation { 858 public: 859 explicit CopyingValueRepresentation(CodeGenFunction &CGF) 860 : CGF(CGF), OldSanOpts(CGF.SanOpts) { 861 CGF.SanOpts.set(SanitizerKind::Bool, false); 862 CGF.SanOpts.set(SanitizerKind::Enum, false); 863 } 864 ~CopyingValueRepresentation() { 865 CGF.SanOpts = OldSanOpts; 866 } 867 private: 868 CodeGenFunction &CGF; 869 SanitizerSet OldSanOpts; 870 }; 871 } // end anonymous namespace 872 873 namespace { 874 class FieldMemcpyizer { 875 public: 876 FieldMemcpyizer(CodeGenFunction &CGF, const CXXRecordDecl *ClassDecl, 877 const VarDecl *SrcRec) 878 : CGF(CGF), ClassDecl(ClassDecl), SrcRec(SrcRec), 879 RecLayout(CGF.getContext().getASTRecordLayout(ClassDecl)), 880 FirstField(nullptr), LastField(nullptr), FirstFieldOffset(0), 881 LastFieldOffset(0), LastAddedFieldIndex(0) {} 882 883 bool isMemcpyableField(FieldDecl *F) const { 884 // Never memcpy fields when we are adding poisoned paddings. 885 if (CGF.getContext().getLangOpts().SanitizeAddressFieldPadding) 886 return false; 887 Qualifiers Qual = F->getType().getQualifiers(); 888 if (Qual.hasVolatile() || Qual.hasObjCLifetime()) 889 return false; 890 return true; 891 } 892 893 void addMemcpyableField(FieldDecl *F) { 894 if (!FirstField) 895 addInitialField(F); 896 else 897 addNextField(F); 898 } 899 900 CharUnits getMemcpySize(uint64_t FirstByteOffset) const { 901 unsigned LastFieldSize = 902 LastField->isBitField() ? 903 LastField->getBitWidthValue(CGF.getContext()) : 904 CGF.getContext().getTypeSize(LastField->getType()); 905 uint64_t MemcpySizeBits = 906 LastFieldOffset + LastFieldSize - FirstByteOffset + 907 CGF.getContext().getCharWidth() - 1; 908 CharUnits MemcpySize = 909 CGF.getContext().toCharUnitsFromBits(MemcpySizeBits); 910 return MemcpySize; 911 } 912 913 void emitMemcpy() { 914 // Give the subclass a chance to bail out if it feels the memcpy isn't 915 // worth it (e.g. Hasn't aggregated enough data). 916 if (!FirstField) { 917 return; 918 } 919 920 uint64_t FirstByteOffset; 921 if (FirstField->isBitField()) { 922 const CGRecordLayout &RL = 923 CGF.getTypes().getCGRecordLayout(FirstField->getParent()); 924 const CGBitFieldInfo &BFInfo = RL.getBitFieldInfo(FirstField); 925 // FirstFieldOffset is not appropriate for bitfields, 926 // we need to use the storage offset instead. 927 FirstByteOffset = CGF.getContext().toBits(BFInfo.StorageOffset); 928 } else { 929 FirstByteOffset = FirstFieldOffset; 930 } 931 932 CharUnits MemcpySize = getMemcpySize(FirstByteOffset); 933 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl); 934 Address ThisPtr = CGF.LoadCXXThisAddress(); 935 LValue DestLV = CGF.MakeAddrLValue(ThisPtr, RecordTy); 936 LValue Dest = CGF.EmitLValueForFieldInitialization(DestLV, FirstField); 937 llvm::Value *SrcPtr = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(SrcRec)); 938 LValue SrcLV = CGF.MakeNaturalAlignAddrLValue(SrcPtr, RecordTy); 939 LValue Src = CGF.EmitLValueForFieldInitialization(SrcLV, FirstField); 940 941 emitMemcpyIR(Dest.isBitField() ? Dest.getBitFieldAddress() : Dest.getAddress(), 942 Src.isBitField() ? Src.getBitFieldAddress() : Src.getAddress(), 943 MemcpySize); 944 reset(); 945 } 946 947 void reset() { 948 FirstField = nullptr; 949 } 950 951 protected: 952 CodeGenFunction &CGF; 953 const CXXRecordDecl *ClassDecl; 954 955 private: 956 void emitMemcpyIR(Address DestPtr, Address SrcPtr, CharUnits Size) { 957 llvm::PointerType *DPT = DestPtr.getType(); 958 llvm::Type *DBP = 959 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), DPT->getAddressSpace()); 960 DestPtr = CGF.Builder.CreateBitCast(DestPtr, DBP); 961 962 llvm::PointerType *SPT = SrcPtr.getType(); 963 llvm::Type *SBP = 964 llvm::Type::getInt8PtrTy(CGF.getLLVMContext(), SPT->getAddressSpace()); 965 SrcPtr = CGF.Builder.CreateBitCast(SrcPtr, SBP); 966 967 CGF.Builder.CreateMemCpy(DestPtr, SrcPtr, Size.getQuantity()); 968 } 969 970 void addInitialField(FieldDecl *F) { 971 FirstField = F; 972 LastField = F; 973 FirstFieldOffset = RecLayout.getFieldOffset(F->getFieldIndex()); 974 LastFieldOffset = FirstFieldOffset; 975 LastAddedFieldIndex = F->getFieldIndex(); 976 } 977 978 void addNextField(FieldDecl *F) { 979 // For the most part, the following invariant will hold: 980 // F->getFieldIndex() == LastAddedFieldIndex + 1 981 // The one exception is that Sema won't add a copy-initializer for an 982 // unnamed bitfield, which will show up here as a gap in the sequence. 983 assert(F->getFieldIndex() >= LastAddedFieldIndex + 1 && 984 "Cannot aggregate fields out of order."); 985 LastAddedFieldIndex = F->getFieldIndex(); 986 987 // The 'first' and 'last' fields are chosen by offset, rather than field 988 // index. This allows the code to support bitfields, as well as regular 989 // fields. 990 uint64_t FOffset = RecLayout.getFieldOffset(F->getFieldIndex()); 991 if (FOffset < FirstFieldOffset) { 992 FirstField = F; 993 FirstFieldOffset = FOffset; 994 } else if (FOffset > LastFieldOffset) { 995 LastField = F; 996 LastFieldOffset = FOffset; 997 } 998 } 999 1000 const VarDecl *SrcRec; 1001 const ASTRecordLayout &RecLayout; 1002 FieldDecl *FirstField; 1003 FieldDecl *LastField; 1004 uint64_t FirstFieldOffset, LastFieldOffset; 1005 unsigned LastAddedFieldIndex; 1006 }; 1007 1008 class ConstructorMemcpyizer : public FieldMemcpyizer { 1009 private: 1010 /// Get source argument for copy constructor. Returns null if not a copy 1011 /// constructor. 1012 static const VarDecl *getTrivialCopySource(CodeGenFunction &CGF, 1013 const CXXConstructorDecl *CD, 1014 FunctionArgList &Args) { 1015 if (CD->isCopyOrMoveConstructor() && CD->isDefaulted()) 1016 return Args[CGF.CGM.getCXXABI().getSrcArgforCopyCtor(CD, Args)]; 1017 return nullptr; 1018 } 1019 1020 // Returns true if a CXXCtorInitializer represents a member initialization 1021 // that can be rolled into a memcpy. 1022 bool isMemberInitMemcpyable(CXXCtorInitializer *MemberInit) const { 1023 if (!MemcpyableCtor) 1024 return false; 1025 FieldDecl *Field = MemberInit->getMember(); 1026 assert(Field && "No field for member init."); 1027 QualType FieldType = Field->getType(); 1028 CXXConstructExpr *CE = dyn_cast<CXXConstructExpr>(MemberInit->getInit()); 1029 1030 // Bail out on non-memcpyable, not-trivially-copyable members. 1031 if (!(CE && isMemcpyEquivalentSpecialMember(CE->getConstructor())) && 1032 !(FieldType.isTriviallyCopyableType(CGF.getContext()) || 1033 FieldType->isReferenceType())) 1034 return false; 1035 1036 // Bail out on volatile fields. 1037 if (!isMemcpyableField(Field)) 1038 return false; 1039 1040 // Otherwise we're good. 1041 return true; 1042 } 1043 1044 public: 1045 ConstructorMemcpyizer(CodeGenFunction &CGF, const CXXConstructorDecl *CD, 1046 FunctionArgList &Args) 1047 : FieldMemcpyizer(CGF, CD->getParent(), getTrivialCopySource(CGF, CD, Args)), 1048 ConstructorDecl(CD), 1049 MemcpyableCtor(CD->isDefaulted() && 1050 CD->isCopyOrMoveConstructor() && 1051 CGF.getLangOpts().getGC() == LangOptions::NonGC), 1052 Args(Args) { } 1053 1054 void addMemberInitializer(CXXCtorInitializer *MemberInit) { 1055 if (isMemberInitMemcpyable(MemberInit)) { 1056 AggregatedInits.push_back(MemberInit); 1057 addMemcpyableField(MemberInit->getMember()); 1058 } else { 1059 emitAggregatedInits(); 1060 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), MemberInit, 1061 ConstructorDecl, Args); 1062 } 1063 } 1064 1065 void emitAggregatedInits() { 1066 if (AggregatedInits.size() <= 1) { 1067 // This memcpy is too small to be worthwhile. Fall back on default 1068 // codegen. 1069 if (!AggregatedInits.empty()) { 1070 CopyingValueRepresentation CVR(CGF); 1071 EmitMemberInitializer(CGF, ConstructorDecl->getParent(), 1072 AggregatedInits[0], ConstructorDecl, Args); 1073 AggregatedInits.clear(); 1074 } 1075 reset(); 1076 return; 1077 } 1078 1079 pushEHDestructors(); 1080 emitMemcpy(); 1081 AggregatedInits.clear(); 1082 } 1083 1084 void pushEHDestructors() { 1085 Address ThisPtr = CGF.LoadCXXThisAddress(); 1086 QualType RecordTy = CGF.getContext().getTypeDeclType(ClassDecl); 1087 LValue LHS = CGF.MakeAddrLValue(ThisPtr, RecordTy); 1088 1089 for (unsigned i = 0; i < AggregatedInits.size(); ++i) { 1090 CXXCtorInitializer *MemberInit = AggregatedInits[i]; 1091 QualType FieldType = MemberInit->getAnyMember()->getType(); 1092 QualType::DestructionKind dtorKind = FieldType.isDestructedType(); 1093 if (!CGF.needsEHCleanup(dtorKind)) 1094 continue; 1095 LValue FieldLHS = LHS; 1096 EmitLValueForAnyFieldInitialization(CGF, MemberInit, FieldLHS); 1097 CGF.pushEHDestroy(dtorKind, FieldLHS.getAddress(), FieldType); 1098 } 1099 } 1100 1101 void finish() { 1102 emitAggregatedInits(); 1103 } 1104 1105 private: 1106 const CXXConstructorDecl *ConstructorDecl; 1107 bool MemcpyableCtor; 1108 FunctionArgList &Args; 1109 SmallVector<CXXCtorInitializer*, 16> AggregatedInits; 1110 }; 1111 1112 class AssignmentMemcpyizer : public FieldMemcpyizer { 1113 private: 1114 // Returns the memcpyable field copied by the given statement, if one 1115 // exists. Otherwise returns null. 1116 FieldDecl *getMemcpyableField(Stmt *S) { 1117 if (!AssignmentsMemcpyable) 1118 return nullptr; 1119 if (BinaryOperator *BO = dyn_cast<BinaryOperator>(S)) { 1120 // Recognise trivial assignments. 1121 if (BO->getOpcode() != BO_Assign) 1122 return nullptr; 1123 MemberExpr *ME = dyn_cast<MemberExpr>(BO->getLHS()); 1124 if (!ME) 1125 return nullptr; 1126 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl()); 1127 if (!Field || !isMemcpyableField(Field)) 1128 return nullptr; 1129 Stmt *RHS = BO->getRHS(); 1130 if (ImplicitCastExpr *EC = dyn_cast<ImplicitCastExpr>(RHS)) 1131 RHS = EC->getSubExpr(); 1132 if (!RHS) 1133 return nullptr; 1134 MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS); 1135 if (dyn_cast<FieldDecl>(ME2->getMemberDecl()) != Field) 1136 return nullptr; 1137 return Field; 1138 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) { 1139 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl()); 1140 if (!(MD && isMemcpyEquivalentSpecialMember(MD))) 1141 return nullptr; 1142 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument()); 1143 if (!IOA) 1144 return nullptr; 1145 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl()); 1146 if (!Field || !isMemcpyableField(Field)) 1147 return nullptr; 1148 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0)); 1149 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl())) 1150 return nullptr; 1151 return Field; 1152 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) { 1153 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); 1154 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy) 1155 return nullptr; 1156 Expr *DstPtr = CE->getArg(0); 1157 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr)) 1158 DstPtr = DC->getSubExpr(); 1159 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr); 1160 if (!DUO || DUO->getOpcode() != UO_AddrOf) 1161 return nullptr; 1162 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr()); 1163 if (!ME) 1164 return nullptr; 1165 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl()); 1166 if (!Field || !isMemcpyableField(Field)) 1167 return nullptr; 1168 Expr *SrcPtr = CE->getArg(1); 1169 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr)) 1170 SrcPtr = SC->getSubExpr(); 1171 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr); 1172 if (!SUO || SUO->getOpcode() != UO_AddrOf) 1173 return nullptr; 1174 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr()); 1175 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl())) 1176 return nullptr; 1177 return Field; 1178 } 1179 1180 return nullptr; 1181 } 1182 1183 bool AssignmentsMemcpyable; 1184 SmallVector<Stmt*, 16> AggregatedStmts; 1185 1186 public: 1187 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD, 1188 FunctionArgList &Args) 1189 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]), 1190 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) { 1191 assert(Args.size() == 2); 1192 } 1193 1194 void emitAssignment(Stmt *S) { 1195 FieldDecl *F = getMemcpyableField(S); 1196 if (F) { 1197 addMemcpyableField(F); 1198 AggregatedStmts.push_back(S); 1199 } else { 1200 emitAggregatedStmts(); 1201 CGF.EmitStmt(S); 1202 } 1203 } 1204 1205 void emitAggregatedStmts() { 1206 if (AggregatedStmts.size() <= 1) { 1207 if (!AggregatedStmts.empty()) { 1208 CopyingValueRepresentation CVR(CGF); 1209 CGF.EmitStmt(AggregatedStmts[0]); 1210 } 1211 reset(); 1212 } 1213 1214 emitMemcpy(); 1215 AggregatedStmts.clear(); 1216 } 1217 1218 void finish() { 1219 emitAggregatedStmts(); 1220 } 1221 }; 1222 } // end anonymous namespace 1223 1224 static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) { 1225 const Type *BaseType = BaseInit->getBaseClass(); 1226 const auto *BaseClassDecl = 1227 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()); 1228 return BaseClassDecl->isDynamicClass(); 1229 } 1230 1231 /// EmitCtorPrologue - This routine generates necessary code to initialize 1232 /// base classes and non-static data members belonging to this constructor. 1233 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD, 1234 CXXCtorType CtorType, 1235 FunctionArgList &Args) { 1236 if (CD->isDelegatingConstructor()) 1237 return EmitDelegatingCXXConstructorCall(CD, Args); 1238 1239 const CXXRecordDecl *ClassDecl = CD->getParent(); 1240 1241 CXXConstructorDecl::init_const_iterator B = CD->init_begin(), 1242 E = CD->init_end(); 1243 1244 llvm::BasicBlock *BaseCtorContinueBB = nullptr; 1245 if (ClassDecl->getNumVBases() && 1246 !CGM.getTarget().getCXXABI().hasConstructorVariants()) { 1247 // The ABIs that don't have constructor variants need to put a branch 1248 // before the virtual base initialization code. 1249 BaseCtorContinueBB = 1250 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl); 1251 assert(BaseCtorContinueBB); 1252 } 1253 1254 llvm::Value *const OldThis = CXXThisValue; 1255 // Virtual base initializers first. 1256 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) { 1257 if (CGM.getCodeGenOpts().StrictVTablePointers && 1258 CGM.getCodeGenOpts().OptimizationLevel > 0 && 1259 isInitializerOfDynamicClass(*B)) 1260 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis()); 1261 EmitBaseInitializer(*this, ClassDecl, *B, CtorType); 1262 } 1263 1264 if (BaseCtorContinueBB) { 1265 // Complete object handler should continue to the remaining initializers. 1266 Builder.CreateBr(BaseCtorContinueBB); 1267 EmitBlock(BaseCtorContinueBB); 1268 } 1269 1270 // Then, non-virtual base initializers. 1271 for (; B != E && (*B)->isBaseInitializer(); B++) { 1272 assert(!(*B)->isBaseVirtual()); 1273 1274 if (CGM.getCodeGenOpts().StrictVTablePointers && 1275 CGM.getCodeGenOpts().OptimizationLevel > 0 && 1276 isInitializerOfDynamicClass(*B)) 1277 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis()); 1278 EmitBaseInitializer(*this, ClassDecl, *B, CtorType); 1279 } 1280 1281 CXXThisValue = OldThis; 1282 1283 InitializeVTablePointers(ClassDecl); 1284 1285 // And finally, initialize class members. 1286 FieldConstructionScope FCS(*this, LoadCXXThisAddress()); 1287 ConstructorMemcpyizer CM(*this, CD, Args); 1288 for (; B != E; B++) { 1289 CXXCtorInitializer *Member = (*B); 1290 assert(!Member->isBaseInitializer()); 1291 assert(Member->isAnyMemberInitializer() && 1292 "Delegating initializer on non-delegating constructor"); 1293 CM.addMemberInitializer(Member); 1294 } 1295 CM.finish(); 1296 } 1297 1298 static bool 1299 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field); 1300 1301 static bool 1302 HasTrivialDestructorBody(ASTContext &Context, 1303 const CXXRecordDecl *BaseClassDecl, 1304 const CXXRecordDecl *MostDerivedClassDecl) 1305 { 1306 // If the destructor is trivial we don't have to check anything else. 1307 if (BaseClassDecl->hasTrivialDestructor()) 1308 return true; 1309 1310 if (!BaseClassDecl->getDestructor()->hasTrivialBody()) 1311 return false; 1312 1313 // Check fields. 1314 for (const auto *Field : BaseClassDecl->fields()) 1315 if (!FieldHasTrivialDestructorBody(Context, Field)) 1316 return false; 1317 1318 // Check non-virtual bases. 1319 for (const auto &I : BaseClassDecl->bases()) { 1320 if (I.isVirtual()) 1321 continue; 1322 1323 const CXXRecordDecl *NonVirtualBase = 1324 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 1325 if (!HasTrivialDestructorBody(Context, NonVirtualBase, 1326 MostDerivedClassDecl)) 1327 return false; 1328 } 1329 1330 if (BaseClassDecl == MostDerivedClassDecl) { 1331 // Check virtual bases. 1332 for (const auto &I : BaseClassDecl->vbases()) { 1333 const CXXRecordDecl *VirtualBase = 1334 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 1335 if (!HasTrivialDestructorBody(Context, VirtualBase, 1336 MostDerivedClassDecl)) 1337 return false; 1338 } 1339 } 1340 1341 return true; 1342 } 1343 1344 static bool 1345 FieldHasTrivialDestructorBody(ASTContext &Context, 1346 const FieldDecl *Field) 1347 { 1348 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType()); 1349 1350 const RecordType *RT = FieldBaseElementType->getAs<RecordType>(); 1351 if (!RT) 1352 return true; 1353 1354 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1355 1356 // The destructor for an implicit anonymous union member is never invoked. 1357 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 1358 return false; 1359 1360 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl); 1361 } 1362 1363 /// CanSkipVTablePointerInitialization - Check whether we need to initialize 1364 /// any vtable pointers before calling this destructor. 1365 static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF, 1366 const CXXDestructorDecl *Dtor) { 1367 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 1368 if (!ClassDecl->isDynamicClass()) 1369 return true; 1370 1371 if (!Dtor->hasTrivialBody()) 1372 return false; 1373 1374 // Check the fields. 1375 for (const auto *Field : ClassDecl->fields()) 1376 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field)) 1377 return false; 1378 1379 return true; 1380 } 1381 1382 /// EmitDestructorBody - Emits the body of the current destructor. 1383 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) { 1384 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl()); 1385 CXXDtorType DtorType = CurGD.getDtorType(); 1386 1387 Stmt *Body = Dtor->getBody(); 1388 if (Body) 1389 incrementProfileCounter(Body); 1390 1391 // The call to operator delete in a deleting destructor happens 1392 // outside of the function-try-block, which means it's always 1393 // possible to delegate the destructor body to the complete 1394 // destructor. Do so. 1395 if (DtorType == Dtor_Deleting) { 1396 EnterDtorCleanups(Dtor, Dtor_Deleting); 1397 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false, 1398 /*Delegating=*/false, LoadCXXThisAddress()); 1399 PopCleanupBlock(); 1400 return; 1401 } 1402 1403 // If the body is a function-try-block, enter the try before 1404 // anything else. 1405 bool isTryBody = (Body && isa<CXXTryStmt>(Body)); 1406 if (isTryBody) 1407 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true); 1408 EmitAsanPrologueOrEpilogue(false); 1409 1410 // Enter the epilogue cleanups. 1411 RunCleanupsScope DtorEpilogue(*this); 1412 1413 // If this is the complete variant, just invoke the base variant; 1414 // the epilogue will destruct the virtual bases. But we can't do 1415 // this optimization if the body is a function-try-block, because 1416 // we'd introduce *two* handler blocks. In the Microsoft ABI, we 1417 // always delegate because we might not have a definition in this TU. 1418 switch (DtorType) { 1419 case Dtor_Comdat: 1420 llvm_unreachable("not expecting a COMDAT"); 1421 1422 case Dtor_Deleting: llvm_unreachable("already handled deleting case"); 1423 1424 case Dtor_Complete: 1425 assert((Body || getTarget().getCXXABI().isMicrosoft()) && 1426 "can't emit a dtor without a body for non-Microsoft ABIs"); 1427 1428 // Enter the cleanup scopes for virtual bases. 1429 EnterDtorCleanups(Dtor, Dtor_Complete); 1430 1431 if (!isTryBody) { 1432 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false, 1433 /*Delegating=*/false, LoadCXXThisAddress()); 1434 break; 1435 } 1436 // Fallthrough: act like we're in the base variant. 1437 1438 case Dtor_Base: 1439 assert(Body); 1440 1441 // Enter the cleanup scopes for fields and non-virtual bases. 1442 EnterDtorCleanups(Dtor, Dtor_Base); 1443 1444 // Initialize the vtable pointers before entering the body. 1445 if (!CanSkipVTablePointerInitialization(*this, Dtor)) { 1446 // Insert the llvm.invariant.group.barrier intrinsic before initializing 1447 // the vptrs to cancel any previous assumptions we might have made. 1448 if (CGM.getCodeGenOpts().StrictVTablePointers && 1449 CGM.getCodeGenOpts().OptimizationLevel > 0) 1450 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis()); 1451 InitializeVTablePointers(Dtor->getParent()); 1452 } 1453 1454 if (isTryBody) 1455 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock()); 1456 else if (Body) 1457 EmitStmt(Body); 1458 else { 1459 assert(Dtor->isImplicit() && "bodyless dtor not implicit"); 1460 // nothing to do besides what's in the epilogue 1461 } 1462 // -fapple-kext must inline any call to this dtor into 1463 // the caller's body. 1464 if (getLangOpts().AppleKext) 1465 CurFn->addFnAttr(llvm::Attribute::AlwaysInline); 1466 1467 break; 1468 } 1469 1470 // Jump out through the epilogue cleanups. 1471 DtorEpilogue.ForceCleanup(); 1472 1473 // Exit the try if applicable. 1474 if (isTryBody) 1475 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true); 1476 } 1477 1478 void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) { 1479 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl()); 1480 const Stmt *RootS = AssignOp->getBody(); 1481 assert(isa<CompoundStmt>(RootS) && 1482 "Body of an implicit assignment operator should be compound stmt."); 1483 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS); 1484 1485 LexicalScope Scope(*this, RootCS->getSourceRange()); 1486 1487 incrementProfileCounter(RootCS); 1488 AssignmentMemcpyizer AM(*this, AssignOp, Args); 1489 for (auto *I : RootCS->body()) 1490 AM.emitAssignment(I); 1491 AM.finish(); 1492 } 1493 1494 namespace { 1495 /// Call the operator delete associated with the current destructor. 1496 struct CallDtorDelete final : EHScopeStack::Cleanup { 1497 CallDtorDelete() {} 1498 1499 void Emit(CodeGenFunction &CGF, Flags flags) override { 1500 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl); 1501 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 1502 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(), 1503 CGF.getContext().getTagDeclType(ClassDecl)); 1504 } 1505 }; 1506 1507 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup { 1508 llvm::Value *ShouldDeleteCondition; 1509 1510 public: 1511 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition) 1512 : ShouldDeleteCondition(ShouldDeleteCondition) { 1513 assert(ShouldDeleteCondition != nullptr); 1514 } 1515 1516 void Emit(CodeGenFunction &CGF, Flags flags) override { 1517 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete"); 1518 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue"); 1519 llvm::Value *ShouldCallDelete 1520 = CGF.Builder.CreateIsNull(ShouldDeleteCondition); 1521 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB); 1522 1523 CGF.EmitBlock(callDeleteBB); 1524 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl); 1525 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 1526 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(), 1527 CGF.getContext().getTagDeclType(ClassDecl)); 1528 CGF.Builder.CreateBr(continueBB); 1529 1530 CGF.EmitBlock(continueBB); 1531 } 1532 }; 1533 1534 class DestroyField final : public EHScopeStack::Cleanup { 1535 const FieldDecl *field; 1536 CodeGenFunction::Destroyer *destroyer; 1537 bool useEHCleanupForArray; 1538 1539 public: 1540 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer, 1541 bool useEHCleanupForArray) 1542 : field(field), destroyer(destroyer), 1543 useEHCleanupForArray(useEHCleanupForArray) {} 1544 1545 void Emit(CodeGenFunction &CGF, Flags flags) override { 1546 // Find the address of the field. 1547 Address thisValue = CGF.LoadCXXThisAddress(); 1548 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent()); 1549 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy); 1550 LValue LV = CGF.EmitLValueForField(ThisLV, field); 1551 assert(LV.isSimple()); 1552 1553 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer, 1554 flags.isForNormalCleanup() && useEHCleanupForArray); 1555 } 1556 }; 1557 1558 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr, 1559 CharUnits::QuantityType PoisonSize) { 1560 // Pass in void pointer and size of region as arguments to runtime 1561 // function 1562 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy), 1563 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)}; 1564 1565 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy}; 1566 1567 llvm::FunctionType *FnType = 1568 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false); 1569 llvm::Value *Fn = 1570 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback"); 1571 CGF.EmitNounwindRuntimeCall(Fn, Args); 1572 } 1573 1574 class SanitizeDtorMembers final : public EHScopeStack::Cleanup { 1575 const CXXDestructorDecl *Dtor; 1576 1577 public: 1578 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {} 1579 1580 // Generate function call for handling object poisoning. 1581 // Disables tail call elimination, to prevent the current stack frame 1582 // from disappearing from the stack trace. 1583 void Emit(CodeGenFunction &CGF, Flags flags) override { 1584 const ASTRecordLayout &Layout = 1585 CGF.getContext().getASTRecordLayout(Dtor->getParent()); 1586 1587 // Nothing to poison. 1588 if (Layout.getFieldCount() == 0) 1589 return; 1590 1591 // Prevent the current stack frame from disappearing from the stack trace. 1592 CGF.CurFn->addFnAttr("disable-tail-calls", "true"); 1593 1594 // Construct pointer to region to begin poisoning, and calculate poison 1595 // size, so that only members declared in this class are poisoned. 1596 ASTContext &Context = CGF.getContext(); 1597 unsigned fieldIndex = 0; 1598 int startIndex = -1; 1599 // RecordDecl::field_iterator Field; 1600 for (const FieldDecl *Field : Dtor->getParent()->fields()) { 1601 // Poison field if it is trivial 1602 if (FieldHasTrivialDestructorBody(Context, Field)) { 1603 // Start sanitizing at this field 1604 if (startIndex < 0) 1605 startIndex = fieldIndex; 1606 1607 // Currently on the last field, and it must be poisoned with the 1608 // current block. 1609 if (fieldIndex == Layout.getFieldCount() - 1) { 1610 PoisonMembers(CGF, startIndex, Layout.getFieldCount()); 1611 } 1612 } else if (startIndex >= 0) { 1613 // No longer within a block of memory to poison, so poison the block 1614 PoisonMembers(CGF, startIndex, fieldIndex); 1615 // Re-set the start index 1616 startIndex = -1; 1617 } 1618 fieldIndex += 1; 1619 } 1620 } 1621 1622 private: 1623 /// \param layoutStartOffset index of the ASTRecordLayout field to 1624 /// start poisoning (inclusive) 1625 /// \param layoutEndOffset index of the ASTRecordLayout field to 1626 /// end poisoning (exclusive) 1627 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset, 1628 unsigned layoutEndOffset) { 1629 ASTContext &Context = CGF.getContext(); 1630 const ASTRecordLayout &Layout = 1631 Context.getASTRecordLayout(Dtor->getParent()); 1632 1633 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get( 1634 CGF.SizeTy, 1635 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset)) 1636 .getQuantity()); 1637 1638 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP( 1639 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy), 1640 OffsetSizePtr); 1641 1642 CharUnits::QuantityType PoisonSize; 1643 if (layoutEndOffset >= Layout.getFieldCount()) { 1644 PoisonSize = Layout.getNonVirtualSize().getQuantity() - 1645 Context.toCharUnitsFromBits( 1646 Layout.getFieldOffset(layoutStartOffset)) 1647 .getQuantity(); 1648 } else { 1649 PoisonSize = Context.toCharUnitsFromBits( 1650 Layout.getFieldOffset(layoutEndOffset) - 1651 Layout.getFieldOffset(layoutStartOffset)) 1652 .getQuantity(); 1653 } 1654 1655 if (PoisonSize == 0) 1656 return; 1657 1658 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize); 1659 } 1660 }; 1661 1662 class SanitizeDtorVTable final : public EHScopeStack::Cleanup { 1663 const CXXDestructorDecl *Dtor; 1664 1665 public: 1666 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {} 1667 1668 // Generate function call for handling vtable pointer poisoning. 1669 void Emit(CodeGenFunction &CGF, Flags flags) override { 1670 assert(Dtor->getParent()->isDynamicClass()); 1671 (void)Dtor; 1672 ASTContext &Context = CGF.getContext(); 1673 // Poison vtable and vtable ptr if they exist for this class. 1674 llvm::Value *VTablePtr = CGF.LoadCXXThis(); 1675 1676 CharUnits::QuantityType PoisonSize = 1677 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity(); 1678 // Pass in void pointer and size of region as arguments to runtime 1679 // function 1680 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize); 1681 } 1682 }; 1683 } // end anonymous namespace 1684 1685 /// \brief Emit all code that comes at the end of class's 1686 /// destructor. This is to call destructors on members and base classes 1687 /// in reverse order of their construction. 1688 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD, 1689 CXXDtorType DtorType) { 1690 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) && 1691 "Should not emit dtor epilogue for non-exported trivial dtor!"); 1692 1693 // The deleting-destructor phase just needs to call the appropriate 1694 // operator delete that Sema picked up. 1695 if (DtorType == Dtor_Deleting) { 1696 assert(DD->getOperatorDelete() && 1697 "operator delete missing - EnterDtorCleanups"); 1698 if (CXXStructorImplicitParamValue) { 1699 // If there is an implicit param to the deleting dtor, it's a boolean 1700 // telling whether we should call delete at the end of the dtor. 1701 EHStack.pushCleanup<CallDtorDeleteConditional>( 1702 NormalAndEHCleanup, CXXStructorImplicitParamValue); 1703 } else { 1704 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup); 1705 } 1706 return; 1707 } 1708 1709 const CXXRecordDecl *ClassDecl = DD->getParent(); 1710 1711 // Unions have no bases and do not call field destructors. 1712 if (ClassDecl->isUnion()) 1713 return; 1714 1715 // The complete-destructor phase just destructs all the virtual bases. 1716 if (DtorType == Dtor_Complete) { 1717 // Poison the vtable pointer such that access after the base 1718 // and member destructors are invoked is invalid. 1719 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor && 1720 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() && 1721 ClassDecl->isPolymorphic()) 1722 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD); 1723 1724 // We push them in the forward order so that they'll be popped in 1725 // the reverse order. 1726 for (const auto &Base : ClassDecl->vbases()) { 1727 CXXRecordDecl *BaseClassDecl 1728 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 1729 1730 // Ignore trivial destructors. 1731 if (BaseClassDecl->hasTrivialDestructor()) 1732 continue; 1733 1734 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 1735 BaseClassDecl, 1736 /*BaseIsVirtual*/ true); 1737 } 1738 1739 return; 1740 } 1741 1742 assert(DtorType == Dtor_Base); 1743 // Poison the vtable pointer if it has no virtual bases, but inherits 1744 // virtual functions. 1745 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor && 1746 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() && 1747 ClassDecl->isPolymorphic()) 1748 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD); 1749 1750 // Destroy non-virtual bases. 1751 for (const auto &Base : ClassDecl->bases()) { 1752 // Ignore virtual bases. 1753 if (Base.isVirtual()) 1754 continue; 1755 1756 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl(); 1757 1758 // Ignore trivial destructors. 1759 if (BaseClassDecl->hasTrivialDestructor()) 1760 continue; 1761 1762 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 1763 BaseClassDecl, 1764 /*BaseIsVirtual*/ false); 1765 } 1766 1767 // Poison fields such that access after their destructors are 1768 // invoked, and before the base class destructor runs, is invalid. 1769 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor && 1770 SanOpts.has(SanitizerKind::Memory)) 1771 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD); 1772 1773 // Destroy direct fields. 1774 for (const auto *Field : ClassDecl->fields()) { 1775 QualType type = Field->getType(); 1776 QualType::DestructionKind dtorKind = type.isDestructedType(); 1777 if (!dtorKind) continue; 1778 1779 // Anonymous union members do not have their destructors called. 1780 const RecordType *RT = type->getAsUnionType(); 1781 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue; 1782 1783 CleanupKind cleanupKind = getCleanupKind(dtorKind); 1784 EHStack.pushCleanup<DestroyField>(cleanupKind, Field, 1785 getDestroyer(dtorKind), 1786 cleanupKind & EHCleanup); 1787 } 1788 } 1789 1790 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular 1791 /// constructor for each of several members of an array. 1792 /// 1793 /// \param ctor the constructor to call for each element 1794 /// \param arrayType the type of the array to initialize 1795 /// \param arrayBegin an arrayType* 1796 /// \param zeroInitialize true if each element should be 1797 /// zero-initialized before it is constructed 1798 void CodeGenFunction::EmitCXXAggrConstructorCall( 1799 const CXXConstructorDecl *ctor, const ArrayType *arrayType, 1800 Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) { 1801 QualType elementType; 1802 llvm::Value *numElements = 1803 emitArrayLength(arrayType, elementType, arrayBegin); 1804 1805 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize); 1806 } 1807 1808 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular 1809 /// constructor for each of several members of an array. 1810 /// 1811 /// \param ctor the constructor to call for each element 1812 /// \param numElements the number of elements in the array; 1813 /// may be zero 1814 /// \param arrayBase a T*, where T is the type constructed by ctor 1815 /// \param zeroInitialize true if each element should be 1816 /// zero-initialized before it is constructed 1817 void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, 1818 llvm::Value *numElements, 1819 Address arrayBase, 1820 const CXXConstructExpr *E, 1821 bool zeroInitialize) { 1822 // It's legal for numElements to be zero. This can happen both 1823 // dynamically, because x can be zero in 'new A[x]', and statically, 1824 // because of GCC extensions that permit zero-length arrays. There 1825 // are probably legitimate places where we could assume that this 1826 // doesn't happen, but it's not clear that it's worth it. 1827 llvm::BranchInst *zeroCheckBranch = nullptr; 1828 1829 // Optimize for a constant count. 1830 llvm::ConstantInt *constantCount 1831 = dyn_cast<llvm::ConstantInt>(numElements); 1832 if (constantCount) { 1833 // Just skip out if the constant count is zero. 1834 if (constantCount->isZero()) return; 1835 1836 // Otherwise, emit the check. 1837 } else { 1838 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop"); 1839 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty"); 1840 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB); 1841 EmitBlock(loopBB); 1842 } 1843 1844 // Find the end of the array. 1845 llvm::Value *arrayBegin = arrayBase.getPointer(); 1846 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements, 1847 "arrayctor.end"); 1848 1849 // Enter the loop, setting up a phi for the current location to initialize. 1850 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 1851 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop"); 1852 EmitBlock(loopBB); 1853 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2, 1854 "arrayctor.cur"); 1855 cur->addIncoming(arrayBegin, entryBB); 1856 1857 // Inside the loop body, emit the constructor call on the array element. 1858 1859 // The alignment of the base, adjusted by the size of a single element, 1860 // provides a conservative estimate of the alignment of every element. 1861 // (This assumes we never start tracking offsetted alignments.) 1862 // 1863 // Note that these are complete objects and so we don't need to 1864 // use the non-virtual size or alignment. 1865 QualType type = getContext().getTypeDeclType(ctor->getParent()); 1866 CharUnits eltAlignment = 1867 arrayBase.getAlignment() 1868 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type)); 1869 Address curAddr = Address(cur, eltAlignment); 1870 1871 // Zero initialize the storage, if requested. 1872 if (zeroInitialize) 1873 EmitNullInitialization(curAddr, type); 1874 1875 // C++ [class.temporary]p4: 1876 // There are two contexts in which temporaries are destroyed at a different 1877 // point than the end of the full-expression. The first context is when a 1878 // default constructor is called to initialize an element of an array. 1879 // If the constructor has one or more default arguments, the destruction of 1880 // every temporary created in a default argument expression is sequenced 1881 // before the construction of the next array element, if any. 1882 1883 { 1884 RunCleanupsScope Scope(*this); 1885 1886 // Evaluate the constructor and its arguments in a regular 1887 // partial-destroy cleanup. 1888 if (getLangOpts().Exceptions && 1889 !ctor->getParent()->hasTrivialDestructor()) { 1890 Destroyer *destroyer = destroyCXXObject; 1891 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment, 1892 *destroyer); 1893 } 1894 1895 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false, 1896 /*Delegating=*/false, curAddr, E); 1897 } 1898 1899 // Go to the next element. 1900 llvm::Value *next = 1901 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1), 1902 "arrayctor.next"); 1903 cur->addIncoming(next, Builder.GetInsertBlock()); 1904 1905 // Check whether that's the end of the loop. 1906 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done"); 1907 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont"); 1908 Builder.CreateCondBr(done, contBB, loopBB); 1909 1910 // Patch the earlier check to skip over the loop. 1911 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB); 1912 1913 EmitBlock(contBB); 1914 } 1915 1916 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF, 1917 Address addr, 1918 QualType type) { 1919 const RecordType *rtype = type->castAs<RecordType>(); 1920 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl()); 1921 const CXXDestructorDecl *dtor = record->getDestructor(); 1922 assert(!dtor->isTrivial()); 1923 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false, 1924 /*Delegating=*/false, addr); 1925 } 1926 1927 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, 1928 CXXCtorType Type, 1929 bool ForVirtualBase, 1930 bool Delegating, Address This, 1931 const CXXConstructExpr *E) { 1932 CallArgList Args; 1933 1934 // Push the this ptr. 1935 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext())); 1936 1937 // If this is a trivial constructor, emit a memcpy now before we lose 1938 // the alignment information on the argument. 1939 // FIXME: It would be better to preserve alignment information into CallArg. 1940 if (isMemcpyEquivalentSpecialMember(D)) { 1941 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor"); 1942 1943 const Expr *Arg = E->getArg(0); 1944 QualType SrcTy = Arg->getType(); 1945 Address Src = EmitLValue(Arg).getAddress(); 1946 QualType DestTy = getContext().getTypeDeclType(D->getParent()); 1947 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy); 1948 return; 1949 } 1950 1951 // Add the rest of the user-supplied arguments. 1952 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>(); 1953 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor()); 1954 1955 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args); 1956 } 1957 1958 static bool canEmitDelegateCallArgs(CodeGenFunction &CGF, 1959 const CXXConstructorDecl *Ctor, 1960 CXXCtorType Type, CallArgList &Args) { 1961 // We can't forward a variadic call. 1962 if (Ctor->isVariadic()) 1963 return false; 1964 1965 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) { 1966 // If the parameters are callee-cleanup, it's not safe to forward. 1967 for (auto *P : Ctor->parameters()) 1968 if (P->getType().isDestructedType()) 1969 return false; 1970 1971 // Likewise if they're inalloca. 1972 const CGFunctionInfo &Info = 1973 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0); 1974 if (Info.usesInAlloca()) 1975 return false; 1976 } 1977 1978 // Anything else should be OK. 1979 return true; 1980 } 1981 1982 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, 1983 CXXCtorType Type, 1984 bool ForVirtualBase, 1985 bool Delegating, 1986 Address This, 1987 CallArgList &Args) { 1988 const CXXRecordDecl *ClassDecl = D->getParent(); 1989 1990 // C++11 [class.mfct.non-static]p2: 1991 // If a non-static member function of a class X is called for an object that 1992 // is not of type X, or of a type derived from X, the behavior is undefined. 1993 // FIXME: Provide a source location here. 1994 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(), 1995 This.getPointer(), getContext().getRecordType(ClassDecl)); 1996 1997 if (D->isTrivial() && D->isDefaultConstructor()) { 1998 assert(Args.size() == 1 && "trivial default ctor with args"); 1999 return; 2000 } 2001 2002 // If this is a trivial constructor, just emit what's needed. If this is a 2003 // union copy constructor, we must emit a memcpy, because the AST does not 2004 // model that copy. 2005 if (isMemcpyEquivalentSpecialMember(D)) { 2006 assert(Args.size() == 2 && "unexpected argcount for trivial ctor"); 2007 2008 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType(); 2009 Address Src(Args[1].RV.getScalarVal(), getNaturalTypeAlignment(SrcTy)); 2010 QualType DestTy = getContext().getTypeDeclType(ClassDecl); 2011 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy); 2012 return; 2013 } 2014 2015 // Check whether we can actually emit the constructor before trying to do so. 2016 if (auto Inherited = D->getInheritedConstructor()) { 2017 if (getTypes().inheritingCtorHasParams(Inherited, Type) && 2018 !canEmitDelegateCallArgs(*this, D, Type, Args)) { 2019 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase, 2020 Delegating, Args); 2021 return; 2022 } 2023 } 2024 2025 // Insert any ABI-specific implicit constructor arguments. 2026 unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs( 2027 *this, D, Type, ForVirtualBase, Delegating, Args); 2028 2029 // Emit the call. 2030 llvm::Constant *CalleePtr = 2031 CGM.getAddrOfCXXStructor(D, getFromCtorType(Type)); 2032 const CGFunctionInfo &Info = 2033 CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs); 2034 CGCallee Callee = CGCallee::forDirect(CalleePtr, D); 2035 EmitCall(Info, Callee, ReturnValueSlot(), Args); 2036 2037 // Generate vtable assumptions if we're constructing a complete object 2038 // with a vtable. We don't do this for base subobjects for two reasons: 2039 // first, it's incorrect for classes with virtual bases, and second, we're 2040 // about to overwrite the vptrs anyway. 2041 // We also have to make sure if we can refer to vtable: 2042 // - Otherwise we can refer to vtable if it's safe to speculatively emit. 2043 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are 2044 // sure that definition of vtable is not hidden, 2045 // then we are always safe to refer to it. 2046 // FIXME: It looks like InstCombine is very inefficient on dealing with 2047 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily. 2048 if (CGM.getCodeGenOpts().OptimizationLevel > 0 && 2049 ClassDecl->isDynamicClass() && Type != Ctor_Base && 2050 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) && 2051 CGM.getCodeGenOpts().StrictVTablePointers) 2052 EmitVTableAssumptionLoads(ClassDecl, This); 2053 } 2054 2055 void CodeGenFunction::EmitInheritedCXXConstructorCall( 2056 const CXXConstructorDecl *D, bool ForVirtualBase, Address This, 2057 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) { 2058 CallArgList Args; 2059 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType(getContext()), 2060 /*NeedsCopy=*/false); 2061 2062 // Forward the parameters. 2063 if (InheritedFromVBase && 2064 CGM.getTarget().getCXXABI().hasConstructorVariants()) { 2065 // Nothing to do; this construction is not responsible for constructing 2066 // the base class containing the inherited constructor. 2067 // FIXME: Can we just pass undef's for the remaining arguments if we don't 2068 // have constructor variants? 2069 Args.push_back(ThisArg); 2070 } else if (!CXXInheritedCtorInitExprArgs.empty()) { 2071 // The inheriting constructor was inlined; just inject its arguments. 2072 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() && 2073 "wrong number of parameters for inherited constructor call"); 2074 Args = CXXInheritedCtorInitExprArgs; 2075 Args[0] = ThisArg; 2076 } else { 2077 // The inheriting constructor was not inlined. Emit delegating arguments. 2078 Args.push_back(ThisArg); 2079 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl); 2080 assert(OuterCtor->getNumParams() == D->getNumParams()); 2081 assert(!OuterCtor->isVariadic() && "should have been inlined"); 2082 2083 for (const auto *Param : OuterCtor->parameters()) { 2084 assert(getContext().hasSameUnqualifiedType( 2085 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(), 2086 Param->getType())); 2087 EmitDelegateCallArg(Args, Param, E->getLocation()); 2088 2089 // Forward __attribute__(pass_object_size). 2090 if (Param->hasAttr<PassObjectSizeAttr>()) { 2091 auto *POSParam = SizeArguments[Param]; 2092 assert(POSParam && "missing pass_object_size value for forwarding"); 2093 EmitDelegateCallArg(Args, POSParam, E->getLocation()); 2094 } 2095 } 2096 } 2097 2098 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false, 2099 This, Args); 2100 } 2101 2102 void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall( 2103 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase, 2104 bool Delegating, CallArgList &Args) { 2105 InlinedInheritingConstructorScope Scope(*this, GlobalDecl(Ctor, CtorType)); 2106 2107 // Save the arguments to be passed to the inherited constructor. 2108 CXXInheritedCtorInitExprArgs = Args; 2109 2110 FunctionArgList Params; 2111 QualType RetType = BuildFunctionArgList(CurGD, Params); 2112 FnRetTy = RetType; 2113 2114 // Insert any ABI-specific implicit constructor arguments. 2115 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType, 2116 ForVirtualBase, Delegating, Args); 2117 2118 // Emit a simplified prolog. We only need to emit the implicit params. 2119 assert(Args.size() >= Params.size() && "too few arguments for call"); 2120 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 2121 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) { 2122 const RValue &RV = Args[I].RV; 2123 assert(!RV.isComplex() && "complex indirect params not supported"); 2124 ParamValue Val = RV.isScalar() 2125 ? ParamValue::forDirect(RV.getScalarVal()) 2126 : ParamValue::forIndirect(RV.getAggregateAddress()); 2127 EmitParmDecl(*Params[I], Val, I + 1); 2128 } 2129 } 2130 2131 // Create a return value slot if the ABI implementation wants one. 2132 // FIXME: This is dumb, we should ask the ABI not to try to set the return 2133 // value instead. 2134 if (!RetType->isVoidType()) 2135 ReturnValue = CreateIRTemp(RetType, "retval.inhctor"); 2136 2137 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 2138 CXXThisValue = CXXABIThisValue; 2139 2140 // Directly emit the constructor initializers. 2141 EmitCtorPrologue(Ctor, CtorType, Params); 2142 } 2143 2144 void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) { 2145 llvm::Value *VTableGlobal = 2146 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass); 2147 if (!VTableGlobal) 2148 return; 2149 2150 // We can just use the base offset in the complete class. 2151 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset(); 2152 2153 if (!NonVirtualOffset.isZero()) 2154 This = 2155 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr, 2156 Vptr.VTableClass, Vptr.NearestVBase); 2157 2158 llvm::Value *VPtrValue = 2159 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass); 2160 llvm::Value *Cmp = 2161 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables"); 2162 Builder.CreateAssumption(Cmp); 2163 } 2164 2165 void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, 2166 Address This) { 2167 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl)) 2168 for (const VPtr &Vptr : getVTablePointers(ClassDecl)) 2169 EmitVTableAssumptionLoad(Vptr, This); 2170 } 2171 2172 void 2173 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 2174 Address This, Address Src, 2175 const CXXConstructExpr *E) { 2176 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>(); 2177 2178 CallArgList Args; 2179 2180 // Push the this ptr. 2181 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext())); 2182 2183 // Push the src ptr. 2184 QualType QT = *(FPT->param_type_begin()); 2185 llvm::Type *t = CGM.getTypes().ConvertType(QT); 2186 Src = Builder.CreateBitCast(Src, t); 2187 Args.add(RValue::get(Src.getPointer()), QT); 2188 2189 // Skip over first argument (Src). 2190 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(), 2191 /*ParamsToSkip*/ 1); 2192 2193 EmitCXXConstructorCall(D, Ctor_Complete, false, false, This, Args); 2194 } 2195 2196 void 2197 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 2198 CXXCtorType CtorType, 2199 const FunctionArgList &Args, 2200 SourceLocation Loc) { 2201 CallArgList DelegateArgs; 2202 2203 FunctionArgList::const_iterator I = Args.begin(), E = Args.end(); 2204 assert(I != E && "no parameters to constructor"); 2205 2206 // this 2207 Address This = LoadCXXThisAddress(); 2208 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType()); 2209 ++I; 2210 2211 // FIXME: The location of the VTT parameter in the parameter list is 2212 // specific to the Itanium ABI and shouldn't be hardcoded here. 2213 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) { 2214 assert(I != E && "cannot skip vtt parameter, already done with args"); 2215 assert((*I)->getType()->isPointerType() && 2216 "skipping parameter not of vtt type"); 2217 ++I; 2218 } 2219 2220 // Explicit arguments. 2221 for (; I != E; ++I) { 2222 const VarDecl *param = *I; 2223 // FIXME: per-argument source location 2224 EmitDelegateCallArg(DelegateArgs, param, Loc); 2225 } 2226 2227 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false, 2228 /*Delegating=*/true, This, DelegateArgs); 2229 } 2230 2231 namespace { 2232 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup { 2233 const CXXDestructorDecl *Dtor; 2234 Address Addr; 2235 CXXDtorType Type; 2236 2237 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr, 2238 CXXDtorType Type) 2239 : Dtor(D), Addr(Addr), Type(Type) {} 2240 2241 void Emit(CodeGenFunction &CGF, Flags flags) override { 2242 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false, 2243 /*Delegating=*/true, Addr); 2244 } 2245 }; 2246 } // end anonymous namespace 2247 2248 void 2249 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2250 const FunctionArgList &Args) { 2251 assert(Ctor->isDelegatingConstructor()); 2252 2253 Address ThisPtr = LoadCXXThisAddress(); 2254 2255 AggValueSlot AggSlot = 2256 AggValueSlot::forAddr(ThisPtr, Qualifiers(), 2257 AggValueSlot::IsDestructed, 2258 AggValueSlot::DoesNotNeedGCBarriers, 2259 AggValueSlot::IsNotAliased); 2260 2261 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot); 2262 2263 const CXXRecordDecl *ClassDecl = Ctor->getParent(); 2264 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) { 2265 CXXDtorType Type = 2266 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base; 2267 2268 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup, 2269 ClassDecl->getDestructor(), 2270 ThisPtr, Type); 2271 } 2272 } 2273 2274 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD, 2275 CXXDtorType Type, 2276 bool ForVirtualBase, 2277 bool Delegating, 2278 Address This) { 2279 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase, 2280 Delegating, This); 2281 } 2282 2283 namespace { 2284 struct CallLocalDtor final : EHScopeStack::Cleanup { 2285 const CXXDestructorDecl *Dtor; 2286 Address Addr; 2287 2288 CallLocalDtor(const CXXDestructorDecl *D, Address Addr) 2289 : Dtor(D), Addr(Addr) {} 2290 2291 void Emit(CodeGenFunction &CGF, Flags flags) override { 2292 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 2293 /*ForVirtualBase=*/false, 2294 /*Delegating=*/false, Addr); 2295 } 2296 }; 2297 } // end anonymous namespace 2298 2299 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D, 2300 Address Addr) { 2301 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr); 2302 } 2303 2304 void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) { 2305 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl(); 2306 if (!ClassDecl) return; 2307 if (ClassDecl->hasTrivialDestructor()) return; 2308 2309 const CXXDestructorDecl *D = ClassDecl->getDestructor(); 2310 assert(D && D->isUsed() && "destructor not marked as used!"); 2311 PushDestructorCleanup(D, Addr); 2312 } 2313 2314 void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) { 2315 // Compute the address point. 2316 llvm::Value *VTableAddressPoint = 2317 CGM.getCXXABI().getVTableAddressPointInStructor( 2318 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase); 2319 2320 if (!VTableAddressPoint) 2321 return; 2322 2323 // Compute where to store the address point. 2324 llvm::Value *VirtualOffset = nullptr; 2325 CharUnits NonVirtualOffset = CharUnits::Zero(); 2326 2327 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) { 2328 // We need to use the virtual base offset offset because the virtual base 2329 // might have a different offset in the most derived class. 2330 2331 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset( 2332 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase); 2333 NonVirtualOffset = Vptr.OffsetFromNearestVBase; 2334 } else { 2335 // We can just use the base offset in the complete class. 2336 NonVirtualOffset = Vptr.Base.getBaseOffset(); 2337 } 2338 2339 // Apply the offsets. 2340 Address VTableField = LoadCXXThisAddress(); 2341 2342 if (!NonVirtualOffset.isZero() || VirtualOffset) 2343 VTableField = ApplyNonVirtualAndVirtualOffset( 2344 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass, 2345 Vptr.NearestVBase); 2346 2347 // Finally, store the address point. Use the same LLVM types as the field to 2348 // support optimization. 2349 llvm::Type *VTablePtrTy = 2350 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true) 2351 ->getPointerTo() 2352 ->getPointerTo(); 2353 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo()); 2354 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy); 2355 2356 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField); 2357 CGM.DecorateInstructionWithTBAA(Store, CGM.getTBAAInfoForVTablePtr()); 2358 if (CGM.getCodeGenOpts().OptimizationLevel > 0 && 2359 CGM.getCodeGenOpts().StrictVTablePointers) 2360 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass); 2361 } 2362 2363 CodeGenFunction::VPtrsVector 2364 CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) { 2365 CodeGenFunction::VPtrsVector VPtrsResult; 2366 VisitedVirtualBasesSetTy VBases; 2367 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()), 2368 /*NearestVBase=*/nullptr, 2369 /*OffsetFromNearestVBase=*/CharUnits::Zero(), 2370 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases, 2371 VPtrsResult); 2372 return VPtrsResult; 2373 } 2374 2375 void CodeGenFunction::getVTablePointers(BaseSubobject Base, 2376 const CXXRecordDecl *NearestVBase, 2377 CharUnits OffsetFromNearestVBase, 2378 bool BaseIsNonVirtualPrimaryBase, 2379 const CXXRecordDecl *VTableClass, 2380 VisitedVirtualBasesSetTy &VBases, 2381 VPtrsVector &Vptrs) { 2382 // If this base is a non-virtual primary base the address point has already 2383 // been set. 2384 if (!BaseIsNonVirtualPrimaryBase) { 2385 // Initialize the vtable pointer for this base. 2386 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass}; 2387 Vptrs.push_back(Vptr); 2388 } 2389 2390 const CXXRecordDecl *RD = Base.getBase(); 2391 2392 // Traverse bases. 2393 for (const auto &I : RD->bases()) { 2394 CXXRecordDecl *BaseDecl 2395 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 2396 2397 // Ignore classes without a vtable. 2398 if (!BaseDecl->isDynamicClass()) 2399 continue; 2400 2401 CharUnits BaseOffset; 2402 CharUnits BaseOffsetFromNearestVBase; 2403 bool BaseDeclIsNonVirtualPrimaryBase; 2404 2405 if (I.isVirtual()) { 2406 // Check if we've visited this virtual base before. 2407 if (!VBases.insert(BaseDecl).second) 2408 continue; 2409 2410 const ASTRecordLayout &Layout = 2411 getContext().getASTRecordLayout(VTableClass); 2412 2413 BaseOffset = Layout.getVBaseClassOffset(BaseDecl); 2414 BaseOffsetFromNearestVBase = CharUnits::Zero(); 2415 BaseDeclIsNonVirtualPrimaryBase = false; 2416 } else { 2417 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 2418 2419 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl); 2420 BaseOffsetFromNearestVBase = 2421 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl); 2422 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl; 2423 } 2424 2425 getVTablePointers( 2426 BaseSubobject(BaseDecl, BaseOffset), 2427 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase, 2428 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs); 2429 } 2430 } 2431 2432 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) { 2433 // Ignore classes without a vtable. 2434 if (!RD->isDynamicClass()) 2435 return; 2436 2437 // Initialize the vtable pointers for this class and all of its bases. 2438 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD)) 2439 for (const VPtr &Vptr : getVTablePointers(RD)) 2440 InitializeVTablePointer(Vptr); 2441 2442 if (RD->getNumVBases()) 2443 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD); 2444 } 2445 2446 llvm::Value *CodeGenFunction::GetVTablePtr(Address This, 2447 llvm::Type *VTableTy, 2448 const CXXRecordDecl *RD) { 2449 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy); 2450 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable"); 2451 CGM.DecorateInstructionWithTBAA(VTable, CGM.getTBAAInfoForVTablePtr()); 2452 2453 if (CGM.getCodeGenOpts().OptimizationLevel > 0 && 2454 CGM.getCodeGenOpts().StrictVTablePointers) 2455 CGM.DecorateInstructionWithInvariantGroup(VTable, RD); 2456 2457 return VTable; 2458 } 2459 2460 // If a class has a single non-virtual base and does not introduce or override 2461 // virtual member functions or fields, it will have the same layout as its base. 2462 // This function returns the least derived such class. 2463 // 2464 // Casting an instance of a base class to such a derived class is technically 2465 // undefined behavior, but it is a relatively common hack for introducing member 2466 // functions on class instances with specific properties (e.g. llvm::Operator) 2467 // that works under most compilers and should not have security implications, so 2468 // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict. 2469 static const CXXRecordDecl * 2470 LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) { 2471 if (!RD->field_empty()) 2472 return RD; 2473 2474 if (RD->getNumVBases() != 0) 2475 return RD; 2476 2477 if (RD->getNumBases() != 1) 2478 return RD; 2479 2480 for (const CXXMethodDecl *MD : RD->methods()) { 2481 if (MD->isVirtual()) { 2482 // Virtual member functions are only ok if they are implicit destructors 2483 // because the implicit destructor will have the same semantics as the 2484 // base class's destructor if no fields are added. 2485 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit()) 2486 continue; 2487 return RD; 2488 } 2489 } 2490 2491 return LeastDerivedClassWithSameLayout( 2492 RD->bases_begin()->getType()->getAsCXXRecordDecl()); 2493 } 2494 2495 void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD, 2496 llvm::Value *VTable, 2497 SourceLocation Loc) { 2498 if (CGM.getCodeGenOpts().WholeProgramVTables && 2499 CGM.HasHiddenLTOVisibility(RD)) { 2500 llvm::Metadata *MD = 2501 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 2502 llvm::Value *TypeId = 2503 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD); 2504 2505 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy); 2506 llvm::Value *TypeTest = 2507 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test), 2508 {CastedVTable, TypeId}); 2509 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest); 2510 } 2511 2512 if (SanOpts.has(SanitizerKind::CFIVCall)) 2513 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc); 2514 } 2515 2516 void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, 2517 llvm::Value *VTable, 2518 CFITypeCheckKind TCK, 2519 SourceLocation Loc) { 2520 if (!SanOpts.has(SanitizerKind::CFICastStrict)) 2521 RD = LeastDerivedClassWithSameLayout(RD); 2522 2523 EmitVTablePtrCheck(RD, VTable, TCK, Loc); 2524 } 2525 2526 void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T, 2527 llvm::Value *Derived, 2528 bool MayBeNull, 2529 CFITypeCheckKind TCK, 2530 SourceLocation Loc) { 2531 if (!getLangOpts().CPlusPlus) 2532 return; 2533 2534 auto *ClassTy = T->getAs<RecordType>(); 2535 if (!ClassTy) 2536 return; 2537 2538 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl()); 2539 2540 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass()) 2541 return; 2542 2543 if (!SanOpts.has(SanitizerKind::CFICastStrict)) 2544 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl); 2545 2546 llvm::BasicBlock *ContBlock = nullptr; 2547 2548 if (MayBeNull) { 2549 llvm::Value *DerivedNotNull = 2550 Builder.CreateIsNotNull(Derived, "cast.nonnull"); 2551 2552 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check"); 2553 ContBlock = createBasicBlock("cast.cont"); 2554 2555 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock); 2556 2557 EmitBlock(CheckBlock); 2558 } 2559 2560 llvm::Value *VTable = 2561 GetVTablePtr(Address(Derived, getPointerAlign()), Int8PtrTy, ClassDecl); 2562 2563 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc); 2564 2565 if (MayBeNull) { 2566 Builder.CreateBr(ContBlock); 2567 EmitBlock(ContBlock); 2568 } 2569 } 2570 2571 void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD, 2572 llvm::Value *VTable, 2573 CFITypeCheckKind TCK, 2574 SourceLocation Loc) { 2575 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso && 2576 !CGM.HasHiddenLTOVisibility(RD)) 2577 return; 2578 2579 std::string TypeName = RD->getQualifiedNameAsString(); 2580 if (getContext().getSanitizerBlacklist().isBlacklistedType(TypeName)) 2581 return; 2582 2583 SanitizerScope SanScope(this); 2584 llvm::SanitizerStatKind SSK; 2585 switch (TCK) { 2586 case CFITCK_VCall: 2587 SSK = llvm::SanStat_CFI_VCall; 2588 break; 2589 case CFITCK_NVCall: 2590 SSK = llvm::SanStat_CFI_NVCall; 2591 break; 2592 case CFITCK_DerivedCast: 2593 SSK = llvm::SanStat_CFI_DerivedCast; 2594 break; 2595 case CFITCK_UnrelatedCast: 2596 SSK = llvm::SanStat_CFI_UnrelatedCast; 2597 break; 2598 case CFITCK_ICall: 2599 llvm_unreachable("not expecting CFITCK_ICall"); 2600 } 2601 EmitSanitizerStatReport(SSK); 2602 2603 llvm::Metadata *MD = 2604 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 2605 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD); 2606 2607 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy); 2608 llvm::Value *TypeTest = Builder.CreateCall( 2609 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId}); 2610 2611 SanitizerMask M; 2612 switch (TCK) { 2613 case CFITCK_VCall: 2614 M = SanitizerKind::CFIVCall; 2615 break; 2616 case CFITCK_NVCall: 2617 M = SanitizerKind::CFINVCall; 2618 break; 2619 case CFITCK_DerivedCast: 2620 M = SanitizerKind::CFIDerivedCast; 2621 break; 2622 case CFITCK_UnrelatedCast: 2623 M = SanitizerKind::CFIUnrelatedCast; 2624 break; 2625 case CFITCK_ICall: 2626 llvm_unreachable("not expecting CFITCK_ICall"); 2627 } 2628 2629 llvm::Constant *StaticData[] = { 2630 llvm::ConstantInt::get(Int8Ty, TCK), 2631 EmitCheckSourceLocation(Loc), 2632 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)), 2633 }; 2634 2635 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD); 2636 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) { 2637 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData); 2638 return; 2639 } 2640 2641 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) { 2642 EmitTrapCheck(TypeTest); 2643 return; 2644 } 2645 2646 llvm::Value *AllVtables = llvm::MetadataAsValue::get( 2647 CGM.getLLVMContext(), 2648 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables")); 2649 llvm::Value *ValidVtable = Builder.CreateCall( 2650 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables}); 2651 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail, 2652 StaticData, {CastedVTable, ValidVtable}); 2653 } 2654 2655 bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) { 2656 if (!CGM.getCodeGenOpts().WholeProgramVTables || 2657 !SanOpts.has(SanitizerKind::CFIVCall) || 2658 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) || 2659 !CGM.HasHiddenLTOVisibility(RD)) 2660 return false; 2661 2662 std::string TypeName = RD->getQualifiedNameAsString(); 2663 return !getContext().getSanitizerBlacklist().isBlacklistedType(TypeName); 2664 } 2665 2666 llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad( 2667 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) { 2668 SanitizerScope SanScope(this); 2669 2670 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall); 2671 2672 llvm::Metadata *MD = 2673 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 2674 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD); 2675 2676 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy); 2677 llvm::Value *CheckedLoad = Builder.CreateCall( 2678 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load), 2679 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset), 2680 TypeId}); 2681 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1); 2682 2683 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall), 2684 SanitizerHandler::CFICheckFail, nullptr, nullptr); 2685 2686 return Builder.CreateBitCast( 2687 Builder.CreateExtractValue(CheckedLoad, 0), 2688 cast<llvm::PointerType>(VTable->getType())->getElementType()); 2689 } 2690 2691 bool 2692 CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base, 2693 const CXXMethodDecl *MD) { 2694 // When building with -fapple-kext, all calls must go through the vtable since 2695 // the kernel linker can do runtime patching of vtables. 2696 if (getLangOpts().AppleKext) 2697 return false; 2698 2699 // If the member function is marked 'final', we know that it can't be 2700 // overridden and can therefore devirtualize it unless it's pure virtual. 2701 if (MD->hasAttr<FinalAttr>()) 2702 return !MD->isPure(); 2703 2704 // If the base expression (after skipping derived-to-base conversions) is a 2705 // class prvalue, then we can devirtualize. 2706 Base = Base->getBestDynamicClassTypeExpr(); 2707 if (Base->isRValue() && Base->getType()->isRecordType()) 2708 return true; 2709 2710 // If we don't even know what we would call, we can't devirtualize. 2711 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType(); 2712 if (!BestDynamicDecl) 2713 return false; 2714 2715 // There may be a method corresponding to MD in a derived class. 2716 const CXXMethodDecl *DevirtualizedMethod = 2717 MD->getCorrespondingMethodInClass(BestDynamicDecl); 2718 2719 // If that method is pure virtual, we can't devirtualize. If this code is 2720 // reached, the result would be UB, not a direct call to the derived class 2721 // function, and we can't assume the derived class function is defined. 2722 if (DevirtualizedMethod->isPure()) 2723 return false; 2724 2725 // If that method is marked final, we can devirtualize it. 2726 if (DevirtualizedMethod->hasAttr<FinalAttr>()) 2727 return true; 2728 2729 // Similarly, if the class itself is marked 'final' it can't be overridden 2730 // and we can therefore devirtualize the member function call. 2731 if (BestDynamicDecl->hasAttr<FinalAttr>()) 2732 return true; 2733 2734 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 2735 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 2736 // This is a record decl. We know the type and can devirtualize it. 2737 return VD->getType()->isRecordType(); 2738 } 2739 2740 return false; 2741 } 2742 2743 // We can devirtualize calls on an object accessed by a class member access 2744 // expression, since by C++11 [basic.life]p6 we know that it can't refer to 2745 // a derived class object constructed in the same location. 2746 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base)) 2747 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl())) 2748 return VD->getType()->isRecordType(); 2749 2750 // Likewise for calls on an object accessed by a (non-reference) pointer to 2751 // member access. 2752 if (auto *BO = dyn_cast<BinaryOperator>(Base)) { 2753 if (BO->isPtrMemOp()) { 2754 auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>(); 2755 if (MPT->getPointeeType()->isRecordType()) 2756 return true; 2757 } 2758 } 2759 2760 // We can't devirtualize the call. 2761 return false; 2762 } 2763 2764 void CodeGenFunction::EmitForwardingCallToLambda( 2765 const CXXMethodDecl *callOperator, 2766 CallArgList &callArgs) { 2767 // Get the address of the call operator. 2768 const CGFunctionInfo &calleeFnInfo = 2769 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator); 2770 llvm::Constant *calleePtr = 2771 CGM.GetAddrOfFunction(GlobalDecl(callOperator), 2772 CGM.getTypes().GetFunctionType(calleeFnInfo)); 2773 2774 // Prepare the return slot. 2775 const FunctionProtoType *FPT = 2776 callOperator->getType()->castAs<FunctionProtoType>(); 2777 QualType resultType = FPT->getReturnType(); 2778 ReturnValueSlot returnSlot; 2779 if (!resultType->isVoidType() && 2780 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect && 2781 !hasScalarEvaluationKind(calleeFnInfo.getReturnType())) 2782 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified()); 2783 2784 // We don't need to separately arrange the call arguments because 2785 // the call can't be variadic anyway --- it's impossible to forward 2786 // variadic arguments. 2787 2788 // Now emit our call. 2789 auto callee = CGCallee::forDirect(calleePtr, callOperator); 2790 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs); 2791 2792 // If necessary, copy the returned value into the slot. 2793 if (!resultType->isVoidType() && returnSlot.isNull()) 2794 EmitReturnOfRValue(RV, resultType); 2795 else 2796 EmitBranchThroughCleanup(ReturnBlock); 2797 } 2798 2799 void CodeGenFunction::EmitLambdaBlockInvokeBody() { 2800 const BlockDecl *BD = BlockInfo->getBlockDecl(); 2801 const VarDecl *variable = BD->capture_begin()->getVariable(); 2802 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl(); 2803 2804 // Start building arguments for forwarding call 2805 CallArgList CallArgs; 2806 2807 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda)); 2808 Address ThisPtr = GetAddrOfBlockDecl(variable, false); 2809 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType); 2810 2811 // Add the rest of the parameters. 2812 for (auto param : BD->parameters()) 2813 EmitDelegateCallArg(CallArgs, param, param->getLocStart()); 2814 2815 assert(!Lambda->isGenericLambda() && 2816 "generic lambda interconversion to block not implemented"); 2817 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs); 2818 } 2819 2820 void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) { 2821 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) { 2822 // FIXME: Making this work correctly is nasty because it requires either 2823 // cloning the body of the call operator or making the call operator forward. 2824 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function"); 2825 return; 2826 } 2827 2828 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody()); 2829 } 2830 2831 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) { 2832 const CXXRecordDecl *Lambda = MD->getParent(); 2833 2834 // Start building arguments for forwarding call 2835 CallArgList CallArgs; 2836 2837 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda)); 2838 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType)); 2839 CallArgs.add(RValue::get(ThisPtr), ThisType); 2840 2841 // Add the rest of the parameters. 2842 for (auto Param : MD->parameters()) 2843 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart()); 2844 2845 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 2846 // For a generic lambda, find the corresponding call operator specialization 2847 // to which the call to the static-invoker shall be forwarded. 2848 if (Lambda->isGenericLambda()) { 2849 assert(MD->isFunctionTemplateSpecialization()); 2850 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 2851 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate(); 2852 void *InsertPos = nullptr; 2853 FunctionDecl *CorrespondingCallOpSpecialization = 2854 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 2855 assert(CorrespondingCallOpSpecialization); 2856 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 2857 } 2858 EmitForwardingCallToLambda(CallOp, CallArgs); 2859 } 2860 2861 void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) { 2862 if (MD->isVariadic()) { 2863 // FIXME: Making this work correctly is nasty because it requires either 2864 // cloning the body of the call operator or making the call operator forward. 2865 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function"); 2866 return; 2867 } 2868 2869 EmitLambdaDelegatingInvokeBody(MD); 2870 } 2871