]> CyberLeo.Net >> Repos - FreeBSD/FreeBSD.git/blob - contrib/llvm/tools/clang/lib/CodeGen/CGCXX.cpp
Upgrade our copies of clang, llvm, lldb, compiler-rt and libc++ to 3.7.0
[FreeBSD/FreeBSD.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 apart.
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   // We are going to instrument this destructor, so give up even if it is
50   // currently empty.
51   if (Class->mayInsertExtraPadding())
52     return true;
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 field has a non-trivial destructor, we have to emit the
63   // destructor separately.
64   for (const auto *I : Class->fields())
65     if (I->getType().isDestructedType())
66       return true;
67
68   // Try to find a unique base class with a non-trivial destructor.
69   const CXXRecordDecl *UniqueBase = nullptr;
70   for (const auto &I : Class->bases()) {
71
72     // We're in the base destructor, so skip virtual bases.
73     if (I.isVirtual()) continue;
74
75     // Skip base classes with trivial destructors.
76     const auto *Base =
77         cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
78     if (Base->hasTrivialDestructor()) continue;
79
80     // If we've already found a base class with a non-trivial
81     // destructor, give up.
82     if (UniqueBase) return true;
83     UniqueBase = Base;
84   }
85
86   // If we didn't find any bases with a non-trivial destructor, then
87   // the base destructor is actually effectively trivial, which can
88   // happen if it was needlessly user-defined or if there are virtual
89   // bases with non-trivial destructors.
90   if (!UniqueBase)
91     return true;
92
93   // If the base is at a non-zero offset, give up.
94   const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
95   if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
96     return true;
97
98   // Give up if the calling conventions don't match. We could update the call,
99   // but it is probably not worth it.
100   const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
101   if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
102       D->getType()->getAs<FunctionType>()->getCallConv())
103     return true;
104
105   return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
106                                   GlobalDecl(BaseD, Dtor_Base),
107                                   false);
108 }
109
110 /// Try to emit a definition as a global alias for another definition.
111 /// If \p InEveryTU is true, we know that an equivalent alias can be produced
112 /// in every translation unit.
113 bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
114                                              GlobalDecl TargetDecl,
115                                              bool InEveryTU) {
116   if (!getCodeGenOpts().CXXCtorDtorAliases)
117     return true;
118
119   // The alias will use the linkage of the referent.  If we can't
120   // support aliases with that linkage, fail.
121   llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
122
123   // We can't use an alias if the linkage is not valid for one.
124   if (!llvm::GlobalAlias::isValidLinkage(Linkage))
125     return true;
126
127   // Don't create a weak alias for a dllexport'd symbol.
128   if (AliasDecl.getDecl()->hasAttr<DLLExportAttr>() &&
129       llvm::GlobalValue::isWeakForLinker(Linkage))
130     return true;
131
132   llvm::GlobalValue::LinkageTypes TargetLinkage =
133       getFunctionLinkage(TargetDecl);
134
135   // Check if we have it already.
136   StringRef MangledName = getMangledName(AliasDecl);
137   llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
138   if (Entry && !Entry->isDeclaration())
139     return false;
140   if (Replacements.count(MangledName))
141     return false;
142
143   // Derive the type for the alias.
144   llvm::PointerType *AliasType
145     = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
146
147   // Find the referent.  Some aliases might require a bitcast, in
148   // which case the caller is responsible for ensuring the soundness
149   // of these semantics.
150   auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
151   llvm::Constant *Aliasee = Ref;
152   if (Ref->getType() != AliasType)
153     Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
154
155   // Instead of creating as alias to a linkonce_odr, replace all of the uses
156   // of the aliasee.
157   if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
158      (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
159       !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
160     // FIXME: An extern template instantiation will create functions with
161     // linkage "AvailableExternally". In libc++, some classes also define
162     // members with attribute "AlwaysInline" and expect no reference to
163     // be generated. It is desirable to reenable this optimisation after
164     // corresponding LLVM changes.
165     Replacements[MangledName] = Aliasee;
166     return false;
167   }
168
169   if (!InEveryTU) {
170     // If we don't have a definition for the destructor yet, don't
171     // emit.  We can't emit aliases to declarations; that's just not
172     // how aliases work.
173     if (Ref->isDeclaration())
174       return true;
175   }
176
177   // Don't create an alias to a linker weak symbol. This avoids producing
178   // different COMDATs in different TUs. Another option would be to
179   // output the alias both for weak_odr and linkonce_odr, but that
180   // requires explicit comdat support in the IL.
181   if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
182     return true;
183
184   // Create the alias with no name.
185   auto *Alias =
186       llvm::GlobalAlias::create(AliasType, Linkage, "", Aliasee, &getModule());
187
188   // Switch any previous uses to the alias.
189   if (Entry) {
190     assert(Entry->getType() == AliasType &&
191            "declaration exists with different type");
192     Alias->takeName(Entry);
193     Entry->replaceAllUsesWith(Alias);
194     Entry->eraseFromParent();
195   } else {
196     Alias->setName(MangledName);
197   }
198
199   // Finally, set up the alias with its proper name and attributes.
200   setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
201
202   return false;
203 }
204
205 llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD,
206                                                   StructorType Type) {
207   const CGFunctionInfo &FnInfo =
208       getTypes().arrangeCXXStructorDeclaration(MD, Type);
209   auto *Fn = cast<llvm::Function>(
210       getAddrOfCXXStructor(MD, Type, &FnInfo, nullptr, true));
211
212   GlobalDecl GD;
213   if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
214     GD = GlobalDecl(DD, toCXXDtorType(Type));
215   } else {
216     const auto *CD = cast<CXXConstructorDecl>(MD);
217     GD = GlobalDecl(CD, toCXXCtorType(Type));
218   }
219
220   setFunctionLinkage(GD, Fn);
221   setFunctionDLLStorageClass(GD, Fn);
222
223   CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
224   setFunctionDefinitionAttributes(MD, Fn);
225   SetLLVMFunctionAttributesForDefinition(MD, Fn);
226   return Fn;
227 }
228
229 llvm::GlobalValue *CodeGenModule::getAddrOfCXXStructor(
230     const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
231     llvm::FunctionType *FnType, bool DontDefer) {
232   GlobalDecl GD;
233   if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
234     GD = GlobalDecl(CD, toCXXCtorType(Type));
235   } else {
236     GD = GlobalDecl(cast<CXXDestructorDecl>(MD), toCXXDtorType(Type));
237   }
238
239   StringRef Name = getMangledName(GD);
240   if (llvm::GlobalValue *Existing = GetGlobalValue(Name))
241     return Existing;
242
243   if (!FnType) {
244     if (!FnInfo)
245       FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
246     FnType = getTypes().GetFunctionType(*FnInfo);
247   }
248
249   return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FnType, GD,
250                                                       /*ForVTable=*/false,
251                                                       DontDefer));
252 }
253
254 static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
255                                               GlobalDecl GD,
256                                               llvm::Type *Ty,
257                                               const CXXRecordDecl *RD) {
258   assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
259          "No kext in Microsoft ABI");
260   GD = GD.getCanonicalDecl();
261   CodeGenModule &CGM = CGF.CGM;
262   llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
263   Ty = Ty->getPointerTo()->getPointerTo();
264   VTable = CGF.Builder.CreateBitCast(VTable, Ty);
265   assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
266   uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
267   uint64_t AddressPoint =
268     CGM.getItaniumVTableContext().getVTableLayout(RD)
269        .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
270   VTableIndex += AddressPoint;
271   llvm::Value *VFuncPtr =
272     CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
273   return CGF.Builder.CreateLoad(VFuncPtr);
274 }
275
276 /// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
277 /// indirect call to virtual functions. It makes the call through indexing
278 /// into the vtable.
279 llvm::Value *
280 CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD, 
281                                   NestedNameSpecifier *Qual,
282                                   llvm::Type *Ty) {
283   assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
284          "BuildAppleKextVirtualCall - bad Qual kind");
285   
286   const Type *QTy = Qual->getAsType();
287   QualType T = QualType(QTy, 0);
288   const RecordType *RT = T->getAs<RecordType>();
289   assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
290   const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
291
292   if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
293     return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
294
295   return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
296 }
297
298 /// BuildVirtualCall - This routine makes indirect vtable call for
299 /// call to virtual destructors. It returns 0 if it could not do it.
300 llvm::Value *
301 CodeGenFunction::BuildAppleKextVirtualDestructorCall(
302                                             const CXXDestructorDecl *DD,
303                                             CXXDtorType Type,
304                                             const CXXRecordDecl *RD) {
305   const auto *MD = cast<CXXMethodDecl>(DD);
306   // FIXME. Dtor_Base dtor is always direct!!
307   // It need be somehow inline expanded into the caller.
308   // -O does that. But need to support -O0 as well.
309   if (MD->isVirtual() && Type != Dtor_Base) {
310     // Compute the function type we're calling.
311     const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
312         DD, StructorType::Complete);
313     llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
314     return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
315   }
316   return nullptr;
317 }