clang 19.0.0git
CGCXX.cpp
Go to the documentation of this file.
1//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with C++ code generation.
10//
11//===----------------------------------------------------------------------===//
12
13// We might split this into multiple files if it gets too unwieldy
14
15#include "CGCXXABI.h"
16#include "CodeGenFunction.h"
17#include "CodeGenModule.h"
19#include "clang/AST/Attr.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"
25#include "clang/AST/StmtCXX.h"
27#include "llvm/ADT/StringExtras.h"
28using namespace clang;
29using namespace CodeGen;
30
31
32/// Try to emit a base destructor as an alias to its primary
33/// base-class destructor.
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 // Disable this optimization for ARM64EC. FIXME: This probably should work,
44 // but getting the symbol table correct is complicated.
45 if (getTarget().getTriple().isWindowsArm64EC())
46 return true;
47
48 // If sanitizing memory to check for use-after-dtor, do not emit as
49 // an alias, unless this class owns no members.
50 if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
51 !D->getParent()->field_empty())
52 return true;
53
54 // If the destructor doesn't have a trivial body, we have to emit it
55 // separately.
56 if (!D->hasTrivialBody())
57 return true;
58
59 const CXXRecordDecl *Class = D->getParent();
60
61 // We are going to instrument this destructor, so give up even if it is
62 // currently empty.
63 if (Class->mayInsertExtraPadding())
64 return true;
65
66 // If we need to manipulate a VTT parameter, give up.
67 if (Class->getNumVBases()) {
68 // Extra Credit: passing extra parameters is perfectly safe
69 // in many calling conventions, so only bail out if the ctor's
70 // calling convention is nonstandard.
71 return true;
72 }
73
74 // If any field has a non-trivial destructor, we have to emit the
75 // destructor separately.
76 for (const auto *I : Class->fields())
77 if (I->getType().isDestructedType())
78 return true;
79
80 // Try to find a unique base class with a non-trivial destructor.
81 const CXXRecordDecl *UniqueBase = nullptr;
82 for (const auto &I : Class->bases()) {
83
84 // We're in the base destructor, so skip virtual bases.
85 if (I.isVirtual()) continue;
86
87 // Skip base classes with trivial destructors.
88 const auto *Base =
89 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
90 if (Base->hasTrivialDestructor()) continue;
91
92 // If we've already found a base class with a non-trivial
93 // destructor, give up.
94 if (UniqueBase) return true;
95 UniqueBase = Base;
96 }
97
98 // If we didn't find any bases with a non-trivial destructor, then
99 // the base destructor is actually effectively trivial, which can
100 // happen if it was needlessly user-defined or if there are virtual
101 // bases with non-trivial destructors.
102 if (!UniqueBase)
103 return true;
104
105 // If the base is at a non-zero offset, give up.
106 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
107 if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
108 return true;
109
110 // Give up if the calling conventions don't match. We could update the call,
111 // but it is probably not worth it.
112 const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
113 if (BaseD->getType()->castAs<FunctionType>()->getCallConv() !=
115 return true;
116
118 GlobalDecl TargetDecl(BaseD, Dtor_Base);
119
120 // The alias will use the linkage of the referent. If we can't
121 // support aliases with that linkage, fail.
122 llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
123
124 // We can't use an alias if the linkage is not valid for one.
125 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
126 return true;
127
128 llvm::GlobalValue::LinkageTypes TargetLinkage =
129 getFunctionLinkage(TargetDecl);
130
131 // Check if we have it already.
132 StringRef MangledName = getMangledName(AliasDecl);
133 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
134 if (Entry && !Entry->isDeclaration())
135 return false;
136 if (Replacements.count(MangledName))
137 return false;
138
139 llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
140
141 // Find the referent.
142 auto *Aliasee = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
143
144 // Instead of creating as alias to a linkonce_odr, replace all of the uses
145 // of the aliasee.
146 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
147 !(TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage &&
148 TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
149 // FIXME: An extern template instantiation will create functions with
150 // linkage "AvailableExternally". In libc++, some classes also define
151 // members with attribute "AlwaysInline" and expect no reference to
152 // be generated. It is desirable to reenable this optimisation after
153 // corresponding LLVM changes.
154 addReplacement(MangledName, Aliasee);
155 return false;
156 }
157
158 // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
159 // template instantiation or a dllexported class, avoid forming it on COFF.
160 // A COFF weak external alias cannot satisfy a normal undefined symbol
161 // reference from another TU. The other TU must also mark the referenced
162 // symbol as weak, which we cannot rely on.
163 if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
164 getTriple().isOSBinFormatCOFF()) {
165 return true;
166 }
167
168 // If we don't have a definition for the destructor yet or the definition is
169 // avaialable_externally, don't emit an alias. We can't emit aliases to
170 // declarations; that's just not how aliases work.
171 if (Aliasee->isDeclarationForLinker())
172 return true;
173
174 // Don't create an alias to a linker weak symbol. This avoids producing
175 // different COMDATs in different TUs. Another option would be to
176 // output the alias both for weak_odr and linkonce_odr, but that
177 // requires explicit comdat support in the IL.
178 if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
179 return true;
180
181 // Create the alias with no name.
182 auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
183 Aliasee, &getModule());
184
185 // Destructors are always unnamed_addr.
186 Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
187
188 // Switch any previous uses to the alias.
189 if (Entry) {
190 assert(Entry->getValueType() == AliasValueType &&
191 Entry->getAddressSpace() == Alias->getAddressSpace() &&
192 "declaration exists with different type");
193 Alias->takeName(Entry);
194 Entry->replaceAllUsesWith(Alias);
195 Entry->eraseFromParent();
196 } else {
197 Alias->setName(MangledName);
198 }
199
200 // Finally, set up the alias with its proper name and attributes.
202
203 return false;
204}
205
208 auto *Fn = cast<llvm::Function>(
209 getAddrOfCXXStructor(GD, &FnInfo, /*FnType=*/nullptr,
210 /*DontDefer=*/true, ForDefinition));
211
212 setFunctionLinkage(GD, Fn);
213
214 CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
215 setNonAliasAttributes(GD, Fn);
216 SetLLVMFunctionAttributesForDefinition(cast<CXXMethodDecl>(GD.getDecl()), Fn);
217 return Fn;
218}
219
221 GlobalDecl GD, const CGFunctionInfo *FnInfo, llvm::FunctionType *FnType,
222 bool DontDefer, ForDefinition_t IsForDefinition) {
223 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
224
225 if (isa<CXXDestructorDecl>(MD)) {
226 // Always alias equivalent complete destructors to base destructors in the
227 // MS ABI.
228 if (getTarget().getCXXABI().isMicrosoft() &&
229 GD.getDtorType() == Dtor_Complete &&
230 MD->getParent()->getNumVBases() == 0)
231 GD = GD.getWithDtorType(Dtor_Base);
232 }
233
234 if (!FnType) {
235 if (!FnInfo)
237 FnType = getTypes().GetFunctionType(*FnInfo);
238 }
239
240 llvm::Constant *Ptr = GetOrCreateLLVMFunction(
241 getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
242 /*IsThunk=*/false, /*ExtraAttrs=*/llvm::AttributeList(), IsForDefinition);
243 return {FnType, Ptr};
244}
245
247 GlobalDecl GD,
248 llvm::Type *Ty,
249 const CXXRecordDecl *RD) {
250 assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
251 "No kext in Microsoft ABI");
252 CodeGenModule &CGM = CGF.CGM;
253 llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
254 Ty = llvm::PointerType::getUnqual(CGM.getLLVMContext());
255 assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
256 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
257 const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD);
260 VTableIndex += VTLayout.getVTableOffset(AddressPoint.VTableIndex) +
261 AddressPoint.AddressPointIndex;
262 llvm::Value *VFuncPtr =
263 CGF.Builder.CreateConstInBoundsGEP1_64(Ty, VTable, VTableIndex, "vfnkxt");
264 llvm::Value *VFunc = CGF.Builder.CreateAlignedLoad(
265 Ty, VFuncPtr, llvm::Align(CGF.PointerAlignInBytes));
266 CGCallee Callee(GD, VFunc);
267 return Callee;
268}
269
270/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
271/// indirect call to virtual functions. It makes the call through indexing
272/// into the vtable.
276 llvm::Type *Ty) {
277 assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
278 "BuildAppleKextVirtualCall - bad Qual kind");
279
280 const Type *QTy = Qual->getAsType();
281 QualType T = QualType(QTy, 0);
282 const RecordType *RT = T->getAs<RecordType>();
283 assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
284 const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
285
286 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
288
289 return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
290}
291
292/// BuildVirtualCall - This routine makes indirect vtable call for
293/// call to virtual destructors. It returns 0 if it could not do it.
296 const CXXDestructorDecl *DD,
298 const CXXRecordDecl *RD) {
299 assert(DD->isVirtual() && Type != Dtor_Base);
300 // Compute the function type we're calling.
303 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
304 return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
305}
Defines the clang::ASTContext interface.
static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF, GlobalDecl GD, llvm::Type *Ty, const CXXRecordDecl *RD)
Definition: CGCXX.cpp:246
Defines the C++ Decl subclasses, other than those for templates (found in DeclTemplate....
const ASTRecordLayout & getASTRecordLayout(const RecordDecl *D) const
Get or compute information about the layout of the specified record (struct/union/class) D,...
ASTRecordLayout - This class contains layout information for one RecordDecl, which is a struct/union/...
Definition: RecordLayout.h:38
CharUnits getBaseClassOffset(const CXXRecordDecl *Base) const
getBaseClassOffset - Get the offset, in chars, for the given base class.
Definition: RecordLayout.h:249
Represents a C++ destructor within a class.
Definition: DeclCXX.h:2799
Represents a static or instance method of a struct/union/class.
Definition: DeclCXX.h:2060
bool isVirtual() const
Definition: DeclCXX.h:2115
const CXXRecordDecl * getParent() const
Return the parent of this method declaration, which is the class in which this method is defined.
Definition: DeclCXX.h:2186
Represents a C++ struct/union/class.
Definition: DeclCXX.h:258
CXXDestructorDecl * getDestructor() const
Returns the destructor decl for this class.
Definition: DeclCXX.cpp:1975
CharUnits - This is an opaque type for sizes expressed in character units.
Definition: CharUnits.h:38
bool isZero() const
isZero - Test whether the quantity equals zero.
Definition: CharUnits.h:122
static CharUnits Zero()
Zero - Construct a CharUnits quantity of zero.
Definition: CharUnits.h:53
llvm::LoadInst * CreateAlignedLoad(llvm::Type *Ty, llvm::Value *Addr, CharUnits Align, const llvm::Twine &Name="")
Definition: CGBuilder.h:128
virtual llvm::GlobalVariable * getAddrOfVTable(const CXXRecordDecl *RD, CharUnits VPtrOffset)=0
Get the address of the vtable for the given record decl which should be used for the vptr at the give...
All available information about a concrete callee.
Definition: CGCall.h:62
CGFunctionInfo - Class to encapsulate the information about a function definition.
CodeGenFunction - This class organizes the per-function state that is used while generating LLVM code...
CGCallee BuildAppleKextVirtualDestructorCall(const CXXDestructorDecl *DD, CXXDtorType Type, const CXXRecordDecl *RD)
CGCallee BuildAppleKextVirtualCall(const CXXMethodDecl *MD, NestedNameSpecifier *Qual, llvm::Type *Ty)
void GenerateCode(GlobalDecl GD, llvm::Function *Fn, const CGFunctionInfo &FnInfo)
This class organizes the cross-function state that is used while generating LLVM code.
llvm::Module & getModule() const
llvm::FunctionCallee getAddrAndTypeOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Definition: CGCXX.cpp:220
llvm::Constant * getAddrOfCXXStructor(GlobalDecl GD, const CGFunctionInfo *FnInfo=nullptr, llvm::FunctionType *FnType=nullptr, bool DontDefer=false, ForDefinition_t IsForDefinition=NotForDefinition)
Return the address of the constructor/destructor of the given type.
const TargetInfo & getTarget() const
bool TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D)
Try to emit a base destructor as an alias to its primary base-class destructor.
Definition: CGCXX.cpp:34
CGCXXABI & getCXXABI() const
llvm::Function * codegenCXXStructor(GlobalDecl GD)
Definition: CGCXX.cpp:206
const llvm::Triple & getTriple() const
llvm::GlobalVariable::LinkageTypes getFunctionLinkage(GlobalDecl GD)
void setFunctionLinkage(GlobalDecl GD, llvm::Function *F)
llvm::Constant * GetAddrOfGlobal(GlobalDecl GD, ForDefinition_t IsForDefinition=NotForDefinition)
ItaniumVTableContext & getItaniumVTableContext()
const CodeGenOptions & getCodeGenOpts() const
StringRef getMangledName(GlobalDecl GD)
void SetCommonAttributes(GlobalDecl GD, llvm::GlobalValue *GV)
Set attributes which are common to any form of a global definition (alias, Objective-C method,...
llvm::LLVMContext & getLLVMContext()
llvm::GlobalValue * GetGlobalValue(StringRef Ref)
void addReplacement(StringRef Name, llvm::Constant *C)
void SetLLVMFunctionAttributesForDefinition(const Decl *D, llvm::Function *F)
Set the LLVM function attributes which only apply to a function definition.
llvm::FunctionType * GetFunctionType(const CGFunctionInfo &Info)
GetFunctionType - Get the LLVM function type for.
Definition: CGCall.cpp:1632
const CGFunctionInfo & arrangeCXXStructorDeclaration(GlobalDecl GD)
Definition: CGCall.cpp:334
bool hasAttr() const
Definition: DeclBase.h:583
bool hasTrivialBody() const
Returns whether the function has a trivial body that does not require any specific codegen.
Definition: Decl.cpp:3167
FunctionType - C99 6.7.5.3 - Function Declarators.
Definition: Type.h:4257
CallingConv getCallConv() const
Definition: Type.h:4585
GlobalDecl - represents a global declaration.
Definition: GlobalDecl.h:56
GlobalDecl getWithDtorType(CXXDtorType Type)
Definition: GlobalDecl.h:176
CXXDtorType getDtorType() const
Definition: GlobalDecl.h:110
const Decl * getDecl() const
Definition: GlobalDecl.h:103
uint64_t getMethodVTableIndex(GlobalDecl GD)
Locate a virtual function in the vtable.
const VTableLayout & getVTableLayout(const CXXRecordDecl *RD)
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
SpecifierKind getKind() const
Determine what kind of nested name specifier is stored.
@ TypeSpec
A type, stored as a Type*.
const Type * getAsType() const
Retrieve the type stored in this nested name specifier.
A (possibly-)qualified type.
Definition: Type.h:940
bool field_empty() const
Definition: Decl.h:4384
A helper class that allows the use of isa/cast/dyncast to detect TagType objects of structs/unions/cl...
Definition: Type.h:5550
RecordDecl * getDecl() const
Definition: Type.h:5560
bool isMicrosoft() const
Is this ABI an MSVC-compatible ABI?
Definition: TargetCXXABI.h:136
TargetCXXABI getCXXABI() const
Get the C++ ABI currently in use.
Definition: TargetInfo.h:1327
The base class of the type hierarchy.
Definition: Type.h:1813
const T * castAs() const
Member-template castAs<specific type>.
Definition: Type.h:8198
const T * getAs() const
Member-template getAs<specific type>'.
Definition: Type.h:8131
size_t getVTableOffset(size_t i) const
AddressPointLocation getAddressPoint(BaseSubobject Base) const
QualType getType() const
Definition: Decl.h:717
The JSON file list parser is used to communicate input to InstallAPI.
Linkage
Describes the different kinds of linkage (C++ [basic.link], C99 6.2.2) that an entity may have.
Definition: Linkage.h:24
CXXDtorType
C++ destructor types.
Definition: ABI.h:33
@ Dtor_Base
Base object dtor.
Definition: ABI.h:36
@ Dtor_Complete
Complete object dtor.
Definition: ABI.h:35
const FunctionProtoType * T
@ Class
The "class" keyword introduces the elaborated-type-specifier.