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