CGCXX.cpp revision 5ec2e7ccb08b2a1598f12b2c6f59c6f31d035b5b
1//===--- CGDecl.cpp - Emit LLVM Code for declarations ---------------------===// 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. 11// 12//===----------------------------------------------------------------------===// 13 14// We might split this into multiple files if it gets too unwieldy 15 16#include "CodeGenFunction.h" 17#include "CodeGenModule.h" 18#include "Mangle.h" 19#include "clang/AST/ASTContext.h" 20#include "clang/AST/RecordLayout.h" 21#include "clang/AST/Decl.h" 22#include "clang/AST/DeclCXX.h" 23#include "clang/AST/DeclObjC.h" 24#include "clang/AST/StmtCXX.h" 25#include "llvm/ADT/StringExtras.h" 26using namespace clang; 27using namespace CodeGen; 28 29void 30CodeGenFunction::EmitCXXGlobalDtorRegistration(llvm::Constant *DtorFn, 31 llvm::Constant *DeclPtr) { 32 const llvm::Type *Int8PtrTy = 33 llvm::Type::getInt8Ty(VMContext)->getPointerTo(); 34 35 std::vector<const llvm::Type *> Params; 36 Params.push_back(Int8PtrTy); 37 38 // Get the destructor function type 39 const llvm::Type *DtorFnTy = 40 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), Params, false); 41 DtorFnTy = llvm::PointerType::getUnqual(DtorFnTy); 42 43 Params.clear(); 44 Params.push_back(DtorFnTy); 45 Params.push_back(Int8PtrTy); 46 Params.push_back(Int8PtrTy); 47 48 // Get the __cxa_atexit function type 49 // extern "C" int __cxa_atexit ( void (*f)(void *), void *p, void *d ); 50 const llvm::FunctionType *AtExitFnTy = 51 llvm::FunctionType::get(ConvertType(getContext().IntTy), Params, false); 52 53 llvm::Constant *AtExitFn = CGM.CreateRuntimeFunction(AtExitFnTy, 54 "__cxa_atexit"); 55 56 llvm::Constant *Handle = CGM.CreateRuntimeVariable(Int8PtrTy, 57 "__dso_handle"); 58 llvm::Value *Args[3] = { llvm::ConstantExpr::getBitCast(DtorFn, DtorFnTy), 59 llvm::ConstantExpr::getBitCast(DeclPtr, Int8PtrTy), 60 llvm::ConstantExpr::getBitCast(Handle, Int8PtrTy) }; 61 Builder.CreateCall(AtExitFn, &Args[0], llvm::array_endof(Args)); 62} 63 64void 65CodeGenModule::EmitCXXGlobalInitFunc() { 66 if (CXXGlobalInits.empty()) 67 return; 68 69 const llvm::FunctionType *FTy 70 = llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), 71 false); 72 73 // Create our global initialization function. 74 // FIXME: Should this be tweakable by targets? 75 llvm::Function *Fn = 76 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage, 77 "__cxx_global_initialization", &TheModule); 78 79 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, 80 &CXXGlobalInits[0], 81 CXXGlobalInits.size()); 82 AddGlobalCtor(Fn); 83} 84 85void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn, 86 const VarDecl **Decls, 87 unsigned NumDecls) { 88 StartFunction(GlobalDecl(), getContext().VoidTy, Fn, FunctionArgList(), 89 SourceLocation()); 90 91 for (unsigned i = 0; i != NumDecls; ++i) { 92 const VarDecl *D = Decls[i]; 93 94 llvm::Constant *DeclPtr = CGM.GetAddrOfGlobalVar(D); 95 EmitCXXGlobalVarDeclInit(*D, DeclPtr); 96 } 97 FinishFunction(); 98} 99 100void 101CodeGenFunction::EmitStaticCXXBlockVarDeclInit(const VarDecl &D, 102 llvm::GlobalVariable *GV) { 103 // FIXME: This should use __cxa_guard_{acquire,release}? 104 105 assert(!getContext().getLangOptions().ThreadsafeStatics && 106 "thread safe statics are currently not supported!"); 107 108 llvm::SmallString<256> GuardVName; 109 CGM.getMangleContext().mangleGuardVariable(&D, GuardVName); 110 111 // Create the guard variable. 112 llvm::GlobalValue *GuardV = 113 new llvm::GlobalVariable(CGM.getModule(), llvm::Type::getInt64Ty(VMContext), 114 false, GV->getLinkage(), 115 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)), 116 GuardVName.str()); 117 118 // Load the first byte of the guard variable. 119 const llvm::Type *PtrTy 120 = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 0); 121 llvm::Value *V = Builder.CreateLoad(Builder.CreateBitCast(GuardV, PtrTy), 122 "tmp"); 123 124 // Compare it against 0. 125 llvm::Value *nullValue 126 = llvm::Constant::getNullValue(llvm::Type::getInt8Ty(VMContext)); 127 llvm::Value *ICmp = Builder.CreateICmpEQ(V, nullValue , "tobool"); 128 129 llvm::BasicBlock *InitBlock = createBasicBlock("init"); 130 llvm::BasicBlock *EndBlock = createBasicBlock("init.end"); 131 132 // If the guard variable is 0, jump to the initializer code. 133 Builder.CreateCondBr(ICmp, InitBlock, EndBlock); 134 135 EmitBlock(InitBlock); 136 137 EmitCXXGlobalVarDeclInit(D, GV); 138 139 Builder.CreateStore(llvm::ConstantInt::get(llvm::Type::getInt8Ty(VMContext), 140 1), 141 Builder.CreateBitCast(GuardV, PtrTy)); 142 143 EmitBlock(EndBlock); 144} 145 146RValue CodeGenFunction::EmitCXXMemberCall(const CXXMethodDecl *MD, 147 llvm::Value *Callee, 148 llvm::Value *This, 149 CallExpr::const_arg_iterator ArgBeg, 150 CallExpr::const_arg_iterator ArgEnd) { 151 assert(MD->isInstance() && 152 "Trying to emit a member call expr on a static method!"); 153 154 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 155 156 CallArgList Args; 157 158 // Push the this ptr. 159 Args.push_back(std::make_pair(RValue::get(This), 160 MD->getThisType(getContext()))); 161 162 // And the rest of the call args 163 EmitCallArgs(Args, FPT, ArgBeg, ArgEnd); 164 165 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType(); 166 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), 167 Callee, Args, MD); 168} 169 170/// canDevirtualizeMemberFunctionCalls - Checks whether virtual calls on given 171/// expr can be devirtualized. 172static bool canDevirtualizeMemberFunctionCalls(const Expr *Base) { 173 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Base)) { 174 if (const VarDecl *VD = dyn_cast<VarDecl>(DRE->getDecl())) { 175 // This is a record decl. We know the type and can devirtualize it. 176 return VD->getType()->isRecordType(); 177 } 178 179 return false; 180 } 181 182 // We can always devirtualize calls on temporary object expressions. 183 if (isa<CXXTemporaryObjectExpr>(Base)) 184 return true; 185 186 // And calls on bound temporaries. 187 if (isa<CXXBindTemporaryExpr>(Base)) 188 return true; 189 190 // Check if this is a call expr that returns a record type. 191 if (const CallExpr *CE = dyn_cast<CallExpr>(Base)) 192 return CE->getCallReturnType()->isRecordType(); 193 194 // We can't devirtualize the call. 195 return false; 196} 197 198RValue CodeGenFunction::EmitCXXMemberCallExpr(const CXXMemberCallExpr *CE) { 199 if (isa<BinaryOperator>(CE->getCallee()->IgnoreParens())) 200 return EmitCXXMemberPointerCallExpr(CE); 201 202 const MemberExpr *ME = cast<MemberExpr>(CE->getCallee()->IgnoreParens()); 203 const CXXMethodDecl *MD = cast<CXXMethodDecl>(ME->getMemberDecl()); 204 205 if (MD->isStatic()) { 206 // The method is static, emit it as we would a regular call. 207 llvm::Value *Callee = CGM.GetAddrOfFunction(MD); 208 return EmitCall(Callee, getContext().getPointerType(MD->getType()), 209 CE->arg_begin(), CE->arg_end(), 0); 210 211 } 212 213 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 214 215 const llvm::Type *Ty = 216 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 217 FPT->isVariadic()); 218 llvm::Value *This; 219 220 if (ME->isArrow()) 221 This = EmitScalarExpr(ME->getBase()); 222 else { 223 LValue BaseLV = EmitLValue(ME->getBase()); 224 This = BaseLV.getAddress(); 225 } 226 227 if (MD->isCopyAssignment() && MD->isTrivial()) { 228 // We don't like to generate the trivial copy assignment operator when 229 // it isn't necessary; just produce the proper effect here. 230 llvm::Value *RHS = EmitLValue(*CE->arg_begin()).getAddress(); 231 EmitAggregateCopy(This, RHS, CE->getType()); 232 return RValue::get(This); 233 } 234 235 // C++ [class.virtual]p12: 236 // Explicit qualification with the scope operator (5.1) suppresses the 237 // virtual call mechanism. 238 // 239 // We also don't emit a virtual call if the base expression has a record type 240 // because then we know what the type is. 241 llvm::Value *Callee; 242 if (const CXXDestructorDecl *Destructor 243 = dyn_cast<CXXDestructorDecl>(MD)) { 244 if (Destructor->isTrivial()) 245 return RValue::get(0); 246 if (MD->isVirtual() && !ME->hasQualifier() && 247 !canDevirtualizeMemberFunctionCalls(ME->getBase())) { 248 Callee = BuildVirtualCall(Destructor, Dtor_Complete, This, Ty); 249 } else { 250 Callee = CGM.GetAddrOfFunction(GlobalDecl(Destructor, Dtor_Complete), Ty); 251 } 252 } else if (MD->isVirtual() && !ME->hasQualifier() && 253 !canDevirtualizeMemberFunctionCalls(ME->getBase())) { 254 Callee = BuildVirtualCall(MD, This, Ty); 255 } else { 256 Callee = CGM.GetAddrOfFunction(MD, Ty); 257 } 258 259 return EmitCXXMemberCall(MD, Callee, This, 260 CE->arg_begin(), CE->arg_end()); 261} 262 263RValue 264CodeGenFunction::EmitCXXMemberPointerCallExpr(const CXXMemberCallExpr *E) { 265 const BinaryOperator *BO = 266 cast<BinaryOperator>(E->getCallee()->IgnoreParens()); 267 const Expr *BaseExpr = BO->getLHS(); 268 const Expr *MemFnExpr = BO->getRHS(); 269 270 const MemberPointerType *MPT = 271 MemFnExpr->getType()->getAs<MemberPointerType>(); 272 const FunctionProtoType *FPT = 273 MPT->getPointeeType()->getAs<FunctionProtoType>(); 274 const CXXRecordDecl *RD = 275 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 276 277 const llvm::FunctionType *FTy = 278 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT), 279 FPT->isVariadic()); 280 281 const llvm::Type *Int8PtrTy = 282 llvm::Type::getInt8Ty(VMContext)->getPointerTo(); 283 284 // Get the member function pointer. 285 llvm::Value *MemFnPtr = 286 CreateTempAlloca(ConvertType(MemFnExpr->getType()), "mem.fn"); 287 EmitAggExpr(MemFnExpr, MemFnPtr, /*VolatileDest=*/false); 288 289 // Emit the 'this' pointer. 290 llvm::Value *This; 291 292 if (BO->getOpcode() == BinaryOperator::PtrMemI) 293 This = EmitScalarExpr(BaseExpr); 294 else 295 This = EmitLValue(BaseExpr).getAddress(); 296 297 // Adjust it. 298 llvm::Value *Adj = Builder.CreateStructGEP(MemFnPtr, 1); 299 Adj = Builder.CreateLoad(Adj, "mem.fn.adj"); 300 301 llvm::Value *Ptr = Builder.CreateBitCast(This, Int8PtrTy, "ptr"); 302 Ptr = Builder.CreateGEP(Ptr, Adj, "adj"); 303 304 This = Builder.CreateBitCast(Ptr, This->getType(), "this"); 305 306 llvm::Value *FnPtr = Builder.CreateStructGEP(MemFnPtr, 0, "mem.fn.ptr"); 307 308 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType()); 309 310 llvm::Value *FnAsInt = Builder.CreateLoad(FnPtr, "fn"); 311 312 // If the LSB in the function pointer is 1, the function pointer points to 313 // a virtual function. 314 llvm::Value *IsVirtual 315 = Builder.CreateAnd(FnAsInt, llvm::ConstantInt::get(PtrDiffTy, 1), 316 "and"); 317 318 IsVirtual = Builder.CreateTrunc(IsVirtual, 319 llvm::Type::getInt1Ty(VMContext)); 320 321 llvm::BasicBlock *FnVirtual = createBasicBlock("fn.virtual"); 322 llvm::BasicBlock *FnNonVirtual = createBasicBlock("fn.nonvirtual"); 323 llvm::BasicBlock *FnEnd = createBasicBlock("fn.end"); 324 325 Builder.CreateCondBr(IsVirtual, FnVirtual, FnNonVirtual); 326 EmitBlock(FnVirtual); 327 328 const llvm::Type *VTableTy = 329 FTy->getPointerTo()->getPointerTo()->getPointerTo(); 330 331 llvm::Value *VTable = Builder.CreateBitCast(This, VTableTy); 332 VTable = Builder.CreateLoad(VTable); 333 334 VTable = Builder.CreateGEP(VTable, FnAsInt, "fn"); 335 336 // Since the function pointer is 1 plus the virtual table offset, we 337 // subtract 1 by using a GEP. 338 VTable = Builder.CreateConstGEP1_64(VTable, (uint64_t)-1); 339 340 llvm::Value *VirtualFn = Builder.CreateLoad(VTable, "virtualfn"); 341 342 EmitBranch(FnEnd); 343 EmitBlock(FnNonVirtual); 344 345 // If the function is not virtual, just load the pointer. 346 llvm::Value *NonVirtualFn = Builder.CreateLoad(FnPtr, "fn"); 347 NonVirtualFn = Builder.CreateIntToPtr(NonVirtualFn, FTy->getPointerTo()); 348 349 EmitBlock(FnEnd); 350 351 llvm::PHINode *Callee = Builder.CreatePHI(FTy->getPointerTo()); 352 Callee->reserveOperandSpace(2); 353 Callee->addIncoming(VirtualFn, FnVirtual); 354 Callee->addIncoming(NonVirtualFn, FnNonVirtual); 355 356 CallArgList Args; 357 358 QualType ThisType = 359 getContext().getPointerType(getContext().getTagDeclType(RD)); 360 361 // Push the this ptr. 362 Args.push_back(std::make_pair(RValue::get(This), ThisType)); 363 364 // And the rest of the call args 365 EmitCallArgs(Args, FPT, E->arg_begin(), E->arg_end()); 366 QualType ResultType = BO->getType()->getAs<FunctionType>()->getResultType(); 367 return EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), 368 Callee, Args, 0); 369} 370 371RValue 372CodeGenFunction::EmitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *E, 373 const CXXMethodDecl *MD) { 374 assert(MD->isInstance() && 375 "Trying to emit a member call expr on a static method!"); 376 377 if (MD->isCopyAssignment()) { 378 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(MD->getDeclContext()); 379 if (ClassDecl->hasTrivialCopyAssignment()) { 380 assert(!ClassDecl->hasUserDeclaredCopyAssignment() && 381 "EmitCXXOperatorMemberCallExpr - user declared copy assignment"); 382 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress(); 383 llvm::Value *Src = EmitLValue(E->getArg(1)).getAddress(); 384 QualType Ty = E->getType(); 385 EmitAggregateCopy(This, Src, Ty); 386 return RValue::get(This); 387 } 388 } 389 390 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 391 const llvm::Type *Ty = 392 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 393 FPT->isVariadic()); 394 395 llvm::Value *This = EmitLValue(E->getArg(0)).getAddress(); 396 397 llvm::Value *Callee; 398 if (MD->isVirtual() && !canDevirtualizeMemberFunctionCalls(E->getArg(0))) 399 Callee = BuildVirtualCall(MD, This, Ty); 400 else 401 Callee = CGM.GetAddrOfFunction(MD, Ty); 402 403 return EmitCXXMemberCall(MD, Callee, This, 404 E->arg_begin() + 1, E->arg_end()); 405} 406 407llvm::Value *CodeGenFunction::LoadCXXThis() { 408 assert(isa<CXXMethodDecl>(CurFuncDecl) && 409 "Must be in a C++ member function decl to load 'this'"); 410 assert(cast<CXXMethodDecl>(CurFuncDecl)->isInstance() && 411 "Must be in a C++ member function decl to load 'this'"); 412 413 // FIXME: What if we're inside a block? 414 // ans: See how CodeGenFunction::LoadObjCSelf() uses 415 // CodeGenFunction::BlockForwardSelf() for how to do this. 416 return Builder.CreateLoad(LocalDeclMap[CXXThisDecl], "this"); 417} 418 419/// EmitCXXAggrConstructorCall - This routine essentially creates a (nested) 420/// for-loop to call the default constructor on individual members of the 421/// array. 422/// 'D' is the default constructor for elements of the array, 'ArrayTy' is the 423/// array type and 'ArrayPtr' points to the beginning fo the array. 424/// It is assumed that all relevant checks have been made by the caller. 425void 426CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 427 const ConstantArrayType *ArrayTy, 428 llvm::Value *ArrayPtr, 429 CallExpr::const_arg_iterator ArgBeg, 430 CallExpr::const_arg_iterator ArgEnd) { 431 432 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 433 llvm::Value * NumElements = 434 llvm::ConstantInt::get(SizeTy, 435 getContext().getConstantArrayElementCount(ArrayTy)); 436 437 EmitCXXAggrConstructorCall(D, NumElements, ArrayPtr, ArgBeg, ArgEnd); 438} 439 440void 441CodeGenFunction::EmitCXXAggrConstructorCall(const CXXConstructorDecl *D, 442 llvm::Value *NumElements, 443 llvm::Value *ArrayPtr, 444 CallExpr::const_arg_iterator ArgBeg, 445 CallExpr::const_arg_iterator ArgEnd) { 446 const llvm::Type *SizeTy = ConvertType(getContext().getSizeType()); 447 448 // Create a temporary for the loop index and initialize it with 0. 449 llvm::Value *IndexPtr = CreateTempAlloca(SizeTy, "loop.index"); 450 llvm::Value *Zero = llvm::Constant::getNullValue(SizeTy); 451 Builder.CreateStore(Zero, IndexPtr); 452 453 // Start the loop with a block that tests the condition. 454 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 455 llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); 456 457 EmitBlock(CondBlock); 458 459 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 460 461 // Generate: if (loop-index < number-of-elements fall to the loop body, 462 // otherwise, go to the block after the for-loop. 463 llvm::Value *Counter = Builder.CreateLoad(IndexPtr); 464 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElements, "isless"); 465 // If the condition is true, execute the body. 466 Builder.CreateCondBr(IsLess, ForBody, AfterFor); 467 468 EmitBlock(ForBody); 469 470 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc"); 471 // Inside the loop body, emit the constructor call on the array element. 472 Counter = Builder.CreateLoad(IndexPtr); 473 llvm::Value *Address = Builder.CreateInBoundsGEP(ArrayPtr, Counter, 474 "arrayidx"); 475 476 // C++ [class.temporary]p4: 477 // There are two contexts in which temporaries are destroyed at a different 478 // point than the end of the full-expression. The first context is when a 479 // default constructor is called to initialize an element of an array. 480 // If the constructor has one or more default arguments, the destruction of 481 // every temporary created in a default argument expression is sequenced 482 // before the construction of the next array element, if any. 483 484 // Keep track of the current number of live temporaries. 485 unsigned OldNumLiveTemporaries = LiveTemporaries.size(); 486 487 EmitCXXConstructorCall(D, Ctor_Complete, Address, ArgBeg, ArgEnd); 488 489 // Pop temporaries. 490 while (LiveTemporaries.size() > OldNumLiveTemporaries) 491 PopCXXTemporary(); 492 493 EmitBlock(ContinueBlock); 494 495 // Emit the increment of the loop counter. 496 llvm::Value *NextVal = llvm::ConstantInt::get(SizeTy, 1); 497 Counter = Builder.CreateLoad(IndexPtr); 498 NextVal = Builder.CreateAdd(Counter, NextVal, "inc"); 499 Builder.CreateStore(NextVal, IndexPtr); 500 501 // Finally, branch back up to the condition for the next iteration. 502 EmitBranch(CondBlock); 503 504 // Emit the fall-through block. 505 EmitBlock(AfterFor, true); 506} 507 508/// EmitCXXAggrDestructorCall - calls the default destructor on array 509/// elements in reverse order of construction. 510void 511CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D, 512 const ArrayType *Array, 513 llvm::Value *This) { 514 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array); 515 assert(CA && "Do we support VLA for destruction ?"); 516 uint64_t ElementCount = getContext().getConstantArrayElementCount(CA); 517 llvm::Value* ElementCountPtr = 518 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), ElementCount); 519 EmitCXXAggrDestructorCall(D, ElementCountPtr, This); 520} 521 522/// EmitCXXAggrDestructorCall - calls the default destructor on array 523/// elements in reverse order of construction. 524void 525CodeGenFunction::EmitCXXAggrDestructorCall(const CXXDestructorDecl *D, 526 llvm::Value *UpperCount, 527 llvm::Value *This) { 528 llvm::Value *One = llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), 529 1); 530 // Create a temporary for the loop index and initialize it with count of 531 // array elements. 532 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext), 533 "loop.index"); 534 // Index = ElementCount; 535 Builder.CreateStore(UpperCount, IndexPtr); 536 537 // Start the loop with a block that tests the condition. 538 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 539 llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); 540 541 EmitBlock(CondBlock); 542 543 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 544 545 // Generate: if (loop-index != 0 fall to the loop body, 546 // otherwise, go to the block after the for-loop. 547 llvm::Value* zeroConstant = 548 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)); 549 llvm::Value *Counter = Builder.CreateLoad(IndexPtr); 550 llvm::Value *IsNE = Builder.CreateICmpNE(Counter, zeroConstant, 551 "isne"); 552 // If the condition is true, execute the body. 553 Builder.CreateCondBr(IsNE, ForBody, AfterFor); 554 555 EmitBlock(ForBody); 556 557 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc"); 558 // Inside the loop body, emit the constructor call on the array element. 559 Counter = Builder.CreateLoad(IndexPtr); 560 Counter = Builder.CreateSub(Counter, One); 561 llvm::Value *Address = Builder.CreateInBoundsGEP(This, Counter, "arrayidx"); 562 EmitCXXDestructorCall(D, Dtor_Complete, Address); 563 564 EmitBlock(ContinueBlock); 565 566 // Emit the decrement of the loop counter. 567 Counter = Builder.CreateLoad(IndexPtr); 568 Counter = Builder.CreateSub(Counter, One, "dec"); 569 Builder.CreateStore(Counter, IndexPtr); 570 571 // Finally, branch back up to the condition for the next iteration. 572 EmitBranch(CondBlock); 573 574 // Emit the fall-through block. 575 EmitBlock(AfterFor, true); 576} 577 578/// GenerateCXXAggrDestructorHelper - Generates a helper function which when 579/// invoked, calls the default destructor on array elements in reverse order of 580/// construction. 581llvm::Constant * 582CodeGenFunction::GenerateCXXAggrDestructorHelper(const CXXDestructorDecl *D, 583 const ArrayType *Array, 584 llvm::Value *This) { 585 static int UniqueCount; 586 FunctionArgList Args; 587 ImplicitParamDecl *Dst = 588 ImplicitParamDecl::Create(getContext(), 0, 589 SourceLocation(), 0, 590 getContext().getPointerType(getContext().VoidTy)); 591 Args.push_back(std::make_pair(Dst, Dst->getType())); 592 593 llvm::SmallString<16> Name; 594 llvm::raw_svector_ostream(Name) << "__tcf_" << (++UniqueCount); 595 QualType R = getContext().VoidTy; 596 const CGFunctionInfo &FI = CGM.getTypes().getFunctionInfo(R, Args); 597 const llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI, false); 598 llvm::Function *Fn = 599 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage, 600 Name.c_str(), 601 &CGM.getModule()); 602 IdentifierInfo *II 603 = &CGM.getContext().Idents.get(Name.c_str()); 604 FunctionDecl *FD = FunctionDecl::Create(getContext(), 605 getContext().getTranslationUnitDecl(), 606 SourceLocation(), II, R, 0, 607 FunctionDecl::Static, 608 false, true); 609 StartFunction(FD, R, Fn, Args, SourceLocation()); 610 QualType BaseElementTy = getContext().getBaseElementType(Array); 611 const llvm::Type *BasePtr = ConvertType(BaseElementTy); 612 BasePtr = llvm::PointerType::getUnqual(BasePtr); 613 llvm::Value *BaseAddrPtr = Builder.CreateBitCast(This, BasePtr); 614 EmitCXXAggrDestructorCall(D, Array, BaseAddrPtr); 615 FinishFunction(); 616 llvm::Type *Ptr8Ty = llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext), 617 0); 618 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty); 619 return m; 620} 621 622void 623CodeGenFunction::EmitCXXConstructorCall(const CXXConstructorDecl *D, 624 CXXCtorType Type, 625 llvm::Value *This, 626 CallExpr::const_arg_iterator ArgBeg, 627 CallExpr::const_arg_iterator ArgEnd) { 628 if (D->isCopyConstructor(getContext())) { 629 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(D->getDeclContext()); 630 if (ClassDecl->hasTrivialCopyConstructor()) { 631 assert(!ClassDecl->hasUserDeclaredCopyConstructor() && 632 "EmitCXXConstructorCall - user declared copy constructor"); 633 const Expr *E = (*ArgBeg); 634 QualType Ty = E->getType(); 635 llvm::Value *Src = EmitLValue(E).getAddress(); 636 EmitAggregateCopy(This, Src, Ty); 637 return; 638 } 639 } else if (D->isTrivial()) { 640 // FIXME: Track down why we're trying to generate calls to the trivial 641 // default constructor! 642 return; 643 } 644 645 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(D, Type); 646 647 EmitCXXMemberCall(D, Callee, This, ArgBeg, ArgEnd); 648} 649 650void CodeGenFunction::EmitCXXDestructorCall(const CXXDestructorDecl *DD, 651 CXXDtorType Type, 652 llvm::Value *This) { 653 llvm::Value *Callee = CGM.GetAddrOfCXXDestructor(DD, Type); 654 655 CallArgList Args; 656 657 // Push the this ptr. 658 Args.push_back(std::make_pair(RValue::get(This), 659 DD->getThisType(getContext()))); 660 661 // Add a VTT parameter if necessary. 662 // FIXME: This should not be a dummy null parameter! 663 if (Type == Dtor_Base && DD->getParent()->getNumVBases() != 0) { 664 QualType T = getContext().getPointerType(getContext().VoidPtrTy); 665 666 Args.push_back(std::make_pair(RValue::get(CGM.EmitNullConstant(T)), T)); 667 } 668 669 // FIXME: We should try to share this code with EmitCXXMemberCall. 670 671 QualType ResultType = DD->getType()->getAs<FunctionType>()->getResultType(); 672 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, Args), Callee, Args, DD); 673} 674 675void 676CodeGenFunction::EmitCXXConstructExpr(llvm::Value *Dest, 677 const CXXConstructExpr *E) { 678 assert(Dest && "Must have a destination!"); 679 const CXXConstructorDecl *CD = E->getConstructor(); 680 const ConstantArrayType *Array = 681 getContext().getAsConstantArrayType(E->getType()); 682 // For a copy constructor, even if it is trivial, must fall thru so 683 // its argument is code-gen'ed. 684 if (!CD->isCopyConstructor(getContext())) { 685 QualType InitType = E->getType(); 686 if (Array) 687 InitType = getContext().getBaseElementType(Array); 688 const CXXRecordDecl *RD = 689 cast<CXXRecordDecl>(InitType->getAs<RecordType>()->getDecl()); 690 if (RD->hasTrivialConstructor()) 691 return; 692 } 693 // Code gen optimization to eliminate copy constructor and return 694 // its first argument instead. 695 if (getContext().getLangOptions().ElideConstructors && E->isElidable()) { 696 const Expr *Arg = E->getArg(0); 697 698 if (const CXXBindTemporaryExpr *BindExpr = 699 dyn_cast<CXXBindTemporaryExpr>(Arg)) 700 Arg = BindExpr->getSubExpr(); 701 702 EmitAggExpr(Arg, Dest, false); 703 return; 704 } 705 if (Array) { 706 QualType BaseElementTy = getContext().getBaseElementType(Array); 707 const llvm::Type *BasePtr = ConvertType(BaseElementTy); 708 BasePtr = llvm::PointerType::getUnqual(BasePtr); 709 llvm::Value *BaseAddrPtr = 710 Builder.CreateBitCast(Dest, BasePtr); 711 EmitCXXAggrConstructorCall(CD, Array, BaseAddrPtr, 712 E->arg_begin(), E->arg_end()); 713 } 714 else 715 // Call the constructor. 716 EmitCXXConstructorCall(CD, Ctor_Complete, Dest, 717 E->arg_begin(), E->arg_end()); 718} 719 720void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) { 721 EmitGlobal(GlobalDecl(D, Ctor_Complete)); 722 EmitGlobal(GlobalDecl(D, Ctor_Base)); 723} 724 725void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D, 726 CXXCtorType Type) { 727 728 llvm::Function *Fn = GetAddrOfCXXConstructor(D, Type); 729 730 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn); 731 732 SetFunctionDefinitionAttributes(D, Fn); 733 SetLLVMFunctionAttributesForDefinition(D, Fn); 734} 735 736llvm::Function * 737CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D, 738 CXXCtorType Type) { 739 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>(); 740 const llvm::FunctionType *FTy = 741 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), 742 FPT->isVariadic()); 743 744 const char *Name = getMangledCXXCtorName(D, Type); 745 return cast<llvm::Function>( 746 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type))); 747} 748 749const char *CodeGenModule::getMangledCXXCtorName(const CXXConstructorDecl *D, 750 CXXCtorType Type) { 751 llvm::SmallString<256> Name; 752 getMangleContext().mangleCXXCtor(D, Type, Name); 753 754 Name += '\0'; 755 return UniqueMangledName(Name.begin(), Name.end()); 756} 757 758void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) { 759 if (D->isVirtual()) 760 EmitGlobalDefinition(GlobalDecl(D, Dtor_Deleting)); 761 EmitGlobalDefinition(GlobalDecl(D, Dtor_Complete)); 762 EmitGlobalDefinition(GlobalDecl(D, Dtor_Base)); 763} 764 765void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D, 766 CXXDtorType Type) { 767 llvm::Function *Fn = GetAddrOfCXXDestructor(D, Type); 768 769 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn); 770 771 SetFunctionDefinitionAttributes(D, Fn); 772 SetLLVMFunctionAttributesForDefinition(D, Fn); 773} 774 775llvm::Function * 776CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D, 777 CXXDtorType Type) { 778 const llvm::FunctionType *FTy = 779 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false); 780 781 const char *Name = getMangledCXXDtorName(D, Type); 782 return cast<llvm::Function>( 783 GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type))); 784} 785 786const char *CodeGenModule::getMangledCXXDtorName(const CXXDestructorDecl *D, 787 CXXDtorType Type) { 788 llvm::SmallString<256> Name; 789 getMangleContext().mangleCXXDtor(D, Type, Name); 790 791 Name += '\0'; 792 return UniqueMangledName(Name.begin(), Name.end()); 793} 794 795llvm::Constant * 796CodeGenFunction::GenerateThunk(llvm::Function *Fn, GlobalDecl GD, 797 bool Extern, 798 const ThunkAdjustment &ThisAdjustment) { 799 return GenerateCovariantThunk(Fn, GD, Extern, 800 CovariantThunkAdjustment(ThisAdjustment, 801 ThunkAdjustment())); 802} 803 804llvm::Value * 805CodeGenFunction::DynamicTypeAdjust(llvm::Value *V, 806 const ThunkAdjustment &Adjustment) { 807 const llvm::Type *Int8PtrTy = llvm::Type::getInt8PtrTy(VMContext); 808 809 const llvm::Type *OrigTy = V->getType(); 810 if (Adjustment.NonVirtual) { 811 // Do the non-virtual adjustment 812 V = Builder.CreateBitCast(V, Int8PtrTy); 813 V = Builder.CreateConstInBoundsGEP1_64(V, Adjustment.NonVirtual); 814 V = Builder.CreateBitCast(V, OrigTy); 815 } 816 817 if (!Adjustment.Virtual) 818 return V; 819 820 assert(Adjustment.Virtual % (LLVMPointerWidth / 8) == 0 && 821 "vtable entry unaligned"); 822 823 // Do the virtual this adjustment 824 const llvm::Type *PtrDiffTy = ConvertType(getContext().getPointerDiffType()); 825 const llvm::Type *PtrDiffPtrTy = PtrDiffTy->getPointerTo(); 826 827 llvm::Value *ThisVal = Builder.CreateBitCast(V, Int8PtrTy); 828 V = Builder.CreateBitCast(V, PtrDiffPtrTy->getPointerTo()); 829 V = Builder.CreateLoad(V, "vtable"); 830 831 llvm::Value *VTablePtr = V; 832 uint64_t VirtualAdjustment = Adjustment.Virtual / (LLVMPointerWidth / 8); 833 V = Builder.CreateConstInBoundsGEP1_64(VTablePtr, VirtualAdjustment); 834 V = Builder.CreateLoad(V); 835 V = Builder.CreateGEP(ThisVal, V); 836 837 return Builder.CreateBitCast(V, OrigTy); 838} 839 840llvm::Constant * 841CodeGenFunction::GenerateCovariantThunk(llvm::Function *Fn, 842 GlobalDecl GD, bool Extern, 843 const CovariantThunkAdjustment &Adjustment) { 844 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 845 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType(); 846 847 FunctionArgList Args; 848 ImplicitParamDecl *ThisDecl = 849 ImplicitParamDecl::Create(getContext(), 0, SourceLocation(), 0, 850 MD->getThisType(getContext())); 851 Args.push_back(std::make_pair(ThisDecl, ThisDecl->getType())); 852 for (FunctionDecl::param_const_iterator i = MD->param_begin(), 853 e = MD->param_end(); 854 i != e; ++i) { 855 ParmVarDecl *D = *i; 856 Args.push_back(std::make_pair(D, D->getType())); 857 } 858 IdentifierInfo *II 859 = &CGM.getContext().Idents.get("__thunk_named_foo_"); 860 FunctionDecl *FD = FunctionDecl::Create(getContext(), 861 getContext().getTranslationUnitDecl(), 862 SourceLocation(), II, ResultType, 0, 863 Extern 864 ? FunctionDecl::Extern 865 : FunctionDecl::Static, 866 false, true); 867 StartFunction(FD, ResultType, Fn, Args, SourceLocation()); 868 869 // generate body 870 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 871 const llvm::Type *Ty = 872 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 873 FPT->isVariadic()); 874 llvm::Value *Callee = CGM.GetAddrOfFunction(GD, Ty); 875 876 CallArgList CallArgs; 877 878 bool ShouldAdjustReturnPointer = true; 879 QualType ArgType = MD->getThisType(getContext()); 880 llvm::Value *Arg = Builder.CreateLoad(LocalDeclMap[ThisDecl], "this"); 881 if (!Adjustment.ThisAdjustment.isEmpty()) { 882 // Do the this adjustment. 883 const llvm::Type *OrigTy = Callee->getType(); 884 Arg = DynamicTypeAdjust(Arg, Adjustment.ThisAdjustment); 885 886 if (!Adjustment.ReturnAdjustment.isEmpty()) { 887 const CovariantThunkAdjustment &ReturnAdjustment = 888 CovariantThunkAdjustment(ThunkAdjustment(), 889 Adjustment.ReturnAdjustment); 890 891 Callee = CGM.BuildCovariantThunk(GD, Extern, ReturnAdjustment); 892 893 Callee = Builder.CreateBitCast(Callee, OrigTy); 894 ShouldAdjustReturnPointer = false; 895 } 896 } 897 898 CallArgs.push_back(std::make_pair(RValue::get(Arg), ArgType)); 899 900 for (FunctionDecl::param_const_iterator i = MD->param_begin(), 901 e = MD->param_end(); 902 i != e; ++i) { 903 ParmVarDecl *D = *i; 904 QualType ArgType = D->getType(); 905 906 // llvm::Value *Arg = CGF.GetAddrOfLocalVar(Dst); 907 Expr *Arg = new (getContext()) DeclRefExpr(D, ArgType.getNonReferenceType(), 908 SourceLocation()); 909 CallArgs.push_back(std::make_pair(EmitCallArg(Arg, ArgType), ArgType)); 910 } 911 912 RValue RV = EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs), 913 Callee, CallArgs, MD); 914 if (ShouldAdjustReturnPointer && !Adjustment.ReturnAdjustment.isEmpty()) { 915 bool CanBeZero = !(ResultType->isReferenceType() 916 // FIXME: attr nonnull can't be zero either 917 /* || ResultType->hasAttr<NonNullAttr>() */ ); 918 // Do the return result adjustment. 919 if (CanBeZero) { 920 llvm::BasicBlock *NonZeroBlock = createBasicBlock(); 921 llvm::BasicBlock *ZeroBlock = createBasicBlock(); 922 llvm::BasicBlock *ContBlock = createBasicBlock(); 923 924 const llvm::Type *Ty = RV.getScalarVal()->getType(); 925 llvm::Value *Zero = llvm::Constant::getNullValue(Ty); 926 Builder.CreateCondBr(Builder.CreateICmpNE(RV.getScalarVal(), Zero), 927 NonZeroBlock, ZeroBlock); 928 EmitBlock(NonZeroBlock); 929 llvm::Value *NZ = 930 DynamicTypeAdjust(RV.getScalarVal(), Adjustment.ReturnAdjustment); 931 EmitBranch(ContBlock); 932 EmitBlock(ZeroBlock); 933 llvm::Value *Z = RV.getScalarVal(); 934 EmitBlock(ContBlock); 935 llvm::PHINode *RVOrZero = Builder.CreatePHI(Ty); 936 RVOrZero->reserveOperandSpace(2); 937 RVOrZero->addIncoming(NZ, NonZeroBlock); 938 RVOrZero->addIncoming(Z, ZeroBlock); 939 RV = RValue::get(RVOrZero); 940 } else 941 RV = RValue::get(DynamicTypeAdjust(RV.getScalarVal(), 942 Adjustment.ReturnAdjustment)); 943 } 944 945 if (!ResultType->isVoidType()) 946 EmitReturnOfRValue(RV, ResultType); 947 948 FinishFunction(); 949 return Fn; 950} 951 952llvm::Constant * 953CodeGenModule::GetAddrOfThunk(GlobalDecl GD, 954 const ThunkAdjustment &ThisAdjustment) { 955 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 956 957 // Compute mangled name 958 llvm::SmallString<256> OutName; 959 if (const CXXDestructorDecl* DD = dyn_cast<CXXDestructorDecl>(MD)) 960 getMangleContext().mangleCXXDtorThunk(DD, GD.getDtorType(), ThisAdjustment, 961 OutName); 962 else 963 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName); 964 OutName += '\0'; 965 const char* Name = UniqueMangledName(OutName.begin(), OutName.end()); 966 967 // Get function for mangled name 968 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD); 969 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl()); 970} 971 972llvm::Constant * 973CodeGenModule::GetAddrOfCovariantThunk(GlobalDecl GD, 974 const CovariantThunkAdjustment &Adjustment) { 975 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 976 977 // Compute mangled name 978 llvm::SmallString<256> OutName; 979 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName); 980 OutName += '\0'; 981 const char* Name = UniqueMangledName(OutName.begin(), OutName.end()); 982 983 // Get function for mangled name 984 const llvm::Type *Ty = getTypes().GetFunctionTypeForVtable(MD); 985 return GetOrCreateLLVMFunction(Name, Ty, GlobalDecl()); 986} 987 988void CodeGenModule::BuildThunksForVirtual(GlobalDecl GD) { 989 CGVtableInfo::AdjustmentVectorTy *AdjPtr = getVtableInfo().getAdjustments(GD); 990 if (!AdjPtr) 991 return; 992 CGVtableInfo::AdjustmentVectorTy &Adj = *AdjPtr; 993 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 994 for (unsigned i = 0; i < Adj.size(); i++) { 995 GlobalDecl OGD = Adj[i].first; 996 const CXXMethodDecl *OMD = cast<CXXMethodDecl>(OGD.getDecl()); 997 QualType nc_oret = OMD->getType()->getAs<FunctionType>()->getResultType(); 998 CanQualType oret = getContext().getCanonicalType(nc_oret); 999 QualType nc_ret = MD->getType()->getAs<FunctionType>()->getResultType(); 1000 CanQualType ret = getContext().getCanonicalType(nc_ret); 1001 ThunkAdjustment ReturnAdjustment; 1002 if (oret != ret) { 1003 QualType qD = nc_ret->getPointeeType(); 1004 QualType qB = nc_oret->getPointeeType(); 1005 CXXRecordDecl *D = cast<CXXRecordDecl>(qD->getAs<RecordType>()->getDecl()); 1006 CXXRecordDecl *B = cast<CXXRecordDecl>(qB->getAs<RecordType>()->getDecl()); 1007 ReturnAdjustment = ComputeThunkAdjustment(D, B); 1008 } 1009 ThunkAdjustment ThisAdjustment = Adj[i].second; 1010 bool Extern = !cast<CXXRecordDecl>(OMD->getDeclContext())->isInAnonymousNamespace(); 1011 if (!ReturnAdjustment.isEmpty() || !ThisAdjustment.isEmpty()) { 1012 CovariantThunkAdjustment CoAdj(ThisAdjustment, ReturnAdjustment); 1013 llvm::Constant *FnConst; 1014 if (!ReturnAdjustment.isEmpty()) 1015 FnConst = GetAddrOfCovariantThunk(GD, CoAdj); 1016 else 1017 FnConst = GetAddrOfThunk(GD, ThisAdjustment); 1018 if (!isa<llvm::Function>(FnConst)) { 1019 llvm::Constant *SubExpr = 1020 cast<llvm::ConstantExpr>(FnConst)->getOperand(0); 1021 llvm::Function *OldFn = cast<llvm::Function>(SubExpr); 1022 std::string Name = OldFn->getNameStr(); 1023 GlobalDeclMap.erase(UniqueMangledName(Name.data(), 1024 Name.data() + Name.size() + 1)); 1025 llvm::Constant *NewFnConst; 1026 if (!ReturnAdjustment.isEmpty()) 1027 NewFnConst = GetAddrOfCovariantThunk(GD, CoAdj); 1028 else 1029 NewFnConst = GetAddrOfThunk(GD, ThisAdjustment); 1030 llvm::Function *NewFn = cast<llvm::Function>(NewFnConst); 1031 NewFn->takeName(OldFn); 1032 llvm::Constant *NewPtrForOldDecl = 1033 llvm::ConstantExpr::getBitCast(NewFn, OldFn->getType()); 1034 OldFn->replaceAllUsesWith(NewPtrForOldDecl); 1035 OldFn->eraseFromParent(); 1036 FnConst = NewFn; 1037 } 1038 llvm::Function *Fn = cast<llvm::Function>(FnConst); 1039 if (Fn->isDeclaration()) { 1040 llvm::GlobalVariable::LinkageTypes linktype; 1041 linktype = llvm::GlobalValue::WeakAnyLinkage; 1042 if (!Extern) 1043 linktype = llvm::GlobalValue::InternalLinkage; 1044 Fn->setLinkage(linktype); 1045 if (!Features.Exceptions && !Features.ObjCNonFragileABI) 1046 Fn->addFnAttr(llvm::Attribute::NoUnwind); 1047 Fn->setAlignment(2); 1048 CodeGenFunction(*this).GenerateCovariantThunk(Fn, GD, Extern, CoAdj); 1049 } 1050 } 1051 } 1052} 1053 1054llvm::Constant * 1055CodeGenModule::BuildThunk(GlobalDecl GD, bool Extern, 1056 const ThunkAdjustment &ThisAdjustment) { 1057 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 1058 llvm::SmallString<256> OutName; 1059 if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(MD)) { 1060 getMangleContext().mangleCXXDtorThunk(D, GD.getDtorType(), ThisAdjustment, 1061 OutName); 1062 } else 1063 getMangleContext().mangleThunk(MD, ThisAdjustment, OutName); 1064 1065 llvm::GlobalVariable::LinkageTypes linktype; 1066 linktype = llvm::GlobalValue::WeakAnyLinkage; 1067 if (!Extern) 1068 linktype = llvm::GlobalValue::InternalLinkage; 1069 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0); 1070 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 1071 const llvm::FunctionType *FTy = 1072 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), 1073 FPT->isVariadic()); 1074 1075 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(), 1076 &getModule()); 1077 CodeGenFunction(*this).GenerateThunk(Fn, GD, Extern, ThisAdjustment); 1078 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty); 1079 return m; 1080} 1081 1082llvm::Constant * 1083CodeGenModule::BuildCovariantThunk(const GlobalDecl &GD, bool Extern, 1084 const CovariantThunkAdjustment &Adjustment) { 1085 const CXXMethodDecl *MD = cast<CXXMethodDecl>(GD.getDecl()); 1086 llvm::SmallString<256> OutName; 1087 getMangleContext().mangleCovariantThunk(MD, Adjustment, OutName); 1088 llvm::GlobalVariable::LinkageTypes linktype; 1089 linktype = llvm::GlobalValue::WeakAnyLinkage; 1090 if (!Extern) 1091 linktype = llvm::GlobalValue::InternalLinkage; 1092 llvm::Type *Ptr8Ty=llvm::PointerType::get(llvm::Type::getInt8Ty(VMContext),0); 1093 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 1094 const llvm::FunctionType *FTy = 1095 getTypes().GetFunctionType(getTypes().getFunctionInfo(MD), 1096 FPT->isVariadic()); 1097 1098 llvm::Function *Fn = llvm::Function::Create(FTy, linktype, OutName.str(), 1099 &getModule()); 1100 CodeGenFunction(*this).GenerateCovariantThunk(Fn, MD, Extern, Adjustment); 1101 llvm::Constant *m = llvm::ConstantExpr::getBitCast(Fn, Ptr8Ty); 1102 return m; 1103} 1104 1105llvm::Value * 1106CodeGenFunction::GetVirtualCXXBaseClassOffset(llvm::Value *This, 1107 const CXXRecordDecl *ClassDecl, 1108 const CXXRecordDecl *BaseClassDecl) { 1109 const llvm::Type *Int8PtrTy = 1110 llvm::Type::getInt8Ty(VMContext)->getPointerTo(); 1111 1112 llvm::Value *VTablePtr = Builder.CreateBitCast(This, 1113 Int8PtrTy->getPointerTo()); 1114 VTablePtr = Builder.CreateLoad(VTablePtr, "vtable"); 1115 1116 int64_t VBaseOffsetIndex = 1117 CGM.getVtableInfo().getVirtualBaseOffsetIndex(ClassDecl, BaseClassDecl); 1118 1119 llvm::Value *VBaseOffsetPtr = 1120 Builder.CreateConstGEP1_64(VTablePtr, VBaseOffsetIndex, "vbase.offset.ptr"); 1121 const llvm::Type *PtrDiffTy = 1122 ConvertType(getContext().getPointerDiffType()); 1123 1124 VBaseOffsetPtr = Builder.CreateBitCast(VBaseOffsetPtr, 1125 PtrDiffTy->getPointerTo()); 1126 1127 llvm::Value *VBaseOffset = Builder.CreateLoad(VBaseOffsetPtr, "vbase.offset"); 1128 1129 return VBaseOffset; 1130} 1131 1132static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VtableIndex, 1133 llvm::Value *This, const llvm::Type *Ty) { 1134 Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo(); 1135 1136 llvm::Value *Vtable = CGF.Builder.CreateBitCast(This, Ty); 1137 Vtable = CGF.Builder.CreateLoad(Vtable); 1138 1139 llvm::Value *VFuncPtr = 1140 CGF.Builder.CreateConstInBoundsGEP1_64(Vtable, VtableIndex, "vfn"); 1141 return CGF.Builder.CreateLoad(VFuncPtr); 1142} 1143 1144llvm::Value * 1145CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This, 1146 const llvm::Type *Ty) { 1147 MD = MD->getCanonicalDecl(); 1148 uint64_t VtableIndex = CGM.getVtableInfo().getMethodVtableIndex(MD); 1149 1150 return ::BuildVirtualCall(*this, VtableIndex, This, Ty); 1151} 1152 1153llvm::Value * 1154CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type, 1155 llvm::Value *&This, const llvm::Type *Ty) { 1156 DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl()); 1157 uint64_t VtableIndex = 1158 CGM.getVtableInfo().getMethodVtableIndex(GlobalDecl(DD, Type)); 1159 1160 return ::BuildVirtualCall(*this, VtableIndex, This, Ty); 1161} 1162 1163/// EmitClassAggrMemberwiseCopy - This routine generates code to copy a class 1164/// array of objects from SrcValue to DestValue. Copying can be either a bitwise 1165/// copy or via a copy constructor call. 1166// FIXME. Consolidate this with EmitCXXAggrConstructorCall. 1167void CodeGenFunction::EmitClassAggrMemberwiseCopy(llvm::Value *Dest, 1168 llvm::Value *Src, 1169 const ArrayType *Array, 1170 const CXXRecordDecl *BaseClassDecl, 1171 QualType Ty) { 1172 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array); 1173 assert(CA && "VLA cannot be copied over"); 1174 bool BitwiseCopy = BaseClassDecl->hasTrivialCopyConstructor(); 1175 1176 // Create a temporary for the loop index and initialize it with 0. 1177 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext), 1178 "loop.index"); 1179 llvm::Value* zeroConstant = 1180 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)); 1181 Builder.CreateStore(zeroConstant, IndexPtr); 1182 // Start the loop with a block that tests the condition. 1183 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 1184 llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); 1185 1186 EmitBlock(CondBlock); 1187 1188 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 1189 // Generate: if (loop-index < number-of-elements fall to the loop body, 1190 // otherwise, go to the block after the for-loop. 1191 uint64_t NumElements = getContext().getConstantArrayElementCount(CA); 1192 llvm::Value * NumElementsPtr = 1193 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements); 1194 llvm::Value *Counter = Builder.CreateLoad(IndexPtr); 1195 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr, 1196 "isless"); 1197 // If the condition is true, execute the body. 1198 Builder.CreateCondBr(IsLess, ForBody, AfterFor); 1199 1200 EmitBlock(ForBody); 1201 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc"); 1202 // Inside the loop body, emit the constructor call on the array element. 1203 Counter = Builder.CreateLoad(IndexPtr); 1204 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress"); 1205 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress"); 1206 if (BitwiseCopy) 1207 EmitAggregateCopy(Dest, Src, Ty); 1208 else if (CXXConstructorDecl *BaseCopyCtor = 1209 BaseClassDecl->getCopyConstructor(getContext(), 0)) { 1210 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor, 1211 Ctor_Complete); 1212 CallArgList CallArgs; 1213 // Push the this (Dest) ptr. 1214 CallArgs.push_back(std::make_pair(RValue::get(Dest), 1215 BaseCopyCtor->getThisType(getContext()))); 1216 1217 // Push the Src ptr. 1218 CallArgs.push_back(std::make_pair(RValue::get(Src), 1219 BaseCopyCtor->getParamDecl(0)->getType())); 1220 QualType ResultType = 1221 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType(); 1222 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs), 1223 Callee, CallArgs, BaseCopyCtor); 1224 } 1225 EmitBlock(ContinueBlock); 1226 1227 // Emit the increment of the loop counter. 1228 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1); 1229 Counter = Builder.CreateLoad(IndexPtr); 1230 NextVal = Builder.CreateAdd(Counter, NextVal, "inc"); 1231 Builder.CreateStore(NextVal, IndexPtr); 1232 1233 // Finally, branch back up to the condition for the next iteration. 1234 EmitBranch(CondBlock); 1235 1236 // Emit the fall-through block. 1237 EmitBlock(AfterFor, true); 1238} 1239 1240/// EmitClassAggrCopyAssignment - This routine generates code to assign a class 1241/// array of objects from SrcValue to DestValue. Assignment can be either a 1242/// bitwise assignment or via a copy assignment operator function call. 1243/// FIXME. This can be consolidated with EmitClassAggrMemberwiseCopy 1244void CodeGenFunction::EmitClassAggrCopyAssignment(llvm::Value *Dest, 1245 llvm::Value *Src, 1246 const ArrayType *Array, 1247 const CXXRecordDecl *BaseClassDecl, 1248 QualType Ty) { 1249 const ConstantArrayType *CA = dyn_cast<ConstantArrayType>(Array); 1250 assert(CA && "VLA cannot be asssigned"); 1251 bool BitwiseAssign = BaseClassDecl->hasTrivialCopyAssignment(); 1252 1253 // Create a temporary for the loop index and initialize it with 0. 1254 llvm::Value *IndexPtr = CreateTempAlloca(llvm::Type::getInt64Ty(VMContext), 1255 "loop.index"); 1256 llvm::Value* zeroConstant = 1257 llvm::Constant::getNullValue(llvm::Type::getInt64Ty(VMContext)); 1258 Builder.CreateStore(zeroConstant, IndexPtr); 1259 // Start the loop with a block that tests the condition. 1260 llvm::BasicBlock *CondBlock = createBasicBlock("for.cond"); 1261 llvm::BasicBlock *AfterFor = createBasicBlock("for.end"); 1262 1263 EmitBlock(CondBlock); 1264 1265 llvm::BasicBlock *ForBody = createBasicBlock("for.body"); 1266 // Generate: if (loop-index < number-of-elements fall to the loop body, 1267 // otherwise, go to the block after the for-loop. 1268 uint64_t NumElements = getContext().getConstantArrayElementCount(CA); 1269 llvm::Value * NumElementsPtr = 1270 llvm::ConstantInt::get(llvm::Type::getInt64Ty(VMContext), NumElements); 1271 llvm::Value *Counter = Builder.CreateLoad(IndexPtr); 1272 llvm::Value *IsLess = Builder.CreateICmpULT(Counter, NumElementsPtr, 1273 "isless"); 1274 // If the condition is true, execute the body. 1275 Builder.CreateCondBr(IsLess, ForBody, AfterFor); 1276 1277 EmitBlock(ForBody); 1278 llvm::BasicBlock *ContinueBlock = createBasicBlock("for.inc"); 1279 // Inside the loop body, emit the assignment operator call on array element. 1280 Counter = Builder.CreateLoad(IndexPtr); 1281 Src = Builder.CreateInBoundsGEP(Src, Counter, "srcaddress"); 1282 Dest = Builder.CreateInBoundsGEP(Dest, Counter, "destaddress"); 1283 const CXXMethodDecl *MD = 0; 1284 if (BitwiseAssign) 1285 EmitAggregateCopy(Dest, Src, Ty); 1286 else { 1287 bool hasCopyAssign = BaseClassDecl->hasConstCopyAssignment(getContext(), 1288 MD); 1289 assert(hasCopyAssign && "EmitClassAggrCopyAssignment - No user assign"); 1290 (void)hasCopyAssign; 1291 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 1292 const llvm::Type *LTy = 1293 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 1294 FPT->isVariadic()); 1295 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy); 1296 1297 CallArgList CallArgs; 1298 // Push the this (Dest) ptr. 1299 CallArgs.push_back(std::make_pair(RValue::get(Dest), 1300 MD->getThisType(getContext()))); 1301 1302 // Push the Src ptr. 1303 CallArgs.push_back(std::make_pair(RValue::get(Src), 1304 MD->getParamDecl(0)->getType())); 1305 QualType ResultType = MD->getType()->getAs<FunctionType>()->getResultType(); 1306 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs), 1307 Callee, CallArgs, MD); 1308 } 1309 EmitBlock(ContinueBlock); 1310 1311 // Emit the increment of the loop counter. 1312 llvm::Value *NextVal = llvm::ConstantInt::get(Counter->getType(), 1); 1313 Counter = Builder.CreateLoad(IndexPtr); 1314 NextVal = Builder.CreateAdd(Counter, NextVal, "inc"); 1315 Builder.CreateStore(NextVal, IndexPtr); 1316 1317 // Finally, branch back up to the condition for the next iteration. 1318 EmitBranch(CondBlock); 1319 1320 // Emit the fall-through block. 1321 EmitBlock(AfterFor, true); 1322} 1323 1324/// EmitClassMemberwiseCopy - This routine generates code to copy a class 1325/// object from SrcValue to DestValue. Copying can be either a bitwise copy 1326/// or via a copy constructor call. 1327void CodeGenFunction::EmitClassMemberwiseCopy( 1328 llvm::Value *Dest, llvm::Value *Src, 1329 const CXXRecordDecl *ClassDecl, 1330 const CXXRecordDecl *BaseClassDecl, QualType Ty) { 1331 if (ClassDecl) { 1332 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl, 1333 /*NullCheckValue=*/false); 1334 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl, 1335 /*NullCheckValue=*/false); 1336 } 1337 if (BaseClassDecl->hasTrivialCopyConstructor()) { 1338 EmitAggregateCopy(Dest, Src, Ty); 1339 return; 1340 } 1341 1342 if (CXXConstructorDecl *BaseCopyCtor = 1343 BaseClassDecl->getCopyConstructor(getContext(), 0)) { 1344 llvm::Value *Callee = CGM.GetAddrOfCXXConstructor(BaseCopyCtor, 1345 Ctor_Complete); 1346 CallArgList CallArgs; 1347 // Push the this (Dest) ptr. 1348 CallArgs.push_back(std::make_pair(RValue::get(Dest), 1349 BaseCopyCtor->getThisType(getContext()))); 1350 1351 // Push the Src ptr. 1352 CallArgs.push_back(std::make_pair(RValue::get(Src), 1353 BaseCopyCtor->getParamDecl(0)->getType())); 1354 QualType ResultType = 1355 BaseCopyCtor->getType()->getAs<FunctionType>()->getResultType(); 1356 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs), 1357 Callee, CallArgs, BaseCopyCtor); 1358 } 1359} 1360 1361/// EmitClassCopyAssignment - This routine generates code to copy assign a class 1362/// object from SrcValue to DestValue. Assignment can be either a bitwise 1363/// assignment of via an assignment operator call. 1364// FIXME. Consolidate this with EmitClassMemberwiseCopy as they share a lot. 1365void CodeGenFunction::EmitClassCopyAssignment( 1366 llvm::Value *Dest, llvm::Value *Src, 1367 const CXXRecordDecl *ClassDecl, 1368 const CXXRecordDecl *BaseClassDecl, 1369 QualType Ty) { 1370 if (ClassDecl) { 1371 Dest = GetAddressOfBaseClass(Dest, ClassDecl, BaseClassDecl, 1372 /*NullCheckValue=*/false); 1373 Src = GetAddressOfBaseClass(Src, ClassDecl, BaseClassDecl, 1374 /*NullCheckValue=*/false); 1375 } 1376 if (BaseClassDecl->hasTrivialCopyAssignment()) { 1377 EmitAggregateCopy(Dest, Src, Ty); 1378 return; 1379 } 1380 1381 const CXXMethodDecl *MD = 0; 1382 bool ConstCopyAssignOp = BaseClassDecl->hasConstCopyAssignment(getContext(), 1383 MD); 1384 assert(ConstCopyAssignOp && "EmitClassCopyAssignment - missing copy assign"); 1385 (void)ConstCopyAssignOp; 1386 1387 const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>(); 1388 const llvm::Type *LTy = 1389 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(MD), 1390 FPT->isVariadic()); 1391 llvm::Constant *Callee = CGM.GetAddrOfFunction(MD, LTy); 1392 1393 CallArgList CallArgs; 1394 // Push the this (Dest) ptr. 1395 CallArgs.push_back(std::make_pair(RValue::get(Dest), 1396 MD->getThisType(getContext()))); 1397 1398 // Push the Src ptr. 1399 CallArgs.push_back(std::make_pair(RValue::get(Src), 1400 MD->getParamDecl(0)->getType())); 1401 QualType ResultType = 1402 MD->getType()->getAs<FunctionType>()->getResultType(); 1403 EmitCall(CGM.getTypes().getFunctionInfo(ResultType, CallArgs), 1404 Callee, CallArgs, MD); 1405} 1406 1407/// SynthesizeDefaultConstructor - synthesize a default constructor 1408void 1409CodeGenFunction::SynthesizeDefaultConstructor(const CXXConstructorDecl *Ctor, 1410 CXXCtorType Type, 1411 llvm::Function *Fn, 1412 const FunctionArgList &Args) { 1413 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor"); 1414 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args, 1415 SourceLocation()); 1416 EmitCtorPrologue(Ctor, Type); 1417 FinishFunction(); 1418} 1419 1420/// SynthesizeCXXCopyConstructor - This routine implicitly defines body of a 1421/// copy constructor, in accordance with section 12.8 (p7 and p8) of C++03 1422/// The implicitly-defined copy constructor for class X performs a memberwise 1423/// copy of its subobjects. The order of copying is the same as the order of 1424/// initialization of bases and members in a user-defined constructor 1425/// Each subobject is copied in the manner appropriate to its type: 1426/// if the subobject is of class type, the copy constructor for the class is 1427/// used; 1428/// if the subobject is an array, each element is copied, in the manner 1429/// appropriate to the element type; 1430/// if the subobject is of scalar type, the built-in assignment operator is 1431/// used. 1432/// Virtual base class subobjects shall be copied only once by the 1433/// implicitly-defined copy constructor 1434 1435void 1436CodeGenFunction::SynthesizeCXXCopyConstructor(const CXXConstructorDecl *Ctor, 1437 CXXCtorType Type, 1438 llvm::Function *Fn, 1439 const FunctionArgList &Args) { 1440 const CXXRecordDecl *ClassDecl = Ctor->getParent(); 1441 assert(!ClassDecl->hasUserDeclaredCopyConstructor() && 1442 "SynthesizeCXXCopyConstructor - copy constructor has definition already"); 1443 assert(!Ctor->isTrivial() && "shouldn't need to generate trivial ctor"); 1444 StartFunction(GlobalDecl(Ctor, Type), Ctor->getResultType(), Fn, Args, 1445 SourceLocation()); 1446 1447 FunctionArgList::const_iterator i = Args.begin(); 1448 const VarDecl *ThisArg = i->first; 1449 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg); 1450 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this"); 1451 const VarDecl *SrcArg = (i+1)->first; 1452 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg); 1453 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj); 1454 1455 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 1456 Base != ClassDecl->bases_end(); ++Base) { 1457 // FIXME. copy constrution of virtual base NYI 1458 if (Base->isVirtual()) 1459 continue; 1460 1461 CXXRecordDecl *BaseClassDecl 1462 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1463 EmitClassMemberwiseCopy(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl, 1464 Base->getType()); 1465 } 1466 1467 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 1468 E = ClassDecl->field_end(); I != E; ++I) { 1469 const FieldDecl *Field = *I; 1470 1471 QualType FieldType = getContext().getCanonicalType(Field->getType()); 1472 const ConstantArrayType *Array = 1473 getContext().getAsConstantArrayType(FieldType); 1474 if (Array) 1475 FieldType = getContext().getBaseElementType(FieldType); 1476 1477 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 1478 CXXRecordDecl *FieldClassDecl 1479 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1480 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0); 1481 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0); 1482 if (Array) { 1483 const llvm::Type *BasePtr = ConvertType(FieldType); 1484 BasePtr = llvm::PointerType::getUnqual(BasePtr); 1485 llvm::Value *DestBaseAddrPtr = 1486 Builder.CreateBitCast(LHS.getAddress(), BasePtr); 1487 llvm::Value *SrcBaseAddrPtr = 1488 Builder.CreateBitCast(RHS.getAddress(), BasePtr); 1489 EmitClassAggrMemberwiseCopy(DestBaseAddrPtr, SrcBaseAddrPtr, Array, 1490 FieldClassDecl, FieldType); 1491 } 1492 else 1493 EmitClassMemberwiseCopy(LHS.getAddress(), RHS.getAddress(), 1494 0 /*ClassDecl*/, FieldClassDecl, FieldType); 1495 continue; 1496 } 1497 1498 if (Field->getType()->isReferenceType()) { 1499 unsigned FieldIndex = CGM.getTypes().getLLVMFieldNo(Field); 1500 1501 llvm::Value *LHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex, 1502 "lhs.ref"); 1503 1504 llvm::Value *RHS = Builder.CreateStructGEP(LoadOfThis, FieldIndex, 1505 "rhs.ref"); 1506 1507 // Load the value in RHS. 1508 RHS = Builder.CreateLoad(RHS); 1509 1510 // And store it in the LHS 1511 Builder.CreateStore(RHS, LHS); 1512 1513 continue; 1514 } 1515 // Do a built-in assignment of scalar data members. 1516 LValue LHS = EmitLValueForField(LoadOfThis, Field, false, 0); 1517 LValue RHS = EmitLValueForField(LoadOfSrc, Field, false, 0); 1518 1519 if (!hasAggregateLLVMType(Field->getType())) { 1520 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType()); 1521 EmitStoreThroughLValue(RVRHS, LHS, Field->getType()); 1522 } else if (Field->getType()->isAnyComplexType()) { 1523 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(), 1524 RHS.isVolatileQualified()); 1525 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified()); 1526 } else { 1527 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType()); 1528 } 1529 } 1530 1531 InitializeVtablePtrs(ClassDecl); 1532 FinishFunction(); 1533} 1534 1535/// SynthesizeCXXCopyAssignment - Implicitly define copy assignment operator. 1536/// Before the implicitly-declared copy assignment operator for a class is 1537/// implicitly defined, all implicitly- declared copy assignment operators for 1538/// its direct base classes and its nonstatic data members shall have been 1539/// implicitly defined. [12.8-p12] 1540/// The implicitly-defined copy assignment operator for class X performs 1541/// memberwise assignment of its subob- jects. The direct base classes of X are 1542/// assigned first, in the order of their declaration in 1543/// the base-specifier-list, and then the immediate nonstatic data members of X 1544/// are assigned, in the order in which they were declared in the class 1545/// definition.Each subobject is assigned in the manner appropriate to its type: 1546/// if the subobject is of class type, the copy assignment operator for the 1547/// class is used (as if by explicit qualification; that is, ignoring any 1548/// possible virtual overriding functions in more derived classes); 1549/// 1550/// if the subobject is an array, each element is assigned, in the manner 1551/// appropriate to the element type; 1552/// 1553/// if the subobject is of scalar type, the built-in assignment operator is 1554/// used. 1555void CodeGenFunction::SynthesizeCXXCopyAssignment(const CXXMethodDecl *CD, 1556 llvm::Function *Fn, 1557 const FunctionArgList &Args) { 1558 1559 const CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(CD->getDeclContext()); 1560 assert(!ClassDecl->hasUserDeclaredCopyAssignment() && 1561 "SynthesizeCXXCopyAssignment - copy assignment has user declaration"); 1562 StartFunction(CD, CD->getResultType(), Fn, Args, SourceLocation()); 1563 1564 FunctionArgList::const_iterator i = Args.begin(); 1565 const VarDecl *ThisArg = i->first; 1566 llvm::Value *ThisObj = GetAddrOfLocalVar(ThisArg); 1567 llvm::Value *LoadOfThis = Builder.CreateLoad(ThisObj, "this"); 1568 const VarDecl *SrcArg = (i+1)->first; 1569 llvm::Value *SrcObj = GetAddrOfLocalVar(SrcArg); 1570 llvm::Value *LoadOfSrc = Builder.CreateLoad(SrcObj); 1571 1572 for (CXXRecordDecl::base_class_const_iterator Base = ClassDecl->bases_begin(); 1573 Base != ClassDecl->bases_end(); ++Base) { 1574 // FIXME. copy assignment of virtual base NYI 1575 if (Base->isVirtual()) 1576 continue; 1577 1578 CXXRecordDecl *BaseClassDecl 1579 = cast<CXXRecordDecl>(Base->getType()->getAs<RecordType>()->getDecl()); 1580 EmitClassCopyAssignment(LoadOfThis, LoadOfSrc, ClassDecl, BaseClassDecl, 1581 Base->getType()); 1582 } 1583 1584 for (CXXRecordDecl::field_iterator Field = ClassDecl->field_begin(), 1585 FieldEnd = ClassDecl->field_end(); 1586 Field != FieldEnd; ++Field) { 1587 QualType FieldType = getContext().getCanonicalType((*Field)->getType()); 1588 const ConstantArrayType *Array = 1589 getContext().getAsConstantArrayType(FieldType); 1590 if (Array) 1591 FieldType = getContext().getBaseElementType(FieldType); 1592 1593 if (const RecordType *FieldClassType = FieldType->getAs<RecordType>()) { 1594 CXXRecordDecl *FieldClassDecl 1595 = cast<CXXRecordDecl>(FieldClassType->getDecl()); 1596 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0); 1597 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0); 1598 if (Array) { 1599 const llvm::Type *BasePtr = ConvertType(FieldType); 1600 BasePtr = llvm::PointerType::getUnqual(BasePtr); 1601 llvm::Value *DestBaseAddrPtr = 1602 Builder.CreateBitCast(LHS.getAddress(), BasePtr); 1603 llvm::Value *SrcBaseAddrPtr = 1604 Builder.CreateBitCast(RHS.getAddress(), BasePtr); 1605 EmitClassAggrCopyAssignment(DestBaseAddrPtr, SrcBaseAddrPtr, Array, 1606 FieldClassDecl, FieldType); 1607 } 1608 else 1609 EmitClassCopyAssignment(LHS.getAddress(), RHS.getAddress(), 1610 0 /*ClassDecl*/, FieldClassDecl, FieldType); 1611 continue; 1612 } 1613 // Do a built-in assignment of scalar data members. 1614 LValue LHS = EmitLValueForField(LoadOfThis, *Field, false, 0); 1615 LValue RHS = EmitLValueForField(LoadOfSrc, *Field, false, 0); 1616 if (!hasAggregateLLVMType(Field->getType())) { 1617 RValue RVRHS = EmitLoadOfLValue(RHS, Field->getType()); 1618 EmitStoreThroughLValue(RVRHS, LHS, Field->getType()); 1619 } else if (Field->getType()->isAnyComplexType()) { 1620 ComplexPairTy Pair = LoadComplexFromAddr(RHS.getAddress(), 1621 RHS.isVolatileQualified()); 1622 StoreComplexToAddr(Pair, LHS.getAddress(), LHS.isVolatileQualified()); 1623 } else { 1624 EmitAggregateCopy(LHS.getAddress(), RHS.getAddress(), Field->getType()); 1625 } 1626 } 1627 1628 // return *this; 1629 Builder.CreateStore(LoadOfThis, ReturnValue); 1630 1631 FinishFunction(); 1632} 1633 1634static void EmitBaseInitializer(CodeGenFunction &CGF, 1635 const CXXRecordDecl *ClassDecl, 1636 CXXBaseOrMemberInitializer *BaseInit, 1637 CXXCtorType CtorType) { 1638 assert(BaseInit->isBaseInitializer() && 1639 "Must have base initializer!"); 1640 1641 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 1642 1643 const Type *BaseType = BaseInit->getBaseClass(); 1644 CXXRecordDecl *BaseClassDecl = 1645 cast<CXXRecordDecl>(BaseType->getAs<RecordType>()->getDecl()); 1646 llvm::Value *V = CGF.GetAddressOfBaseClass(ThisPtr, ClassDecl, 1647 BaseClassDecl, 1648 /*NullCheckValue=*/false); 1649 CGF.EmitCXXConstructorCall(BaseInit->getConstructor(), 1650 CtorType, V, 1651 BaseInit->const_arg_begin(), 1652 BaseInit->const_arg_end()); 1653} 1654 1655static void EmitMemberInitializer(CodeGenFunction &CGF, 1656 const CXXRecordDecl *ClassDecl, 1657 CXXBaseOrMemberInitializer *MemberInit) { 1658 assert(MemberInit->isMemberInitializer() && 1659 "Must have member initializer!"); 1660 1661 // non-static data member initializers. 1662 FieldDecl *Field = MemberInit->getMember(); 1663 QualType FieldType = CGF.getContext().getCanonicalType(Field->getType()); 1664 1665 llvm::Value *ThisPtr = CGF.LoadCXXThis(); 1666 LValue LHS; 1667 if (FieldType->isReferenceType()) { 1668 // FIXME: This is really ugly; should be refactored somehow 1669 unsigned idx = CGF.CGM.getTypes().getLLVMFieldNo(Field); 1670 llvm::Value *V = CGF.Builder.CreateStructGEP(ThisPtr, idx, "tmp"); 1671 assert(!FieldType.getObjCGCAttr() && "fields cannot have GC attrs"); 1672 LHS = LValue::MakeAddr(V, CGF.MakeQualifiers(FieldType)); 1673 } else { 1674 LHS = CGF.EmitLValueForField(ThisPtr, Field, ClassDecl->isUnion(), 0); 1675 } 1676 1677 // If we are initializing an anonymous union field, drill down to the field. 1678 if (MemberInit->getAnonUnionMember()) { 1679 Field = MemberInit->getAnonUnionMember(); 1680 LHS = CGF.EmitLValueForField(LHS.getAddress(), Field, 1681 /*IsUnion=*/true, 0); 1682 FieldType = Field->getType(); 1683 } 1684 1685 // If the field is an array, branch based on the element type. 1686 const ConstantArrayType *Array = 1687 CGF.getContext().getAsConstantArrayType(FieldType); 1688 if (Array) 1689 FieldType = CGF.getContext().getBaseElementType(FieldType); 1690 1691 // We lose the constructor for anonymous union members, so handle them 1692 // explicitly. 1693 // FIXME: This is somwhat ugly. 1694 if (MemberInit->getAnonUnionMember() && FieldType->getAs<RecordType>()) { 1695 if (MemberInit->getNumArgs()) 1696 CGF.EmitAggExpr(*MemberInit->arg_begin(), LHS.getAddress(), 1697 LHS.isVolatileQualified()); 1698 else 1699 CGF.EmitAggregateClear(LHS.getAddress(), Field->getType()); 1700 return; 1701 } 1702 1703 if (FieldType->getAs<RecordType>()) { 1704 assert(MemberInit->getConstructor() && 1705 "EmitCtorPrologue - no constructor to initialize member"); 1706 if (Array) { 1707 const llvm::Type *BasePtr = CGF.ConvertType(FieldType); 1708 BasePtr = llvm::PointerType::getUnqual(BasePtr); 1709 llvm::Value *BaseAddrPtr = 1710 CGF.Builder.CreateBitCast(LHS.getAddress(), BasePtr); 1711 CGF.EmitCXXAggrConstructorCall(MemberInit->getConstructor(), 1712 Array, BaseAddrPtr, 1713 MemberInit->const_arg_begin(), 1714 MemberInit->const_arg_end()); 1715 } 1716 else 1717 CGF.EmitCXXConstructorCall(MemberInit->getConstructor(), 1718 Ctor_Complete, LHS.getAddress(), 1719 MemberInit->const_arg_begin(), 1720 MemberInit->const_arg_end()); 1721 return; 1722 } 1723 1724 assert(MemberInit->getNumArgs() == 1 && "Initializer count must be 1 only"); 1725 Expr *RhsExpr = *MemberInit->arg_begin(); 1726 RValue RHS; 1727 if (FieldType->isReferenceType()) { 1728 RHS = CGF.EmitReferenceBindingToExpr(RhsExpr, FieldType, 1729 /*IsInitializer=*/true); 1730 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType); 1731 } else if (Array) { 1732 CGF.EmitMemSetToZero(LHS.getAddress(), Field->getType()); 1733 } else if (!CGF.hasAggregateLLVMType(RhsExpr->getType())) { 1734 RHS = RValue::get(CGF.EmitScalarExpr(RhsExpr, true)); 1735 CGF.EmitStoreThroughLValue(RHS, LHS, FieldType); 1736 } else if (RhsExpr->getType()->isAnyComplexType()) { 1737 CGF.EmitComplexExprIntoAddr(RhsExpr, LHS.getAddress(), 1738 LHS.isVolatileQualified()); 1739 } else { 1740 // Handle member function pointers; other aggregates shouldn't get this far. 1741 CGF.EmitAggExpr(RhsExpr, LHS.getAddress(), LHS.isVolatileQualified()); 1742 } 1743} 1744 1745/// EmitCtorPrologue - This routine generates necessary code to initialize 1746/// base classes and non-static data members belonging to this constructor. 1747/// FIXME: This needs to take a CXXCtorType. 1748void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD, 1749 CXXCtorType CtorType) { 1750 const CXXRecordDecl *ClassDecl = CD->getParent(); 1751 1752 // FIXME: Add vbase initialization 1753 1754 for (CXXConstructorDecl::init_const_iterator B = CD->init_begin(), 1755 E = CD->init_end(); 1756 B != E; ++B) { 1757 CXXBaseOrMemberInitializer *Member = (*B); 1758 1759 assert(LiveTemporaries.empty() && 1760 "Should not have any live temporaries at initializer start!"); 1761 1762 if (Member->isBaseInitializer()) 1763 EmitBaseInitializer(*this, ClassDecl, Member, CtorType); 1764 else 1765 EmitMemberInitializer(*this, ClassDecl, Member); 1766 1767 // Pop any live temporaries that the initializers might have pushed. 1768 while (!LiveTemporaries.empty()) 1769 PopCXXTemporary(); 1770 } 1771 1772 InitializeVtablePtrs(ClassDecl); 1773} 1774 1775void CodeGenFunction::InitializeVtablePtrs(const CXXRecordDecl *ClassDecl) { 1776 if (!ClassDecl->isDynamicClass()) 1777 return; 1778 1779 // Initialize the vtable pointer. 1780 // FIXME: This needs to initialize secondary vtable pointers too. 1781 llvm::Value *ThisPtr = LoadCXXThis(); 1782 1783 llvm::Constant *Vtable = CGM.getVtableInfo().getVtable(ClassDecl); 1784 uint64_t AddressPoint = CGM.getVtableInfo().getVtableAddressPoint(ClassDecl); 1785 1786 llvm::Value *VtableAddressPoint = 1787 Builder.CreateConstInBoundsGEP2_64(Vtable, 0, AddressPoint); 1788 1789 llvm::Value *VtableField = 1790 Builder.CreateBitCast(ThisPtr, 1791 VtableAddressPoint->getType()->getPointerTo()); 1792 1793 Builder.CreateStore(VtableAddressPoint, VtableField); 1794} 1795 1796/// EmitDtorEpilogue - Emit all code that comes at the end of class's 1797/// destructor. This is to call destructors on members and base classes 1798/// in reverse order of their construction. 1799/// FIXME: This needs to take a CXXDtorType. 1800void CodeGenFunction::EmitDtorEpilogue(const CXXDestructorDecl *DD, 1801 CXXDtorType DtorType) { 1802 assert(!DD->isTrivial() && 1803 "Should not emit dtor epilogue for trivial dtor!"); 1804 1805 const CXXRecordDecl *ClassDecl = DD->getParent(); 1806 1807 // Collect the fields. 1808 llvm::SmallVector<const FieldDecl *, 16> FieldDecls; 1809 for (CXXRecordDecl::field_iterator I = ClassDecl->field_begin(), 1810 E = ClassDecl->field_end(); I != E; ++I) { 1811 const FieldDecl *Field = *I; 1812 1813 QualType FieldType = getContext().getCanonicalType(Field->getType()); 1814 FieldType = getContext().getBaseElementType(FieldType); 1815 1816 const RecordType *RT = FieldType->getAs<RecordType>(); 1817 if (!RT) 1818 continue; 1819 1820 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1821 if (FieldClassDecl->hasTrivialDestructor()) 1822 continue; 1823 1824 FieldDecls.push_back(Field); 1825 } 1826 1827 // Now destroy the fields. 1828 for (size_t i = FieldDecls.size(); i > 0; --i) { 1829 const FieldDecl *Field = FieldDecls[i - 1]; 1830 1831 QualType FieldType = Field->getType(); 1832 const ConstantArrayType *Array = 1833 getContext().getAsConstantArrayType(FieldType); 1834 if (Array) 1835 FieldType = getContext().getBaseElementType(FieldType); 1836 1837 const RecordType *RT = FieldType->getAs<RecordType>(); 1838 CXXRecordDecl *FieldClassDecl = cast<CXXRecordDecl>(RT->getDecl()); 1839 1840 llvm::Value *ThisPtr = LoadCXXThis(); 1841 1842 LValue LHS = EmitLValueForField(ThisPtr, Field, 1843 /*isUnion=*/false, 1844 // FIXME: Qualifiers? 1845 /*CVRQualifiers=*/0); 1846 if (Array) { 1847 const llvm::Type *BasePtr = ConvertType(FieldType); 1848 BasePtr = llvm::PointerType::getUnqual(BasePtr); 1849 llvm::Value *BaseAddrPtr = 1850 Builder.CreateBitCast(LHS.getAddress(), BasePtr); 1851 EmitCXXAggrDestructorCall(FieldClassDecl->getDestructor(getContext()), 1852 Array, BaseAddrPtr); 1853 } else 1854 EmitCXXDestructorCall(FieldClassDecl->getDestructor(getContext()), 1855 Dtor_Complete, LHS.getAddress()); 1856 } 1857 1858 // Destroy non-virtual bases. 1859 for (CXXRecordDecl::reverse_base_class_const_iterator I = 1860 ClassDecl->bases_rbegin(), E = ClassDecl->bases_rend(); I != E; ++I) { 1861 const CXXBaseSpecifier &Base = *I; 1862 1863 // Ignore virtual bases. 1864 if (Base.isVirtual()) 1865 continue; 1866 1867 CXXRecordDecl *BaseClassDecl 1868 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 1869 1870 // Ignore trivial destructors. 1871 if (BaseClassDecl->hasTrivialDestructor()) 1872 continue; 1873 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext()); 1874 1875 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(), 1876 ClassDecl, BaseClassDecl, 1877 /*NullCheckValue=*/false); 1878 EmitCXXDestructorCall(D, Dtor_Base, V); 1879 } 1880 1881 // If we're emitting a base destructor, we don't want to emit calls to the 1882 // virtual bases. 1883 if (DtorType == Dtor_Base) 1884 return; 1885 1886 // Handle virtual bases. 1887 for (CXXRecordDecl::reverse_base_class_const_iterator I = 1888 ClassDecl->vbases_rbegin(), E = ClassDecl->vbases_rend(); I != E; ++I) { 1889 const CXXBaseSpecifier &Base = *I; 1890 CXXRecordDecl *BaseClassDecl 1891 = cast<CXXRecordDecl>(Base.getType()->getAs<RecordType>()->getDecl()); 1892 1893 // Ignore trivial destructors. 1894 if (BaseClassDecl->hasTrivialDestructor()) 1895 continue; 1896 const CXXDestructorDecl *D = BaseClassDecl->getDestructor(getContext()); 1897 llvm::Value *V = GetAddressOfBaseClass(LoadCXXThis(), 1898 ClassDecl, BaseClassDecl, 1899 /*NullCheckValue=*/false); 1900 EmitCXXDestructorCall(D, Dtor_Base, V); 1901 } 1902 1903 // If we have a deleting destructor, emit a call to the delete operator. 1904 if (DtorType == Dtor_Deleting) { 1905 assert(DD->getOperatorDelete() && 1906 "operator delete missing - EmitDtorEpilogue"); 1907 EmitDeleteCall(DD->getOperatorDelete(), LoadCXXThis(), 1908 getContext().getTagDeclType(ClassDecl)); 1909 } 1910} 1911 1912void CodeGenFunction::SynthesizeDefaultDestructor(const CXXDestructorDecl *Dtor, 1913 CXXDtorType DtorType, 1914 llvm::Function *Fn, 1915 const FunctionArgList &Args) { 1916 assert(!Dtor->getParent()->hasUserDeclaredDestructor() && 1917 "SynthesizeDefaultDestructor - destructor has user declaration"); 1918 1919 StartFunction(GlobalDecl(Dtor, DtorType), Dtor->getResultType(), Fn, Args, 1920 SourceLocation()); 1921 1922 EmitDtorEpilogue(Dtor, DtorType); 1923 FinishFunction(); 1924} 1925