1 //===--- CGClass.cpp - Emit LLVM Code for C++ classes ---------------------===// 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 "CGDebugInfo.h" 15 #include "CodeGenFunction.h" 16 #include "clang/AST/CXXInheritance.h" 17 #include "clang/AST/EvaluatedExprVisitor.h" 18 #include "clang/AST/RecordLayout.h" 19 #include "clang/AST/StmtCXX.h" 20 #include "clang/Frontend/CodeGenOptions.h" 21 22 using namespace clang; 23 using namespace CodeGen; 24 25 static CharUnits 26 ComputeNonVirtualBaseClassOffset(ASTContext &Context, 27 const CXXRecordDecl *DerivedClass, 28 CastExpr::path_const_iterator Start, 29 CastExpr::path_const_iterator End) { 30 CharUnits Offset = CharUnits::Zero(); 31 32 const CXXRecordDecl *RD = DerivedClass; 33 34 for (CastExpr::path_const_iterator I = Start; I != End; ++I) { 35 const CXXBaseSpecifier *Base = *I; 36 assert(!Base->isVirtual() && "Should not see virtual bases here!"); 37 38 // Get the layout. 39 const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD); 40 41 const CXXRecordDecl *BaseDecl = 42 cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 43 44 // Add the offset. 45 Offset += Layout.getBaseClassOffset(BaseDecl); 46 47 RD = BaseDecl; 48 } 49 50 return Offset; 51 } 52 53 llvm::Constant * 54 CodeGenModule::GetNonVirtualBaseClassOffset(const CXXRecordDecl *ClassDecl, 55 CastExpr::path_const_iterator PathBegin, 56 CastExpr::path_const_iterator PathEnd) { 57 assert(PathBegin != PathEnd && "Base path should not be empty!"); 58 59 CharUnits Offset = 60 ComputeNonVirtualBaseClassOffset(getContext(), ClassDecl, 61 PathBegin, PathEnd); 62 if (Offset.isZero()) 63 return 0; 64 65 const llvm::Type *PtrDiffTy = 66 Types.ConvertType(getContext().getPointerDiffType()); 67 68 return llvm::ConstantInt::get(PtrDiffTy, Offset.getQuantity()); 69 } 70 71 /// Gets the address of a direct base class within a complete object. 72 /// This should only be used for (1) non-virtual bases or (2) virtual bases 73 /// when the type is known to be complete (e.g. in complete destructors). 74 /// 75 /// The object pointed to by 'This' is assumed to be non-null. 76 llvm::Value * 77 CodeGenFunction::GetAddressOfDirectBaseInCompleteClass(llvm::Value *This, 78 const CXXRecordDecl *Derived, 79 const CXXRecordDecl *Base, 80 bool BaseIsVirtual) { 81 // 'this' must be a pointer (in some address space) to Derived. 82 assert(This->getType()->isPointerTy() && 83 cast<llvm::PointerType>(This->getType())->getElementType() 84 == ConvertType(Derived)); 85 86 // Compute the offset of the virtual base. 87 CharUnits Offset; 88 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived); 89 if (BaseIsVirtual) 90 Offset = Layout.getVBaseClassOffset(Base); 91 else 92 Offset = Layout.getBaseClassOffset(Base); 93 94 // Shift and cast down to the base type. 95 // TODO: for complete types, this should be possible with a GEP. 96 llvm::Value *V = This; 97 if (Offset.isPositive()) { 98 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(getLLVMContext()); 99 V = Builder.CreateBitCast(V, Int8PtrTy); 100 V = Builder.CreateConstInBoundsGEP1_64(V, Offset.getQuantity()); 101 } 102 V = Builder.CreateBitCast(V, ConvertType(Base)->getPointerTo()); 103 104 return V; 105 } 106 107 static llvm::Value * 108 ApplyNonVirtualAndVirtualOffset(CodeGenFunction &CGF, llvm::Value *ThisPtr, 109 CharUnits NonVirtual, llvm::Value *Virtual) { 110 const llvm::Type *PtrDiffTy = 111 CGF.ConvertType(CGF.getContext().getPointerDiffType()); 112 113 llvm::Value *NonVirtualOffset = 0; 114 if (!NonVirtual.isZero()) 115 NonVirtualOffset = llvm::ConstantInt::get(PtrDiffTy, 116 NonVirtual.getQuantity()); 117 118 llvm::Value *BaseOffset; 119 if (Virtual) { 120 if (NonVirtualOffset) 121 BaseOffset = CGF.Builder.CreateAdd(Virtual, NonVirtualOffset); 122 else 123 BaseOffset = Virtual; 124 } else 125 BaseOffset = NonVirtualOffset; 126 127 // Apply the base offset. 128 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(CGF.getLLVMContext()); 129 ThisPtr = CGF.Builder.CreateBitCast(ThisPtr, Int8PtrTy); 130 ThisPtr = CGF.Builder.CreateGEP(ThisPtr, BaseOffset, "add.ptr"); 131 132 return ThisPtr; 133 } 134 135 llvm::Value * 136 CodeGenFunction::GetAddressOfBaseClass(llvm::Value *Value, 137 const CXXRecordDecl *Derived, 138 CastExpr::path_const_iterator PathBegin, 139 CastExpr::path_const_iterator PathEnd, 140 bool NullCheckValue) { 141 assert(PathBegin != PathEnd && "Base path should not be empty!"); 142 143 CastExpr::path_const_iterator Start = PathBegin; 144 const CXXRecordDecl *VBase = 0; 145 146 // Get the virtual base. 147 if ((*Start)->isVirtual()) { 148 VBase = 149 cast<CXXRecordDecl>((*Start)->getType()->getAs<RecordType>()->getDecl()); 150 ++Start; 151 } 152 153 CharUnits NonVirtualOffset = 154 ComputeNonVirtualBaseClassOffset(getContext(), VBase ? VBase : Derived, 155 Start, PathEnd); 156 157 // Get the base pointer type. 158 const llvm::Type *BasePtrTy = 159 ConvertType((PathEnd[-1])->getType())->getPointerTo(); 160 161 if (NonVirtualOffset.isZero() && !VBase) { 162 // Just cast back. 163 return Builder.CreateBitCast(Value, BasePtrTy); 164 } 165 166 llvm::BasicBlock *CastNull = 0; 167 llvm::BasicBlock *CastNotNull = 0; 168 llvm::BasicBlock *CastEnd = 0; 169 170 if (NullCheckValue) { 171 CastNull = createBasicBlock("cast.null"); 172 CastNotNull = createBasicBlock("cast.notnull"); 173 CastEnd = createBasicBlock("cast.end"); 174 175 llvm::Value *IsNull = Builder.CreateIsNull(Value); 176 Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 177 EmitBlock(CastNotNull); 178 } 179 180 llvm::Value *VirtualOffset = 0; 181 182 if (VBase) { 183 if (Derived->hasAttr<FinalAttr>()) { 184 VirtualOffset = 0; 185 186 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(Derived); 187 188 CharUnits VBaseOffset = Layout.getVBaseClassOffset(VBase); 189 NonVirtualOffset += VBaseOffset; 190 } else 191 VirtualOffset = GetVirtualBaseClassOffset(Value, Derived, VBase); 192 } 193 194 // Apply the offsets. 195 Value = ApplyNonVirtualAndVirtualOffset(*this, Value, 196 NonVirtualOffset, 197 VirtualOffset); 198 199 // Cast back. 200 Value = Builder.CreateBitCast(Value, BasePtrTy); 201 202 if (NullCheckValue) { 203 Builder.CreateBr(CastEnd); 204 EmitBlock(CastNull); 205 Builder.CreateBr(CastEnd); 206 EmitBlock(CastEnd); 207 208 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 209 PHI->addIncoming(Value, CastNotNull); 210 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), 211 CastNull); 212 Value = PHI; 213 } 214 215 return Value; 216 } 217 218 llvm::Value * 219 CodeGenFunction::GetAddressOfDerivedClass(llvm::Value *Value, 220 const CXXRecordDecl *Derived, 221 CastExpr::path_const_iterator PathBegin, 222 CastExpr::path_const_iterator PathEnd, 223 bool NullCheckValue) { 224 assert(PathBegin != PathEnd && "Base path should not be empty!"); 225 226 QualType DerivedTy = 227 getContext().getCanonicalType(getContext().getTagDeclType(Derived)); 228 const llvm::Type *DerivedPtrTy = ConvertType(DerivedTy)->getPointerTo(); 229 230 llvm::Value *NonVirtualOffset = 231 CGM.GetNonVirtualBaseClassOffset(Derived, PathBegin, PathEnd); 232 233 if (!NonVirtualOffset) { 234 // No offset, we can just cast back. 235 return Builder.CreateBitCast(Value, DerivedPtrTy); 236 } 237 238 llvm::BasicBlock *CastNull = 0; 239 llvm::BasicBlock *CastNotNull = 0; 240 llvm::BasicBlock *CastEnd = 0; 241 242 if (NullCheckValue) { 243 CastNull = createBasicBlock("cast.null"); 244 CastNotNull = createBasicBlock("cast.notnull"); 245 CastEnd = createBasicBlock("cast.end"); 246 247 llvm::Value *IsNull = Builder.CreateIsNull(Value); 248 Builder.CreateCondBr(IsNull, CastNull, CastNotNull); 249 EmitBlock(CastNotNull); 250 } 251 252 // Apply the offset. 253 Value = Builder.CreatePtrToInt(Value, NonVirtualOffset->getType()); 254 Value = Builder.CreateSub(Value, NonVirtualOffset); 255 Value = Builder.CreateIntToPtr(Value, DerivedPtrTy); 256 257 // Just cast. 258 Value = Builder.CreateBitCast(Value, DerivedPtrTy); 259 260 if (NullCheckValue) { 261 Builder.CreateBr(CastEnd); 262 EmitBlock(CastNull); 263 Builder.CreateBr(CastEnd); 264 EmitBlock(CastEnd); 265 266 llvm::PHINode *PHI = Builder.CreatePHI(Value->getType(), 2); 267 PHI->addIncoming(Value, CastNotNull); 268 PHI->addIncoming(llvm::Constant::getNullValue(Value->getType()), 269 CastNull); 270 Value = PHI; 271 } 272 273 return Value; 274 } 275 276 /// GetVTTParameter - Return the VTT parameter that should be passed to a 277 /// base constructor/destructor with virtual bases. 278 static llvm::Value *GetVTTParameter(CodeGenFunction &CGF, GlobalDecl GD, 279 bool ForVirtualBase) { 280 if (!CodeGenVTables::needsVTTParameter(GD)) { 281 // This constructor/destructor does not need a VTT parameter. 282 return 0; 283 } 284 285 const CXXRecordDecl *RD = cast<CXXMethodDecl>(CGF.CurFuncDecl)->getParent(); 286 const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent(); 287 288 llvm::Value *VTT; 289 290 uint64_t SubVTTIndex; 291 292 // If the record matches the base, this is the complete ctor/dtor 293 // variant calling the base variant in a class with virtual bases. 294 if (RD == Base) { 295 assert(!CodeGenVTables::needsVTTParameter(CGF.CurGD) && 296 "doing no-op VTT offset in base dtor/ctor?"); 297 assert(!ForVirtualBase && "Can't have same class as virtual base!"); 298 SubVTTIndex = 0; 299 } else { 300 const ASTRecordLayout &Layout = 301 CGF.getContext().getASTRecordLayout(RD); 302 CharUnits BaseOffset = ForVirtualBase ? 303 Layout.getVBaseClassOffset(Base) : 304 Layout.getBaseClassOffset(Base); 305 306 SubVTTIndex = 307 CGF.CGM.getVTables().getSubVTTIndex(RD, BaseSubobject(Base, BaseOffset)); 308 assert(SubVTTIndex != 0 && "Sub-VTT index must be greater than zero!"); 309 } 310 311 if (CodeGenVTables::needsVTTParameter(CGF.CurGD)) { 312 // A VTT parameter was passed to the constructor, use it. 313 VTT = CGF.LoadCXXVTT(); 314 VTT = CGF.Builder.CreateConstInBoundsGEP1_64(VTT, SubVTTIndex); 315 } else { 316 // We're the complete constructor, so get the VTT by name. 317 VTT = CGF.CGM.getVTables().GetAddrOfVTT(RD); 318 VTT = CGF.Builder.CreateConstInBoundsGEP2_64(VTT, 0, SubVTTIndex); 319 } 320 321 return VTT; 322 } 323 324 namespace { 325 /// Call the destructor for a direct base class. 326 struct CallBaseDtor : EHScopeStack::Cleanup { 327 const CXXRecordDecl *BaseClass; 328 bool BaseIsVirtual; 329 CallBaseDtor(const CXXRecordDecl *Base, bool BaseIsVirtual) 330 : BaseClass(Base), BaseIsVirtual(BaseIsVirtual) {} 331 332 void Emit(CodeGenFunction &CGF, bool IsForEH) { 333 const CXXRecordDecl *DerivedClass = 334 cast<CXXMethodDecl>(CGF.CurCodeDecl)->getParent(); 335 336 const CXXDestructorDecl *D = BaseClass->getDestructor(); 337 llvm::Value *Addr = 338 CGF.GetAddressOfDirectBaseInCompleteClass(CGF.LoadCXXThis(), 339 DerivedClass, BaseClass, 340 BaseIsVirtual); 341 CGF.EmitCXXDestructorCall(D, Dtor_Base, BaseIsVirtual, Addr); 342 } 343 }; 344 345 /// A visitor which checks whether an initializer uses 'this' in a 346 /// way which requires the vtable to be properly set. 347 struct DynamicThisUseChecker : EvaluatedExprVisitor<DynamicThisUseChecker> { 348 typedef EvaluatedExprVisitor<DynamicThisUseChecker> super; 349 350 bool UsesThis; 351 352 DynamicThisUseChecker(ASTContext &C) : super(C), UsesThis(false) {} 353 354 // Black-list all explicit and implicit references to 'this'. 355 // 356 // Do we need to worry about external references to 'this' derived 357 // from arbitrary code? If so, then anything which runs arbitrary 358 // external code might potentially access the vtable. 359 void VisitCXXThisExpr(CXXThisExpr *E) { UsesThis = true; } 360 }; 361 } 362 363 static bool BaseInitializerUsesThis(ASTContext &C, const Expr *Init) { 364 DynamicThisUseChecker Checker(C); 365 Checker.Visit(const_cast<Expr*>(Init)); 366 return Checker.UsesThis; 367 } 368 369 static void EmitBaseInitializer(CodeGenFunction &CGF, 370 const CXXRecordDecl *ClassDecl, 371 CXXCtorInitializer *BaseInit, 372 CXXCtorType CtorType) { 373 assert(BaseInit->isBaseInitializer() && 374 "Must have base initializer!"); 375 376 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 377 378 const Type *BaseType = BaseInit->getBaseClass(); 379 CXXRecordDecl *BaseClassDecl = 380 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()); 381 382 bool isBaseVirtual = BaseInit->isBaseVirtual(); 383 384 // The base constructor doesn't construct virtual bases. 385 if (CtorType == Ctor_Base && isBaseVirtual) 386 return; 387 388 // If the initializer for the base (other than the constructor 389 // itself) accesses 'this' in any way, we need to initialize the 390 // vtables. 391 if (BaseInitializerUsesThis(CGF.getContext(), BaseInit->getInit())) 392 CGF.InitializeVTablePointers(ClassDecl); 393 394 // We can pretend to be a complete class because it only matters for 395 // virtual bases, and we only do virtual bases for complete ctors. 396 llvm::Value *V = 397 CGF.GetAddressOfDirectBaseInCompleteClass(ThisPtr, ClassDecl, 398 BaseClassDecl, 399 isBaseVirtual); 400 401 AggValueSlot AggSlot = AggValueSlot::forAddr(V, Qualifiers(), 402 /*Lifetime*/ true); 403 404 CGF.EmitAggExpr(BaseInit->getInit(), AggSlot); 405 406 if (CGF.CGM.getLangOptions().Exceptions && 407 !BaseClassDecl->hasTrivialDestructor()) 408 CGF.EHStack.pushCleanup<CallBaseDtor>(EHCleanup, BaseClassDecl, 409 isBaseVirtual); 410 } 411 412 static void EmitAggMemberInitializer(CodeGenFunction &CGF, 413 LValue LHS, 414 llvm::Value *ArrayIndexVar, 415 CXXCtorInitializer *MemberInit, 416 QualType T, 417 unsigned Index) { 418 if (Index == MemberInit->getNumArrayIndices()) { 419 CodeGenFunction::RunCleanupsScope Cleanups(CGF); 420 421 llvm::Value *Dest = LHS.getAddress(); 422 if (ArrayIndexVar) { 423 // If we have an array index variable, load it and use it as an offset. 424 // Then, increment the value. 425 llvm::Value *ArrayIndex = CGF.Builder.CreateLoad(ArrayIndexVar); 426 Dest = CGF.Builder.CreateInBoundsGEP(Dest, ArrayIndex, "destaddress"); 427 llvm::Value *Next = llvm::ConstantInt::get(ArrayIndex->getType(), 1); 428 Next = CGF.Builder.CreateAdd(ArrayIndex, Next, "inc"); 429 CGF.Builder.CreateStore(Next, ArrayIndexVar); 430 } 431 432 if (!CGF.hasAggregateLLVMType(T)) { 433 LValue lvalue = CGF.MakeAddrLValue(Dest, T); 434 CGF.EmitScalarInit(MemberInit->getInit(), /*decl*/ 0, lvalue, false); 435 } else if (T->isAnyComplexType()) { 436 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), Dest, 437 LHS.isVolatileQualified()); 438 } else { 439 AggValueSlot Slot = AggValueSlot::forAddr(Dest, LHS.getQuals(), 440 /*Lifetime*/ true); 441 442 CGF.EmitAggExpr(MemberInit->getInit(), Slot); 443 } 444 445 return; 446 } 447 448 const ConstantArrayType *Array = CGF.getContext().getAsConstantArrayType(T); 449 assert(Array && "Array initialization without the array type?"); 450 llvm::Value *IndexVar 451 = CGF.GetAddrOfLocalVar(MemberInit->getArrayIndex(Index)); 452 assert(IndexVar && "Array index variable not loaded"); 453 454 // Initialize this index variable to zero. 455 llvm::Value* Zero 456 = llvm::Constant::getNullValue( 457 CGF.ConvertType(CGF.getContext().getSizeType())); 458 CGF.Builder.CreateStore(Zero, IndexVar); 459 460 // Start the loop with a block that tests the condition. 461 llvm::BasicBlock *CondBlock = CGF.createBasicBlock("for.cond"); 462 llvm::BasicBlock *AfterFor = CGF.createBasicBlock("for.end"); 463 464 CGF.EmitBlock(CondBlock); 465 466 llvm::BasicBlock *ForBody = CGF.createBasicBlock("for.body"); 467 // Generate: if (loop-index < number-of-elements) fall to the loop body, 468 // otherwise, go to the block after the for-loop. 469 uint64_t NumElements = Array->getSize().getZExtValue(); 470 llvm::Value *Counter = CGF.Builder.CreateLoad(IndexVar); 471 llvm::Value *NumElementsPtr = 472 llvm::ConstantInt::get(Counter->getType(), NumElements); 473 llvm::Value *IsLess = CGF.Builder.CreateICmpULT(Counter, NumElementsPtr, 474 "isless"); 475 476 // If the condition is true, execute the body. 477 CGF.Builder.CreateCondBr(IsLess, ForBody, AfterFor); 478 479 CGF.EmitBlock(ForBody); 480 llvm::BasicBlock *ContinueBlock = CGF.createBasicBlock("for.inc"); 481 482 { 483 CodeGenFunction::RunCleanupsScope Cleanups(CGF); 484 485 // Inside the loop body recurse to emit the inner loop or, eventually, the 486 // constructor call. 487 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, 488 Array->getElementType(), Index + 1); 489 } 490 491 CGF.EmitBlock(ContinueBlock); 492 493 // Emit the increment of the loop counter. 494 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1); 495 Counter = CGF.Builder.CreateLoad(IndexVar); 496 NextVal = CGF.Builder.CreateAdd(Counter, NextVal, "inc"); 497 CGF.Builder.CreateStore(NextVal, IndexVar); 498 499 // Finally, branch back up to the condition for the next iteration. 500 CGF.EmitBranch(CondBlock); 501 502 // Emit the fall-through block. 503 CGF.EmitBlock(AfterFor, true); 504 } 505 506 namespace { 507 struct CallMemberDtor : EHScopeStack::Cleanup { 508 FieldDecl *Field; 509 CXXDestructorDecl *Dtor; 510 511 CallMemberDtor(FieldDecl *Field, CXXDestructorDecl *Dtor) 512 : Field(Field), Dtor(Dtor) {} 513 514 void Emit(CodeGenFunction &CGF, bool IsForEH) { 515 // FIXME: Is this OK for C++0x delegating constructors? 516 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 517 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 0); 518 519 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false, 520 LHS.getAddress()); 521 } 522 }; 523 } 524 525 static void EmitMemberInitializer(CodeGenFunction &CGF, 526 const CXXRecordDecl *ClassDecl, 527 CXXCtorInitializer *MemberInit, 528 const CXXConstructorDecl *Constructor, 529 FunctionArgList &Args) { 530 assert(MemberInit->isAnyMemberInitializer() && 531 "Must have member initializer!"); 532 assert(MemberInit->getInit() && "Must have initializer!"); 533 534 // non-static data member initializers. 535 FieldDecl *Field = MemberInit->getAnyMember(); 536 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType()); 537 538 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 539 LValue LHS; 540 541 // If we are initializing an anonymous union field, drill down to the field. 542 if (MemberInit->isIndirectMemberInitializer()) { 543 LHS = CGF.EmitLValueForAnonRecordField(ThisPtr, 544 MemberInit->getIndirectMember(), 0); 545 FieldType = MemberInit->getIndirectMember()->getAnonField()->getType(); 546 } else { 547 LHS = CGF.EmitLValueForFieldInitialization(ThisPtr, Field, 0); 548 } 549 550 // FIXME: If there's no initializer and the CXXCtorInitializer 551 // was implicitly generated, we shouldn't be zeroing memory. 552 if (FieldType->isArrayType() && !MemberInit->getInit()) { 553 CGF.EmitNullInitialization(LHS.getAddress(), Field->getType()); 554 } else if (!CGF.hasAggregateLLVMType(Field->getType())) { 555 if (LHS.isSimple()) { 556 CGF.EmitExprAsInit(MemberInit->getInit(), Field, LHS, false); 557 } else { 558 RValue RHS = RValue::get(CGF.EmitScalarExpr(MemberInit->getInit())); 559 CGF.EmitStoreThroughLValue(RHS, LHS); 560 } 561 } else if (MemberInit->getInit()->getType()->isAnyComplexType()) { 562 CGF.EmitComplexExprIntoAddr(MemberInit->getInit(), LHS.getAddress(), 563 LHS.isVolatileQualified()); 564 } else { 565 llvm::Value *ArrayIndexVar = 0; 566 const ConstantArrayType *Array 567 = CGF.getContext().getAsConstantArrayType(FieldType); 568 if (Array && Constructor->isImplicit() && 569 Constructor->isCopyConstructor()) { 570 const llvm::Type *SizeTy 571 = CGF.ConvertType(CGF.getContext().getSizeType()); 572 573 // The LHS is a pointer to the first object we'll be constructing, as 574 // a flat array. 575 QualType BaseElementTy = CGF.getContext().getBaseElementType(Array); 576 const llvm::Type *BasePtr = CGF.ConvertType(BaseElementTy); 577 BasePtr = llvm::PointerType::getUnqual(BasePtr); 578 llvm::Value *BaseAddrPtr = CGF.Builder.CreateBitCast(LHS.getAddress(), 579 BasePtr); 580 LHS = CGF.MakeAddrLValue(BaseAddrPtr, BaseElementTy); 581 582 // Create an array index that will be used to walk over all of the 583 // objects we're constructing. 584 ArrayIndexVar = CGF.CreateTempAlloca(SizeTy, "object.index"); 585 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy); 586 CGF.Builder.CreateStore(Zero, ArrayIndexVar); 587 588 // If we are copying an array of PODs or classes with trivial copy 589 // constructors, perform a single aggregate copy. 590 const CXXRecordDecl *Record = BaseElementTy->getAsCXXRecordDecl(); 591 if (BaseElementTy.isPODType(CGF.getContext()) || 592 (Record && Record->hasTrivialCopyConstructor())) { 593 // Find the source pointer. We knows it's the last argument because 594 // we know we're in a copy constructor. 595 unsigned SrcArgIndex = Args.size() - 1; 596 llvm::Value *SrcPtr 597 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(Args[SrcArgIndex])); 598 LValue Src = CGF.EmitLValueForFieldInitialization(SrcPtr, Field, 0); 599 600 // Copy the aggregate. 601 CGF.EmitAggregateCopy(LHS.getAddress(), Src.getAddress(), FieldType, 602 LHS.isVolatileQualified()); 603 return; 604 } 605 606 // Emit the block variables for the array indices, if any. 607 for (unsigned I = 0, N = MemberInit->getNumArrayIndices(); I != N; ++I) 608 CGF.EmitAutoVarDecl(*MemberInit->getArrayIndex(I)); 609 } 610 611 EmitAggMemberInitializer(CGF, LHS, ArrayIndexVar, MemberInit, FieldType, 0); 612 613 if (!CGF.CGM.getLangOptions().Exceptions) 614 return; 615 616 // FIXME: If we have an array of classes w/ non-trivial destructors, 617 // we need to destroy in reverse order of construction along the exception 618 // path. 619 const RecordType *RT = FieldType->getAs<RecordType>(); 620 if (!RT) 621 return; 622 623 CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl()); 624 if (!RD->hasTrivialDestructor()) 625 CGF.EHStack.pushCleanup<CallMemberDtor>(EHCleanup, Field, 626 RD->getDestructor()); 627 } 628 } 629 630 /// Checks whether the given constructor is a valid subject for the 631 /// complete-to-base constructor delegation optimization, i.e. 632 /// emitting the complete constructor as a simple call to the base 633 /// constructor. 634 static bool IsConstructorDelegationValid(const CXXConstructorDecl *Ctor) { 635 636 // Currently we disable the optimization for classes with virtual 637 // bases because (1) the addresses of parameter variables need to be 638 // consistent across all initializers but (2) the delegate function 639 // call necessarily creates a second copy of the parameter variable. 640 // 641 // The limiting example (purely theoretical AFAIK): 642 // struct A { A(int &c) { c++; } }; 643 // struct B : virtual A { 644 // B(int count) : A(count) { printf("%d\n", count); } 645 // }; 646 // ...although even this example could in principle be emitted as a 647 // delegation since the address of the parameter doesn't escape. 648 if (Ctor->getParent()->getNumVBases()) { 649 // TODO: white-list trivial vbase initializers. This case wouldn't 650 // be subject to the restrictions below. 651 652 // TODO: white-list cases where: 653 // - there are no non-reference parameters to the constructor 654 // - the initializers don't access any non-reference parameters 655 // - the initializers don't take the address of non-reference 656 // parameters 657 // - etc. 658 // If we ever add any of the above cases, remember that: 659 // - function-try-blocks will always blacklist this optimization 660 // - we need to perform the constructor prologue and cleanup in 661 // EmitConstructorBody. 662 663 return false; 664 } 665 666 // We also disable the optimization for variadic functions because 667 // it's impossible to "re-pass" varargs. 668 if (Ctor->getType()->getAs<FunctionProtoType>()->isVariadic()) 669 return false; 670 671 // FIXME: Decide if we can do a delegation of a delegating constructor. 672 if (Ctor->isDelegatingConstructor()) 673 return false; 674 675 return true; 676 } 677 678 /// EmitConstructorBody - Emits the body of the current constructor. 679 void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) { 680 const CXXConstructorDecl *Ctor = cast<CXXConstructorDecl>(CurGD.getDecl()); 681 CXXCtorType CtorType = CurGD.getCtorType(); 682 683 // Before we go any further, try the complete->base constructor 684 // delegation optimization. 685 if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor)) { 686 if (CGDebugInfo *DI = getDebugInfo()) 687 DI->EmitStopPoint(Builder); 688 EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args); 689 return; 690 } 691 692 Stmt *Body = Ctor->getBody(); 693 694 // Enter the function-try-block before the constructor prologue if 695 // applicable. 696 bool IsTryBody = (Body && isa<CXXTryStmt>(Body)); 697 if (IsTryBody) 698 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true); 699 700 EHScopeStack::stable_iterator CleanupDepth = EHStack.stable_begin(); 701 702 // Emit the constructor prologue, i.e. the base and member 703 // initializers. 704 EmitCtorPrologue(Ctor, CtorType, Args); 705 706 // Emit the body of the statement. 707 if (IsTryBody) 708 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock()); 709 else if (Body) 710 EmitStmt(Body); 711 712 // Emit any cleanup blocks associated with the member or base 713 // initializers, which includes (along the exceptional path) the 714 // destructors for those members and bases that were fully 715 // constructed. 716 PopCleanupBlocks(CleanupDepth); 717 718 if (IsTryBody) 719 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true); 720 } 721 722 /// EmitCtorPrologue - This routine generates necessary code to initialize 723 /// base classes and non-static data members belonging to this constructor. 724 void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD, 725 CXXCtorType CtorType, 726 FunctionArgList &Args) { 727 if (CD->isDelegatingConstructor()) 728 return EmitDelegatingCXXConstructorCall(CD, Args); 729 730 const CXXRecordDecl *ClassDecl = CD->getParent(); 731 732 llvm::SmallVector<CXXCtorInitializer *, 8> MemberInitializers; 733 734 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(), 735 E = CD->init_end(); 736 B != E; ++B) { 737 CXXCtorInitializer *Member = (*B); 738 739 if (Member->isBaseInitializer()) { 740 EmitBaseInitializer(*this, ClassDecl, Member, CtorType); 741 } else { 742 assert(Member->isAnyMemberInitializer() && 743 "Delegating initializer on non-delegating constructor"); 744 MemberInitializers.push_back(Member); 745 } 746 } 747 748 InitializeVTablePointers(ClassDecl); 749 750 for (unsigned I = 0, E = MemberInitializers.size(); I != E; ++I) 751 EmitMemberInitializer(*this, ClassDecl, MemberInitializers[I], CD, Args); 752 } 753 754 static bool 755 FieldHasTrivialDestructorBody(ASTContext &Context, const FieldDecl *Field); 756 757 static bool 758 HasTrivialDestructorBody(ASTContext &Context, 759 const CXXRecordDecl *BaseClassDecl, 760 const CXXRecordDecl *MostDerivedClassDecl) 761 { 762 // If the destructor is trivial we don't have to check anything else. 763 if (BaseClassDecl->hasTrivialDestructor()) 764 return true; 765 766 if (!BaseClassDecl->getDestructor()->hasTrivialBody()) 767 return false; 768 769 // Check fields. 770 for (CXXRecordDecl::field_iterator I = BaseClassDecl->field_begin(), 771 E = BaseClassDecl->field_end(); I != E; ++I) { 772 const FieldDecl *Field = *I; 773 774 if (!FieldHasTrivialDestructorBody(Context, Field)) 775 return false; 776 } 777 778 // Check non-virtual bases. 779 for (CXXRecordDecl::base_class_const_iterator I = 780 BaseClassDecl->bases_begin(), E = BaseClassDecl->bases_end(); 781 I != E; ++I) { 782 if (I->isVirtual()) 783 continue; 784 785 const CXXRecordDecl *NonVirtualBase = 786 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl()); 787 if (!HasTrivialDestructorBody(Context, NonVirtualBase, 788 MostDerivedClassDecl)) 789 return false; 790 } 791 792 if (BaseClassDecl == MostDerivedClassDecl) { 793 // Check virtual bases. 794 for (CXXRecordDecl::base_class_const_iterator I = 795 BaseClassDecl->vbases_begin(), E = BaseClassDecl->vbases_end(); 796 I != E; ++I) { 797 const CXXRecordDecl *VirtualBase = 798 cast<CXXRecordDecl>(I->getType()->castAs<RecordType>()->getDecl()); 799 if (!HasTrivialDestructorBody(Context, VirtualBase, 800 MostDerivedClassDecl)) 801 return false; 802 } 803 } 804 805 return true; 806 } 807 808 static bool 809 FieldHasTrivialDestructorBody(ASTContext &Context, 810 const FieldDecl *Field) 811 { 812 QualType FieldBaseElementType = Context.getBaseElementType(Field->getType()); 813 814 const RecordType *RT = FieldBaseElementType->getAs<RecordType>(); 815 if (!RT) 816 return true; 817 818 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 819 return HasTrivialDestructorBody(Context, FieldClassDecl, FieldClassDecl); 820 } 821 822 /// CanSkipVTablePointerInitialization - Check whether we need to initialize 823 /// any vtable pointers before calling this destructor. 824 static bool CanSkipVTablePointerInitialization(ASTContext &Context, 825 const CXXDestructorDecl *Dtor) { 826 if (!Dtor->hasTrivialBody()) 827 return false; 828 829 // Check the fields. 830 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 831 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 832 E = ClassDecl->field_end(); I != E; ++I) { 833 const FieldDecl *Field = *I; 834 835 if (!FieldHasTrivialDestructorBody(Context, Field)) 836 return false; 837 } 838 839 return true; 840 } 841 842 /// EmitDestructorBody - Emits the body of the current destructor. 843 void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) { 844 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CurGD.getDecl()); 845 CXXDtorType DtorType = CurGD.getDtorType(); 846 847 // The call to operator delete in a deleting destructor happens 848 // outside of the function-try-block, which means it's always 849 // possible to delegate the destructor body to the complete 850 // destructor. Do so. 851 if (DtorType == Dtor_Deleting) { 852 EnterDtorCleanups(Dtor, Dtor_Deleting); 853 EmitCXXDestructorCall(Dtor, Dtor_Complete, /*ForVirtualBase=*/false, 854 LoadCXXThis()); 855 PopCleanupBlock(); 856 return; 857 } 858 859 Stmt *Body = Dtor->getBody(); 860 861 // If the body is a function-try-block, enter the try before 862 // anything else. 863 bool isTryBody = (Body && isa<CXXTryStmt>(Body)); 864 if (isTryBody) 865 EnterCXXTryStmt(*cast<CXXTryStmt>(Body), true); 866 867 // Enter the epilogue cleanups. 868 RunCleanupsScope DtorEpilogue(*this); 869 870 // If this is the complete variant, just invoke the base variant; 871 // the epilogue will destruct the virtual bases. But we can't do 872 // this optimization if the body is a function-try-block, because 873 // we'd introduce *two* handler blocks. 874 switch (DtorType) { 875 case Dtor_Deleting: llvm_unreachable("already handled deleting case"); 876 877 case Dtor_Complete: 878 // Enter the cleanup scopes for virtual bases. 879 EnterDtorCleanups(Dtor, Dtor_Complete); 880 881 if (!isTryBody) { 882 EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false, 883 LoadCXXThis()); 884 break; 885 } 886 // Fallthrough: act like we're in the base variant. 887 888 case Dtor_Base: 889 // Enter the cleanup scopes for fields and non-virtual bases. 890 EnterDtorCleanups(Dtor, Dtor_Base); 891 892 // Initialize the vtable pointers before entering the body. 893 if (!CanSkipVTablePointerInitialization(getContext(), Dtor)) 894 InitializeVTablePointers(Dtor->getParent()); 895 896 if (isTryBody) 897 EmitStmt(cast<CXXTryStmt>(Body)->getTryBlock()); 898 else if (Body) 899 EmitStmt(Body); 900 else { 901 assert(Dtor->isImplicit() && "bodyless dtor not implicit"); 902 // nothing to do besides what's in the epilogue 903 } 904 // -fapple-kext must inline any call to this dtor into 905 // the caller's body. 906 if (getContext().getLangOptions().AppleKext) 907 CurFn->addFnAttr(llvm::Attribute::AlwaysInline); 908 break; 909 } 910 911 // Jump out through the epilogue cleanups. 912 DtorEpilogue.ForceCleanup(); 913 914 // Exit the try if applicable. 915 if (isTryBody) 916 ExitCXXTryStmt(*cast<CXXTryStmt>(Body), true); 917 } 918 919 namespace { 920 /// Call the operator delete associated with the current destructor. 921 struct CallDtorDelete : EHScopeStack::Cleanup { 922 CallDtorDelete() {} 923 924 void Emit(CodeGenFunction &CGF, bool IsForEH) { 925 const CXXDestructorDecl *Dtor = cast<CXXDestructorDecl>(CGF.CurCodeDecl); 926 const CXXRecordDecl *ClassDecl = Dtor->getParent(); 927 CGF.EmitDeleteCall(Dtor->getOperatorDelete(), CGF.LoadCXXThis(), 928 CGF.getContext().getTagDeclType(ClassDecl)); 929 } 930 }; 931 932 struct CallArrayFieldDtor : EHScopeStack::Cleanup { 933 const FieldDecl *Field; 934 CallArrayFieldDtor(const FieldDecl *Field) : Field(Field) {} 935 936 void Emit(CodeGenFunction &CGF, bool IsForEH) { 937 QualType FieldType = Field->getType(); 938 QualType BaseType = CGF.getContext().getBaseElementType(FieldType); 939 const CXXRecordDecl *FieldClassDecl = BaseType->getAsCXXRecordDecl(); 940 941 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 942 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 943 // FIXME: Qualifiers? 944 /*CVRQualifiers=*/0); 945 946 const llvm::Type *BasePtr 947 = CGF.ConvertType(BaseType)->getPointerTo(); 948 llvm::Value *BaseAddrPtr 949 = CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr); 950 const ConstantArrayType *Array 951 = CGF.getContext().getAsConstantArrayType(FieldType); 952 CGF.EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(), 953 Array, BaseAddrPtr); 954 } 955 }; 956 957 struct CallFieldDtor : EHScopeStack::Cleanup { 958 const FieldDecl *Field; 959 CallFieldDtor(const FieldDecl *Field) : Field(Field) {} 960 961 void Emit(CodeGenFunction &CGF, bool IsForEH) { 962 const CXXRecordDecl *FieldClassDecl = 963 Field->getType()->getAsCXXRecordDecl(); 964 965 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 966 LValue LHS = CGF.EmitLValueForField(ThisPtr, Field, 967 // FIXME: Qualifiers? 968 /*CVRQualifiers=*/0); 969 970 CGF.EmitCXXDestructorCall(FieldClassDecl->getDestructor(), 971 Dtor_Complete, /*ForVirtualBase=*/false, 972 LHS.getAddress()); 973 } 974 }; 975 } 976 977 /// EmitDtorEpilogue - Emit all code that comes at the end of class's 978 /// destructor. This is to call destructors on members and base classes 979 /// in reverse order of their construction. 980 void CodeGenFunction::EnterDtorCleanups(const CXXDestructorDecl *DD, 981 CXXDtorType DtorType) { 982 assert(!DD->isTrivial() && 983 "Should not emit dtor epilogue for trivial dtor!"); 984 985 // The deleting-destructor phase just needs to call the appropriate 986 // operator delete that Sema picked up. 987 if (DtorType == Dtor_Deleting) { 988 assert(DD->getOperatorDelete() && 989 "operator delete missing - EmitDtorEpilogue"); 990 EHStack.pushCleanup<CallDtorDelete>(NormalAndEHCleanup); 991 return; 992 } 993 994 const CXXRecordDecl *ClassDecl = DD->getParent(); 995 996 // The complete-destructor phase just destructs all the virtual bases. 997 if (DtorType == Dtor_Complete) { 998 999 // We push them in the forward order so that they'll be popped in 1000 // the reverse order. 1001 for (CXXRecordDecl::base_class_const_iterator I = 1002 ClassDecl->vbases_begin(), E = ClassDecl->vbases_end(); 1003 I != E; ++I) { 1004 const CXXBaseSpecifier &Base = *I; 1005 CXXRecordDecl *BaseClassDecl 1006 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 1007 1008 // Ignore trivial destructors. 1009 if (BaseClassDecl->hasTrivialDestructor()) 1010 continue; 1011 1012 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 1013 BaseClassDecl, 1014 /*BaseIsVirtual*/ true); 1015 } 1016 1017 return; 1018 } 1019 1020 assert(DtorType == Dtor_Base); 1021 1022 // Destroy non-virtual bases. 1023 for (CXXRecordDecl::base_class_const_iterator I = 1024 ClassDecl->bases_begin(), E = ClassDecl->bases_end(); I != E; ++I) { 1025 const CXXBaseSpecifier &Base = *I; 1026 1027 // Ignore virtual bases. 1028 if (Base.isVirtual()) 1029 continue; 1030 1031 CXXRecordDecl *BaseClassDecl = Base.getType()->getAsCXXRecordDecl(); 1032 1033 // Ignore trivial destructors. 1034 if (BaseClassDecl->hasTrivialDestructor()) 1035 continue; 1036 1037 EHStack.pushCleanup<CallBaseDtor>(NormalAndEHCleanup, 1038 BaseClassDecl, 1039 /*BaseIsVirtual*/ false); 1040 } 1041 1042 // Destroy direct fields. 1043 llvm::SmallVector<const FieldDecl *, 16> FieldDecls; 1044 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 1045 E = ClassDecl->field_end(); I != E; ++I) { 1046 const FieldDecl *Field = *I; 1047 1048 QualType FieldType = getContext().getCanonicalType(Field->getType()); 1049 const ConstantArrayType *Array = 1050 getContext().getAsConstantArrayType(FieldType); 1051 if (Array) 1052 FieldType = getContext().getBaseElementType(Array->getElementType()); 1053 1054 switch (FieldType.isDestructedType()) { 1055 case QualType::DK_none: 1056 continue; 1057 1058 case QualType::DK_cxx_destructor: 1059 if (Array) 1060 EHStack.pushCleanup<CallArrayFieldDtor>(NormalAndEHCleanup, Field); 1061 else 1062 EHStack.pushCleanup<CallFieldDtor>(NormalAndEHCleanup, Field); 1063 break; 1064 1065 case QualType::DK_objc_strong_lifetime: 1066 PushARCFieldReleaseCleanup(getARCCleanupKind(), Field); 1067 break; 1068 1069 case QualType::DK_objc_weak_lifetime: 1070 PushARCFieldWeakReleaseCleanup(getARCCleanupKind(), Field); 1071 break; 1072 } 1073 } 1074 } 1075 1076 /// EmitCXXAggrConstructorCall - This routine essentially creates a (nested) 1077 /// for-loop to call the default constructor on individual members of the 1078 /// array. 1079 /// 'D' is the default constructor for elements of the array, 'ArrayTy' is the 1080 /// array type and 'ArrayPtr' points to the beginning fo the array. 1081 /// It is assumed that all relevant checks have been made by the caller. 1082 /// 1083 /// \param ZeroInitialization True if each element should be zero-initialized 1084 /// before it is constructed. 1085 void 1086 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 1087 const ConstantArrayType *ArrayTy, 1088 llvm::Value *ArrayPtr, 1089 CallExpr::const_arg_iterator ArgBeg, 1090 CallExpr::const_arg_iterator ArgEnd, 1091 bool ZeroInitialization) { 1092 1093 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 1094 llvm::Value * NumElements = 1095 llvm::ConstantInt::get(SizeTy, 1096 getContext().getConstantArrayElementCount(ArrayTy)); 1097 1098 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd, 1099 ZeroInitialization); 1100 } 1101 1102 void 1103 CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 1104 llvm::Value *NumElements, 1105 llvm::Value *ArrayPtr, 1106 CallExpr::const_arg_iterator ArgBeg, 1107 CallExpr::const_arg_iterator ArgEnd, 1108 bool ZeroInitialization) { 1109 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 1110 1111 // Create a temporary for the loop index and initialize it with 0. 1112 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index"); 1113 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy); 1114 Builder.CreateStore(Zero, IndexPtr); 1115 1116 // Start the loop with a block that tests the condition. 1117 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 1118 llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); 1119 1120 EmitBlock(CondBlock); 1121 1122 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 1123 1124 // Generate: if (loop-index < number-of-elements fall to the loop body, 1125 // otherwise, go to the block after the for-loop. 1126 llvm::Value *Counter = Builder.CreateLoad(IndexPtr); 1127 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless"); 1128 // If the condition is true, execute the body. 1129 Builder.CreateCondBr(IsLess, ForBody, AfterFor); 1130 1131 EmitBlock(ForBody); 1132 1133 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc"); 1134 // Inside the loop body, emit the constructor call on the array element. 1135 Counter = Builder.CreateLoad(IndexPtr); 1136 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter, 1137 "arrayidx"); 1138 1139 // Zero initialize the storage, if requested. 1140 if (ZeroInitialization) 1141 EmitNullInitialization(Address, 1142 getContext().getTypeDeclType(D->getParent())); 1143 1144 // C++ [class.temporary]p4: 1145 // There are two contexts in which temporaries are destroyed at a different 1146 // point than the end of the full-expression. The first context is when a 1147 // default constructor is called to initialize an element of an array. 1148 // If the constructor has one or more default arguments, the destruction of 1149 // every temporary created in a default argument expression is sequenced 1150 // before the construction of the next array element, if any. 1151 1152 // Keep track of the current number of live temporaries. 1153 { 1154 RunCleanupsScope Scope(*this); 1155 1156 EmitCXXConstructorCall(D, Ctor_Complete, /*ForVirtualBase=*/false, Address, 1157 ArgBeg, ArgEnd); 1158 } 1159 1160 EmitBlock(ContinueBlock); 1161 1162 // Emit the increment of the loop counter. 1163 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1); 1164 Counter = Builder.CreateLoad(IndexPtr); 1165 NextVal = Builder.CreateAdd(Counter, NextVal, "inc"); 1166 Builder.CreateStore(NextVal, IndexPtr); 1167 1168 // Finally, branch back up to the condition for the next iteration. 1169 EmitBranch(CondBlock); 1170 1171 // Emit the fall-through block. 1172 EmitBlock(AfterFor, true); 1173 } 1174 1175 void CodeGenFunction::destroyCXXObject(CodeGenFunction &CGF, 1176 llvm::Value *addr, 1177 QualType type) { 1178 const RecordType *rtype = type->castAs<RecordType>(); 1179 const CXXRecordDecl *record = cast<CXXRecordDecl>(rtype->getDecl()); 1180 const CXXDestructorDecl *dtor = record->getDestructor(); 1181 assert(!dtor->isTrivial()); 1182 CGF.EmitCXXDestructorCall(dtor, Dtor_Complete, /*for vbase*/ false, 1183 addr); 1184 } 1185 1186 /// EmitCXXAggrDestructorCall - calls the default destructor on array 1187 /// elements in reverse order of construction. 1188 void 1189 CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D, 1190 const ArrayType *Array, 1191 llvm::Value *This) { 1192 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array); 1193 assert(CA && "Do we support VLA for destruction ?"); 1194 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA); 1195 1196 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType()); 1197 llvm::Value* ElementCountPtr = llvm::ConstantInt::get(SizeLTy, ElementCount); 1198 EmitCXXAggrDestructorCall(D, ElementCountPtr, This); 1199 } 1200 1201 /// EmitCXXAggrDestructorCall - calls the default destructor on array 1202 /// elements in reverse order of construction. 1203 void 1204 CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D, 1205 llvm::Value *UpperCount, 1206 llvm::Value *This) { 1207 const llvm::Type *SizeLTy = ConvertType(getContext().getSizeType()); 1208 llvm::Value *One = llvm::ConstantInt::get(SizeLTy, 1); 1209 1210 // Create a temporary for the loop index and initialize it with count of 1211 // array elements. 1212 llvm::Value *IndexPtr = CreateTempAlloca(SizeLTy, "loop.index"); 1213 1214 // Store the number of elements in the index pointer. 1215 Builder.CreateStore(UpperCount, IndexPtr); 1216 1217 // Start the loop with a block that tests the condition. 1218 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 1219 llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); 1220 1221 EmitBlock(CondBlock); 1222 1223 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 1224 1225 // Generate: if (loop-index != 0 fall to the loop body, 1226 // otherwise, go to the block after the for-loop. 1227 llvm::Value* zeroConstant = 1228 llvm::Constant::getNullValue(SizeLTy); 1229 llvm::Value *Counter = Builder.CreateLoad(IndexPtr); 1230 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant, 1231 "isne"); 1232 // If the condition is true, execute the body. 1233 Builder.CreateCondBr(IsNE, ForBody, AfterFor); 1234 1235 EmitBlock(ForBody); 1236 1237 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc"); 1238 // Inside the loop body, emit the constructor call on the array element. 1239 Counter = Builder.CreateLoad(IndexPtr); 1240 Counter = Builder.CreateSub(Counter, One); 1241 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx"); 1242 EmitCXXDestructorCall(D, Dtor_Complete, /*ForVirtualBase=*/false, Address); 1243 1244 EmitBlock(ContinueBlock); 1245 1246 // Emit the decrement of the loop counter. 1247 Counter = Builder.CreateLoad(IndexPtr); 1248 Counter = Builder.CreateSub(Counter, One, "dec"); 1249 Builder.CreateStore(Counter, IndexPtr); 1250 1251 // Finally, branch back up to the condition for the next iteration. 1252 EmitBranch(CondBlock); 1253 1254 // Emit the fall-through block. 1255 EmitBlock(AfterFor, true); 1256 } 1257 1258 void 1259 CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, 1260 CXXCtorType Type, bool ForVirtualBase, 1261 llvm::Value *This, 1262 CallExpr::const_arg_iterator ArgBeg, 1263 CallExpr::const_arg_iterator ArgEnd) { 1264 1265 CGDebugInfo *DI = getDebugInfo(); 1266 if (DI && CGM.getCodeGenOpts().LimitDebugInfo) { 1267 // If debug info for this class has been emitted then this is the right time 1268 // to do so. 1269 const CXXRecordDecl *Parent = D->getParent(); 1270 DI->getOrCreateRecordType(CGM.getContext().getTypeDeclType(Parent), 1271 Parent->getLocation()); 1272 } 1273 1274 if (D->isTrivial()) { 1275 if (ArgBeg == ArgEnd) { 1276 // Trivial default constructor, no codegen required. 1277 assert(D->isDefaultConstructor() && 1278 "trivial 0-arg ctor not a default ctor"); 1279 return; 1280 } 1281 1282 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor"); 1283 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor"); 1284 1285 const Expr *E = (*ArgBeg); 1286 QualType Ty = E->getType(); 1287 llvm::Value *Src = EmitLValue(E).getAddress(); 1288 EmitAggregateCopy(This, Src, Ty); 1289 return; 1290 } 1291 1292 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(D, Type), ForVirtualBase); 1293 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type); 1294 1295 EmitCXXMemberCall(D, Callee, ReturnValueSlot(), This, VTT, ArgBeg, ArgEnd); 1296 } 1297 1298 void 1299 CodeGenFunction::EmitSynthesizedCXXCopyCtorCall(const CXXConstructorDecl *D, 1300 llvm::Value *This, llvm::Value *Src, 1301 CallExpr::const_arg_iterator ArgBeg, 1302 CallExpr::const_arg_iterator ArgEnd) { 1303 if (D->isTrivial()) { 1304 assert(ArgBeg + 1 == ArgEnd && "unexpected argcount for trivial ctor"); 1305 assert(D->isCopyConstructor() && "trivial 1-arg ctor not a copy ctor"); 1306 EmitAggregateCopy(This, Src, (*ArgBeg)->getType()); 1307 return; 1308 } 1309 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, 1310 clang::Ctor_Complete); 1311 assert(D->isInstance() && 1312 "Trying to emit a member call expr on a static method!"); 1313 1314 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>(); 1315 1316 CallArgList Args; 1317 1318 // Push the this ptr. 1319 Args.add(RValue::get(This), D->getThisType(getContext())); 1320 1321 1322 // Push the src ptr. 1323 QualType QT = *(FPT->arg_type_begin()); 1324 const llvm::Type *t = CGM.getTypes().ConvertType(QT); 1325 Src = Builder.CreateBitCast(Src, t); 1326 Args.add(RValue::get(Src), QT); 1327 1328 // Skip over first argument (Src). 1329 ++ArgBeg; 1330 CallExpr::const_arg_iterator Arg = ArgBeg; 1331 for (FunctionProtoType::arg_type_iterator I = FPT->arg_type_begin()+1, 1332 E = FPT->arg_type_end(); I != E; ++I, ++Arg) { 1333 assert(Arg != ArgEnd && "Running over edge of argument list!"); 1334 EmitCallArg(Args, *Arg, *I); 1335 } 1336 // Either we've emitted all the call args, or we have a call to a 1337 // variadic function. 1338 assert((Arg == ArgEnd || FPT->isVariadic()) && 1339 "Extra arguments in non-variadic function!"); 1340 // If we still have any arguments, emit them using the type of the argument. 1341 for (; Arg != ArgEnd; ++Arg) { 1342 QualType ArgType = Arg->getType(); 1343 EmitCallArg(Args, *Arg, ArgType); 1344 } 1345 1346 QualType ResultType = FPT->getResultType(); 1347 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args, 1348 FPT->getExtInfo()), 1349 Callee, ReturnValueSlot(), Args, D); 1350 } 1351 1352 void 1353 CodeGenFunction::EmitDelegateCXXConstructorCall(const CXXConstructorDecl *Ctor, 1354 CXXCtorType CtorType, 1355 const FunctionArgList &Args) { 1356 CallArgList DelegateArgs; 1357 1358 FunctionArgList::const_iterator I = Args.begin(), E = Args.end(); 1359 assert(I != E && "no parameters to constructor"); 1360 1361 // this 1362 DelegateArgs.add(RValue::get(LoadCXXThis()), (*I)->getType()); 1363 ++I; 1364 1365 // vtt 1366 if (llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(Ctor, CtorType), 1367 /*ForVirtualBase=*/false)) { 1368 QualType VoidPP = getContext().getPointerType(getContext().VoidPtrTy); 1369 DelegateArgs.add(RValue::get(VTT), VoidPP); 1370 1371 if (CodeGenVTables::needsVTTParameter(CurGD)) { 1372 assert(I != E && "cannot skip vtt parameter, already done with args"); 1373 assert((*I)->getType() == VoidPP && "skipping parameter not of vtt type"); 1374 ++I; 1375 } 1376 } 1377 1378 // Explicit arguments. 1379 for (; I != E; ++I) { 1380 const VarDecl *param = *I; 1381 EmitDelegateCallArg(DelegateArgs, param); 1382 } 1383 1384 EmitCall(CGM.getTypes().getFunctionInfo(Ctor, CtorType), 1385 CGM.GetAddrOfCXXConstructor(Ctor, CtorType), 1386 ReturnValueSlot(), DelegateArgs, Ctor); 1387 } 1388 1389 namespace { 1390 struct CallDelegatingCtorDtor : EHScopeStack::Cleanup { 1391 const CXXDestructorDecl *Dtor; 1392 llvm::Value *Addr; 1393 CXXDtorType Type; 1394 1395 CallDelegatingCtorDtor(const CXXDestructorDecl *D, llvm::Value *Addr, 1396 CXXDtorType Type) 1397 : Dtor(D), Addr(Addr), Type(Type) {} 1398 1399 void Emit(CodeGenFunction &CGF, bool IsForEH) { 1400 CGF.EmitCXXDestructorCall(Dtor, Type, /*ForVirtualBase=*/false, 1401 Addr); 1402 } 1403 }; 1404 } 1405 1406 void 1407 CodeGenFunction::EmitDelegatingCXXConstructorCall(const CXXConstructorDecl *Ctor, 1408 const FunctionArgList &Args) { 1409 assert(Ctor->isDelegatingConstructor()); 1410 1411 llvm::Value *ThisPtr = LoadCXXThis(); 1412 1413 AggValueSlot AggSlot = 1414 AggValueSlot::forAddr(ThisPtr, Qualifiers(), /*Lifetime*/ true); 1415 1416 EmitAggExpr(Ctor->init_begin()[0]->getInit(), AggSlot); 1417 1418 const CXXRecordDecl *ClassDecl = Ctor->getParent(); 1419 if (CGM.getLangOptions().Exceptions && !ClassDecl->hasTrivialDestructor()) { 1420 CXXDtorType Type = 1421 CurGD.getCtorType() == Ctor_Complete ? Dtor_Complete : Dtor_Base; 1422 1423 EHStack.pushCleanup<CallDelegatingCtorDtor>(EHCleanup, 1424 ClassDecl->getDestructor(), 1425 ThisPtr, Type); 1426 } 1427 } 1428 1429 void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD, 1430 CXXDtorType Type, 1431 bool ForVirtualBase, 1432 llvm::Value *This) { 1433 llvm::Value *VTT = GetVTTParameter(*this, GlobalDecl(DD, Type), 1434 ForVirtualBase); 1435 llvm::Value *Callee = 0; 1436 if (getContext().getLangOptions().AppleKext) 1437 Callee = BuildAppleKextVirtualDestructorCall(DD, Type, 1438 DD->getParent()); 1439 1440 if (!Callee) 1441 Callee = CGM.GetAddrOfCXXDestructor(DD, Type); 1442 1443 EmitCXXMemberCall(DD, Callee, ReturnValueSlot(), This, VTT, 0, 0); 1444 } 1445 1446 namespace { 1447 struct CallLocalDtor : EHScopeStack::Cleanup { 1448 const CXXDestructorDecl *Dtor; 1449 llvm::Value *Addr; 1450 1451 CallLocalDtor(const CXXDestructorDecl *D, llvm::Value *Addr) 1452 : Dtor(D), Addr(Addr) {} 1453 1454 void Emit(CodeGenFunction &CGF, bool IsForEH) { 1455 CGF.EmitCXXDestructorCall(Dtor, Dtor_Complete, 1456 /*ForVirtualBase=*/false, Addr); 1457 } 1458 }; 1459 } 1460 1461 void CodeGenFunction::PushDestructorCleanup(const CXXDestructorDecl *D, 1462 llvm::Value *Addr) { 1463 EHStack.pushCleanup<CallLocalDtor>(NormalAndEHCleanup, D, Addr); 1464 } 1465 1466 void CodeGenFunction::PushDestructorCleanup(QualType T, llvm::Value *Addr) { 1467 CXXRecordDecl *ClassDecl = T->getAsCXXRecordDecl(); 1468 if (!ClassDecl) return; 1469 if (ClassDecl->hasTrivialDestructor()) return; 1470 1471 const CXXDestructorDecl *D = ClassDecl->getDestructor(); 1472 assert(D && D->isUsed() && "destructor not marked as used!"); 1473 PushDestructorCleanup(D, Addr); 1474 } 1475 1476 llvm::Value * 1477 CodeGenFunction::GetVirtualBaseClassOffset(llvm::Value *This, 1478 const CXXRecordDecl *ClassDecl, 1479 const CXXRecordDecl *BaseClassDecl) { 1480 llvm::Value *VTablePtr = GetVTablePtr(This, Int8PtrTy); 1481 CharUnits VBaseOffsetOffset = 1482 CGM.getVTables().getVirtualBaseOffsetOffset(ClassDecl, BaseClassDecl); 1483 1484 llvm::Value *VBaseOffsetPtr = 1485 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetOffset.getQuantity(), 1486 "vbase.offset.ptr"); 1487 const llvm::Type *PtrDiffTy = 1488 ConvertType(getContext().getPointerDiffType()); 1489 1490 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr, 1491 PtrDiffTy->getPointerTo()); 1492 1493 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset"); 1494 1495 return VBaseOffset; 1496 } 1497 1498 void 1499 CodeGenFunction::InitializeVTablePointer(BaseSubobject Base, 1500 const CXXRecordDecl *NearestVBase, 1501 CharUnits OffsetFromNearestVBase, 1502 llvm::Constant *VTable, 1503 const CXXRecordDecl *VTableClass) { 1504 const CXXRecordDecl *RD = Base.getBase(); 1505 1506 // Compute the address point. 1507 llvm::Value *VTableAddressPoint; 1508 1509 // Check if we need to use a vtable from the VTT. 1510 if (CodeGenVTables::needsVTTParameter(CurGD) && 1511 (RD->getNumVBases() || NearestVBase)) { 1512 // Get the secondary vpointer index. 1513 uint64_t VirtualPointerIndex = 1514 CGM.getVTables().getSecondaryVirtualPointerIndex(VTableClass, Base); 1515 1516 /// Load the VTT. 1517 llvm::Value *VTT = LoadCXXVTT(); 1518 if (VirtualPointerIndex) 1519 VTT = Builder.CreateConstInBoundsGEP1_64(VTT, VirtualPointerIndex); 1520 1521 // And load the address point from the VTT. 1522 VTableAddressPoint = Builder.CreateLoad(VTT); 1523 } else { 1524 uint64_t AddressPoint = CGM.getVTables().getAddressPoint(Base, VTableClass); 1525 VTableAddressPoint = 1526 Builder.CreateConstInBoundsGEP2_64(VTable, 0, AddressPoint); 1527 } 1528 1529 // Compute where to store the address point. 1530 llvm::Value *VirtualOffset = 0; 1531 CharUnits NonVirtualOffset = CharUnits::Zero(); 1532 1533 if (CodeGenVTables::needsVTTParameter(CurGD) && NearestVBase) { 1534 // We need to use the virtual base offset offset because the virtual base 1535 // might have a different offset in the most derived class. 1536 VirtualOffset = GetVirtualBaseClassOffset(LoadCXXThis(), VTableClass, 1537 NearestVBase); 1538 NonVirtualOffset = OffsetFromNearestVBase; 1539 } else { 1540 // We can just use the base offset in the complete class. 1541 NonVirtualOffset = Base.getBaseOffset(); 1542 } 1543 1544 // Apply the offsets. 1545 llvm::Value *VTableField = LoadCXXThis(); 1546 1547 if (!NonVirtualOffset.isZero() || VirtualOffset) 1548 VTableField = ApplyNonVirtualAndVirtualOffset(*this, VTableField, 1549 NonVirtualOffset, 1550 VirtualOffset); 1551 1552 // Finally, store the address point. 1553 const llvm::Type *AddressPointPtrTy = 1554 VTableAddressPoint->getType()->getPointerTo(); 1555 VTableField = Builder.CreateBitCast(VTableField, AddressPointPtrTy); 1556 Builder.CreateStore(VTableAddressPoint, VTableField); 1557 } 1558 1559 void 1560 CodeGenFunction::InitializeVTablePointers(BaseSubobject Base, 1561 const CXXRecordDecl *NearestVBase, 1562 CharUnits OffsetFromNearestVBase, 1563 bool BaseIsNonVirtualPrimaryBase, 1564 llvm::Constant *VTable, 1565 const CXXRecordDecl *VTableClass, 1566 VisitedVirtualBasesSetTy& VBases) { 1567 // If this base is a non-virtual primary base the address point has already 1568 // been set. 1569 if (!BaseIsNonVirtualPrimaryBase) { 1570 // Initialize the vtable pointer for this base. 1571 InitializeVTablePointer(Base, NearestVBase, OffsetFromNearestVBase, 1572 VTable, VTableClass); 1573 } 1574 1575 const CXXRecordDecl *RD = Base.getBase(); 1576 1577 // Traverse bases. 1578 for (CXXRecordDecl::base_class_const_iterator I = RD->bases_begin(), 1579 E = RD->bases_end(); I != E; ++I) { 1580 CXXRecordDecl *BaseDecl 1581 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 1582 1583 // Ignore classes without a vtable. 1584 if (!BaseDecl->isDynamicClass()) 1585 continue; 1586 1587 CharUnits BaseOffset; 1588 CharUnits BaseOffsetFromNearestVBase; 1589 bool BaseDeclIsNonVirtualPrimaryBase; 1590 1591 if (I->isVirtual()) { 1592 // Check if we've visited this virtual base before. 1593 if (!VBases.insert(BaseDecl)) 1594 continue; 1595 1596 const ASTRecordLayout &Layout = 1597 getContext().getASTRecordLayout(VTableClass); 1598 1599 BaseOffset = Layout.getVBaseClassOffset(BaseDecl); 1600 BaseOffsetFromNearestVBase = CharUnits::Zero(); 1601 BaseDeclIsNonVirtualPrimaryBase = false; 1602 } else { 1603 const ASTRecordLayout &Layout = getContext().getASTRecordLayout(RD); 1604 1605 BaseOffset = Base.getBaseOffset() + Layout.getBaseClassOffset(BaseDecl); 1606 BaseOffsetFromNearestVBase = 1607 OffsetFromNearestVBase + Layout.getBaseClassOffset(BaseDecl); 1608 BaseDeclIsNonVirtualPrimaryBase = Layout.getPrimaryBase() == BaseDecl; 1609 } 1610 1611 InitializeVTablePointers(BaseSubobject(BaseDecl, BaseOffset), 1612 I->isVirtual() ? BaseDecl : NearestVBase, 1613 BaseOffsetFromNearestVBase, 1614 BaseDeclIsNonVirtualPrimaryBase, 1615 VTable, VTableClass, VBases); 1616 } 1617 } 1618 1619 void CodeGenFunction::InitializeVTablePointers(const CXXRecordDecl *RD) { 1620 // Ignore classes without a vtable. 1621 if (!RD->isDynamicClass()) 1622 return; 1623 1624 // Get the VTable. 1625 llvm::Constant *VTable = CGM.getVTables().GetAddrOfVTable(RD); 1626 1627 // Initialize the vtable pointers for this class and all of its bases. 1628 VisitedVirtualBasesSetTy VBases; 1629 InitializeVTablePointers(BaseSubobject(RD, CharUnits::Zero()), 1630 /*NearestVBase=*/0, 1631 /*OffsetFromNearestVBase=*/CharUnits::Zero(), 1632 /*BaseIsNonVirtualPrimaryBase=*/false, 1633 VTable, RD, VBases); 1634 } 1635 1636 llvm::Value *CodeGenFunction::GetVTablePtr(llvm::Value *This, 1637 const llvm::Type *Ty) { 1638 llvm::Value *VTablePtrSrc = Builder.CreateBitCast(This, Ty->getPointerTo()); 1639 return Builder.CreateLoad(VTablePtrSrc, "vtable"); 1640 } 1641 1642 static const CXXRecordDecl *getMostDerivedClassDecl(const Expr *Base) { 1643 const Expr *E = Base; 1644 1645 while (true) { 1646 E = E->IgnoreParens(); 1647 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 1648 if (CE->getCastKind() == CK_DerivedToBase || 1649 CE->getCastKind() == CK_UncheckedDerivedToBase || 1650 CE->getCastKind() == CK_NoOp) { 1651 E = CE->getSubExpr(); 1652 continue; 1653 } 1654 } 1655 1656 break; 1657 } 1658 1659 QualType DerivedType = E->getType(); 1660 if (const PointerType *PTy = DerivedType->getAs<PointerType>()) 1661 DerivedType = PTy->getPointeeType(); 1662 1663 return cast<CXXRecordDecl>(DerivedType->castAs<RecordType>()->getDecl()); 1664 } 1665 1666 // FIXME: Ideally Expr::IgnoreParenNoopCasts should do this, but it doesn't do 1667 // quite what we want. 1668 static const Expr *skipNoOpCastsAndParens(const Expr *E) { 1669 while (true) { 1670 if (const ParenExpr *PE = dyn_cast<ParenExpr>(E)) { 1671 E = PE->getSubExpr(); 1672 continue; 1673 } 1674 1675 if (const CastExpr *CE = dyn_cast<CastExpr>(E)) { 1676 if (CE->getCastKind() == CK_NoOp) { 1677 E = CE->getSubExpr(); 1678 continue; 1679 } 1680 } 1681 if (const UnaryOperator *UO = dyn_cast<UnaryOperator>(E)) { 1682 if (UO->getOpcode() == UO_Extension) { 1683 E = UO->getSubExpr(); 1684 continue; 1685 } 1686 } 1687 return E; 1688 } 1689 } 1690 1691 /// canDevirtualizeMemberFunctionCall - Checks whether the given virtual member 1692 /// function call on the given expr can be devirtualized. 1693 /// expr can be devirtualized. 1694 static bool canDevirtualizeMemberFunctionCall(const Expr *Base, 1695 const CXXMethodDecl *MD) { 1696 // If the most derived class is marked final, we know that no subclass can 1697 // override this member function and so we can devirtualize it. For example: 1698 // 1699 // struct A { virtual void f(); } 1700 // struct B final : A { }; 1701 // 1702 // void f(B *b) { 1703 // b->f(); 1704 // } 1705 // 1706 const CXXRecordDecl *MostDerivedClassDecl = getMostDerivedClassDecl(Base); 1707 if (MostDerivedClassDecl->hasAttr<FinalAttr>()) 1708 return true; 1709 1710 // If the member function is marked 'final', we know that it can't be 1711 // overridden and can therefore devirtualize it. 1712 if (MD->hasAttr<FinalAttr>()) 1713 return true; 1714 1715 // Similarly, if the class itself is marked 'final' it can't be overridden 1716 // and we can therefore devirtualize the member function call. 1717 if (MD->getParent()->hasAttr<FinalAttr>()) 1718 return true; 1719 1720 Base = skipNoOpCastsAndParens(Base); 1721 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 1722 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 1723 // This is a record decl. We know the type and can devirtualize it. 1724 return VD->getType()->isRecordType(); 1725 } 1726 1727 return false; 1728 } 1729 1730 // We can always devirtualize calls on temporary object expressions. 1731 if (isa<CXXConstructExpr>(Base)) 1732 return true; 1733 1734 // And calls on bound temporaries. 1735 if (isa<CXXBindTemporaryExpr>(Base)) 1736 return true; 1737 1738 // Check if this is a call expr that returns a record type. 1739 if (const CallExpr *CE = dyn_cast<CallExpr>(Base)) 1740 return CE->getCallReturnType()->isRecordType(); 1741 1742 // We can't devirtualize the call. 1743 return false; 1744 } 1745 1746 static bool UseVirtualCall(ASTContext &Context, 1747 const CXXOperatorCallExpr *CE, 1748 const CXXMethodDecl *MD) { 1749 if (!MD->isVirtual()) 1750 return false; 1751 1752 // When building with -fapple-kext, all calls must go through the vtable since 1753 // the kernel linker can do runtime patching of vtables. 1754 if (Context.getLangOptions().AppleKext) 1755 return true; 1756 1757 return !canDevirtualizeMemberFunctionCall(CE->getArg(0), MD); 1758 } 1759 1760 llvm::Value * 1761 CodeGenFunction::EmitCXXOperatorMemberCallee(const CXXOperatorCallExpr *E, 1762 const CXXMethodDecl *MD, 1763 llvm::Value *This) { 1764 const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>(); 1765 const llvm::Type *Ty = 1766 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 1767 FPT->isVariadic()); 1768 1769 if (UseVirtualCall(getContext(), E, MD)) 1770 return BuildVirtualCall(MD, This, Ty); 1771 1772 return CGM.GetAddrOfFunction(MD, Ty); 1773 } 1774