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 "CGCXXABI.h"
17 #include "CodeGenFunction.h"
18 #include "CodeGenModule.h"
19 #include "clang/AST/ASTContext.h"
20 #include "clang/AST/RecordLayout.h"
21 #include "clang/AST/Decl.h"
22 #include "clang/AST/DeclCXX.h"
23 #include "clang/AST/DeclObjC.h"
24 #include "clang/AST/Mangle.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 /// Determines whether the given function has a trivial body that does
32 /// not require any specific codegen.
33 static bool HasTrivialBody(const FunctionDecl *FD) {
34   Stmt *S = FD->getBody();
35   if (!S)
36     return true;
37   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
38     return true;
39   return false;
40 }
41 
42 /// Try to emit a base destructor as an alias to its primary
43 /// base-class destructor.
44 bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
45   if (!getCodeGenOpts().CXXCtorDtorAliases)
46     return true;
47 
48   // If the destructor doesn't have a trivial body, we have to emit it
49   // separately.
50   if (!HasTrivialBody(D))
51     return true;
52 
53   const CXXRecordDecl *Class = D->getParent();
54 
55   // If we need to manipulate a VTT parameter, give up.
56   if (Class->getNumVBases()) {
57     // Extra Credit:  passing extra parameters is perfectly safe
58     // in many calling conventions, so only bail out if the ctor's
59     // calling convention is nonstandard.
60     return true;
61   }
62 
63   // If any field has a non-trivial destructor, we have to emit the
64   // destructor separately.
65   for (CXXRecordDecl::field_iterator I = Class->field_begin(),
66          E = Class->field_end(); I != E; ++I)
67     if ((*I)->getType().isDestructedType())
68       return true;
69 
70   // Try to find a unique base class with a non-trivial destructor.
71   const CXXRecordDecl *UniqueBase = 0;
72   for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
73          E = Class->bases_end(); I != E; ++I) {
74 
75     // We're in the base destructor, so skip virtual bases.
76     if (I->isVirtual()) continue;
77 
78     // Skip base classes with trivial destructors.
79     const CXXRecordDecl *Base
80       = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
81     if (Base->hasTrivialDestructor()) continue;
82 
83     // If we've already found a base class with a non-trivial
84     // destructor, give up.
85     if (UniqueBase) return true;
86     UniqueBase = Base;
87   }
88 
89   // If we didn't find any bases with a non-trivial destructor, then
90   // the base destructor is actually effectively trivial, which can
91   // happen if it was needlessly user-defined or if there are virtual
92   // bases with non-trivial destructors.
93   if (!UniqueBase)
94     return true;
95 
96   /// If we don't have a definition for the destructor yet, don't
97   /// emit.  We can't emit aliases to declarations; that's just not
98   /// how aliases work.
99   const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
100   if (!BaseD->isImplicit() && !BaseD->hasBody())
101     return true;
102 
103   // If the base is at a non-zero offset, give up.
104   const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
105   if (ClassLayout.getBaseClassOffsetInBits(UniqueBase) != 0)
106     return true;
107 
108   return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
109                                   GlobalDecl(BaseD, Dtor_Base));
110 }
111 
112 /// Try to emit a definition as a global alias for another definition.
113 bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
114                                              GlobalDecl TargetDecl) {
115   if (!getCodeGenOpts().CXXCtorDtorAliases)
116     return true;
117 
118   // The alias will use the linkage of the referrent.  If we can't
119   // support aliases with that linkage, fail.
120   llvm::GlobalValue::LinkageTypes Linkage
121     = getFunctionLinkage(cast<FunctionDecl>(AliasDecl.getDecl()));
122 
123   switch (Linkage) {
124   // We can definitely emit aliases to definitions with external linkage.
125   case llvm::GlobalValue::ExternalLinkage:
126   case llvm::GlobalValue::ExternalWeakLinkage:
127     break;
128 
129   // Same with local linkage.
130   case llvm::GlobalValue::InternalLinkage:
131   case llvm::GlobalValue::PrivateLinkage:
132   case llvm::GlobalValue::LinkerPrivateLinkage:
133     break;
134 
135   // We should try to support linkonce linkages.
136   case llvm::GlobalValue::LinkOnceAnyLinkage:
137   case llvm::GlobalValue::LinkOnceODRLinkage:
138     return true;
139 
140   // Other linkages will probably never be supported.
141   default:
142     return true;
143   }
144 
145   llvm::GlobalValue::LinkageTypes TargetLinkage
146     = getFunctionLinkage(cast<FunctionDecl>(TargetDecl.getDecl()));
147 
148   if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
149     return true;
150 
151   // Derive the type for the alias.
152   const llvm::PointerType *AliasType
153     = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
154 
155   // Find the referrent.  Some aliases might require a bitcast, in
156   // which case the caller is responsible for ensuring the soundness
157   // of these semantics.
158   llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
159   llvm::Constant *Aliasee = Ref;
160   if (Ref->getType() != AliasType)
161     Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
162 
163   // Create the alias with no name.
164   llvm::GlobalAlias *Alias =
165     new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule());
166 
167   // Switch any previous uses to the alias.
168   llvm::StringRef MangledName = getMangledName(AliasDecl);
169   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
170   if (Entry) {
171     assert(Entry->isDeclaration() && "definition already exists for alias");
172     assert(Entry->getType() == AliasType &&
173            "declaration exists with different type");
174     Alias->takeName(Entry);
175     Entry->replaceAllUsesWith(Alias);
176     Entry->eraseFromParent();
177   } else {
178     Alias->setName(MangledName);
179   }
180 
181   // Finally, set up the alias with its proper name and attributes.
182   SetCommonAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
183 
184   return false;
185 }
186 
187 void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
188   // The constructor used for constructing this as a complete class;
189   // constucts the virtual bases, then calls the base constructor.
190   EmitGlobal(GlobalDecl(D, Ctor_Complete));
191 
192   // The constructor used for constructing this as a base class;
193   // ignores virtual bases.
194   EmitGlobal(GlobalDecl(D, Ctor_Base));
195 }
196 
197 void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *ctor,
198                                        CXXCtorType ctorType) {
199   // The complete constructor is equivalent to the base constructor
200   // for classes with no virtual bases.  Try to emit it as an alias.
201   if (ctorType == Ctor_Complete &&
202       !ctor->getParent()->getNumVBases() &&
203       !TryEmitDefinitionAsAlias(GlobalDecl(ctor, Ctor_Complete),
204                                 GlobalDecl(ctor, Ctor_Base)))
205     return;
206 
207   const CGFunctionInfo &fnInfo = getTypes().getFunctionInfo(ctor, ctorType);
208 
209   llvm::Function *fn =
210     cast<llvm::Function>(GetAddrOfCXXConstructor(ctor, ctorType, &fnInfo));
211   setFunctionLinkage(ctor, fn);
212 
213   CodeGenFunction(*this).GenerateCode(GlobalDecl(ctor, ctorType), fn, fnInfo);
214 
215   SetFunctionDefinitionAttributes(ctor, fn);
216   SetLLVMFunctionAttributesForDefinition(ctor, fn);
217 }
218 
219 llvm::GlobalValue *
220 CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor,
221                                        CXXCtorType ctorType,
222                                        const CGFunctionInfo *fnInfo) {
223   GlobalDecl GD(ctor, ctorType);
224 
225   llvm::StringRef name = getMangledName(GD);
226   if (llvm::GlobalValue *existing = GetGlobalValue(name))
227     return existing;
228 
229   if (!fnInfo) fnInfo = &getTypes().getFunctionInfo(ctor, ctorType);
230 
231   const FunctionProtoType *proto = ctor->getType()->castAs<FunctionProtoType>();
232   const llvm::FunctionType *fnType =
233     getTypes().GetFunctionType(*fnInfo, proto->isVariadic());
234   return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
235                                                       /*ForVTable=*/false));
236 }
237 
238 void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
239   // The destructor in a virtual table is always a 'deleting'
240   // destructor, which calls the complete destructor and then uses the
241   // appropriate operator delete.
242   if (D->isVirtual())
243     EmitGlobal(GlobalDecl(D, Dtor_Deleting));
244 
245   // The destructor used for destructing this as a most-derived class;
246   // call the base destructor and then destructs any virtual bases.
247   EmitGlobal(GlobalDecl(D, Dtor_Complete));
248 
249   // The destructor used for destructing this as a base class; ignores
250   // virtual bases.
251   EmitGlobal(GlobalDecl(D, Dtor_Base));
252 }
253 
254 void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *dtor,
255                                       CXXDtorType dtorType) {
256   // The complete destructor is equivalent to the base destructor for
257   // classes with no virtual bases, so try to emit it as an alias.
258   if (dtorType == Dtor_Complete &&
259       !dtor->getParent()->getNumVBases() &&
260       !TryEmitDefinitionAsAlias(GlobalDecl(dtor, Dtor_Complete),
261                                 GlobalDecl(dtor, Dtor_Base)))
262     return;
263 
264   // The base destructor is equivalent to the base destructor of its
265   // base class if there is exactly one non-virtual base class with a
266   // non-trivial destructor, there are no fields with a non-trivial
267   // destructor, and the body of the destructor is trivial.
268   if (dtorType == Dtor_Base && !TryEmitBaseDestructorAsAlias(dtor))
269     return;
270 
271   const CGFunctionInfo &fnInfo = getTypes().getFunctionInfo(dtor, dtorType);
272 
273   llvm::Function *fn =
274     cast<llvm::Function>(GetAddrOfCXXDestructor(dtor, dtorType, &fnInfo));
275   setFunctionLinkage(dtor, fn);
276 
277   CodeGenFunction(*this).GenerateCode(GlobalDecl(dtor, dtorType), fn, fnInfo);
278 
279   SetFunctionDefinitionAttributes(dtor, fn);
280   SetLLVMFunctionAttributesForDefinition(dtor, fn);
281 }
282 
283 llvm::GlobalValue *
284 CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
285                                       CXXDtorType dtorType,
286                                       const CGFunctionInfo *fnInfo) {
287   GlobalDecl GD(dtor, dtorType);
288 
289   llvm::StringRef name = getMangledName(GD);
290   if (llvm::GlobalValue *existing = GetGlobalValue(name))
291     return existing;
292 
293   if (!fnInfo) fnInfo = &getTypes().getFunctionInfo(dtor, dtorType);
294 
295   const llvm::FunctionType *fnType =
296     getTypes().GetFunctionType(*fnInfo, false);
297 
298   return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
299                                                       /*ForVTable=*/false));
300 }
301 
302 static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VTableIndex,
303                                      llvm::Value *This, const llvm::Type *Ty) {
304   Ty = Ty->getPointerTo()->getPointerTo();
305 
306   llvm::Value *VTable = CGF.GetVTablePtr(This, Ty);
307   llvm::Value *VFuncPtr =
308     CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
309   return CGF.Builder.CreateLoad(VFuncPtr);
310 }
311 
312 llvm::Value *
313 CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
314                                   const llvm::Type *Ty) {
315   MD = MD->getCanonicalDecl();
316   uint64_t VTableIndex = CGM.getVTables().getMethodVTableIndex(MD);
317 
318   return ::BuildVirtualCall(*this, VTableIndex, This, Ty);
319 }
320 
321 /// BuildVirtualCall - This routine is to support gcc's kext ABI making
322 /// indirect call to virtual functions. It makes the call through indexing
323 /// into the vtable.
324 llvm::Value *
325 CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
326                                   NestedNameSpecifier *Qual,
327                                   const llvm::Type *Ty) {
328   llvm::Value *VTable = 0;
329   assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
330          "BuildAppleKextVirtualCall - bad Qual kind");
331 
332   const Type *QTy = Qual->getAsType();
333   QualType T = QualType(QTy, 0);
334   const RecordType *RT = T->getAs<RecordType>();
335   assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
336   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
337 
338   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
339     return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
340 
341   VTable = CGM.getVTables().GetAddrOfVTable(RD);
342   Ty = Ty->getPointerTo()->getPointerTo();
343   VTable = Builder.CreateBitCast(VTable, Ty);
344   assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
345   MD = MD->getCanonicalDecl();
346   uint64_t VTableIndex = CGM.getVTables().getMethodVTableIndex(MD);
347   uint64_t AddressPoint =
348     CGM.getVTables().getAddressPoint(BaseSubobject(RD, CharUnits::Zero()), RD);
349   VTableIndex += AddressPoint;
350   llvm::Value *VFuncPtr =
351     Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
352   return Builder.CreateLoad(VFuncPtr);
353 }
354 
355 /// BuildVirtualCall - This routine makes indirect vtable call for
356 /// call to virtual destructors. It returns 0 if it could not do it.
357 llvm::Value *
358 CodeGenFunction::BuildAppleKextVirtualDestructorCall(
359                                             const CXXDestructorDecl *DD,
360                                             CXXDtorType Type,
361                                             const CXXRecordDecl *RD) {
362   llvm::Value * Callee = 0;
363   const CXXMethodDecl *MD = cast<CXXMethodDecl>(DD);
364   // FIXME. Dtor_Base dtor is always direct!!
365   // It need be somehow inline expanded into the caller.
366   // -O does that. But need to support -O0 as well.
367   if (MD->isVirtual() && Type != Dtor_Base) {
368     // Compute the function type we're calling.
369     const CGFunctionInfo *FInfo =
370     &CGM.getTypes().getFunctionInfo(cast<CXXDestructorDecl>(MD),
371                                     Dtor_Complete);
372     const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
373     const llvm::Type *Ty
374       = CGM.getTypes().GetFunctionType(*FInfo, FPT->isVariadic());
375 
376     llvm::Value *VTable = CGM.getVTables().GetAddrOfVTable(RD);
377     Ty = Ty->getPointerTo()->getPointerTo();
378     VTable = Builder.CreateBitCast(VTable, Ty);
379     DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
380     uint64_t VTableIndex =
381       CGM.getVTables().getMethodVTableIndex(GlobalDecl(DD, Type));
382     uint64_t AddressPoint =
383       CGM.getVTables().getAddressPoint(BaseSubobject(RD, CharUnits::Zero()), RD);
384     VTableIndex += AddressPoint;
385     llvm::Value *VFuncPtr =
386       Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
387     Callee = Builder.CreateLoad(VFuncPtr);
388   }
389   return Callee;
390 }
391 
392 llvm::Value *
393 CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
394                                   llvm::Value *This, const llvm::Type *Ty) {
395   DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
396   uint64_t VTableIndex =
397     CGM.getVTables().getMethodVTableIndex(GlobalDecl(DD, Type));
398 
399   return ::BuildVirtualCall(*this, VTableIndex, This, Ty);
400 }
401 
402