1 //===--- CGCXX.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 "CodeGenModule.h" 17 #include "CGCXXABI.h" 18 #include "CodeGenFunction.h" 19 #include "clang/AST/ASTContext.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclCXX.h" 22 #include "clang/AST/DeclObjC.h" 23 #include "clang/AST/Mangle.h" 24 #include "clang/AST/RecordLayout.h" 25 #include "clang/AST/StmtCXX.h" 26 #include "clang/Frontend/CodeGenOptions.h" 27 #include "llvm/ADT/StringExtras.h" 28 using namespace clang; 29 using namespace CodeGen; 30 31 32 /// Try to emit a base destructor as an alias to its primary 33 /// base-class destructor. 34 bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) { 35 if (!getCodeGenOpts().CXXCtorDtorAliases) 36 return true; 37 38 // Producing an alias to a base class ctor/dtor can degrade debug quality 39 // as the debugger cannot tell them apart. 40 if (getCodeGenOpts().OptimizationLevel == 0) 41 return true; 42 43 // If sanitizing memory to check for use-after-dtor, do not emit as 44 // an alias, unless this class owns no members. 45 if (getCodeGenOpts().SanitizeMemoryUseAfterDtor && 46 !D->getParent()->field_empty()) 47 return true; 48 49 // If the destructor doesn't have a trivial body, we have to emit it 50 // separately. 51 if (!D->hasTrivialBody()) 52 return true; 53 54 const CXXRecordDecl *Class = D->getParent(); 55 56 // We are going to instrument this destructor, so give up even if it is 57 // currently empty. 58 if (Class->mayInsertExtraPadding()) 59 return true; 60 61 // If we need to manipulate a VTT parameter, give up. 62 if (Class->getNumVBases()) { 63 // Extra Credit: passing extra parameters is perfectly safe 64 // in many calling conventions, so only bail out if the ctor's 65 // calling convention is nonstandard. 66 return true; 67 } 68 69 // If any field has a non-trivial destructor, we have to emit the 70 // destructor separately. 71 for (const auto *I : Class->fields()) 72 if (I->getType().isDestructedType()) 73 return true; 74 75 // Try to find a unique base class with a non-trivial destructor. 76 const CXXRecordDecl *UniqueBase = nullptr; 77 for (const auto &I : Class->bases()) { 78 79 // We're in the base destructor, so skip virtual bases. 80 if (I.isVirtual()) continue; 81 82 // Skip base classes with trivial destructors. 83 const auto *Base = 84 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl()); 85 if (Base->hasTrivialDestructor()) continue; 86 87 // If we've already found a base class with a non-trivial 88 // destructor, give up. 89 if (UniqueBase) return true; 90 UniqueBase = Base; 91 } 92 93 // If we didn't find any bases with a non-trivial destructor, then 94 // the base destructor is actually effectively trivial, which can 95 // happen if it was needlessly user-defined or if there are virtual 96 // bases with non-trivial destructors. 97 if (!UniqueBase) 98 return true; 99 100 // If the base is at a non-zero offset, give up. 101 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class); 102 if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero()) 103 return true; 104 105 // Give up if the calling conventions don't match. We could update the call, 106 // but it is probably not worth it. 107 const CXXDestructorDecl *BaseD = UniqueBase->getDestructor(); 108 if (BaseD->getType()->getAs<FunctionType>()->getCallConv() != 109 D->getType()->getAs<FunctionType>()->getCallConv()) 110 return true; 111 112 return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base), 113 GlobalDecl(BaseD, Dtor_Base), 114 false); 115 } 116 117 /// Try to emit a definition as a global alias for another definition. 118 /// If \p InEveryTU is true, we know that an equivalent alias can be produced 119 /// in every translation unit. 120 bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl, 121 GlobalDecl TargetDecl, 122 bool InEveryTU) { 123 if (!getCodeGenOpts().CXXCtorDtorAliases) 124 return true; 125 126 // The alias will use the linkage of the referent. If we can't 127 // support aliases with that linkage, fail. 128 llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl); 129 130 // We can't use an alias if the linkage is not valid for one. 131 if (!llvm::GlobalAlias::isValidLinkage(Linkage)) 132 return true; 133 134 // Don't create a weak alias for a dllexport'd symbol. 135 if (AliasDecl.getDecl()->hasAttr<DLLExportAttr>() && 136 llvm::GlobalValue::isWeakForLinker(Linkage)) 137 return true; 138 139 llvm::GlobalValue::LinkageTypes TargetLinkage = 140 getFunctionLinkage(TargetDecl); 141 142 // Check if we have it already. 143 StringRef MangledName = getMangledName(AliasDecl); 144 llvm::GlobalValue *Entry = GetGlobalValue(MangledName); 145 if (Entry && !Entry->isDeclaration()) 146 return false; 147 if (Replacements.count(MangledName)) 148 return false; 149 150 // Derive the type for the alias. 151 llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl); 152 llvm::PointerType *AliasType = AliasValueType->getPointerTo(); 153 154 // Find the referent. Some aliases might require a bitcast, in 155 // which case the caller is responsible for ensuring the soundness 156 // of these semantics. 157 auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl)); 158 llvm::Constant *Aliasee = Ref; 159 if (Ref->getType() != AliasType) 160 Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType); 161 162 // Instead of creating as alias to a linkonce_odr, replace all of the uses 163 // of the aliasee. 164 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) && 165 (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage || 166 !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) { 167 // FIXME: An extern template instantiation will create functions with 168 // linkage "AvailableExternally". In libc++, some classes also define 169 // members with attribute "AlwaysInline" and expect no reference to 170 // be generated. It is desirable to reenable this optimisation after 171 // corresponding LLVM changes. 172 Replacements[MangledName] = Aliasee; 173 return false; 174 } 175 176 if (!InEveryTU) { 177 // If we don't have a definition for the destructor yet, don't 178 // emit. We can't emit aliases to declarations; that's just not 179 // how aliases work. 180 if (Ref->isDeclaration()) 181 return true; 182 } 183 184 // Don't create an alias to a linker weak symbol. This avoids producing 185 // different COMDATs in different TUs. Another option would be to 186 // output the alias both for weak_odr and linkonce_odr, but that 187 // requires explicit comdat support in the IL. 188 if (llvm::GlobalValue::isWeakForLinker(TargetLinkage)) 189 return true; 190 191 // Create the alias with no name. 192 auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "", 193 Aliasee, &getModule()); 194 195 // Switch any previous uses to the alias. 196 if (Entry) { 197 assert(Entry->getType() == AliasType && 198 "declaration exists with different type"); 199 Alias->takeName(Entry); 200 Entry->replaceAllUsesWith(Alias); 201 Entry->eraseFromParent(); 202 } else { 203 Alias->setName(MangledName); 204 } 205 206 // Finally, set up the alias with its proper name and attributes. 207 setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias); 208 209 return false; 210 } 211 212 llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD, 213 StructorType Type) { 214 const CGFunctionInfo &FnInfo = 215 getTypes().arrangeCXXStructorDeclaration(MD, Type); 216 auto *Fn = cast<llvm::Function>( 217 getAddrOfCXXStructor(MD, Type, &FnInfo, /*FnType=*/nullptr, 218 /*DontDefer=*/true, /*IsForDefinition=*/true)); 219 220 GlobalDecl GD; 221 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) { 222 GD = GlobalDecl(DD, toCXXDtorType(Type)); 223 } else { 224 const auto *CD = cast<CXXConstructorDecl>(MD); 225 GD = GlobalDecl(CD, toCXXCtorType(Type)); 226 } 227 228 setFunctionLinkage(GD, Fn); 229 setFunctionDLLStorageClass(GD, Fn); 230 231 CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo); 232 setFunctionDefinitionAttributes(MD, Fn); 233 SetLLVMFunctionAttributesForDefinition(MD, Fn); 234 return Fn; 235 } 236 237 llvm::Constant *CodeGenModule::getAddrOfCXXStructor( 238 const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo, 239 llvm::FunctionType *FnType, bool DontDefer, bool IsForDefinition) { 240 GlobalDecl GD; 241 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) { 242 GD = GlobalDecl(CD, toCXXCtorType(Type)); 243 } else { 244 GD = GlobalDecl(cast<CXXDestructorDecl>(MD), toCXXDtorType(Type)); 245 } 246 247 if (!FnType) { 248 if (!FnInfo) 249 FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type); 250 FnType = getTypes().GetFunctionType(*FnInfo); 251 } 252 253 return GetOrCreateLLVMFunction( 254 getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer, 255 /*isThunk=*/false, /*ExtraAttrs=*/llvm::AttributeSet(), IsForDefinition); 256 } 257 258 static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF, 259 GlobalDecl GD, 260 llvm::Type *Ty, 261 const CXXRecordDecl *RD) { 262 assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() && 263 "No kext in Microsoft ABI"); 264 GD = GD.getCanonicalDecl(); 265 CodeGenModule &CGM = CGF.CGM; 266 llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits()); 267 Ty = Ty->getPointerTo()->getPointerTo(); 268 VTable = CGF.Builder.CreateBitCast(VTable, Ty); 269 assert(VTable && "BuildVirtualCall = kext vtbl pointer is null"); 270 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD); 271 uint64_t AddressPoint = 272 CGM.getItaniumVTableContext().getVTableLayout(RD) 273 .getAddressPoint(BaseSubobject(RD, CharUnits::Zero())); 274 VTableIndex += AddressPoint; 275 llvm::Value *VFuncPtr = 276 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt"); 277 return CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.PointerAlignInBytes); 278 } 279 280 /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making 281 /// indirect call to virtual functions. It makes the call through indexing 282 /// into the vtable. 283 llvm::Value * 284 CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 285 NestedNameSpecifier *Qual, 286 llvm::Type *Ty) { 287 assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) && 288 "BuildAppleKextVirtualCall - bad Qual kind"); 289 290 const Type *QTy = Qual->getAsType(); 291 QualType T = QualType(QTy, 0); 292 const RecordType *RT = T->getAs<RecordType>(); 293 assert(RT && "BuildAppleKextVirtualCall - Qual type must be record"); 294 const auto *RD = cast<CXXRecordDecl>(RT->getDecl()); 295 296 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) 297 return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD); 298 299 return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD); 300 } 301 302 /// BuildVirtualCall - This routine makes indirect vtable call for 303 /// call to virtual destructors. It returns 0 if it could not do it. 304 llvm::Value * 305 CodeGenFunction::BuildAppleKextVirtualDestructorCall( 306 const CXXDestructorDecl *DD, 307 CXXDtorType Type, 308 const CXXRecordDecl *RD) { 309 const auto *MD = cast<CXXMethodDecl>(DD); 310 // FIXME. Dtor_Base dtor is always direct!! 311 // It need be somehow inline expanded into the caller. 312 // -O does that. But need to support -O0 as well. 313 if (MD->isVirtual() && Type != Dtor_Base) { 314 // Compute the function type we're calling. 315 const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration( 316 DD, StructorType::Complete); 317 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo); 318 return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD); 319 } 320 return nullptr; 321 } 322