1 //===--- CGDecl.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 "CodeGenFunction.h"
17 #include "CodeGenModule.h"
18 #include "Mangle.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/StmtCXX.h"
25 #include "clang/CodeGen/CodeGenOptions.h"
26 #include "llvm/ADT/StringExtras.h"
27 using namespace clang;
28 using namespace CodeGen;
29 
30 /// Determines whether the given function has a trivial body that does
31 /// not require any specific codegen.
32 static bool HasTrivialBody(const FunctionDecl *FD) {
33   Stmt *S = FD->getBody();
34   if (!S)
35     return true;
36   if (isa<CompoundStmt>(S) && cast<CompoundStmt>(S)->body_empty())
37     return true;
38   return false;
39 }
40 
41 /// Try to emit a base destructor as an alias to its primary
42 /// base-class destructor.
43 bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
44   if (!getCodeGenOpts().CXXCtorDtorAliases)
45     return true;
46 
47   // If the destructor doesn't have a trivial body, we have to emit it
48   // separately.
49   if (!HasTrivialBody(D))
50     return true;
51 
52   const CXXRecordDecl *Class = D->getParent();
53 
54   // If we need to manipulate a VTT parameter, give up.
55   if (Class->getNumVBases()) {
56     // Extra Credit:  passing extra parameters is perfectly safe
57     // in many calling conventions, so only bail out if the ctor's
58     // calling convention is nonstandard.
59     return true;
60   }
61 
62   // If any fields have a non-trivial destructor, we have to emit it
63   // separately.
64   for (CXXRecordDecl::field_iterator I = Class->field_begin(),
65          E = Class->field_end(); I != E; ++I)
66     if (const RecordType *RT = (*I)->getType()->getAs<RecordType>())
67       if (!cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor())
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(getContext());
100   if (!BaseD->isImplicit() && !BaseD->getBody())
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.getBaseClassOffset(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   MangleBuffer MangledName;
169   getMangledName(MangledName, AliasDecl);
170   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
171   if (Entry) {
172     assert(Entry->isDeclaration() && "definition already exists for alias");
173     assert(Entry->getType() == AliasType &&
174            "declaration exists with different type");
175     Alias->takeName(Entry);
176     Entry->replaceAllUsesWith(Alias);
177     Entry->eraseFromParent();
178   } else {
179     Alias->setName(MangledName.getString());
180   }
181 
182   // Finally, set up the alias with its proper name and attributes.
183   SetCommonAttributes(AliasDecl.getDecl(), Alias);
184 
185   return false;
186 }
187 
188 void CodeGenModule::EmitCXXConstructors(const CXXConstructorDecl *D) {
189   // The constructor used for constructing this as a complete class;
190   // constucts the virtual bases, then calls the base constructor.
191   EmitGlobal(GlobalDecl(D, Ctor_Complete));
192 
193   // The constructor used for constructing this as a base class;
194   // ignores virtual bases.
195   EmitGlobal(GlobalDecl(D, Ctor_Base));
196 }
197 
198 void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *D,
199                                        CXXCtorType Type) {
200   // The complete constructor is equivalent to the base constructor
201   // for classes with no virtual bases.  Try to emit it as an alias.
202   if (Type == Ctor_Complete &&
203       !D->getParent()->getNumVBases() &&
204       !TryEmitDefinitionAsAlias(GlobalDecl(D, Ctor_Complete),
205                                 GlobalDecl(D, Ctor_Base)))
206     return;
207 
208   llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXConstructor(D, Type));
209 
210   CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
211 
212   SetFunctionDefinitionAttributes(D, Fn);
213   SetLLVMFunctionAttributesForDefinition(D, Fn);
214 }
215 
216 llvm::GlobalValue *
217 CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
218                                        CXXCtorType Type) {
219   MangleBuffer Name;
220   getMangledCXXCtorName(Name, D, Type);
221   if (llvm::GlobalValue *V = GetGlobalValue(Name))
222     return V;
223 
224   const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
225   const llvm::FunctionType *FTy =
226     getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
227                                FPT->isVariadic());
228   return cast<llvm::Function>(
229                       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
230 }
231 
232 void CodeGenModule::getMangledCXXCtorName(MangleBuffer &Name,
233                                           const CXXConstructorDecl *D,
234                                           CXXCtorType Type) {
235   getMangleContext().mangleCXXCtor(D, Type, Name.getBuffer());
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 *D,
255                                       CXXDtorType Type) {
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 (Type == Dtor_Complete &&
259       !D->getParent()->getNumVBases() &&
260       !TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Complete),
261                                 GlobalDecl(D, 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 (Type == Dtor_Base && !TryEmitBaseDestructorAsAlias(D))
269     return;
270 
271   llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXDestructor(D, Type));
272 
273   CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
274 
275   SetFunctionDefinitionAttributes(D, Fn);
276   SetLLVMFunctionAttributesForDefinition(D, Fn);
277 }
278 
279 llvm::GlobalValue *
280 CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
281                                       CXXDtorType Type) {
282   MangleBuffer Name;
283   getMangledCXXDtorName(Name, D, Type);
284   if (llvm::GlobalValue *V = GetGlobalValue(Name))
285     return V;
286 
287   const llvm::FunctionType *FTy =
288     getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
289 
290   return cast<llvm::Function>(
291                       GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(D, Type)));
292 }
293 
294 void CodeGenModule::getMangledCXXDtorName(MangleBuffer &Name,
295                                           const CXXDestructorDecl *D,
296                                           CXXDtorType Type) {
297   getMangleContext().mangleCXXDtor(D, Type, Name.getBuffer());
298 }
299 
300 static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VTableIndex,
301                                      llvm::Value *This, const llvm::Type *Ty) {
302   Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo();
303 
304   llvm::Value *VTable = CGF.Builder.CreateBitCast(This, Ty);
305   VTable = CGF.Builder.CreateLoad(VTable);
306 
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 llvm::Value *
322 CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
323                                   llvm::Value *&This, const llvm::Type *Ty) {
324   DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
325   uint64_t VTableIndex =
326     CGM.getVTables().getMethodVTableIndex(GlobalDecl(DD, Type));
327 
328   return ::BuildVirtualCall(*this, VTableIndex, This, Ty);
329 }
330