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   // If the destructor doesn't have a trivial body, we have to emit it
38   // separately.
39   if (!D->hasTrivialBody())
40     return true;
41 
42   const CXXRecordDecl *Class = D->getParent();
43 
44   // If we need to manipulate a VTT parameter, give up.
45   if (Class->getNumVBases()) {
46     // Extra Credit:  passing extra parameters is perfectly safe
47     // in many calling conventions, so only bail out if the ctor's
48     // calling convention is nonstandard.
49     return true;
50   }
51 
52   // If any field has a non-trivial destructor, we have to emit the
53   // destructor separately.
54   for (CXXRecordDecl::field_iterator I = Class->field_begin(),
55          E = Class->field_end(); I != E; ++I)
56     if (I->getType().isDestructedType())
57       return true;
58 
59   // Try to find a unique base class with a non-trivial destructor.
60   const CXXRecordDecl *UniqueBase = 0;
61   for (CXXRecordDecl::base_class_const_iterator I = Class->bases_begin(),
62          E = Class->bases_end(); I != E; ++I) {
63 
64     // We're in the base destructor, so skip virtual bases.
65     if (I->isVirtual()) continue;
66 
67     // Skip base classes with trivial destructors.
68     const CXXRecordDecl *Base
69       = cast<CXXRecordDecl>(I->getType()->getAs<RecordType>()->getDecl());
70     if (Base->hasTrivialDestructor()) continue;
71 
72     // If we've already found a base class with a non-trivial
73     // destructor, give up.
74     if (UniqueBase) return true;
75     UniqueBase = Base;
76   }
77 
78   // If we didn't find any bases with a non-trivial destructor, then
79   // the base destructor is actually effectively trivial, which can
80   // happen if it was needlessly user-defined or if there are virtual
81   // bases with non-trivial destructors.
82   if (!UniqueBase)
83     return true;
84 
85   /// If we don't have a definition for the destructor yet, don't
86   /// emit.  We can't emit aliases to declarations; that's just not
87   /// how aliases work.
88   const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
89   if (!BaseD->isImplicit() && !BaseD->hasBody())
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   return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
98                                   GlobalDecl(BaseD, Dtor_Base));
99 }
100 
101 /// Try to emit a definition as a global alias for another definition.
102 bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
103                                              GlobalDecl TargetDecl) {
104   if (!getCodeGenOpts().CXXCtorDtorAliases)
105     return true;
106 
107   // The alias will use the linkage of the referrent.  If we can't
108   // support aliases with that linkage, fail.
109   llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
110 
111   // We can't use an alias if the linkage is not valid for one.
112   if (!llvm::GlobalAlias::isValidLinkage(Linkage))
113     return true;
114 
115   llvm::GlobalValue::LinkageTypes TargetLinkage
116     = getFunctionLinkage(TargetDecl);
117 
118   // Don't create an strong alias to a linker weak symbol. If the linker
119   // decides to drop the symbol, the alias would become undefined.
120   if (llvm::GlobalValue::isWeakForLinker(TargetLinkage) &&
121       !llvm::GlobalValue::isWeakForLinker(Linkage))
122     return true;
123 
124   // Derive the type for the alias.
125   llvm::PointerType *AliasType
126     = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
127 
128   // Find the referrent.  Some aliases might require a bitcast, in
129   // which case the caller is responsible for ensuring the soundness
130   // of these semantics.
131   llvm::GlobalValue *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
132   llvm::Constant *Aliasee = Ref;
133   if (Ref->getType() != AliasType)
134     Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
135 
136   // Create the alias with no name.
137   llvm::GlobalAlias *Alias =
138     new llvm::GlobalAlias(AliasType, Linkage, "", Aliasee, &getModule());
139 
140   // Switch any previous uses to the alias.
141   StringRef MangledName = getMangledName(AliasDecl);
142   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
143   if (Entry) {
144     assert(Entry->isDeclaration() && "definition already exists for alias");
145     assert(Entry->getType() == AliasType &&
146            "declaration exists with different type");
147     Alias->takeName(Entry);
148     Entry->replaceAllUsesWith(Alias);
149     Entry->eraseFromParent();
150   } else {
151     Alias->setName(MangledName);
152   }
153 
154   // Finally, set up the alias with its proper name and attributes.
155   SetCommonAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
156 
157   return false;
158 }
159 
160 void CodeGenModule::EmitCXXConstructor(const CXXConstructorDecl *ctor,
161                                        CXXCtorType ctorType) {
162   // The complete constructor is equivalent to the base constructor
163   // for classes with no virtual bases.  Try to emit it as an alias.
164   if (getTarget().getCXXABI().hasConstructorVariants() &&
165       ctorType == Ctor_Complete &&
166       !ctor->getParent()->getNumVBases() &&
167       !TryEmitDefinitionAsAlias(GlobalDecl(ctor, Ctor_Complete),
168                                 GlobalDecl(ctor, Ctor_Base)))
169     return;
170 
171   const CGFunctionInfo &fnInfo =
172     getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType);
173 
174   llvm::Function *fn =
175     cast<llvm::Function>(GetAddrOfCXXConstructor(ctor, ctorType, &fnInfo));
176   setFunctionLinkage(GlobalDecl(ctor, ctorType), fn);
177 
178   CodeGenFunction(*this).GenerateCode(GlobalDecl(ctor, ctorType), fn, fnInfo);
179 
180   SetFunctionDefinitionAttributes(ctor, fn);
181   SetLLVMFunctionAttributesForDefinition(ctor, fn);
182 }
183 
184 llvm::GlobalValue *
185 CodeGenModule::GetAddrOfCXXConstructor(const CXXConstructorDecl *ctor,
186                                        CXXCtorType ctorType,
187                                        const CGFunctionInfo *fnInfo) {
188   GlobalDecl GD(ctor, ctorType);
189 
190   StringRef name = getMangledName(GD);
191   if (llvm::GlobalValue *existing = GetGlobalValue(name))
192     return existing;
193 
194   if (!fnInfo)
195     fnInfo = &getTypes().arrangeCXXConstructorDeclaration(ctor, ctorType);
196 
197   llvm::FunctionType *fnType = getTypes().GetFunctionType(*fnInfo);
198   return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
199                                                       /*ForVTable=*/false));
200 }
201 
202 void CodeGenModule::EmitCXXDestructor(const CXXDestructorDecl *dtor,
203                                       CXXDtorType dtorType) {
204   // The complete destructor is equivalent to the base destructor for
205   // classes with no virtual bases, so try to emit it as an alias.
206   if (dtorType == Dtor_Complete &&
207       !dtor->getParent()->getNumVBases() &&
208       !TryEmitDefinitionAsAlias(GlobalDecl(dtor, Dtor_Complete),
209                                 GlobalDecl(dtor, Dtor_Base)))
210     return;
211 
212   // The base destructor is equivalent to the base destructor of its
213   // base class if there is exactly one non-virtual base class with a
214   // non-trivial destructor, there are no fields with a non-trivial
215   // destructor, and the body of the destructor is trivial.
216   if (dtorType == Dtor_Base && !TryEmitBaseDestructorAsAlias(dtor))
217     return;
218 
219   const CGFunctionInfo &fnInfo =
220     getTypes().arrangeCXXDestructor(dtor, dtorType);
221 
222   llvm::Function *fn =
223     cast<llvm::Function>(GetAddrOfCXXDestructor(dtor, dtorType, &fnInfo));
224   setFunctionLinkage(GlobalDecl(dtor, dtorType), fn);
225 
226   CodeGenFunction(*this).GenerateCode(GlobalDecl(dtor, dtorType), fn, fnInfo);
227 
228   SetFunctionDefinitionAttributes(dtor, fn);
229   SetLLVMFunctionAttributesForDefinition(dtor, fn);
230 }
231 
232 llvm::GlobalValue *
233 CodeGenModule::GetAddrOfCXXDestructor(const CXXDestructorDecl *dtor,
234                                       CXXDtorType dtorType,
235                                       const CGFunctionInfo *fnInfo,
236                                       llvm::FunctionType *fnType) {
237   // If the class has no virtual bases, then the complete and base destructors
238   // are equivalent, for all C++ ABIs supported by clang.  We can save on code
239   // size by calling the base dtor directly, especially if we'd have to emit a
240   // thunk otherwise.
241   // FIXME: We should do this for Itanium, after verifying that nothing breaks.
242   if (dtorType == Dtor_Complete && dtor->getParent()->getNumVBases() == 0 &&
243       getCXXABI().useThunkForDtorVariant(dtor, Dtor_Complete))
244     dtorType = Dtor_Base;
245 
246   GlobalDecl GD(dtor, dtorType);
247 
248   StringRef name = getMangledName(GD);
249   if (llvm::GlobalValue *existing = GetGlobalValue(name))
250     return existing;
251 
252   if (!fnType) {
253     if (!fnInfo) fnInfo = &getTypes().arrangeCXXDestructor(dtor, dtorType);
254     fnType = getTypes().GetFunctionType(*fnInfo);
255   }
256   return cast<llvm::Function>(GetOrCreateLLVMFunction(name, fnType, GD,
257                                                       /*ForVTable=*/false));
258 }
259 
260 static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
261                                               GlobalDecl GD,
262                                               llvm::Type *Ty,
263                                               const CXXRecordDecl *RD) {
264   assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
265          "No kext in Microsoft ABI");
266   GD = GD.getCanonicalDecl();
267   CodeGenModule &CGM = CGF.CGM;
268   llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
269   Ty = Ty->getPointerTo()->getPointerTo();
270   VTable = CGF.Builder.CreateBitCast(VTable, Ty);
271   assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
272   uint64_t VTableIndex = CGM.getVTableContext().getMethodVTableIndex(GD);
273   uint64_t AddressPoint =
274     CGM.getVTableContext().getVTableLayout(RD)
275        .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
276   VTableIndex += AddressPoint;
277   llvm::Value *VFuncPtr =
278     CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
279   return CGF.Builder.CreateLoad(VFuncPtr);
280 }
281 
282 /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
283 /// indirect call to virtual functions. It makes the call through indexing
284 /// into the vtable.
285 llvm::Value *
286 CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
287                                   NestedNameSpecifier *Qual,
288                                   llvm::Type *Ty) {
289   assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
290          "BuildAppleKextVirtualCall - bad Qual kind");
291 
292   const Type *QTy = Qual->getAsType();
293   QualType T = QualType(QTy, 0);
294   const RecordType *RT = T->getAs<RecordType>();
295   assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
296   const CXXRecordDecl *RD = cast<CXXRecordDecl>(RT->getDecl());
297 
298   if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(MD))
299     return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
300 
301   return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
302 }
303 
304 /// BuildVirtualCall - This routine makes indirect vtable call for
305 /// call to virtual destructors. It returns 0 if it could not do it.
306 llvm::Value *
307 CodeGenFunction::BuildAppleKextVirtualDestructorCall(
308                                             const CXXDestructorDecl *DD,
309                                             CXXDtorType Type,
310                                             const CXXRecordDecl *RD) {
311   const CXXMethodDecl *MD = cast<CXXMethodDecl>(DD);
312   // FIXME. Dtor_Base dtor is always direct!!
313   // It need be somehow inline expanded into the caller.
314   // -O does that. But need to support -O0 as well.
315   if (MD->isVirtual() && Type != Dtor_Base) {
316     // Compute the function type we're calling.
317     const CGFunctionInfo &FInfo =
318       CGM.getTypes().arrangeCXXDestructor(DD, Dtor_Complete);
319     llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
320     return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
321   }
322   return 0;
323 }
324