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