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 "CGCXXABI.h"
17 #include "CodeGenFunction.h"
18 #include "CodeGenModule.h"
19 #include "Mangle.h"
20 #include "clang/AST/ASTContext.h"
21 #include "clang/AST/RecordLayout.h"
22 #include "clang/AST/Decl.h"
23 #include "clang/AST/DeclCXX.h"
24 #include "clang/AST/DeclObjC.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 fields have a non-trivial destructor, we have to emit it
64   // separately.
65   for (CXXRecordDecl::field_iterator I = Class->field_begin(),
66          E = Class->field_end(); I != E; ++I)
67     if (const RecordType *RT = (*I)->getType()->getAs<RecordType>())
68       if (!cast<CXXRecordDecl>(RT->getDecl())->hasTrivialDestructor())
69         return true;
70 
71   // Try to find a unique base class with a non-trivial destructor.
72   const CXXRecordDecl *UniqueBase = 0;
73   for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
74          E = Class->bases_end(); I != E; ++I) {
75 
76     // We're in the base destructor, so skip virtual bases.
77     if (I->isVirtual()) continue;
78 
79     // Skip base classes with trivial destructors.
80     const CXXRecordDecl *Base
81       = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
82     if (Base->hasTrivialDestructor()) continue;
83 
84     // If we've already found a base class with a non-trivial
85     // destructor, give up.
86     if (UniqueBase) return true;
87     UniqueBase = Base;
88   }
89 
90   // If we didn't find any bases with a non-trivial destructor, then
91   // the base destructor is actually effectively trivial, which can
92   // happen if it was needlessly user-defined or if there are virtual
93   // bases with non-trivial destructors.
94   if (!UniqueBase)
95     return true;
96 
97   /// If we don't have a definition for the destructor yet, don't
98   /// emit.  We can't emit aliases to declarations; that's just not
99   /// how aliases work.
100   const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
101   if (!BaseD->isImplicit() && !BaseD->hasBody())
102     return true;
103 
104   // If the base is at a non-zero offset, give up.
105   const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
106   if (ClassLayout.getBaseClassOffset(UniqueBase) != 0)
107     return true;
108 
109   return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
110                                   GlobalDecl(BaseD, Dtor_Base));
111 }
112 
113 /// Try to emit a definition as a global alias for another definition.
114 bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
115                                              GlobalDecl TargetDecl) {
116   if (!getCodeGenOpts().CXXCtorDtorAliases)
117     return true;
118 
119   // The alias will use the linkage of the referrent.  If we can't
120   // support aliases with that linkage, fail.
121   llvm::GlobalValue::LinkageTypes Linkage
122     = getFunctionLinkage(cast<FunctionDecl>(AliasDecl.getDecl()));
123 
124   switch (Linkage) {
125   // We can definitely emit aliases to definitions with external linkage.
126   case llvm::GlobalValue::ExternalLinkage:
127   case llvm::GlobalValue::ExternalWeakLinkage:
128     break;
129 
130   // Same with local linkage.
131   case llvm::GlobalValue::InternalLinkage:
132   case llvm::GlobalValue::PrivateLinkage:
133   case llvm::GlobalValue::LinkerPrivateLinkage:
134     break;
135 
136   // We should try to support linkonce linkages.
137   case llvm::GlobalValue::LinkOnceAnyLinkage:
138   case llvm::GlobalValue::LinkOnceODRLinkage:
139     return true;
140 
141   // Other linkages will probably never be supported.
142   default:
143     return true;
144   }
145 
146   llvm::GlobalValue::LinkageTypes TargetLinkage
147     = getFunctionLinkage(cast<FunctionDecl>(TargetDecl.getDecl()));
148 
149   if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
150     return true;
151 
152   // Derive the type for the alias.
153   const llvm::PointerType *AliasType
154     = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
155 
156   // Find the referrent.  Some aliases might require a bitcast, in
157   // which case the caller is responsible for ensuring the soundness
158   // of these semantics.
159   llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
160   llvm::Constant *Aliasee = Ref;
161   if (Ref->getType() != AliasType)
162     Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
163 
164   // Create the alias with no name.
165   llvm::GlobalAlias *Alias =
166     new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule());
167 
168   // Switch any previous uses to the alias.
169   llvm::StringRef MangledName = getMangledName(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);
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   setFunctionLinkage(D, Fn);
210 
211   CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
212 
213   SetFunctionDefinitionAttributes(D, Fn);
214   SetLLVMFunctionAttributesForDefinition(D, Fn);
215 }
216 
217 llvm::GlobalValue *
218 CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *D,
219                                        CXXCtorType Type) {
220   GlobalDecl GD(D, Type);
221 
222   llvm::StringRef Name = getMangledName(GD);
223   if (llvm::GlobalValue *V = GetGlobalValue(Name))
224     return V;
225 
226   const FunctionProtoType *FPT = D->getType()->getAs<FunctionProtoType>();
227   const llvm::FunctionType *FTy =
228     getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type),
229                                FPT->isVariadic());
230   return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FTy, GD));
231 }
232 
233 void CodeGenModule::EmitCXXDestructors(const CXXDestructorDecl *D) {
234   // The destructor in a virtual table is always a 'deleting'
235   // destructor, which calls the complete destructor and then uses the
236   // appropriate operator delete.
237   if (D->isVirtual())
238     EmitGlobal(GlobalDecl(D, Dtor_Deleting));
239 
240   // The destructor used for destructing this as a most-derived class;
241   // call the base destructor and then destructs any virtual bases.
242   EmitGlobal(GlobalDecl(D, Dtor_Complete));
243 
244   // The destructor used for destructing this as a base class; ignores
245   // virtual bases.
246   EmitGlobal(GlobalDecl(D, Dtor_Base));
247 }
248 
249 void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *D,
250                                       CXXDtorType Type) {
251   // The complete destructor is equivalent to the base destructor for
252   // classes with no virtual bases, so try to emit it as an alias.
253   if (Type == Dtor_Complete &&
254       !D->getParent()->getNumVBases() &&
255       !TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Complete),
256                                 GlobalDecl(D, Dtor_Base)))
257     return;
258 
259   // The base destructor is equivalent to the base destructor of its
260   // base class if there is exactly one non-virtual base class with a
261   // non-trivial destructor, there are no fields with a non-trivial
262   // destructor, and the body of the destructor is trivial.
263   if (Type == Dtor_Base && !TryEmitBaseDestructorAsAlias(D))
264     return;
265 
266   llvm::Function *Fn = cast<llvm::Function>(GetAddrOfCXXDestructor(D, Type));
267   setFunctionLinkage(D, Fn);
268 
269   CodeGenFunction(*this).GenerateCode(GlobalDecl(D, Type), Fn);
270 
271   SetFunctionDefinitionAttributes(D, Fn);
272   SetLLVMFunctionAttributesForDefinition(D, Fn);
273 }
274 
275 llvm::GlobalValue *
276 CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *D,
277                                       CXXDtorType Type) {
278   GlobalDecl GD(D, Type);
279 
280   llvm::StringRef Name = getMangledName(GD);
281   if (llvm::GlobalValue *V = GetGlobalValue(Name))
282     return V;
283 
284   const llvm::FunctionType *FTy =
285     getTypes().GetFunctionType(getTypes().getFunctionInfo(D, Type), false);
286 
287   return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FTy, GD));
288 }
289 
290 llvm::Constant *
291 CodeGenModule::GetCXXMemberFunctionPointerValue(const CXXMethodDecl *MD) {
292   assert(MD->isInstance() && "Member function must not be static!");
293 
294   MD = MD->getCanonicalDecl();
295 
296   const llvm::Type *PtrDiffTy = Types.ConvertType(Context.getPointerDiffType());
297 
298   // Get the function pointer (or index if this is a virtual function).
299   if (MD->isVirtual()) {
300     uint64_t Index = VTables.getMethodVTableIndex(MD);
301 
302     // FIXME: We shouldn't use / 8 here.
303     uint64_t PointerWidthInBytes = Context.Target.getPointerWidth(0) / 8;
304 
305     // Itanium C++ ABI 2.3:
306     //   For a non-virtual function, this field is a simple function pointer.
307     //   For a virtual function, it is 1 plus the virtual table offset
308     //   (in bytes) of the function, represented as a ptrdiff_t.
309     return llvm::ConstantInt::get(PtrDiffTy, (Index * PointerWidthInBytes) + 1);
310   }
311 
312   const FunctionProtoType *FPT = MD->getType()->getAs<FunctionProtoType>();
313   const llvm::Type *Ty;
314   // Check whether the function has a computable LLVM signature.
315   if (!CodeGenTypes::VerifyFuncTypeComplete(FPT)) {
316     // The function has a computable LLVM signature; use the correct type.
317     Ty = Types.GetFunctionType(Types.getFunctionInfo(MD), FPT->isVariadic());
318   } else {
319     // Use an arbitrary non-function type to tell GetAddrOfFunction that the
320     // function type is incomplete.
321     Ty = PtrDiffTy;
322   }
323 
324   llvm::Constant *FuncPtr = GetAddrOfFunction(MD, Ty);
325   return llvm::ConstantExpr::getPtrToInt(FuncPtr, PtrDiffTy);
326 }
327 
328 static llvm::Value *BuildVirtualCall(CodeGenFunction &CGF, uint64_t VTableIndex,
329                                      llvm::Value *This, const llvm::Type *Ty) {
330   Ty = Ty->getPointerTo()->getPointerTo()->getPointerTo();
331 
332   llvm::Value *VTable = CGF.Builder.CreateBitCast(This, Ty);
333   VTable = CGF.Builder.CreateLoad(VTable);
334 
335   llvm::Value *VFuncPtr =
336     CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfn");
337   return CGF.Builder.CreateLoad(VFuncPtr);
338 }
339 
340 llvm::Value *
341 CodeGenFunction::BuildVirtualCall(const CXXMethodDecl *MD, llvm::Value *This,
342                                   const llvm::Type *Ty) {
343   MD = MD->getCanonicalDecl();
344   uint64_t VTableIndex = CGM.getVTables().getMethodVTableIndex(MD);
345 
346   return ::BuildVirtualCall(*this, VTableIndex, This, Ty);
347 }
348 
349 llvm::Value *
350 CodeGenFunction::BuildVirtualCall(const CXXDestructorDecl *DD, CXXDtorType Type,
351                                   llvm::Value *&This, const llvm::Type *Ty) {
352   DD = cast<CXXDestructorDecl>(DD->getCanonicalDecl());
353   uint64_t VTableIndex =
354     CGM.getVTables().getMethodVTableIndex(GlobalDecl(DD, Type));
355 
356   return ::BuildVirtualCall(*this, VTableIndex, This, Ty);
357 }
358 
359 CXXABI::~CXXABI() {}
360