clang API Documentation
00001 //===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===// 00002 // 00003 // The LLVM Compiler Infrastructure 00004 // 00005 // This file is distributed under the University of Illinois Open Source 00006 // License. See LICENSE.TXT for details. 00007 // 00008 //===----------------------------------------------------------------------===// 00009 // 00010 // This contains code dealing with C++ code generation. 00011 // 00012 //===----------------------------------------------------------------------===// 00013 00014 // We might split this into multiple files if it gets too unwieldy 00015 00016 #include "CodeGenModule.h" 00017 #include "CGCXXABI.h" 00018 #include "CodeGenFunction.h" 00019 #include "clang/AST/ASTContext.h" 00020 #include "clang/AST/Decl.h" 00021 #include "clang/AST/DeclCXX.h" 00022 #include "clang/AST/DeclObjC.h" 00023 #include "clang/AST/Mangle.h" 00024 #include "clang/AST/RecordLayout.h" 00025 #include "clang/AST/StmtCXX.h" 00026 #include "clang/Frontend/CodeGenOptions.h" 00027 #include "llvm/ADT/StringExtras.h" 00028 using namespace clang; 00029 using namespace CodeGen; 00030 00031 /// Try to emit a base destructor as an alias to its primary 00032 /// base-class destructor. 00033 bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) { 00034 if (!getCodeGenOpts().CXXCtorDtorAliases) 00035 return true; 00036 00037 // Producing an alias to a base class ctor/dtor can degrade debug quality 00038 // as the debugger cannot tell them apart. 00039 if (getCodeGenOpts().OptimizationLevel == 0) 00040 return true; 00041 00042 // If the destructor doesn't have a trivial body, we have to emit it 00043 // separately. 00044 if (!D->hasTrivialBody()) 00045 return true; 00046 00047 const CXXRecordDecl *Class = D->getParent(); 00048 00049 // We are going to instrument this destructor, so give up even if it is 00050 // currently empty. 00051 if (Class->mayInsertExtraPadding()) 00052 return true; 00053 00054 // If we need to manipulate a VTT parameter, give up. 00055 if (Class->getNumVBases()) { 00056 // Extra Credit: passing extra parameters is perfectly safe 00057 // in many calling conventions, so only bail out if the ctor's 00058 // calling convention is nonstandard. 00059 return true; 00060 } 00061 00062 // If any field has a non-trivial destructor, we have to emit the 00063 // destructor separately. 00064 for (const auto *I : Class->fields()) 00065 if (I->getType().isDestructedType()) 00066 return true; 00067 00068 // Try to find a unique base class with a non-trivial destructor. 00069 const CXXRecordDecl *UniqueBase = nullptr; 00070 for (const auto &I : Class->bases()) { 00071 00072 // We're in the base destructor, so skip virtual bases. 00073 if (I.isVirtual()) continue; 00074 00075 // Skip base classes with trivial destructors. 00076 const auto *Base = 00077 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 00078 if (Base->hasTrivialDestructor()) continue; 00079 00080 // If we've already found a base class with a non-trivial 00081 // destructor, give up. 00082 if (UniqueBase) return true; 00083 UniqueBase = Base; 00084 } 00085 00086 // If we didn't find any bases with a non-trivial destructor, then 00087 // the base destructor is actually effectively trivial, which can 00088 // happen if it was needlessly user-defined or if there are virtual 00089 // bases with non-trivial destructors. 00090 if (!UniqueBase) 00091 return true; 00092 00093 // If the base is at a non-zero offset, give up. 00094 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class); 00095 if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero()) 00096 return true; 00097 00098 // Give up if the calling conventions don't match. We could update the call, 00099 // but it is probably not worth it. 00100 const CXXDestructorDecl *BaseD = UniqueBase->getDestructor(); 00101 if (BaseD->getType()->getAs<FunctionType>()->getCallConv() != 00102 D->getType()->getAs<FunctionType>()->getCallConv()) 00103 return true; 00104 00105 return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base), 00106 GlobalDecl(BaseD, Dtor_Base), 00107 false); 00108 } 00109 00110 /// Try to emit a definition as a global alias for another definition. 00111 /// If \p InEveryTU is true, we know that an equivalent alias can be produced 00112 /// in every translation unit. 00113 bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl, 00114 GlobalDecl TargetDecl, 00115 bool InEveryTU) { 00116 if (!getCodeGenOpts().CXXCtorDtorAliases) 00117 return true; 00118 00119 // The alias will use the linkage of the referent. If we can't 00120 // support aliases with that linkage, fail. 00121 llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl); 00122 00123 // We can't use an alias if the linkage is not valid for one. 00124 if (!llvm::GlobalAlias::isValidLinkage(Linkage)) 00125 return true; 00126 00127 // Don't create a weak alias for a dllexport'd symbol. 00128 if (AliasDecl.getDecl()->hasAttr<DLLExportAttr>() && 00129 llvm::GlobalValue::isWeakForLinker(Linkage)) 00130 return true; 00131 00132 llvm::GlobalValue::LinkageTypes TargetLinkage = 00133 getFunctionLinkage(TargetDecl); 00134 00135 // Check if we have it already. 00136 StringRef MangledName = getMangledName(AliasDecl); 00137 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 00138 if (Entry && !Entry->isDeclaration()) 00139 return false; 00140 if (Replacements.count(MangledName)) 00141 return false; 00142 00143 // Derive the type for the alias. 00144 llvm::PointerType *AliasType 00145 = getTypes().GetFunctionType(AliasDecl)->getPointerTo(); 00146 00147 // Find the referent. Some aliases might require a bitcast, in 00148 // which case the caller is responsible for ensuring the soundness 00149 // of these semantics. 00150 auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl)); 00151 llvm::Constant *Aliasee = Ref; 00152 if (Ref->getType() != AliasType) 00153 Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType); 00154 00155 // Instead of creating as alias to a linkonce_odr, replace all of the uses 00156 // of the aliasee. 00157 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) && 00158 (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage || 00159 !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) { 00160 // FIXME: An extern template instantiation will create functions with 00161 // linkage "AvailableExternally". In libc++, some classes also define 00162 // members with attribute "AlwaysInline" and expect no reference to 00163 // be generated. It is desirable to reenable this optimisation after 00164 // corresponding LLVM changes. 00165 Replacements[MangledName] = Aliasee; 00166 return false; 00167 } 00168 00169 if (!InEveryTU) { 00170 /// If we don't have a definition for the destructor yet, don't 00171 /// emit. We can't emit aliases to declarations; that's just not 00172 /// how aliases work. 00173 if (Ref->isDeclaration()) 00174 return true; 00175 } 00176 00177 // Don't create an alias to a linker weak symbol. This avoids producing 00178 // different COMDATs in different TUs. Another option would be to 00179 // output the alias both for weak_odr and linkonce_odr, but that 00180 // requires explicit comdat support in the IL. 00181 if (llvm::GlobalValue::isWeakForLinker(TargetLinkage)) 00182 return true; 00183 00184 // Create the alias with no name. 00185 auto *Alias = llvm::GlobalAlias::create(AliasType->getElementType(), 0, 00186 Linkage, "", Aliasee, &getModule()); 00187 00188 // Switch any previous uses to the alias. 00189 if (Entry) { 00190 assert(Entry->getType() == AliasType && 00191 "declaration exists with different type"); 00192 Alias->takeName(Entry); 00193 Entry->replaceAllUsesWith(Alias); 00194 Entry->eraseFromParent(); 00195 } else { 00196 Alias->setName(MangledName); 00197 } 00198 00199 // Finally, set up the alias with its proper name and attributes. 00200 setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias); 00201 00202 return false; 00203 } 00204 00205 llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD, 00206 StructorType Type) { 00207 const CGFunctionInfo &FnInfo = 00208 getTypes().arrangeCXXStructorDeclaration(MD, Type); 00209 auto *Fn = cast<llvm::Function>( 00210 getAddrOfCXXStructor(MD, Type, &FnInfo, nullptr, true)); 00211 00212 GlobalDecl GD; 00213 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) { 00214 GD = GlobalDecl(DD, toCXXDtorType(Type)); 00215 } else { 00216 const auto *CD = cast<CXXConstructorDecl>(MD); 00217 GD = GlobalDecl(CD, toCXXCtorType(Type)); 00218 } 00219 00220 setFunctionLinkage(GD, Fn); 00221 CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo); 00222 setFunctionDefinitionAttributes(MD, Fn); 00223 SetLLVMFunctionAttributesForDefinition(MD, Fn); 00224 return Fn; 00225 } 00226 00227 llvm::GlobalValue *CodeGenModule::getAddrOfCXXStructor( 00228 const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo, 00229 llvm::FunctionType *FnType, bool DontDefer) { 00230 GlobalDecl GD; 00231 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) { 00232 GD = GlobalDecl(CD, toCXXCtorType(Type)); 00233 } else { 00234 auto *DD = dyn_cast<CXXDestructorDecl>(MD); 00235 GD = GlobalDecl(DD, toCXXDtorType(Type)); 00236 } 00237 00238 StringRef Name = getMangledName(GD); 00239 if (llvm::GlobalValue *Existing = GetGlobalValue(Name)) 00240 return Existing; 00241 00242 if (!FnType) { 00243 if (!FnInfo) 00244 FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type); 00245 FnType = getTypes().GetFunctionType(*FnInfo); 00246 } 00247 00248 return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FnType, GD, 00249 /*ForVTable=*/false, 00250 DontDefer)); 00251 } 00252 00253 static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF, 00254 GlobalDecl GD, 00255 llvm::Type *Ty, 00256 const CXXRecordDecl *RD) { 00257 assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() && 00258 "No kext in Microsoft ABI"); 00259 GD = GD.getCanonicalDecl(); 00260 CodeGenModule &CGM = CGF.CGM; 00261 llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits()); 00262 Ty = Ty->getPointerTo()->getPointerTo(); 00263 VTable = CGF.Builder.CreateBitCast(VTable, Ty); 00264 assert(VTable && "BuildVirtualCall = kext vtbl pointer is null"); 00265 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD); 00266 uint64_t AddressPoint = 00267 CGM.getItaniumVTableContext().getVTableLayout(RD) 00268 .getAddressPoint(BaseSubobject(RD, CharUnits::Zero())); 00269 VTableIndex += AddressPoint; 00270 llvm::Value *VFuncPtr = 00271 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt"); 00272 return CGF.Builder.CreateLoad(VFuncPtr); 00273 } 00274 00275 /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making 00276 /// indirect call to virtual functions. It makes the call through indexing 00277 /// into the vtable. 00278 llvm::Value * 00279 CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 00280 NestedNameSpecifier *Qual, 00281 llvm::Type *Ty) { 00282 assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) && 00283 "BuildAppleKextVirtualCall - bad Qual kind"); 00284 00285 const Type *QTy = Qual->getAsType(); 00286 QualType T = QualType(QTy, 0); 00287 const RecordType *RT = T->getAs<RecordType>(); 00288 assert(RT && "BuildAppleKextVirtualCall - Qual type must be record"); 00289 const auto *RD = cast<CXXRecordDecl>(RT->getDecl()); 00290 00291 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) 00292 return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD); 00293 00294 return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD); 00295 } 00296 00297 /// BuildVirtualCall - This routine makes indirect vtable call for 00298 /// call to virtual destructors. It returns 0 if it could not do it. 00299 llvm::Value * 00300 CodeGenFunction::BuildAppleKextVirtualDestructorCall( 00301 const CXXDestructorDecl *DD, 00302 CXXDtorType Type, 00303 const CXXRecordDecl *RD) { 00304 const auto *MD = cast<CXXMethodDecl>(DD); 00305 // FIXME. Dtor_Base dtor is always direct!! 00306 // It need be somehow inline expanded into the caller. 00307 // -O does that. But need to support -O0 as well. 00308 if (MD->isVirtual() && Type != Dtor_Base) { 00309 // Compute the function type we're calling. 00310 const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration( 00311 DD, StructorType::Complete); 00312 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo); 00313 return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD); 00314 } 00315 return nullptr; 00316 }