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 if (MemberExpr *ME2 = dyn_cast<MemberExpr>(RHS)) { 1135 if (ME2->getMemberDecl() == Field) 1136 return Field; 1137 } 1138 return nullptr; 1139 } else if (CXXMemberCallExpr *MCE = dyn_cast<CXXMemberCallExpr>(S)) { 1140 CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(MCE->getCalleeDecl()); 1141 if (!(MD && isMemcpyEquivalentSpecialMember(MD))) 1142 return nullptr; 1143 MemberExpr *IOA = dyn_cast<MemberExpr>(MCE->getImplicitObjectArgument()); 1144 if (!IOA) 1145 return nullptr; 1146 FieldDecl *Field = dyn_cast<FieldDecl>(IOA->getMemberDecl()); 1147 if (!Field || !isMemcpyableField(Field)) 1148 return nullptr; 1149 MemberExpr *Arg0 = dyn_cast<MemberExpr>(MCE->getArg(0)); 1150 if (!Arg0 || Field != dyn_cast<FieldDecl>(Arg0->getMemberDecl())) 1151 return nullptr; 1152 return Field; 1153 } else if (CallExpr *CE = dyn_cast<CallExpr>(S)) { 1154 FunctionDecl *FD = dyn_cast<FunctionDecl>(CE->getCalleeDecl()); 1155 if (!FD || FD->getBuiltinID() != Builtin::BI__builtin_memcpy) 1156 return nullptr; 1157 Expr *DstPtr = CE->getArg(0); 1158 if (ImplicitCastExpr *DC = dyn_cast<ImplicitCastExpr>(DstPtr)) 1159 DstPtr = DC->getSubExpr(); 1160 UnaryOperator *DUO = dyn_cast<UnaryOperator>(DstPtr); 1161 if (!DUO || DUO->getOpcode() != UO_AddrOf) 1162 return nullptr; 1163 MemberExpr *ME = dyn_cast<MemberExpr>(DUO->getSubExpr()); 1164 if (!ME) 1165 return nullptr; 1166 FieldDecl *Field = dyn_cast<FieldDecl>(ME->getMemberDecl()); 1167 if (!Field || !isMemcpyableField(Field)) 1168 return nullptr; 1169 Expr *SrcPtr = CE->getArg(1); 1170 if (ImplicitCastExpr *SC = dyn_cast<ImplicitCastExpr>(SrcPtr)) 1171 SrcPtr = SC->getSubExpr(); 1172 UnaryOperator *SUO = dyn_cast<UnaryOperator>(SrcPtr); 1173 if (!SUO || SUO->getOpcode() != UO_AddrOf) 1174 return nullptr; 1175 MemberExpr *ME2 = dyn_cast<MemberExpr>(SUO->getSubExpr()); 1176 if (!ME2 || Field != dyn_cast<FieldDecl>(ME2->getMemberDecl())) 1177 return nullptr; 1178 return Field; 1179 } 1180 1181 return nullptr; 1182 } 1183 1184 bool AssignmentsMemcpyable; 1185 SmallVector<Stmt*, 16> AggregatedStmts; 1186 1187 public: 1188 AssignmentMemcpyizer(CodeGenFunction &CGF, const CXXMethodDecl *AD, 1189 FunctionArgList &Args) 1190 : FieldMemcpyizer(CGF, AD->getParent(), Args[Args.size() - 1]), 1191 AssignmentsMemcpyable(CGF.getLangOpts().getGC() == LangOptions::NonGC) { 1192 assert(Args.size() == 2); 1193 } 1194 1195 void emitAssignment(Stmt *S) { 1196 FieldDecl *F = getMemcpyableField(S); 1197 if (F) { 1198 addMemcpyableField(F); 1199 AggregatedStmts.push_back(S); 1200 } else { 1201 emitAggregatedStmts(); 1202 CGF.EmitStmt(S); 1203 } 1204 } 1205 1206 void emitAggregatedStmts() { 1207 if (AggregatedStmts.size() <= 1) { 1208 if (!AggregatedStmts.empty()) { 1209 CopyingValueRepresentation CVR(CGF); 1210 CGF.EmitStmt(AggregatedStmts[0]); 1211 } 1212 reset(); 1213 } 1214 1215 emitMemcpy(); 1216 AggregatedStmts.clear(); 1217 } 1218 1219 void finish() { 1220 emitAggregatedStmts(); 1221 } 1222 }; 1223 } // end anonymous namespace 1224 1225 static bool isInitializerOfDynamicClass(const CXXCtorInitializer *BaseInit) { 1226 const Type *BaseType = BaseInit->getBaseClass(); 1227 const auto *BaseClassDecl = 1228 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()); 1229 return BaseClassDecl->isDynamicClass(); 1230 } 1231 1232 /// EmitCtorPrologue - This routine generates necessary code to initialize 1233 /// base classes and non-static data members belonging to this constructor. 1234 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD, 1235 CXXCtorType CtorType, 1236 FunctionArgList &Args) { 1237 if (CD->isDelegatingConstructor()) 1238 return EmitDelegatingCXXConstructorCall(CD, Args); 1239 1240 const CXXRecordDecl *ClassDecl = CD->getParent(); 1241 1242 CXXConstructorDecl::init_const_iterator B = CD->init_begin(), 1243 E = CD->init_end(); 1244 1245 llvm::BasicBlock *BaseCtorContinueBB = nullptr; 1246 if (ClassDecl->getNumVBases() && 1247 !CGM.getTarget().getCXXABI().hasConstructorVariants()) { 1248 // The ABIs that don't have constructor variants need to put a branch 1249 // before the virtual base initialization code. 1250 BaseCtorContinueBB = 1251 CGM.getCXXABI().EmitCtorCompleteObjectHandler(*this, ClassDecl); 1252 assert(BaseCtorContinueBB); 1253 } 1254 1255 llvm::Value *const OldThis = CXXThisValue; 1256 // Virtual base initializers first. 1257 for (; B != E && (*B)->isBaseInitializer() && (*B)->isBaseVirtual(); B++) { 1258 if (CGM.getCodeGenOpts().StrictVTablePointers && 1259 CGM.getCodeGenOpts().OptimizationLevel > 0 && 1260 isInitializerOfDynamicClass(*B)) 1261 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis()); 1262 EmitBaseInitializer(*this, ClassDecl, *B, CtorType); 1263 } 1264 1265 if (BaseCtorContinueBB) { 1266 // Complete object handler should continue to the remaining initializers. 1267 Builder.CreateBr(BaseCtorContinueBB); 1268 EmitBlock(BaseCtorContinueBB); 1269 } 1270 1271 // Then, non-virtual base initializers. 1272 for (; B != E && (*B)->isBaseInitializer(); B++) { 1273 assert(!(*B)->isBaseVirtual()); 1274 1275 if (CGM.getCodeGenOpts().StrictVTablePointers && 1276 CGM.getCodeGenOpts().OptimizationLevel > 0 && 1277 isInitializerOfDynamicClass(*B)) 1278 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis()); 1279 EmitBaseInitializer(*this, ClassDecl, *B, CtorType); 1280 } 1281 1282 CXXThisValue = OldThis; 1283 1284 InitializeVTablePointers(ClassDecl); 1285 1286 // And finally, initialize class members. 1287 FieldConstructionScope FCS(*this, LoadCXXThisAddress()); 1288 ConstructorMemcpyizer CM(*this, CD, Args); 1289 for (; B != E; B++) { 1290 CXXCtorInitializer *Member = (*B); 1291 assert(!Member->isBaseInitializer()); 1292 assert(Member->isAnyMemberInitializer() && 1293 "Delegating initializer on non-delegating constructor"); 1294 CM.addMemberInitializer(Member); 1295 } 1296 CM.finish(); 1297 } 1298 1299 static bool 1300 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field); 1301 1302 static bool 1303 HasTrivialDestructorBody(ASTContext &Context, 1304 const CXXRecordDecl *BaseClassDecl, 1305 const CXXRecordDecl *MostDerivedClassDecl) 1306 { 1307 // If the destructor is trivial we don't have to check anything else. 1308 if (BaseClassDecl->hasTrivialDestructor()) 1309 return true; 1310 1311 if (!BaseClassDecl->getDestructor()->hasTrivialBody()) 1312 return false; 1313 1314 // Check fields. 1315 for (const auto *Field : BaseClassDecl->fields()) 1316 if (!FieldHasTrivialDestructorBody(Context, Field)) 1317 return false; 1318 1319 // Check non-virtual bases. 1320 for (const auto &I : BaseClassDecl->bases()) { 1321 if (I.isVirtual()) 1322 continue; 1323 1324 const CXXRecordDecl *NonVirtualBase = 1325 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 1326 if (!HasTrivialDestructorBody(Context, NonVirtualBase, 1327 MostDerivedClassDecl)) 1328 return false; 1329 } 1330 1331 if (BaseClassDecl == MostDerivedClassDecl) { 1332 // Check virtual bases. 1333 for (const auto &I : BaseClassDecl->vbases()) { 1334 const CXXRecordDecl *VirtualBase = 1335 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 1336 if (!HasTrivialDestructorBody(Context, VirtualBase, 1337 MostDerivedClassDecl)) 1338 return false; 1339 } 1340 } 1341 1342 return true; 1343 } 1344 1345 static bool 1346 FieldHasTrivialDestructorBody(ASTContext &Context, 1347 const FieldDecl *Field) 1348 { 1349 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType()); 1350 1351 const RecordType *RT = FieldBaseElementType->getAs<RecordType>(); 1352 if (!RT) 1353 return true; 1354 1355 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1356 1357 // The destructor for an implicit anonymous union member is never invoked. 1358 if (FieldClassDecl->isUnion() && FieldClassDecl->isAnonymousStructOrUnion()) 1359 return false; 1360 1361 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl); 1362 } 1363 1364 /// CanSkipVTablePointerInitialization - Check whether we need to initialize 1365 /// any vtable pointers before calling this destructor. 1366 static bool CanSkipVTablePointerInitialization(CodeGenFunction &CGF, 1367 const CXXDestructorDecl *Dtor) { 1368 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 1369 if (!ClassDecl->isDynamicClass()) 1370 return true; 1371 1372 if (!Dtor->hasTrivialBody()) 1373 return false; 1374 1375 // Check the fields. 1376 for (const auto *Field : ClassDecl->fields()) 1377 if (!FieldHasTrivialDestructorBody(CGF.getContext(), Field)) 1378 return false; 1379 1380 return true; 1381 } 1382 1383 /// EmitDestructorBody - Emits the body of the current destructor. 1384 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) { 1385 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl()); 1386 CXXDtorType DtorType = CurGD.getDtorType(); 1387 1388 Stmt *Body = Dtor->getBody(); 1389 if (Body) 1390 incrementProfileCounter(Body); 1391 1392 // The call to operator delete in a deleting destructor happens 1393 // outside of the function-try-block, which means it's always 1394 // possible to delegate the destructor body to the complete 1395 // destructor. Do so. 1396 if (DtorType == Dtor_Deleting) { 1397 EnterDtorCleanups(Dtor, Dtor_Deleting); 1398 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false, 1399 /*Delegating=*/false, LoadCXXThisAddress()); 1400 PopCleanupBlock(); 1401 return; 1402 } 1403 1404 // If the body is a function-try-block, enter the try before 1405 // anything else. 1406 bool isTryBody = (Body && isa<CXXTryStmt>(Body)); 1407 if (isTryBody) 1408 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true); 1409 EmitAsanPrologueOrEpilogue(false); 1410 1411 // Enter the epilogue cleanups. 1412 RunCleanupsScope DtorEpilogue(*this); 1413 1414 // If this is the complete variant, just invoke the base variant; 1415 // the epilogue will destruct the virtual bases. But we can't do 1416 // this optimization if the body is a function-try-block, because 1417 // we'd introduce *two* handler blocks. In the Microsoft ABI, we 1418 // always delegate because we might not have a definition in this TU. 1419 switch (DtorType) { 1420 case Dtor_Comdat: llvm_unreachable("not expecting a COMDAT"); 1421 case Dtor_Deleting: llvm_unreachable("already handled deleting case"); 1422 1423 case Dtor_Complete: 1424 assert((Body || getTarget().getCXXABI().isMicrosoft()) && 1425 "can't emit a dtor without a body for non-Microsoft ABIs"); 1426 1427 // Enter the cleanup scopes for virtual bases. 1428 EnterDtorCleanups(Dtor, Dtor_Complete); 1429 1430 if (!isTryBody) { 1431 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false, 1432 /*Delegating=*/false, LoadCXXThisAddress()); 1433 break; 1434 } 1435 1436 // Fallthrough: act like we're in the base variant. 1437 LLVM_FALLTHROUGH; 1438 1439 case Dtor_Base: 1440 assert(Body); 1441 1442 // Enter the cleanup scopes for fields and non-virtual bases. 1443 EnterDtorCleanups(Dtor, Dtor_Base); 1444 1445 // Initialize the vtable pointers before entering the body. 1446 if (!CanSkipVTablePointerInitialization(*this, Dtor)) { 1447 // Insert the llvm.invariant.group.barrier intrinsic before initializing 1448 // the vptrs to cancel any previous assumptions we might have made. 1449 if (CGM.getCodeGenOpts().StrictVTablePointers && 1450 CGM.getCodeGenOpts().OptimizationLevel > 0) 1451 CXXThisValue = Builder.CreateInvariantGroupBarrier(LoadCXXThis()); 1452 InitializeVTablePointers(Dtor->getParent()); 1453 } 1454 1455 if (isTryBody) 1456 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock()); 1457 else if (Body) 1458 EmitStmt(Body); 1459 else { 1460 assert(Dtor->isImplicit() && "bodyless dtor not implicit"); 1461 // nothing to do besides what's in the epilogue 1462 } 1463 // -fapple-kext must inline any call to this dtor into 1464 // the caller's body. 1465 if (getLangOpts().AppleKext) 1466 CurFn->addFnAttr(llvm::Attribute::AlwaysInline); 1467 1468 break; 1469 } 1470 1471 // Jump out through the epilogue cleanups. 1472 DtorEpilogue.ForceCleanup(); 1473 1474 // Exit the try if applicable. 1475 if (isTryBody) 1476 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true); 1477 } 1478 1479 void CodeGenFunction::emitImplicitAssignmentOperatorBody(FunctionArgList &Args) { 1480 const CXXMethodDecl *AssignOp = cast<CXXMethodDecl>(CurGD.getDecl()); 1481 const Stmt *RootS = AssignOp->getBody(); 1482 assert(isa<CompoundStmt>(RootS) && 1483 "Body of an implicit assignment operator should be compound stmt."); 1484 const CompoundStmt *RootCS = cast<CompoundStmt>(RootS); 1485 1486 LexicalScope Scope(*this, RootCS->getSourceRange()); 1487 1488 incrementProfileCounter(RootCS); 1489 AssignmentMemcpyizer AM(*this, AssignOp, Args); 1490 for (auto *I : RootCS->body()) 1491 AM.emitAssignment(I); 1492 AM.finish(); 1493 } 1494 1495 namespace { 1496 /// Call the operator delete associated with the current destructor. 1497 struct CallDtorDelete final : EHScopeStack::Cleanup { 1498 CallDtorDelete() {} 1499 1500 void Emit(CodeGenFunction &CGF, Flags flags) override { 1501 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl); 1502 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 1503 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(), 1504 CGF.getContext().getTagDeclType(ClassDecl)); 1505 } 1506 }; 1507 1508 struct CallDtorDeleteConditional final : EHScopeStack::Cleanup { 1509 llvm::Value *ShouldDeleteCondition; 1510 1511 public: 1512 CallDtorDeleteConditional(llvm::Value *ShouldDeleteCondition) 1513 : ShouldDeleteCondition(ShouldDeleteCondition) { 1514 assert(ShouldDeleteCondition != nullptr); 1515 } 1516 1517 void Emit(CodeGenFunction &CGF, Flags flags) override { 1518 llvm::BasicBlock *callDeleteBB = CGF.createBasicBlock("dtor.call_delete"); 1519 llvm::BasicBlock *continueBB = CGF.createBasicBlock("dtor.continue"); 1520 llvm::Value *ShouldCallDelete 1521 = CGF.Builder.CreateIsNull(ShouldDeleteCondition); 1522 CGF.Builder.CreateCondBr(ShouldCallDelete, continueBB, callDeleteBB); 1523 1524 CGF.EmitBlock(callDeleteBB); 1525 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl); 1526 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 1527 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(), 1528 CGF.getContext().getTagDeclType(ClassDecl)); 1529 CGF.Builder.CreateBr(continueBB); 1530 1531 CGF.EmitBlock(continueBB); 1532 } 1533 }; 1534 1535 class DestroyField final : public EHScopeStack::Cleanup { 1536 const FieldDecl *field; 1537 CodeGenFunction::Destroyer *destroyer; 1538 bool useEHCleanupForArray; 1539 1540 public: 1541 DestroyField(const FieldDecl *field, CodeGenFunction::Destroyer *destroyer, 1542 bool useEHCleanupForArray) 1543 : field(field), destroyer(destroyer), 1544 useEHCleanupForArray(useEHCleanupForArray) {} 1545 1546 void Emit(CodeGenFunction &CGF, Flags flags) override { 1547 // Find the address of the field. 1548 Address thisValue = CGF.LoadCXXThisAddress(); 1549 QualType RecordTy = CGF.getContext().getTagDeclType(field->getParent()); 1550 LValue ThisLV = CGF.MakeAddrLValue(thisValue, RecordTy); 1551 LValue LV = CGF.EmitLValueForField(ThisLV, field); 1552 assert(LV.isSimple()); 1553 1554 CGF.emitDestroy(LV.getAddress(), field->getType(), destroyer, 1555 flags.isForNormalCleanup() && useEHCleanupForArray); 1556 } 1557 }; 1558 1559 static void EmitSanitizerDtorCallback(CodeGenFunction &CGF, llvm::Value *Ptr, 1560 CharUnits::QuantityType PoisonSize) { 1561 // Pass in void pointer and size of region as arguments to runtime 1562 // function 1563 llvm::Value *Args[] = {CGF.Builder.CreateBitCast(Ptr, CGF.VoidPtrTy), 1564 llvm::ConstantInt::get(CGF.SizeTy, PoisonSize)}; 1565 1566 llvm::Type *ArgTypes[] = {CGF.VoidPtrTy, CGF.SizeTy}; 1567 1568 llvm::FunctionType *FnType = 1569 llvm::FunctionType::get(CGF.VoidTy, ArgTypes, false); 1570 llvm::Value *Fn = 1571 CGF.CGM.CreateRuntimeFunction(FnType, "__sanitizer_dtor_callback"); 1572 CGF.EmitNounwindRuntimeCall(Fn, Args); 1573 } 1574 1575 class SanitizeDtorMembers final : public EHScopeStack::Cleanup { 1576 const CXXDestructorDecl *Dtor; 1577 1578 public: 1579 SanitizeDtorMembers(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {} 1580 1581 // Generate function call for handling object poisoning. 1582 // Disables tail call elimination, to prevent the current stack frame 1583 // from disappearing from the stack trace. 1584 void Emit(CodeGenFunction &CGF, Flags flags) override { 1585 const ASTRecordLayout &Layout = 1586 CGF.getContext().getASTRecordLayout(Dtor->getParent()); 1587 1588 // Nothing to poison. 1589 if (Layout.getFieldCount() == 0) 1590 return; 1591 1592 // Prevent the current stack frame from disappearing from the stack trace. 1593 CGF.CurFn->addFnAttr("disable-tail-calls", "true"); 1594 1595 // Construct pointer to region to begin poisoning, and calculate poison 1596 // size, so that only members declared in this class are poisoned. 1597 ASTContext &Context = CGF.getContext(); 1598 unsigned fieldIndex = 0; 1599 int startIndex = -1; 1600 // RecordDecl::field_iterator Field; 1601 for (const FieldDecl *Field : Dtor->getParent()->fields()) { 1602 // Poison field if it is trivial 1603 if (FieldHasTrivialDestructorBody(Context, Field)) { 1604 // Start sanitizing at this field 1605 if (startIndex < 0) 1606 startIndex = fieldIndex; 1607 1608 // Currently on the last field, and it must be poisoned with the 1609 // current block. 1610 if (fieldIndex == Layout.getFieldCount() - 1) { 1611 PoisonMembers(CGF, startIndex, Layout.getFieldCount()); 1612 } 1613 } else if (startIndex >= 0) { 1614 // No longer within a block of memory to poison, so poison the block 1615 PoisonMembers(CGF, startIndex, fieldIndex); 1616 // Re-set the start index 1617 startIndex = -1; 1618 } 1619 fieldIndex += 1; 1620 } 1621 } 1622 1623 private: 1624 /// \param layoutStartOffset index of the ASTRecordLayout field to 1625 /// start poisoning (inclusive) 1626 /// \param layoutEndOffset index of the ASTRecordLayout field to 1627 /// end poisoning (exclusive) 1628 void PoisonMembers(CodeGenFunction &CGF, unsigned layoutStartOffset, 1629 unsigned layoutEndOffset) { 1630 ASTContext &Context = CGF.getContext(); 1631 const ASTRecordLayout &Layout = 1632 Context.getASTRecordLayout(Dtor->getParent()); 1633 1634 llvm::ConstantInt *OffsetSizePtr = llvm::ConstantInt::get( 1635 CGF.SizeTy, 1636 Context.toCharUnitsFromBits(Layout.getFieldOffset(layoutStartOffset)) 1637 .getQuantity()); 1638 1639 llvm::Value *OffsetPtr = CGF.Builder.CreateGEP( 1640 CGF.Builder.CreateBitCast(CGF.LoadCXXThis(), CGF.Int8PtrTy), 1641 OffsetSizePtr); 1642 1643 CharUnits::QuantityType PoisonSize; 1644 if (layoutEndOffset >= Layout.getFieldCount()) { 1645 PoisonSize = Layout.getNonVirtualSize().getQuantity() - 1646 Context.toCharUnitsFromBits( 1647 Layout.getFieldOffset(layoutStartOffset)) 1648 .getQuantity(); 1649 } else { 1650 PoisonSize = Context.toCharUnitsFromBits( 1651 Layout.getFieldOffset(layoutEndOffset) - 1652 Layout.getFieldOffset(layoutStartOffset)) 1653 .getQuantity(); 1654 } 1655 1656 if (PoisonSize == 0) 1657 return; 1658 1659 EmitSanitizerDtorCallback(CGF, OffsetPtr, PoisonSize); 1660 } 1661 }; 1662 1663 class SanitizeDtorVTable final : public EHScopeStack::Cleanup { 1664 const CXXDestructorDecl *Dtor; 1665 1666 public: 1667 SanitizeDtorVTable(const CXXDestructorDecl *Dtor) : Dtor(Dtor) {} 1668 1669 // Generate function call for handling vtable pointer poisoning. 1670 void Emit(CodeGenFunction &CGF, Flags flags) override { 1671 assert(Dtor->getParent()->isDynamicClass()); 1672 (void)Dtor; 1673 ASTContext &Context = CGF.getContext(); 1674 // Poison vtable and vtable ptr if they exist for this class. 1675 llvm::Value *VTablePtr = CGF.LoadCXXThis(); 1676 1677 CharUnits::QuantityType PoisonSize = 1678 Context.toCharUnitsFromBits(CGF.PointerWidthInBits).getQuantity(); 1679 // Pass in void pointer and size of region as arguments to runtime 1680 // function 1681 EmitSanitizerDtorCallback(CGF, VTablePtr, PoisonSize); 1682 } 1683 }; 1684 } // end anonymous namespace 1685 1686 /// \brief Emit all code that comes at the end of class's 1687 /// destructor. This is to call destructors on members and base classes 1688 /// in reverse order of their construction. 1689 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD, 1690 CXXDtorType DtorType) { 1691 assert((!DD->isTrivial() || DD->hasAttr<DLLExportAttr>()) && 1692 "Should not emit dtor epilogue for non-exported trivial dtor!"); 1693 1694 // The deleting-destructor phase just needs to call the appropriate 1695 // operator delete that Sema picked up. 1696 if (DtorType == Dtor_Deleting) { 1697 assert(DD->getOperatorDelete() && 1698 "operator delete missing - EnterDtorCleanups"); 1699 if (CXXStructorImplicitParamValue) { 1700 // If there is an implicit param to the deleting dtor, it's a boolean 1701 // telling whether we should call delete at the end of the dtor. 1702 EHStack.pushCleanup<CallDtorDeleteConditional>( 1703 NormalAndEHCleanup, CXXStructorImplicitParamValue); 1704 } else { 1705 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup); 1706 } 1707 return; 1708 } 1709 1710 const CXXRecordDecl *ClassDecl = DD->getParent(); 1711 1712 // Unions have no bases and do not call field destructors. 1713 if (ClassDecl->isUnion()) 1714 return; 1715 1716 // The complete-destructor phase just destructs all the virtual bases. 1717 if (DtorType == Dtor_Complete) { 1718 // Poison the vtable pointer such that access after the base 1719 // and member destructors are invoked is invalid. 1720 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor && 1721 SanOpts.has(SanitizerKind::Memory) && ClassDecl->getNumVBases() && 1722 ClassDecl->isPolymorphic()) 1723 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD); 1724 1725 // We push them in the forward order so that they'll be popped in 1726 // the reverse order. 1727 for (const auto &Base : ClassDecl->vbases()) { 1728 CXXRecordDecl *BaseClassDecl 1729 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 1730 1731 // Ignore trivial destructors. 1732 if (BaseClassDecl->hasTrivialDestructor()) 1733 continue; 1734 1735 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 1736 BaseClassDecl, 1737 /*BaseIsVirtual*/ true); 1738 } 1739 1740 return; 1741 } 1742 1743 assert(DtorType == Dtor_Base); 1744 // Poison the vtable pointer if it has no virtual bases, but inherits 1745 // virtual functions. 1746 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor && 1747 SanOpts.has(SanitizerKind::Memory) && !ClassDecl->getNumVBases() && 1748 ClassDecl->isPolymorphic()) 1749 EHStack.pushCleanup<SanitizeDtorVTable>(NormalAndEHCleanup, DD); 1750 1751 // Destroy non-virtual bases. 1752 for (const auto &Base : ClassDecl->bases()) { 1753 // Ignore virtual bases. 1754 if (Base.isVirtual()) 1755 continue; 1756 1757 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl(); 1758 1759 // Ignore trivial destructors. 1760 if (BaseClassDecl->hasTrivialDestructor()) 1761 continue; 1762 1763 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 1764 BaseClassDecl, 1765 /*BaseIsVirtual*/ false); 1766 } 1767 1768 // Poison fields such that access after their destructors are 1769 // invoked, and before the base class destructor runs, is invalid. 1770 if (CGM.getCodeGenOpts().SanitizeMemoryUseAfterDtor && 1771 SanOpts.has(SanitizerKind::Memory)) 1772 EHStack.pushCleanup<SanitizeDtorMembers>(NormalAndEHCleanup, DD); 1773 1774 // Destroy direct fields. 1775 for (const auto *Field : ClassDecl->fields()) { 1776 QualType type = Field->getType(); 1777 QualType::DestructionKind dtorKind = type.isDestructedType(); 1778 if (!dtorKind) continue; 1779 1780 // Anonymous union members do not have their destructors called. 1781 const RecordType *RT = type->getAsUnionType(); 1782 if (RT && RT->getDecl()->isAnonymousStructOrUnion()) continue; 1783 1784 CleanupKind cleanupKind = getCleanupKind(dtorKind); 1785 EHStack.pushCleanup<DestroyField>(cleanupKind, Field, 1786 getDestroyer(dtorKind), 1787 cleanupKind & EHCleanup); 1788 } 1789 } 1790 1791 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular 1792 /// constructor for each of several members of an array. 1793 /// 1794 /// \param ctor the constructor to call for each element 1795 /// \param arrayType the type of the array to initialize 1796 /// \param arrayBegin an arrayType* 1797 /// \param zeroInitialize true if each element should be 1798 /// zero-initialized before it is constructed 1799 void CodeGenFunction::EmitCXXAggrConstructorCall( 1800 const CXXConstructorDecl *ctor, const ArrayType *arrayType, 1801 Address arrayBegin, const CXXConstructExpr *E, bool zeroInitialize) { 1802 QualType elementType; 1803 llvm::Value *numElements = 1804 emitArrayLength(arrayType, elementType, arrayBegin); 1805 1806 EmitCXXAggrConstructorCall(ctor, numElements, arrayBegin, E, zeroInitialize); 1807 } 1808 1809 /// EmitCXXAggrConstructorCall - Emit a loop to call a particular 1810 /// constructor for each of several members of an array. 1811 /// 1812 /// \param ctor the constructor to call for each element 1813 /// \param numElements the number of elements in the array; 1814 /// may be zero 1815 /// \param arrayBase a T*, where T is the type constructed by ctor 1816 /// \param zeroInitialize true if each element should be 1817 /// zero-initialized before it is constructed 1818 void CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *ctor, 1819 llvm::Value *numElements, 1820 Address arrayBase, 1821 const CXXConstructExpr *E, 1822 bool zeroInitialize) { 1823 // It's legal for numElements to be zero. This can happen both 1824 // dynamically, because x can be zero in 'new A[x]', and statically, 1825 // because of GCC extensions that permit zero-length arrays. There 1826 // are probably legitimate places where we could assume that this 1827 // doesn't happen, but it's not clear that it's worth it. 1828 llvm::BranchInst *zeroCheckBranch = nullptr; 1829 1830 // Optimize for a constant count. 1831 llvm::ConstantInt *constantCount 1832 = dyn_cast<llvm::ConstantInt>(numElements); 1833 if (constantCount) { 1834 // Just skip out if the constant count is zero. 1835 if (constantCount->isZero()) return; 1836 1837 // Otherwise, emit the check. 1838 } else { 1839 llvm::BasicBlock *loopBB = createBasicBlock("new.ctorloop"); 1840 llvm::Value *iszero = Builder.CreateIsNull(numElements, "isempty"); 1841 zeroCheckBranch = Builder.CreateCondBr(iszero, loopBB, loopBB); 1842 EmitBlock(loopBB); 1843 } 1844 1845 // Find the end of the array. 1846 llvm::Value *arrayBegin = arrayBase.getPointer(); 1847 llvm::Value *arrayEnd = Builder.CreateInBoundsGEP(arrayBegin, numElements, 1848 "arrayctor.end"); 1849 1850 // Enter the loop, setting up a phi for the current location to initialize. 1851 llvm::BasicBlock *entryBB = Builder.GetInsertBlock(); 1852 llvm::BasicBlock *loopBB = createBasicBlock("arrayctor.loop"); 1853 EmitBlock(loopBB); 1854 llvm::PHINode *cur = Builder.CreatePHI(arrayBegin->getType(), 2, 1855 "arrayctor.cur"); 1856 cur->addIncoming(arrayBegin, entryBB); 1857 1858 // Inside the loop body, emit the constructor call on the array element. 1859 1860 // The alignment of the base, adjusted by the size of a single element, 1861 // provides a conservative estimate of the alignment of every element. 1862 // (This assumes we never start tracking offsetted alignments.) 1863 // 1864 // Note that these are complete objects and so we don't need to 1865 // use the non-virtual size or alignment. 1866 QualType type = getContext().getTypeDeclType(ctor->getParent()); 1867 CharUnits eltAlignment = 1868 arrayBase.getAlignment() 1869 .alignmentOfArrayElement(getContext().getTypeSizeInChars(type)); 1870 Address curAddr = Address(cur, eltAlignment); 1871 1872 // Zero initialize the storage, if requested. 1873 if (zeroInitialize) 1874 EmitNullInitialization(curAddr, type); 1875 1876 // C++ [class.temporary]p4: 1877 // There are two contexts in which temporaries are destroyed at a different 1878 // point than the end of the full-expression. The first context is when a 1879 // default constructor is called to initialize an element of an array. 1880 // If the constructor has one or more default arguments, the destruction of 1881 // every temporary created in a default argument expression is sequenced 1882 // before the construction of the next array element, if any. 1883 1884 { 1885 RunCleanupsScope Scope(*this); 1886 1887 // Evaluate the constructor and its arguments in a regular 1888 // partial-destroy cleanup. 1889 if (getLangOpts().Exceptions && 1890 !ctor->getParent()->hasTrivialDestructor()) { 1891 Destroyer *destroyer = destroyCXXObject; 1892 pushRegularPartialArrayCleanup(arrayBegin, cur, type, eltAlignment, 1893 *destroyer); 1894 } 1895 1896 EmitCXXConstructorCall(ctor, Ctor_Complete, /*ForVirtualBase=*/false, 1897 /*Delegating=*/false, curAddr, E); 1898 } 1899 1900 // Go to the next element. 1901 llvm::Value *next = 1902 Builder.CreateInBoundsGEP(cur, llvm::ConstantInt::get(SizeTy, 1), 1903 "arrayctor.next"); 1904 cur->addIncoming(next, Builder.GetInsertBlock()); 1905 1906 // Check whether that's the end of the loop. 1907 llvm::Value *done = Builder.CreateICmpEQ(next, arrayEnd, "arrayctor.done"); 1908 llvm::BasicBlock *contBB = createBasicBlock("arrayctor.cont"); 1909 Builder.CreateCondBr(done, contBB, loopBB); 1910 1911 // Patch the earlier check to skip over the loop. 1912 if (zeroCheckBranch) zeroCheckBranch->setSuccessor(0, contBB); 1913 1914 EmitBlock(contBB); 1915 } 1916 1917 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF, 1918 Address addr, 1919 QualType type) { 1920 const RecordType *rtype = type->castAs<RecordType>(); 1921 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl()); 1922 const CXXDestructorDecl *dtor = record->getDestructor(); 1923 assert(!dtor->isTrivial()); 1924 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false, 1925 /*Delegating=*/false, addr); 1926 } 1927 1928 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, 1929 CXXCtorType Type, 1930 bool ForVirtualBase, 1931 bool Delegating, Address This, 1932 const CXXConstructExpr *E) { 1933 CallArgList Args; 1934 1935 // Push the this ptr. 1936 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext())); 1937 1938 // If this is a trivial constructor, emit a memcpy now before we lose 1939 // the alignment information on the argument. 1940 // FIXME: It would be better to preserve alignment information into CallArg. 1941 if (isMemcpyEquivalentSpecialMember(D)) { 1942 assert(E->getNumArgs() == 1 && "unexpected argcount for trivial ctor"); 1943 1944 const Expr *Arg = E->getArg(0); 1945 QualType SrcTy = Arg->getType(); 1946 Address Src = EmitLValue(Arg).getAddress(); 1947 QualType DestTy = getContext().getTypeDeclType(D->getParent()); 1948 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy); 1949 return; 1950 } 1951 1952 // Add the rest of the user-supplied arguments. 1953 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>(); 1954 EvaluationOrder Order = E->isListInitialization() 1955 ? EvaluationOrder::ForceLeftToRight 1956 : EvaluationOrder::Default; 1957 EmitCallArgs(Args, FPT, E->arguments(), E->getConstructor(), 1958 /*ParamsToSkip*/ 0, Order); 1959 1960 EmitCXXConstructorCall(D, Type, ForVirtualBase, Delegating, This, Args); 1961 } 1962 1963 static bool canEmitDelegateCallArgs(CodeGenFunction &CGF, 1964 const CXXConstructorDecl *Ctor, 1965 CXXCtorType Type, CallArgList &Args) { 1966 // We can't forward a variadic call. 1967 if (Ctor->isVariadic()) 1968 return false; 1969 1970 if (CGF.getTarget().getCXXABI().areArgsDestroyedLeftToRightInCallee()) { 1971 // If the parameters are callee-cleanup, it's not safe to forward. 1972 for (auto *P : Ctor->parameters()) 1973 if (P->getType().isDestructedType()) 1974 return false; 1975 1976 // Likewise if they're inalloca. 1977 const CGFunctionInfo &Info = 1978 CGF.CGM.getTypes().arrangeCXXConstructorCall(Args, Ctor, Type, 0); 1979 if (Info.usesInAlloca()) 1980 return false; 1981 } 1982 1983 // Anything else should be OK. 1984 return true; 1985 } 1986 1987 void CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, 1988 CXXCtorType Type, 1989 bool ForVirtualBase, 1990 bool Delegating, 1991 Address This, 1992 CallArgList &Args) { 1993 const CXXRecordDecl *ClassDecl = D->getParent(); 1994 1995 // C++11 [class.mfct.non-static]p2: 1996 // If a non-static member function of a class X is called for an object that 1997 // is not of type X, or of a type derived from X, the behavior is undefined. 1998 // FIXME: Provide a source location here. 1999 EmitTypeCheck(CodeGenFunction::TCK_ConstructorCall, SourceLocation(), 2000 This.getPointer(), getContext().getRecordType(ClassDecl)); 2001 2002 if (D->isTrivial() && D->isDefaultConstructor()) { 2003 assert(Args.size() == 1 && "trivial default ctor with args"); 2004 return; 2005 } 2006 2007 // If this is a trivial constructor, just emit what's needed. If this is a 2008 // union copy constructor, we must emit a memcpy, because the AST does not 2009 // model that copy. 2010 if (isMemcpyEquivalentSpecialMember(D)) { 2011 assert(Args.size() == 2 && "unexpected argcount for trivial ctor"); 2012 2013 QualType SrcTy = D->getParamDecl(0)->getType().getNonReferenceType(); 2014 Address Src(Args[1].RV.getScalarVal(), getNaturalTypeAlignment(SrcTy)); 2015 QualType DestTy = getContext().getTypeDeclType(ClassDecl); 2016 EmitAggregateCopyCtor(This, Src, DestTy, SrcTy); 2017 return; 2018 } 2019 2020 // Check whether we can actually emit the constructor before trying to do so. 2021 if (auto Inherited = D->getInheritedConstructor()) { 2022 if (getTypes().inheritingCtorHasParams(Inherited, Type) && 2023 !canEmitDelegateCallArgs(*this, D, Type, Args)) { 2024 EmitInlinedInheritingCXXConstructorCall(D, Type, ForVirtualBase, 2025 Delegating, Args); 2026 return; 2027 } 2028 } 2029 2030 // Insert any ABI-specific implicit constructor arguments. 2031 unsigned ExtraArgs = CGM.getCXXABI().addImplicitConstructorArgs( 2032 *this, D, Type, ForVirtualBase, Delegating, Args); 2033 2034 // Emit the call. 2035 llvm::Constant *CalleePtr = 2036 CGM.getAddrOfCXXStructor(D, getFromCtorType(Type)); 2037 const CGFunctionInfo &Info = 2038 CGM.getTypes().arrangeCXXConstructorCall(Args, D, Type, ExtraArgs); 2039 CGCallee Callee = CGCallee::forDirect(CalleePtr, D); 2040 EmitCall(Info, Callee, ReturnValueSlot(), Args); 2041 2042 // Generate vtable assumptions if we're constructing a complete object 2043 // with a vtable. We don't do this for base subobjects for two reasons: 2044 // first, it's incorrect for classes with virtual bases, and second, we're 2045 // about to overwrite the vptrs anyway. 2046 // We also have to make sure if we can refer to vtable: 2047 // - Otherwise we can refer to vtable if it's safe to speculatively emit. 2048 // FIXME: If vtable is used by ctor/dtor, or if vtable is external and we are 2049 // sure that definition of vtable is not hidden, 2050 // then we are always safe to refer to it. 2051 // FIXME: It looks like InstCombine is very inefficient on dealing with 2052 // assumes. Make assumption loads require -fstrict-vtable-pointers temporarily. 2053 if (CGM.getCodeGenOpts().OptimizationLevel > 0 && 2054 ClassDecl->isDynamicClass() && Type != Ctor_Base && 2055 CGM.getCXXABI().canSpeculativelyEmitVTable(ClassDecl) && 2056 CGM.getCodeGenOpts().StrictVTablePointers) 2057 EmitVTableAssumptionLoads(ClassDecl, This); 2058 } 2059 2060 void CodeGenFunction::EmitInheritedCXXConstructorCall( 2061 const CXXConstructorDecl *D, bool ForVirtualBase, Address This, 2062 bool InheritedFromVBase, const CXXInheritedCtorInitExpr *E) { 2063 CallArgList Args; 2064 CallArg ThisArg(RValue::get(This.getPointer()), D->getThisType(getContext()), 2065 /*NeedsCopy=*/false); 2066 2067 // Forward the parameters. 2068 if (InheritedFromVBase && 2069 CGM.getTarget().getCXXABI().hasConstructorVariants()) { 2070 // Nothing to do; this construction is not responsible for constructing 2071 // the base class containing the inherited constructor. 2072 // FIXME: Can we just pass undef's for the remaining arguments if we don't 2073 // have constructor variants? 2074 Args.push_back(ThisArg); 2075 } else if (!CXXInheritedCtorInitExprArgs.empty()) { 2076 // The inheriting constructor was inlined; just inject its arguments. 2077 assert(CXXInheritedCtorInitExprArgs.size() >= D->getNumParams() && 2078 "wrong number of parameters for inherited constructor call"); 2079 Args = CXXInheritedCtorInitExprArgs; 2080 Args[0] = ThisArg; 2081 } else { 2082 // The inheriting constructor was not inlined. Emit delegating arguments. 2083 Args.push_back(ThisArg); 2084 const auto *OuterCtor = cast<CXXConstructorDecl>(CurCodeDecl); 2085 assert(OuterCtor->getNumParams() == D->getNumParams()); 2086 assert(!OuterCtor->isVariadic() && "should have been inlined"); 2087 2088 for (const auto *Param : OuterCtor->parameters()) { 2089 assert(getContext().hasSameUnqualifiedType( 2090 OuterCtor->getParamDecl(Param->getFunctionScopeIndex())->getType(), 2091 Param->getType())); 2092 EmitDelegateCallArg(Args, Param, E->getLocation()); 2093 2094 // Forward __attribute__(pass_object_size). 2095 if (Param->hasAttr<PassObjectSizeAttr>()) { 2096 auto *POSParam = SizeArguments[Param]; 2097 assert(POSParam && "missing pass_object_size value for forwarding"); 2098 EmitDelegateCallArg(Args, POSParam, E->getLocation()); 2099 } 2100 } 2101 } 2102 2103 EmitCXXConstructorCall(D, Ctor_Base, ForVirtualBase, /*Delegating*/false, 2104 This, Args); 2105 } 2106 2107 void CodeGenFunction::EmitInlinedInheritingCXXConstructorCall( 2108 const CXXConstructorDecl *Ctor, CXXCtorType CtorType, bool ForVirtualBase, 2109 bool Delegating, CallArgList &Args) { 2110 InlinedInheritingConstructorScope Scope(*this, GlobalDecl(Ctor, CtorType)); 2111 2112 // Save the arguments to be passed to the inherited constructor. 2113 CXXInheritedCtorInitExprArgs = Args; 2114 2115 FunctionArgList Params; 2116 QualType RetType = BuildFunctionArgList(CurGD, Params); 2117 FnRetTy = RetType; 2118 2119 // Insert any ABI-specific implicit constructor arguments. 2120 CGM.getCXXABI().addImplicitConstructorArgs(*this, Ctor, CtorType, 2121 ForVirtualBase, Delegating, Args); 2122 2123 // Emit a simplified prolog. We only need to emit the implicit params. 2124 assert(Args.size() >= Params.size() && "too few arguments for call"); 2125 for (unsigned I = 0, N = Args.size(); I != N; ++I) { 2126 if (I < Params.size() && isa<ImplicitParamDecl>(Params[I])) { 2127 const RValue &RV = Args[I].RV; 2128 assert(!RV.isComplex() && "complex indirect params not supported"); 2129 ParamValue Val = RV.isScalar() 2130 ? ParamValue::forDirect(RV.getScalarVal()) 2131 : ParamValue::forIndirect(RV.getAggregateAddress()); 2132 EmitParmDecl(*Params[I], Val, I + 1); 2133 } 2134 } 2135 2136 // Create a return value slot if the ABI implementation wants one. 2137 // FIXME: This is dumb, we should ask the ABI not to try to set the return 2138 // value instead. 2139 if (!RetType->isVoidType()) 2140 ReturnValue = CreateIRTemp(RetType, "retval.inhctor"); 2141 2142 CGM.getCXXABI().EmitInstanceFunctionProlog(*this); 2143 CXXThisValue = CXXABIThisValue; 2144 2145 // Directly emit the constructor initializers. 2146 EmitCtorPrologue(Ctor, CtorType, Params); 2147 } 2148 2149 void CodeGenFunction::EmitVTableAssumptionLoad(const VPtr &Vptr, Address This) { 2150 llvm::Value *VTableGlobal = 2151 CGM.getCXXABI().getVTableAddressPoint(Vptr.Base, Vptr.VTableClass); 2152 if (!VTableGlobal) 2153 return; 2154 2155 // We can just use the base offset in the complete class. 2156 CharUnits NonVirtualOffset = Vptr.Base.getBaseOffset(); 2157 2158 if (!NonVirtualOffset.isZero()) 2159 This = 2160 ApplyNonVirtualAndVirtualOffset(*this, This, NonVirtualOffset, nullptr, 2161 Vptr.VTableClass, Vptr.NearestVBase); 2162 2163 llvm::Value *VPtrValue = 2164 GetVTablePtr(This, VTableGlobal->getType(), Vptr.VTableClass); 2165 llvm::Value *Cmp = 2166 Builder.CreateICmpEQ(VPtrValue, VTableGlobal, "cmp.vtables"); 2167 Builder.CreateAssumption(Cmp); 2168 } 2169 2170 void CodeGenFunction::EmitVTableAssumptionLoads(const CXXRecordDecl *ClassDecl, 2171 Address This) { 2172 if (CGM.getCXXABI().doStructorsInitializeVPtrs(ClassDecl)) 2173 for (const VPtr &Vptr : getVTablePointers(ClassDecl)) 2174 EmitVTableAssumptionLoad(Vptr, This); 2175 } 2176 2177 void 2178 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 2179 Address This, Address Src, 2180 const CXXConstructExpr *E) { 2181 const FunctionProtoType *FPT = D->getType()->castAs<FunctionProtoType>(); 2182 2183 CallArgList Args; 2184 2185 // Push the this ptr. 2186 Args.add(RValue::get(This.getPointer()), D->getThisType(getContext())); 2187 2188 // Push the src ptr. 2189 QualType QT = *(FPT->param_type_begin()); 2190 llvm::Type *t = CGM.getTypes().ConvertType(QT); 2191 Src = Builder.CreateBitCast(Src, t); 2192 Args.add(RValue::get(Src.getPointer()), QT); 2193 2194 // Skip over first argument (Src). 2195 EmitCallArgs(Args, FPT, drop_begin(E->arguments(), 1), E->getConstructor(), 2196 /*ParamsToSkip*/ 1); 2197 2198 EmitCXXConstructorCall(D, Ctor_Complete, false, false, This, Args); 2199 } 2200 2201 void 2202 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 2203 CXXCtorType CtorType, 2204 const FunctionArgList &Args, 2205 SourceLocation Loc) { 2206 CallArgList DelegateArgs; 2207 2208 FunctionArgList::const_iterator I = Args.begin(), E = Args.end(); 2209 assert(I != E && "no parameters to constructor"); 2210 2211 // this 2212 Address This = LoadCXXThisAddress(); 2213 DelegateArgs.add(RValue::get(This.getPointer()), (*I)->getType()); 2214 ++I; 2215 2216 // FIXME: The location of the VTT parameter in the parameter list is 2217 // specific to the Itanium ABI and shouldn't be hardcoded here. 2218 if (CGM.getCXXABI().NeedsVTTParameter(CurGD)) { 2219 assert(I != E && "cannot skip vtt parameter, already done with args"); 2220 assert((*I)->getType()->isPointerType() && 2221 "skipping parameter not of vtt type"); 2222 ++I; 2223 } 2224 2225 // Explicit arguments. 2226 for (; I != E; ++I) { 2227 const VarDecl *param = *I; 2228 // FIXME: per-argument source location 2229 EmitDelegateCallArg(DelegateArgs, param, Loc); 2230 } 2231 2232 EmitCXXConstructorCall(Ctor, CtorType, /*ForVirtualBase=*/false, 2233 /*Delegating=*/true, This, DelegateArgs); 2234 } 2235 2236 namespace { 2237 struct CallDelegatingCtorDtor final : EHScopeStack::Cleanup { 2238 const CXXDestructorDecl *Dtor; 2239 Address Addr; 2240 CXXDtorType Type; 2241 2242 CallDelegatingCtorDtor(const CXXDestructorDecl *D, Address Addr, 2243 CXXDtorType Type) 2244 : Dtor(D), Addr(Addr), Type(Type) {} 2245 2246 void Emit(CodeGenFunction &CGF, Flags flags) override { 2247 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false, 2248 /*Delegating=*/true, Addr); 2249 } 2250 }; 2251 } // end anonymous namespace 2252 2253 void 2254 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 2255 const FunctionArgList &Args) { 2256 assert(Ctor->isDelegatingConstructor()); 2257 2258 Address ThisPtr = LoadCXXThisAddress(); 2259 2260 AggValueSlot AggSlot = 2261 AggValueSlot::forAddr(ThisPtr, Qualifiers(), 2262 AggValueSlot::IsDestructed, 2263 AggValueSlot::DoesNotNeedGCBarriers, 2264 AggValueSlot::IsNotAliased); 2265 2266 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot); 2267 2268 const CXXRecordDecl *ClassDecl = Ctor->getParent(); 2269 if (CGM.getLangOpts().Exceptions && !ClassDecl->hasTrivialDestructor()) { 2270 CXXDtorType Type = 2271 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base; 2272 2273 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup, 2274 ClassDecl->getDestructor(), 2275 ThisPtr, Type); 2276 } 2277 } 2278 2279 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD, 2280 CXXDtorType Type, 2281 bool ForVirtualBase, 2282 bool Delegating, 2283 Address This) { 2284 CGM.getCXXABI().EmitDestructorCall(*this, DD, Type, ForVirtualBase, 2285 Delegating, This); 2286 } 2287 2288 namespace { 2289 struct CallLocalDtor final : EHScopeStack::Cleanup { 2290 const CXXDestructorDecl *Dtor; 2291 Address Addr; 2292 2293 CallLocalDtor(const CXXDestructorDecl *D, Address Addr) 2294 : Dtor(D), Addr(Addr) {} 2295 2296 void Emit(CodeGenFunction &CGF, Flags flags) override { 2297 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 2298 /*ForVirtualBase=*/false, 2299 /*Delegating=*/false, Addr); 2300 } 2301 }; 2302 } // end anonymous namespace 2303 2304 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D, 2305 Address Addr) { 2306 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr); 2307 } 2308 2309 void CodeGenFunction::PushDestructorCleanup(QualType T, Address Addr) { 2310 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl(); 2311 if (!ClassDecl) return; 2312 if (ClassDecl->hasTrivialDestructor()) return; 2313 2314 const CXXDestructorDecl *D = ClassDecl->getDestructor(); 2315 assert(D && D->isUsed() && "destructor not marked as used!"); 2316 PushDestructorCleanup(D, Addr); 2317 } 2318 2319 void CodeGenFunction::InitializeVTablePointer(const VPtr &Vptr) { 2320 // Compute the address point. 2321 llvm::Value *VTableAddressPoint = 2322 CGM.getCXXABI().getVTableAddressPointInStructor( 2323 *this, Vptr.VTableClass, Vptr.Base, Vptr.NearestVBase); 2324 2325 if (!VTableAddressPoint) 2326 return; 2327 2328 // Compute where to store the address point. 2329 llvm::Value *VirtualOffset = nullptr; 2330 CharUnits NonVirtualOffset = CharUnits::Zero(); 2331 2332 if (CGM.getCXXABI().isVirtualOffsetNeededForVTableField(*this, Vptr)) { 2333 // We need to use the virtual base offset offset because the virtual base 2334 // might have a different offset in the most derived class. 2335 2336 VirtualOffset = CGM.getCXXABI().GetVirtualBaseClassOffset( 2337 *this, LoadCXXThisAddress(), Vptr.VTableClass, Vptr.NearestVBase); 2338 NonVirtualOffset = Vptr.OffsetFromNearestVBase; 2339 } else { 2340 // We can just use the base offset in the complete class. 2341 NonVirtualOffset = Vptr.Base.getBaseOffset(); 2342 } 2343 2344 // Apply the offsets. 2345 Address VTableField = LoadCXXThisAddress(); 2346 2347 if (!NonVirtualOffset.isZero() || VirtualOffset) 2348 VTableField = ApplyNonVirtualAndVirtualOffset( 2349 *this, VTableField, NonVirtualOffset, VirtualOffset, Vptr.VTableClass, 2350 Vptr.NearestVBase); 2351 2352 // Finally, store the address point. Use the same LLVM types as the field to 2353 // support optimization. 2354 llvm::Type *VTablePtrTy = 2355 llvm::FunctionType::get(CGM.Int32Ty, /*isVarArg=*/true) 2356 ->getPointerTo() 2357 ->getPointerTo(); 2358 VTableField = Builder.CreateBitCast(VTableField, VTablePtrTy->getPointerTo()); 2359 VTableAddressPoint = Builder.CreateBitCast(VTableAddressPoint, VTablePtrTy); 2360 2361 llvm::StoreInst *Store = Builder.CreateStore(VTableAddressPoint, VTableField); 2362 CGM.DecorateInstructionWithTBAA(Store, CGM.getTBAAInfoForVTablePtr()); 2363 if (CGM.getCodeGenOpts().OptimizationLevel > 0 && 2364 CGM.getCodeGenOpts().StrictVTablePointers) 2365 CGM.DecorateInstructionWithInvariantGroup(Store, Vptr.VTableClass); 2366 } 2367 2368 CodeGenFunction::VPtrsVector 2369 CodeGenFunction::getVTablePointers(const CXXRecordDecl *VTableClass) { 2370 CodeGenFunction::VPtrsVector VPtrsResult; 2371 VisitedVirtualBasesSetTy VBases; 2372 getVTablePointers(BaseSubobject(VTableClass, CharUnits::Zero()), 2373 /*NearestVBase=*/nullptr, 2374 /*OffsetFromNearestVBase=*/CharUnits::Zero(), 2375 /*BaseIsNonVirtualPrimaryBase=*/false, VTableClass, VBases, 2376 VPtrsResult); 2377 return VPtrsResult; 2378 } 2379 2380 void CodeGenFunction::getVTablePointers(BaseSubobject Base, 2381 const CXXRecordDecl *NearestVBase, 2382 CharUnits OffsetFromNearestVBase, 2383 bool BaseIsNonVirtualPrimaryBase, 2384 const CXXRecordDecl *VTableClass, 2385 VisitedVirtualBasesSetTy &VBases, 2386 VPtrsVector &Vptrs) { 2387 // If this base is a non-virtual primary base the address point has already 2388 // been set. 2389 if (!BaseIsNonVirtualPrimaryBase) { 2390 // Initialize the vtable pointer for this base. 2391 VPtr Vptr = {Base, NearestVBase, OffsetFromNearestVBase, VTableClass}; 2392 Vptrs.push_back(Vptr); 2393 } 2394 2395 const CXXRecordDecl *RD = Base.getBase(); 2396 2397 // Traverse bases. 2398 for (const auto &I : RD->bases()) { 2399 CXXRecordDecl *BaseDecl 2400 = cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 2401 2402 // Ignore classes without a vtable. 2403 if (!BaseDecl->isDynamicClass()) 2404 continue; 2405 2406 CharUnits BaseOffset; 2407 CharUnits BaseOffsetFromNearestVBase; 2408 bool BaseDeclIsNonVirtualPrimaryBase; 2409 2410 if (I.isVirtual()) { 2411 // Check if we've visited this virtual base before. 2412 if (!VBases.insert(BaseDecl).second) 2413 continue; 2414 2415 const ASTRecordLayout &Layout = 2416 getContext().getASTRecordLayout(VTableClass); 2417 2418 BaseOffset = Layout.getVBaseClassOffset(BaseDecl); 2419 BaseOffsetFromNearestVBase = CharUnits::Zero(); 2420 BaseDeclIsNonVirtualPrimaryBase = false; 2421 } else { 2422 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 2423 2424 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl); 2425 BaseOffsetFromNearestVBase = 2426 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl); 2427 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl; 2428 } 2429 2430 getVTablePointers( 2431 BaseSubobject(BaseDecl, BaseOffset), 2432 I.isVirtual() ? BaseDecl : NearestVBase, BaseOffsetFromNearestVBase, 2433 BaseDeclIsNonVirtualPrimaryBase, VTableClass, VBases, Vptrs); 2434 } 2435 } 2436 2437 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) { 2438 // Ignore classes without a vtable. 2439 if (!RD->isDynamicClass()) 2440 return; 2441 2442 // Initialize the vtable pointers for this class and all of its bases. 2443 if (CGM.getCXXABI().doStructorsInitializeVPtrs(RD)) 2444 for (const VPtr &Vptr : getVTablePointers(RD)) 2445 InitializeVTablePointer(Vptr); 2446 2447 if (RD->getNumVBases()) 2448 CGM.getCXXABI().initializeHiddenVirtualInheritanceMembers(*this, RD); 2449 } 2450 2451 llvm::Value *CodeGenFunction::GetVTablePtr(Address This, 2452 llvm::Type *VTableTy, 2453 const CXXRecordDecl *RD) { 2454 Address VTablePtrSrc = Builder.CreateElementBitCast(This, VTableTy); 2455 llvm::Instruction *VTable = Builder.CreateLoad(VTablePtrSrc, "vtable"); 2456 CGM.DecorateInstructionWithTBAA(VTable, CGM.getTBAAInfoForVTablePtr()); 2457 2458 if (CGM.getCodeGenOpts().OptimizationLevel > 0 && 2459 CGM.getCodeGenOpts().StrictVTablePointers) 2460 CGM.DecorateInstructionWithInvariantGroup(VTable, RD); 2461 2462 return VTable; 2463 } 2464 2465 // If a class has a single non-virtual base and does not introduce or override 2466 // virtual member functions or fields, it will have the same layout as its base. 2467 // This function returns the least derived such class. 2468 // 2469 // Casting an instance of a base class to such a derived class is technically 2470 // undefined behavior, but it is a relatively common hack for introducing member 2471 // functions on class instances with specific properties (e.g. llvm::Operator) 2472 // that works under most compilers and should not have security implications, so 2473 // we allow it by default. It can be disabled with -fsanitize=cfi-cast-strict. 2474 static const CXXRecordDecl * 2475 LeastDerivedClassWithSameLayout(const CXXRecordDecl *RD) { 2476 if (!RD->field_empty()) 2477 return RD; 2478 2479 if (RD->getNumVBases() != 0) 2480 return RD; 2481 2482 if (RD->getNumBases() != 1) 2483 return RD; 2484 2485 for (const CXXMethodDecl *MD : RD->methods()) { 2486 if (MD->isVirtual()) { 2487 // Virtual member functions are only ok if they are implicit destructors 2488 // because the implicit destructor will have the same semantics as the 2489 // base class's destructor if no fields are added. 2490 if (isa<CXXDestructorDecl>(MD) && MD->isImplicit()) 2491 continue; 2492 return RD; 2493 } 2494 } 2495 2496 return LeastDerivedClassWithSameLayout( 2497 RD->bases_begin()->getType()->getAsCXXRecordDecl()); 2498 } 2499 2500 void CodeGenFunction::EmitTypeMetadataCodeForVCall(const CXXRecordDecl *RD, 2501 llvm::Value *VTable, 2502 SourceLocation Loc) { 2503 if (CGM.getCodeGenOpts().WholeProgramVTables && 2504 CGM.HasHiddenLTOVisibility(RD)) { 2505 llvm::Metadata *MD = 2506 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 2507 llvm::Value *TypeId = 2508 llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD); 2509 2510 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy); 2511 llvm::Value *TypeTest = 2512 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::type_test), 2513 {CastedVTable, TypeId}); 2514 Builder.CreateCall(CGM.getIntrinsic(llvm::Intrinsic::assume), TypeTest); 2515 } 2516 2517 if (SanOpts.has(SanitizerKind::CFIVCall)) 2518 EmitVTablePtrCheckForCall(RD, VTable, CodeGenFunction::CFITCK_VCall, Loc); 2519 } 2520 2521 void CodeGenFunction::EmitVTablePtrCheckForCall(const CXXRecordDecl *RD, 2522 llvm::Value *VTable, 2523 CFITypeCheckKind TCK, 2524 SourceLocation Loc) { 2525 if (!SanOpts.has(SanitizerKind::CFICastStrict)) 2526 RD = LeastDerivedClassWithSameLayout(RD); 2527 2528 EmitVTablePtrCheck(RD, VTable, TCK, Loc); 2529 } 2530 2531 void CodeGenFunction::EmitVTablePtrCheckForCast(QualType T, 2532 llvm::Value *Derived, 2533 bool MayBeNull, 2534 CFITypeCheckKind TCK, 2535 SourceLocation Loc) { 2536 if (!getLangOpts().CPlusPlus) 2537 return; 2538 2539 auto *ClassTy = T->getAs<RecordType>(); 2540 if (!ClassTy) 2541 return; 2542 2543 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(ClassTy->getDecl()); 2544 2545 if (!ClassDecl->isCompleteDefinition() || !ClassDecl->isDynamicClass()) 2546 return; 2547 2548 if (!SanOpts.has(SanitizerKind::CFICastStrict)) 2549 ClassDecl = LeastDerivedClassWithSameLayout(ClassDecl); 2550 2551 llvm::BasicBlock *ContBlock = nullptr; 2552 2553 if (MayBeNull) { 2554 llvm::Value *DerivedNotNull = 2555 Builder.CreateIsNotNull(Derived, "cast.nonnull"); 2556 2557 llvm::BasicBlock *CheckBlock = createBasicBlock("cast.check"); 2558 ContBlock = createBasicBlock("cast.cont"); 2559 2560 Builder.CreateCondBr(DerivedNotNull, CheckBlock, ContBlock); 2561 2562 EmitBlock(CheckBlock); 2563 } 2564 2565 llvm::Value *VTable = 2566 GetVTablePtr(Address(Derived, getPointerAlign()), Int8PtrTy, ClassDecl); 2567 2568 EmitVTablePtrCheck(ClassDecl, VTable, TCK, Loc); 2569 2570 if (MayBeNull) { 2571 Builder.CreateBr(ContBlock); 2572 EmitBlock(ContBlock); 2573 } 2574 } 2575 2576 void CodeGenFunction::EmitVTablePtrCheck(const CXXRecordDecl *RD, 2577 llvm::Value *VTable, 2578 CFITypeCheckKind TCK, 2579 SourceLocation Loc) { 2580 if (!CGM.getCodeGenOpts().SanitizeCfiCrossDso && 2581 !CGM.HasHiddenLTOVisibility(RD)) 2582 return; 2583 2584 std::string TypeName = RD->getQualifiedNameAsString(); 2585 if (getContext().getSanitizerBlacklist().isBlacklistedType(TypeName)) 2586 return; 2587 2588 SanitizerScope SanScope(this); 2589 llvm::SanitizerStatKind SSK; 2590 switch (TCK) { 2591 case CFITCK_VCall: 2592 SSK = llvm::SanStat_CFI_VCall; 2593 break; 2594 case CFITCK_NVCall: 2595 SSK = llvm::SanStat_CFI_NVCall; 2596 break; 2597 case CFITCK_DerivedCast: 2598 SSK = llvm::SanStat_CFI_DerivedCast; 2599 break; 2600 case CFITCK_UnrelatedCast: 2601 SSK = llvm::SanStat_CFI_UnrelatedCast; 2602 break; 2603 case CFITCK_ICall: 2604 llvm_unreachable("not expecting CFITCK_ICall"); 2605 } 2606 EmitSanitizerStatReport(SSK); 2607 2608 llvm::Metadata *MD = 2609 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 2610 llvm::Value *TypeId = llvm::MetadataAsValue::get(getLLVMContext(), MD); 2611 2612 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy); 2613 llvm::Value *TypeTest = Builder.CreateCall( 2614 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, TypeId}); 2615 2616 SanitizerMask M; 2617 switch (TCK) { 2618 case CFITCK_VCall: 2619 M = SanitizerKind::CFIVCall; 2620 break; 2621 case CFITCK_NVCall: 2622 M = SanitizerKind::CFINVCall; 2623 break; 2624 case CFITCK_DerivedCast: 2625 M = SanitizerKind::CFIDerivedCast; 2626 break; 2627 case CFITCK_UnrelatedCast: 2628 M = SanitizerKind::CFIUnrelatedCast; 2629 break; 2630 case CFITCK_ICall: 2631 llvm_unreachable("not expecting CFITCK_ICall"); 2632 } 2633 2634 llvm::Constant *StaticData[] = { 2635 llvm::ConstantInt::get(Int8Ty, TCK), 2636 EmitCheckSourceLocation(Loc), 2637 EmitCheckTypeDescriptor(QualType(RD->getTypeForDecl(), 0)), 2638 }; 2639 2640 auto CrossDsoTypeId = CGM.CreateCrossDsoCfiTypeId(MD); 2641 if (CGM.getCodeGenOpts().SanitizeCfiCrossDso && CrossDsoTypeId) { 2642 EmitCfiSlowPathCheck(M, TypeTest, CrossDsoTypeId, CastedVTable, StaticData); 2643 return; 2644 } 2645 2646 if (CGM.getCodeGenOpts().SanitizeTrap.has(M)) { 2647 EmitTrapCheck(TypeTest); 2648 return; 2649 } 2650 2651 llvm::Value *AllVtables = llvm::MetadataAsValue::get( 2652 CGM.getLLVMContext(), 2653 llvm::MDString::get(CGM.getLLVMContext(), "all-vtables")); 2654 llvm::Value *ValidVtable = Builder.CreateCall( 2655 CGM.getIntrinsic(llvm::Intrinsic::type_test), {CastedVTable, AllVtables}); 2656 EmitCheck(std::make_pair(TypeTest, M), SanitizerHandler::CFICheckFail, 2657 StaticData, {CastedVTable, ValidVtable}); 2658 } 2659 2660 bool CodeGenFunction::ShouldEmitVTableTypeCheckedLoad(const CXXRecordDecl *RD) { 2661 if (!CGM.getCodeGenOpts().WholeProgramVTables || 2662 !SanOpts.has(SanitizerKind::CFIVCall) || 2663 !CGM.getCodeGenOpts().SanitizeTrap.has(SanitizerKind::CFIVCall) || 2664 !CGM.HasHiddenLTOVisibility(RD)) 2665 return false; 2666 2667 std::string TypeName = RD->getQualifiedNameAsString(); 2668 return !getContext().getSanitizerBlacklist().isBlacklistedType(TypeName); 2669 } 2670 2671 llvm::Value *CodeGenFunction::EmitVTableTypeCheckedLoad( 2672 const CXXRecordDecl *RD, llvm::Value *VTable, uint64_t VTableByteOffset) { 2673 SanitizerScope SanScope(this); 2674 2675 EmitSanitizerStatReport(llvm::SanStat_CFI_VCall); 2676 2677 llvm::Metadata *MD = 2678 CGM.CreateMetadataIdentifierForType(QualType(RD->getTypeForDecl(), 0)); 2679 llvm::Value *TypeId = llvm::MetadataAsValue::get(CGM.getLLVMContext(), MD); 2680 2681 llvm::Value *CastedVTable = Builder.CreateBitCast(VTable, Int8PtrTy); 2682 llvm::Value *CheckedLoad = Builder.CreateCall( 2683 CGM.getIntrinsic(llvm::Intrinsic::type_checked_load), 2684 {CastedVTable, llvm::ConstantInt::get(Int32Ty, VTableByteOffset), 2685 TypeId}); 2686 llvm::Value *CheckResult = Builder.CreateExtractValue(CheckedLoad, 1); 2687 2688 EmitCheck(std::make_pair(CheckResult, SanitizerKind::CFIVCall), 2689 SanitizerHandler::CFICheckFail, nullptr, nullptr); 2690 2691 return Builder.CreateBitCast( 2692 Builder.CreateExtractValue(CheckedLoad, 0), 2693 cast<llvm::PointerType>(VTable->getType())->getElementType()); 2694 } 2695 2696 bool 2697 CodeGenFunction::CanDevirtualizeMemberFunctionCall(const Expr *Base, 2698 const CXXMethodDecl *MD) { 2699 // When building with -fapple-kext, all calls must go through the vtable since 2700 // the kernel linker can do runtime patching of vtables. 2701 if (getLangOpts().AppleKext) 2702 return false; 2703 2704 // If the member function is marked 'final', we know that it can't be 2705 // overridden and can therefore devirtualize it unless it's pure virtual. 2706 if (MD->hasAttr<FinalAttr>()) 2707 return !MD->isPure(); 2708 2709 // If the base expression (after skipping derived-to-base conversions) is a 2710 // class prvalue, then we can devirtualize. 2711 Base = Base->getBestDynamicClassTypeExpr(); 2712 if (Base->isRValue() && Base->getType()->isRecordType()) 2713 return true; 2714 2715 // If we don't even know what we would call, we can't devirtualize. 2716 const CXXRecordDecl *BestDynamicDecl = Base->getBestDynamicClassType(); 2717 if (!BestDynamicDecl) 2718 return false; 2719 2720 // There may be a method corresponding to MD in a derived class. 2721 const CXXMethodDecl *DevirtualizedMethod = 2722 MD->getCorrespondingMethodInClass(BestDynamicDecl); 2723 2724 // If that method is pure virtual, we can't devirtualize. If this code is 2725 // reached, the result would be UB, not a direct call to the derived class 2726 // function, and we can't assume the derived class function is defined. 2727 if (DevirtualizedMethod->isPure()) 2728 return false; 2729 2730 // If that method is marked final, we can devirtualize it. 2731 if (DevirtualizedMethod->hasAttr<FinalAttr>()) 2732 return true; 2733 2734 // Similarly, if the class itself is marked 'final' it can't be overridden 2735 // and we can therefore devirtualize the member function call. 2736 if (BestDynamicDecl->hasAttr<FinalAttr>()) 2737 return true; 2738 2739 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 2740 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 2741 // This is a record decl. We know the type and can devirtualize it. 2742 return VD->getType()->isRecordType(); 2743 } 2744 2745 return false; 2746 } 2747 2748 // We can devirtualize calls on an object accessed by a class member access 2749 // expression, since by C++11 [basic.life]p6 we know that it can't refer to 2750 // a derived class object constructed in the same location. 2751 if (const MemberExpr *ME = dyn_cast<MemberExpr>(Base)) 2752 if (const ValueDecl *VD = dyn_cast<ValueDecl>(ME->getMemberDecl())) 2753 return VD->getType()->isRecordType(); 2754 2755 // Likewise for calls on an object accessed by a (non-reference) pointer to 2756 // member access. 2757 if (auto *BO = dyn_cast<BinaryOperator>(Base)) { 2758 if (BO->isPtrMemOp()) { 2759 auto *MPT = BO->getRHS()->getType()->castAs<MemberPointerType>(); 2760 if (MPT->getPointeeType()->isRecordType()) 2761 return true; 2762 } 2763 } 2764 2765 // We can't devirtualize the call. 2766 return false; 2767 } 2768 2769 void CodeGenFunction::EmitForwardingCallToLambda( 2770 const CXXMethodDecl *callOperator, 2771 CallArgList &callArgs) { 2772 // Get the address of the call operator. 2773 const CGFunctionInfo &calleeFnInfo = 2774 CGM.getTypes().arrangeCXXMethodDeclaration(callOperator); 2775 llvm::Constant *calleePtr = 2776 CGM.GetAddrOfFunction(GlobalDecl(callOperator), 2777 CGM.getTypes().GetFunctionType(calleeFnInfo)); 2778 2779 // Prepare the return slot. 2780 const FunctionProtoType *FPT = 2781 callOperator->getType()->castAs<FunctionProtoType>(); 2782 QualType resultType = FPT->getReturnType(); 2783 ReturnValueSlot returnSlot; 2784 if (!resultType->isVoidType() && 2785 calleeFnInfo.getReturnInfo().getKind() == ABIArgInfo::Indirect && 2786 !hasScalarEvaluationKind(calleeFnInfo.getReturnType())) 2787 returnSlot = ReturnValueSlot(ReturnValue, resultType.isVolatileQualified()); 2788 2789 // We don't need to separately arrange the call arguments because 2790 // the call can't be variadic anyway --- it's impossible to forward 2791 // variadic arguments. 2792 2793 // Now emit our call. 2794 auto callee = CGCallee::forDirect(calleePtr, callOperator); 2795 RValue RV = EmitCall(calleeFnInfo, callee, returnSlot, callArgs); 2796 2797 // If necessary, copy the returned value into the slot. 2798 if (!resultType->isVoidType() && returnSlot.isNull()) 2799 EmitReturnOfRValue(RV, resultType); 2800 else 2801 EmitBranchThroughCleanup(ReturnBlock); 2802 } 2803 2804 void CodeGenFunction::EmitLambdaBlockInvokeBody() { 2805 const BlockDecl *BD = BlockInfo->getBlockDecl(); 2806 const VarDecl *variable = BD->capture_begin()->getVariable(); 2807 const CXXRecordDecl *Lambda = variable->getType()->getAsCXXRecordDecl(); 2808 2809 // Start building arguments for forwarding call 2810 CallArgList CallArgs; 2811 2812 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda)); 2813 Address ThisPtr = GetAddrOfBlockDecl(variable, false); 2814 CallArgs.add(RValue::get(ThisPtr.getPointer()), ThisType); 2815 2816 // Add the rest of the parameters. 2817 for (auto param : BD->parameters()) 2818 EmitDelegateCallArg(CallArgs, param, param->getLocStart()); 2819 2820 assert(!Lambda->isGenericLambda() && 2821 "generic lambda interconversion to block not implemented"); 2822 EmitForwardingCallToLambda(Lambda->getLambdaCallOperator(), CallArgs); 2823 } 2824 2825 void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) { 2826 if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) { 2827 // FIXME: Making this work correctly is nasty because it requires either 2828 // cloning the body of the call operator or making the call operator forward. 2829 CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function"); 2830 return; 2831 } 2832 2833 EmitFunctionBody(Args, cast<FunctionDecl>(CurGD.getDecl())->getBody()); 2834 } 2835 2836 void CodeGenFunction::EmitLambdaDelegatingInvokeBody(const CXXMethodDecl *MD) { 2837 const CXXRecordDecl *Lambda = MD->getParent(); 2838 2839 // Start building arguments for forwarding call 2840 CallArgList CallArgs; 2841 2842 QualType ThisType = getContext().getPointerType(getContext().getRecordType(Lambda)); 2843 llvm::Value *ThisPtr = llvm::UndefValue::get(getTypes().ConvertType(ThisType)); 2844 CallArgs.add(RValue::get(ThisPtr), ThisType); 2845 2846 // Add the rest of the parameters. 2847 for (auto Param : MD->parameters()) 2848 EmitDelegateCallArg(CallArgs, Param, Param->getLocStart()); 2849 2850 const CXXMethodDecl *CallOp = Lambda->getLambdaCallOperator(); 2851 // For a generic lambda, find the corresponding call operator specialization 2852 // to which the call to the static-invoker shall be forwarded. 2853 if (Lambda->isGenericLambda()) { 2854 assert(MD->isFunctionTemplateSpecialization()); 2855 const TemplateArgumentList *TAL = MD->getTemplateSpecializationArgs(); 2856 FunctionTemplateDecl *CallOpTemplate = CallOp->getDescribedFunctionTemplate(); 2857 void *InsertPos = nullptr; 2858 FunctionDecl *CorrespondingCallOpSpecialization = 2859 CallOpTemplate->findSpecialization(TAL->asArray(), InsertPos); 2860 assert(CorrespondingCallOpSpecialization); 2861 CallOp = cast<CXXMethodDecl>(CorrespondingCallOpSpecialization); 2862 } 2863 EmitForwardingCallToLambda(CallOp, CallArgs); 2864 } 2865 2866 void CodeGenFunction::EmitLambdaStaticInvokeFunction(const CXXMethodDecl *MD) { 2867 if (MD->isVariadic()) { 2868 // FIXME: Making this work correctly is nasty because it requires either 2869 // cloning the body of the call operator or making the call operator forward. 2870 CGM.ErrorUnsupported(MD, "lambda conversion to variadic function"); 2871 return; 2872 } 2873 2874 EmitLambdaDelegatingInvokeBody(MD); 2875 } 2876