xref: /freebsd/contrib/llvm-project/clang/lib/CodeGen/CGCXX.cpp (revision a7dea1671b87c07d2d266f836bfa8b58efc7c134)
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 "CodeGenModule.h"
16 #include "CGCXXABI.h"
17 #include "CodeGenFunction.h"
18 #include "clang/AST/ASTContext.h"
19 #include "clang/AST/Decl.h"
20 #include "clang/AST/DeclCXX.h"
21 #include "clang/AST/DeclObjC.h"
22 #include "clang/AST/Mangle.h"
23 #include "clang/AST/RecordLayout.h"
24 #include "clang/AST/StmtCXX.h"
25 #include "clang/Basic/CodeGenOptions.h"
26 #include "llvm/ADT/StringExtras.h"
27 using namespace clang;
28 using namespace CodeGen;
29 
30 
31 /// Try to emit a base destructor as an alias to its primary
32 /// base-class destructor.
33 bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
34   if (!getCodeGenOpts().CXXCtorDtorAliases)
35     return true;
36 
37   // Producing an alias to a base class ctor/dtor can degrade debug quality
38   // as the debugger cannot tell them apart.
39   if (getCodeGenOpts().OptimizationLevel == 0)
40     return true;
41 
42   // If sanitizing memory to check for use-after-dtor, do not emit as
43   //  an alias, unless this class owns no members.
44   if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
45       !D->getParent()->field_empty())
46     return true;
47 
48   // If the destructor doesn't have a trivial body, we have to emit it
49   // separately.
50   if (!D->hasTrivialBody())
51     return true;
52 
53   const CXXRecordDecl *Class = D->getParent();
54 
55   // We are going to instrument this destructor, so give up even if it is
56   // currently empty.
57   if (Class->mayInsertExtraPadding())
58     return true;
59 
60   // If we need to manipulate a VTT parameter, give up.
61   if (Class->getNumVBases()) {
62     // Extra Credit:  passing extra parameters is perfectly safe
63     // in many calling conventions, so only bail out if the ctor's
64     // calling convention is nonstandard.
65     return true;
66   }
67 
68   // If any field has a non-trivial destructor, we have to emit the
69   // destructor separately.
70   for (const auto *I : Class->fields())
71     if (I->getType().isDestructedType())
72       return true;
73 
74   // Try to find a unique base class with a non-trivial destructor.
75   const CXXRecordDecl *UniqueBase = nullptr;
76   for (const auto &I : Class->bases()) {
77 
78     // We're in the base destructor, so skip virtual bases.
79     if (I.isVirtual()) continue;
80 
81     // Skip base classes with trivial destructors.
82     const auto *Base =
83         cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl());
84     if (Base->hasTrivialDestructor()) continue;
85 
86     // If we've already found a base class with a non-trivial
87     // destructor, give up.
88     if (UniqueBase) return true;
89     UniqueBase = Base;
90   }
91 
92   // If we didn't find any bases with a non-trivial destructor, then
93   // the base destructor is actually effectively trivial, which can
94   // happen if it was needlessly user-defined or if there are virtual
95   // bases with non-trivial destructors.
96   if (!UniqueBase)
97     return true;
98 
99   // If the base is at a non-zero offset, give up.
100   const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
101   if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
102     return true;
103 
104   // Give up if the calling conventions don't match. We could update the call,
105   // but it is probably not worth it.
106   const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
107   if (BaseD->getType()->castAs<FunctionType>()->getCallConv() !=
108       D->getType()->castAs<FunctionType>()->getCallConv())
109     return true;
110 
111   GlobalDecl AliasDecl(D, Dtor_Base);
112   GlobalDecl TargetDecl(BaseD, Dtor_Base);
113 
114   // The alias will use the linkage of the referent.  If we can't
115   // support aliases with that linkage, fail.
116   llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
117 
118   // We can't use an alias if the linkage is not valid for one.
119   if (!llvm::GlobalAlias::isValidLinkage(Linkage))
120     return true;
121 
122   llvm::GlobalValue::LinkageTypes TargetLinkage =
123       getFunctionLinkage(TargetDecl);
124 
125   // Check if we have it already.
126   StringRef MangledName = getMangledName(AliasDecl);
127   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
128   if (Entry && !Entry->isDeclaration())
129     return false;
130   if (Replacements.count(MangledName))
131     return false;
132 
133   // Derive the type for the alias.
134   llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
135   llvm::PointerType *AliasType = AliasValueType->getPointerTo();
136 
137   // Find the referent.  Some aliases might require a bitcast, in
138   // which case the caller is responsible for ensuring the soundness
139   // of these semantics.
140   auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
141   llvm::Constant *Aliasee = Ref;
142   if (Ref->getType() != AliasType)
143     Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
144 
145   // Instead of creating as alias to a linkonce_odr, replace all of the uses
146   // of the aliasee.
147   if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
148       !(TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage &&
149         TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
150     // FIXME: An extern template instantiation will create functions with
151     // linkage "AvailableExternally". In libc++, some classes also define
152     // members with attribute "AlwaysInline" and expect no reference to
153     // be generated. It is desirable to reenable this optimisation after
154     // corresponding LLVM changes.
155     addReplacement(MangledName, Aliasee);
156     return false;
157   }
158 
159   // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
160   // template instantiation or a dllexported class, avoid forming it on COFF.
161   // A COFF weak external alias cannot satisfy a normal undefined symbol
162   // reference from another TU. The other TU must also mark the referenced
163   // symbol as weak, which we cannot rely on.
164   if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
165       getTriple().isOSBinFormatCOFF()) {
166     return true;
167   }
168 
169   // If we don't have a definition for the destructor yet or the definition is
170   // avaialable_externally, don't emit an alias.  We can't emit aliases to
171   // declarations; that's just not how aliases work.
172   if (Ref->isDeclarationForLinker())
173     return true;
174 
175   // Don't create an alias to a linker weak symbol. This avoids producing
176   // different COMDATs in different TUs. Another option would be to
177   // output the alias both for weak_odr and linkonce_odr, but that
178   // requires explicit comdat support in the IL.
179   if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
180     return true;
181 
182   // Create the alias with no name.
183   auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
184                                           Aliasee, &getModule());
185 
186   // Destructors are always unnamed_addr.
187   Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
188 
189   // Switch any previous uses to the alias.
190   if (Entry) {
191     assert(Entry->getType() == AliasType &&
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.
201   SetCommonAttributes(AliasDecl, Alias);
202 
203   return false;
204 }
205 
206 llvm::Function *CodeGenModule::codegenCXXStructor(GlobalDecl GD) {
207   const CGFunctionInfo &FnInfo = getTypes().arrangeCXXStructorDeclaration(GD);
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 
220 llvm::FunctionCallee CodeGenModule::getAddrAndTypeOfCXXStructor(
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)
236       FnInfo = &getTypes().arrangeCXXStructorDeclaration(GD);
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 
246 static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF,
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 = Ty->getPointerTo()->getPointerTo();
255   VTable = CGF.Builder.CreateBitCast(VTable, Ty);
256   assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
257   uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
258   const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD);
259   VTableLayout::AddressPointLocation AddressPoint =
260       VTLayout.getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
261   VTableIndex += VTLayout.getVTableOffset(AddressPoint.VTableIndex) +
262                  AddressPoint.AddressPointIndex;
263   llvm::Value *VFuncPtr =
264     CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
265   llvm::Value *VFunc =
266     CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.PointerAlignInBytes);
267   CGCallee Callee(GD, VFunc);
268   return Callee;
269 }
270 
271 /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
272 /// indirect call to virtual functions. It makes the call through indexing
273 /// into the vtable.
274 CGCallee
275 CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
276                                            NestedNameSpecifier *Qual,
277                                            llvm::Type *Ty) {
278   assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
279          "BuildAppleKextVirtualCall - bad Qual kind");
280 
281   const Type *QTy = Qual->getAsType();
282   QualType T = QualType(QTy, 0);
283   const RecordType *RT = T->getAs<RecordType>();
284   assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
285   const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
286 
287   if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
288     return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
289 
290   return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
291 }
292 
293 /// BuildVirtualCall - This routine makes indirect vtable call for
294 /// call to virtual destructors. It returns 0 if it could not do it.
295 CGCallee
296 CodeGenFunction::BuildAppleKextVirtualDestructorCall(
297                                             const CXXDestructorDecl *DD,
298                                             CXXDtorType Type,
299                                             const CXXRecordDecl *RD) {
300   assert(DD->isVirtual() && Type != Dtor_Base);
301   // Compute the function type we're calling.
302   const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
303       GlobalDecl(DD, Dtor_Complete));
304   llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
305   return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
306 }
307