CGCXX.cpp revision 1e7fe751466ea82665fd21e9162fd7cc9c5f412d
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 "CGCXXABI.h" 17#include "CodeGenFunction.h" 18#include "CodeGenModule.h" 19#include "Mangle.h" 20#include "clang/AST/ASTContext.h" 21#include "clang/AST/RecordLayout.h" 22#include "clang/AST/Decl.h" 23#include "clang/AST/DeclCXX.h" 24#include "clang/AST/DeclObjC.h" 25#include "clang/AST/StmtCXX.h" 26#include "clang/Frontend/CodeGenOptions.h" 27#include "llvm/ADT/StringExtras.h" 28using namespace clang; 29using namespace CodeGen; 30 31/// Determines whether the given function has a trivial body that does 32/// not require any specific codegen. 33static bool HasTrivialBody(const FunctionDecl *FD) { 34 Stmt *S = FD->getBody(); 35 if (!S) 36 return true; 37 if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty()) 38 return true; 39 return false; 40} 41 42/// Try to emit a base destructor as an alias to its primary 43/// base-class destructor. 44bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) { 45 if (!getCodeGenOpts().CXXCtorDtorAliases) 46 return true; 47 48 // If the destructor doesn't have a trivial body, we have to emit it 49 // separately. 50 if (!HasTrivialBody(D)) 51 return true; 52 53 const CXXRecordDecl *Class = D->getParent(); 54 55 // If we need to manipulate a VTT parameter, give up. 56 if (Class->getNumVBases()) { 57 // Extra Credit: passing extra parameters is perfectly safe 58 // in many calling conventions, so only bail out if the ctor's 59 // calling convention is nonstandard. 60 return true; 61 } 62 63 // If any fields have a non-trivial destructor, we have to emit it 64 // separately. 65 for (CXXRecordDecl::field_iterator I = Class->field_begin(), 66 E = Class->field_end(); I != E; ++I) 67 if (const RecordType *RT = (*I)->getType()->getAs<RecordType>()) 68 if (!cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor()) 69 return true; 70 71 // Try to find a unique base class with a non-trivial destructor. 72 const CXXRecordDecl *UniqueBase = 0; 73 for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(), 74 E = Class->bases_end(); I != E; ++I) { 75 76 // We're in the base destructor, so skip virtual bases. 77 if (I->isVirtual()) continue; 78 79 // Skip base classes with trivial destructors. 80 const CXXRecordDecl *Base 81 = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl()); 82 if (Base->hasTrivialDestructor()) continue; 83 84 // If we've already found a base class with a non-trivial 85 // destructor, give up. 86 if (UniqueBase) return true; 87 UniqueBase = Base; 88 } 89 90 // If we didn't find any bases with a non-trivial destructor, then 91 // the base destructor is actually effectively trivial, which can 92 // happen if it was needlessly user-defined or if there are virtual 93 // bases with non-trivial destructors. 94 if (!UniqueBase) 95 return true; 96 97 /// If we don't have a definition for the destructor yet, don't 98 /// emit. We can't emit aliases to declarations; that's just not 99 /// how aliases work. 100 const CXXDestructorDecl *BaseD = UniqueBase->getDestructor(); 101 if (!BaseD->isImplicit() && !BaseD->hasBody()) 102 return true; 103 104 // If the base is at a non-zero offset, give up. 105 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class); 106 if (ClassLayout.getBaseClassOffset(UniqueBase) != 0) 107 return true; 108 109 return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base), 110 GlobalDecl(BaseD, Dtor_Base)); 111} 112 113/// Try to emit a definition as a global alias for another definition. 114bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl, 115 GlobalDecl TargetDecl) { 116 if (!getCodeGenOpts().CXXCtorDtorAliases) 117 return true; 118 119 // The alias will use the linkage of the referrent. If we can't 120 // support aliases with that linkage, fail. 121 llvm::GlobalValue::LinkageTypes Linkage 122 = getFunctionLinkage(cast<FunctionDecl>(AliasDecl.getDecl())); 123 124 switch (Linkage) { 125 // We can definitely emit aliases to definitions with external linkage. 126 case llvm::GlobalValue::ExternalLinkage: 127 case llvm::GlobalValue::ExternalWeakLinkage: 128 break; 129 130 // Same with local linkage. 131 case llvm::GlobalValue::InternalLinkage: 132 case llvm::GlobalValue::PrivateLinkage: 133 case llvm::GlobalValue::LinkerPrivateLinkage: 134 break; 135 136 // We should try to support linkonce linkages. 137 case llvm::GlobalValue::LinkOnceAnyLinkage: 138 case llvm::GlobalValue::LinkOnceODRLinkage: 139 return true; 140 141 // Other linkages will probably never be supported. 142 default: 143 return true; 144 } 145 146 llvm::GlobalValue::LinkageTypes TargetLinkage 147 = getFunctionLinkage(cast<FunctionDecl>(TargetDecl.getDecl())); 148 149 if (llvm::GlobalValue::isWeakForLinker(TargetLinkage)) 150 return true; 151 152 // Derive the type for the alias. 153 const llvm::PointerType *AliasType 154 = getTypes().GetFunctionType(AliasDecl)->getPointerTo(); 155 156 // Find the referrent. Some aliases might require a bitcast, in 157 // which case the caller is responsible for ensuring the soundness 158 // of these semantics. 159 llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl)); 160 llvm::Constant *Aliasee = Ref; 161 if (Ref->getType() != AliasType) 162 Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType); 163 164 // Create the alias with no name. 165 llvm::GlobalAlias *Alias = 166 new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule()); 167 168 // Switch any previous uses to the alias. 169 llvm::StringRef MangledName = getMangledName(AliasDecl); 170 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 171 if (Entry) { 172 assert(Entry->isDeclaration() && "definition already exists for alias"); 173 assert(Entry->getType() == AliasType && 174 "declaration exists with different type"); 175 Alias->takeName(Entry); 176 Entry->replaceAllUsesWith(Alias); 177 Entry->eraseFromParent(); 178 } else { 179 Alias->setName(MangledName); 180 } 181 182 // Finally, set up the alias with its proper name and attributes. 183 SetCommonAttributes(AliasDecl.getDecl(), Alias); 184 185 return false; 186} 187 188void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) { 189 // The constructor used for constructing this as a complete class; 190 // constucts the virtual bases, then calls the base constructor. 191 EmitGlobal(GlobalDecl(D, Ctor_Complete)); 192 193 // The constructor used for constructing this as a base class; 194 // ignores virtual bases. 195 EmitGlobal(GlobalDecl(D, Ctor_Base)); 196} 197 198void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D, 199 CXXCtorType Type) { 200 // The complete constructor is equivalent to the base constructor 201 // for classes with no virtual bases. Try to emit it as an alias. 202 if (Type == Ctor_Complete && 203 !D->getParent()->getNumVBases() && 204 !TryEmitDefinitionAsAlias(GlobalDecl(D, Ctor_Complete), 205 GlobalDecl(D, Ctor_Base))) 206 return; 207 208 llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXConstructor(D, Type)); 209 setFunctionLinkage(D, Fn); 210 211 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn); 212 213 SetFunctionDefinitionAttributes(D, Fn); 214 SetLLVMFunctionAttributesForDefinition(D, Fn); 215} 216 217llvm::GlobalValue * 218CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D, 219 CXXCtorType Type) { 220 GlobalDecl GD(D, Type); 221 222 llvm::StringRef Name = getMangledName(GD); 223 if (llvm::GlobalValue *V = GetGlobalValue(Name)) 224 return V; 225 226 const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>(); 227 const llvm::FunctionType *FTy = 228 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), 229 FPT->isVariadic()); 230 return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FTy, GD)); 231} 232 233void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) { 234 // The destructor in a virtual table is always a 'deleting' 235 // destructor, which calls the complete destructor and then uses the 236 // appropriate operator delete. 237 if (D->isVirtual()) 238 EmitGlobal(GlobalDecl(D, Dtor_Deleting)); 239 240 // The destructor used for destructing this as a most-derived class; 241 // call the base destructor and then destructs any virtual bases. 242 EmitGlobal(GlobalDecl(D, Dtor_Complete)); 243 244 // The destructor used for destructing this as a base class; ignores 245 // virtual bases. 246 EmitGlobal(GlobalDecl(D, Dtor_Base)); 247} 248 249void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D, 250 CXXDtorType Type) { 251 // The complete destructor is equivalent to the base destructor for 252 // classes with no virtual bases, so try to emit it as an alias. 253 if (Type == Dtor_Complete && 254 !D->getParent()->getNumVBases() && 255 !TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Complete), 256 GlobalDecl(D, Dtor_Base))) 257 return; 258 259 // The base destructor is equivalent to the base destructor of its 260 // base class if there is exactly one non-virtual base class with a 261 // non-trivial destructor, there are no fields with a non-trivial 262 // destructor, and the body of the destructor is trivial. 263 if (Type == Dtor_Base && !TryEmitBaseDestructorAsAlias(D)) 264 return; 265 266 llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXDestructor(D, Type)); 267 setFunctionLinkage(D, Fn); 268 269 CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn); 270 271 SetFunctionDefinitionAttributes(D, Fn); 272 SetLLVMFunctionAttributesForDefinition(D, Fn); 273} 274 275llvm::GlobalValue * 276CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D, 277 CXXDtorType Type) { 278 GlobalDecl GD(D, Type); 279 280 llvm::StringRef Name = getMangledName(GD); 281 if (llvm::GlobalValue *V = GetGlobalValue(Name)) 282 return V; 283 284 const llvm::FunctionType *FTy = 285 getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false); 286 287 return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FTy, GD)); 288} 289 290static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VTableIndex, 291 llvm::Value *This, const llvm::Type *Ty) { 292 Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo(); 293 294 llvm::Value *VTable = CGF.Builder.CreateBitCast(This, Ty); 295 VTable = CGF.Builder.CreateLoad(VTable); 296 297 llvm::Value *VFuncPtr = 298 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn"); 299 return CGF.Builder.CreateLoad(VFuncPtr); 300} 301 302llvm::Value * 303CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This, 304 const llvm::Type *Ty) { 305 MD = MD->getCanonicalDecl(); 306 uint64_t VTableIndex = CGM.getVTables().getMethodVTableIndex(MD); 307 308 return ::BuildVirtualCall(*this, VTableIndex, This, Ty); 309} 310 311llvm::Value * 312CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type, 313 llvm::Value *&This, const llvm::Type *Ty) { 314 DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl()); 315 uint64_t VTableIndex = 316 CGM.getVTables().getMethodVTableIndex(GlobalDecl(DD, Type)); 317 318 return ::BuildVirtualCall(*this, VTableIndex, This, Ty); 319} 320 321/// Implementation for CGCXXABI. Possibly this should be moved into 322/// the incomplete ABI implementations? 323 324CGCXXABI::~CGCXXABI() {} 325 326static void ErrorUnsupportedABI(CodeGenFunction &CGF, 327 llvm::StringRef S) { 328 Diagnostic &Diags = CGF.CGM.getDiags(); 329 unsigned DiagID = Diags.getCustomDiagID(Diagnostic::Error, 330 "cannot yet compile %1 in this ABI"); 331 Diags.Report(CGF.getContext().getFullLoc(CGF.CurCodeDecl->getLocation()), 332 DiagID) 333 << S; 334} 335 336static llvm::Constant *GetBogusMemberPointer(CodeGenModule &CGM, 337 QualType T) { 338 return llvm::Constant::getNullValue(CGM.getTypes().ConvertType(T)); 339} 340 341const llvm::Type * 342CGCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) { 343 return CGM.getTypes().ConvertType(CGM.getContext().getPointerDiffType()); 344} 345 346llvm::Value *CGCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF, 347 llvm::Value *&This, 348 llvm::Value *MemPtr, 349 const MemberPointerType *MPT) { 350 ErrorUnsupportedABI(CGF, "calls through member pointers"); 351 352 const FunctionProtoType *FPT = 353 MPT->getPointeeType()->getAs<FunctionProtoType>(); 354 const CXXRecordDecl *RD = 355 cast<CXXRecordDecl>(MPT->getClass()->getAs<RecordType>()->getDecl()); 356 const llvm::FunctionType *FTy = 357 CGM.getTypes().GetFunctionType(CGM.getTypes().getFunctionInfo(RD, FPT), 358 FPT->isVariadic()); 359 return llvm::Constant::getNullValue(FTy->getPointerTo()); 360} 361 362llvm::Value *CGCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF, 363 llvm::Value *Base, 364 llvm::Value *MemPtr, 365 const MemberPointerType *MPT) { 366 ErrorUnsupportedABI(CGF, "loads of member pointers"); 367 const llvm::Type *Ty = CGF.ConvertType(MPT->getPointeeType())->getPointerTo(); 368 return llvm::Constant::getNullValue(Ty); 369} 370 371llvm::Value *CGCXXABI::EmitMemberPointerConversion(CodeGenFunction &CGF, 372 const CastExpr *E, 373 llvm::Value *Src) { 374 ErrorUnsupportedABI(CGF, "member function pointer conversions"); 375 return GetBogusMemberPointer(CGM, E->getType()); 376} 377 378llvm::Value * 379CGCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF, 380 llvm::Value *L, 381 llvm::Value *R, 382 const MemberPointerType *MPT, 383 bool Inequality) { 384 ErrorUnsupportedABI(CGF, "member function pointer comparison"); 385 return CGF.Builder.getFalse(); 386} 387 388llvm::Value * 389CGCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF, 390 llvm::Value *MemPtr, 391 const MemberPointerType *MPT) { 392 ErrorUnsupportedABI(CGF, "member function pointer null testing"); 393 return CGF.Builder.getFalse(); 394} 395 396llvm::Constant * 397CGCXXABI::EmitMemberPointerConversion(llvm::Constant *C, const CastExpr *E) { 398 return GetBogusMemberPointer(CGM, E->getType()); 399} 400 401llvm::Constant * 402CGCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) { 403 return GetBogusMemberPointer(CGM, QualType(MPT, 0)); 404} 405 406llvm::Constant *CGCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) { 407 return GetBogusMemberPointer(CGM, 408 CGM.getContext().getMemberPointerType(MD->getType(), 409 MD->getParent()->getTypeForDecl())); 410} 411 412llvm::Constant *CGCXXABI::EmitMemberPointer(const FieldDecl *FD) { 413 return GetBogusMemberPointer(CGM, 414 CGM.getContext().getMemberPointerType(FD->getType(), 415 FD->getParent()->getTypeForDecl())); 416} 417 418bool CGCXXABI::isZeroInitializable(const MemberPointerType *MPT) { 419 // Fake answer. 420 return true; 421} 422 423void CGCXXABI::BuildThisParam(CodeGenFunction &CGF, FunctionArgList &Params) { 424 const CXXMethodDecl *MD = cast<CXXMethodDecl>(CGF.CurGD.getDecl()); 425 426 // FIXME: I'm not entirely sure I like using a fake decl just for code 427 // generation. Maybe we can come up with a better way? 428 ImplicitParamDecl *ThisDecl 429 = ImplicitParamDecl::Create(CGM.getContext(), 0, MD->getLocation(), 430 &CGM.getContext().Idents.get("this"), 431 MD->getThisType(CGM.getContext())); 432 Params.push_back(std::make_pair(ThisDecl, ThisDecl->getType())); 433 getThisDecl(CGF) = ThisDecl; 434} 435 436void CGCXXABI::EmitThisParam(CodeGenFunction &CGF) { 437 /// Initialize the 'this' slot. 438 assert(getThisDecl(CGF) && "no 'this' variable for function"); 439 getThisValue(CGF) 440 = CGF.Builder.CreateLoad(CGF.GetAddrOfLocalVar(getThisDecl(CGF)), 441 "this"); 442} 443 444void CGCXXABI::EmitReturnFromThunk(CodeGenFunction &CGF, 445 RValue RV, QualType ResultType) { 446 CGF.EmitReturnOfRValue(RV, ResultType); 447} 448 449CharUnits CGCXXABI::GetArrayCookieSize(QualType ElementType) { 450 return CharUnits::Zero(); 451} 452 453llvm::Value *CGCXXABI::InitializeArrayCookie(CodeGenFunction &CGF, 454 llvm::Value *NewPtr, 455 llvm::Value *NumElements, 456 QualType ElementType) { 457 // Should never be called. 458 ErrorUnsupportedABI(CGF, "array cookie initialization"); 459 return 0; 460} 461 462void CGCXXABI::ReadArrayCookie(CodeGenFunction &CGF, llvm::Value *Ptr, 463 QualType ElementType, llvm::Value *&NumElements, 464 llvm::Value *&AllocPtr, CharUnits &CookieSize) { 465 ErrorUnsupportedABI(CGF, "array cookie reading"); 466 467 // This should be enough to avoid assertions. 468 NumElements = 0; 469 AllocPtr = llvm::Constant::getNullValue(CGF.Builder.getInt8PtrTy()); 470 CookieSize = CharUnits::Zero(); 471} 472