blob: 93e17601cc61d9b6f2239e6192590ddbcf00c36a [file] [log] [blame]
Devang Patelcbc7bc92010-10-04 21:15:33 +00001//===--- CGCXX.cpp - Emit LLVM Code for declarations ----------------------===//
Anders Carlsson87fc5a52008-08-22 16:00:37 +00002//
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
Mike Stump11289f42009-09-09 15:08:12 +000014// We might split this into multiple files if it gets too unwieldy
Anders Carlsson87fc5a52008-08-22 16:00:37 +000015
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CodeGenModule.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000017#include "CGCXXABI.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000018#include "CodeGenFunction.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000019#include "clang/AST/ASTContext.h"
20#include "clang/AST/Decl.h"
Anders Carlssone5fd6f22009-04-03 22:50:24 +000021#include "clang/AST/DeclCXX.h"
Anders Carlsson131be8b2008-08-23 19:42:54 +000022#include "clang/AST/DeclObjC.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000023#include "clang/AST/Mangle.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000024#include "clang/AST/RecordLayout.h"
Anders Carlsson52d78a52009-09-27 18:58:34 +000025#include "clang/AST/StmtCXX.h"
Chandler Carruth85098242010-06-15 23:19:56 +000026#include "clang/Frontend/CodeGenOptions.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000027#include "llvm/ADT/StringExtras.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000028using namespace clang;
29using namespace CodeGen;
30
John McCallf8ff7b92010-02-23 00:48:20 +000031/// Try to emit a base destructor as an alias to its primary
32/// base-class destructor.
33bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
34 if (!getCodeGenOpts().CXXCtorDtorAliases)
35 return true;
36
Rafael Espindolad967bad2013-11-13 23:20:45 +000037 // Producing an alias to a base class ctor/dtor can degrade debug quality
Alp Tokerf6a24ce2013-12-05 16:25:25 +000038 // as the debugger cannot tell them apart.
Rafael Espindolad967bad2013-11-13 23:20:45 +000039 if (getCodeGenOpts().OptimizationLevel == 0)
40 return true;
41
John McCallf8ff7b92010-02-23 00:48:20 +000042 // If the destructor doesn't have a trivial body, we have to emit it
43 // separately.
Anders Carlsson9bd7d162011-05-14 23:26:09 +000044 if (!D->hasTrivialBody())
John McCallf8ff7b92010-02-23 00:48:20 +000045 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
John McCall2b3c5532011-02-13 00:46:43 +000057 // If any field has a non-trivial destructor, we have to emit the
58 // destructor separately.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000059 for (const auto *I : Class->fields())
David Blaikie2d7c57e2012-04-30 02:36:29 +000060 if (I->getType().isDestructedType())
John McCall2b3c5532011-02-13 00:46:43 +000061 return true;
John McCallf8ff7b92010-02-23 00:48:20 +000062
63 // Try to find a unique base class with a non-trivial destructor.
Craig Topper8a13c412014-05-21 05:09:00 +000064 const CXXRecordDecl *UniqueBase = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +000065 for (const auto &I : Class->bases()) {
John McCallf8ff7b92010-02-23 00:48:20 +000066
67 // We're in the base destructor, so skip virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +000068 if (I.isVirtual()) continue;
John McCallf8ff7b92010-02-23 00:48:20 +000069
70 // Skip base classes with trivial destructors.
Rafael Espindola2ae250c2014-05-09 00:08:36 +000071 const auto *Base =
72 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
John McCallf8ff7b92010-02-23 00:48:20 +000073 if (Base->hasTrivialDestructor()) continue;
74
75 // If we've already found a base class with a non-trivial
76 // destructor, give up.
77 if (UniqueBase) return true;
78 UniqueBase = Base;
79 }
80
81 // If we didn't find any bases with a non-trivial destructor, then
82 // the base destructor is actually effectively trivial, which can
83 // happen if it was needlessly user-defined or if there are virtual
84 // bases with non-trivial destructors.
85 if (!UniqueBase)
86 return true;
87
88 // If the base is at a non-zero offset, give up.
89 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
Benjamin Kramer2ef30312012-07-04 18:45:14 +000090 if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
John McCallf8ff7b92010-02-23 00:48:20 +000091 return true;
92
Rafael Espindola191b9512014-03-05 21:04:41 +000093 // Give up if the calling conventions don't match. We could update the call,
94 // but it is probably not worth it.
Rafael Espindola961ba212013-11-09 01:57:21 +000095 const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
Rafael Espindola191b9512014-03-05 21:04:41 +000096 if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
97 D->getType()->getAs<FunctionType>()->getCallConv())
98 return true;
99
John McCallf8ff7b92010-02-23 00:48:20 +0000100 return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000101 GlobalDecl(BaseD, Dtor_Base),
102 false);
John McCallf8ff7b92010-02-23 00:48:20 +0000103}
104
John McCalld4324142010-02-19 01:32:20 +0000105/// Try to emit a definition as a global alias for another definition.
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000106/// If \p InEveryTU is true, we know that an equivalent alias can be produced
107/// in every translation unit.
John McCalld4324142010-02-19 01:32:20 +0000108bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000109 GlobalDecl TargetDecl,
110 bool InEveryTU) {
John McCalld4324142010-02-19 01:32:20 +0000111 if (!getCodeGenOpts().CXXCtorDtorAliases)
112 return true;
113
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000114 // The alias will use the linkage of the referent. If we can't
John McCalld4324142010-02-19 01:32:20 +0000115 // support aliases with that linkage, fail.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +0000116 llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
John McCalld4324142010-02-19 01:32:20 +0000117
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000118 // We can't use an alias if the linkage is not valid for one.
119 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola4c489c72010-03-05 01:21:10 +0000120 return true;
121
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000122 llvm::GlobalValue::LinkageTypes TargetLinkage =
123 getFunctionLinkage(TargetDecl);
124
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000125 // Check if we have it already.
126 StringRef MangledName = getMangledName(AliasDecl);
127 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
128 if (Entry && !Entry->isDeclaration())
129 return false;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000130 if (Replacements.count(MangledName))
131 return false;
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000132
John McCallf8ff7b92010-02-23 00:48:20 +0000133 // Derive the type for the alias.
Chris Lattner2192fe52011-07-18 04:24:23 +0000134 llvm::PointerType *AliasType
John McCallf8ff7b92010-02-23 00:48:20 +0000135 = getTypes().GetFunctionType(AliasDecl)->getPointerTo();
136
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000137 // Find the referent. Some aliases might require a bitcast, in
John McCallf8ff7b92010-02-23 00:48:20 +0000138 // which case the caller is responsible for ensuring the soundness
139 // of these semantics.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000140 auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
Rafael Espindola27c60b52014-06-03 02:42:01 +0000141 llvm::Constant *Aliasee = Ref;
142 if (Ref->getType() != AliasType)
143 Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
John McCallf8ff7b92010-02-23 00:48:20 +0000144
Rafael Espindolae2ec6fa2013-11-08 22:59:46 +0000145 // Instead of creating as alias to a linkonce_odr, replace all of the uses
Rafael Espindolab2633b92014-05-16 19:35:48 +0000146 // of the aliasee.
Joerg Sonnenberger374c2bb2013-11-22 21:34:35 +0000147 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
148 (TargetLinkage != llvm::GlobalValue::AvailableExternallyLinkage ||
149 !TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000150 // FIXME: An extern template instantiation will create functions with
Joerg Sonnenberger374c2bb2013-11-22 21:34:35 +0000151 // linkage "AvailableExternally". In libc++, some classes also define
152 // members with attribute "AlwaysInline" and expect no reference to
153 // be generated. It is desirable to reenable this optimisation after
154 // corresponding LLVM changes.
Rafael Espindola27c60b52014-06-03 02:42:01 +0000155 Replacements[MangledName] = Aliasee;
Rafael Espindolae2ec6fa2013-11-08 22:59:46 +0000156 return false;
157 }
158
Rafael Espindola961ba212013-11-09 01:57:21 +0000159 if (!InEveryTU) {
160 /// If we don't have a definition for the destructor yet, don't
161 /// emit. We can't emit aliases to declarations; that's just not
162 /// how aliases work.
Rafael Espindola27c60b52014-06-03 02:42:01 +0000163 if (Ref->isDeclaration())
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000164 return true;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000165 }
166
Rafael Espindola129d3132013-11-12 22:06:46 +0000167 // Don't create an alias to a linker weak symbol. This avoids producing
168 // different COMDATs in different TUs. Another option would be to
169 // output the alias both for weak_odr and linkonce_odr, but that
170 // requires explicit comdat support in the IL.
171 if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
172 return true;
173
John McCalld4324142010-02-19 01:32:20 +0000174 // Create the alias with no name.
Rafael Espindola234405b2014-05-17 21:30:14 +0000175 auto *Alias = llvm::GlobalAlias::create(AliasType->getElementType(), 0,
Rafael Espindola27c60b52014-06-03 02:42:01 +0000176 Linkage, "", Aliasee, &getModule());
John McCalld4324142010-02-19 01:32:20 +0000177
John McCallaea181d2010-02-24 20:32:01 +0000178 // Switch any previous uses to the alias.
John McCalld4324142010-02-19 01:32:20 +0000179 if (Entry) {
John McCallaea181d2010-02-24 20:32:01 +0000180 assert(Entry->getType() == AliasType &&
181 "declaration exists with different type");
John McCall7ec50432010-03-19 23:29:14 +0000182 Alias->takeName(Entry);
John McCalld4324142010-02-19 01:32:20 +0000183 Entry->replaceAllUsesWith(Alias);
184 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +0000185 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +0000186 Alias->setName(MangledName);
John McCalld4324142010-02-19 01:32:20 +0000187 }
John McCalld4324142010-02-19 01:32:20 +0000188
189 // Finally, set up the alias with its proper name and attributes.
Rafael Espindolae04a17d2014-10-07 13:34:42 +0000190 setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
John McCalld4324142010-02-19 01:32:20 +0000191
192 return false;
193}
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000194
Rafael Espindola53686182014-09-15 19:34:18 +0000195llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD,
196 StructorType Type) {
197 const CGFunctionInfo &FnInfo =
198 getTypes().arrangeCXXStructorDeclaration(MD, Type);
199 auto *Fn = cast<llvm::Function>(
200 getAddrOfCXXStructor(MD, Type, &FnInfo, nullptr, true));
201
202 GlobalDecl GD;
203 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
204 GD = GlobalDecl(DD, toCXXDtorType(Type));
205 } else {
206 const auto *CD = cast<CXXConstructorDecl>(MD);
207 GD = GlobalDecl(CD, toCXXCtorType(Type));
208 }
209
210 setFunctionLinkage(GD, Fn);
211 CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
212 setFunctionDefinitionAttributes(MD, Fn);
213 SetLLVMFunctionAttributesForDefinition(MD, Fn);
214 return Fn;
215}
216
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000217llvm::GlobalValue *CodeGenModule::getAddrOfCXXStructor(
218 const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
219 llvm::FunctionType *FnType, bool DontDefer) {
220 GlobalDecl GD;
221 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
222 GD = GlobalDecl(CD, toCXXCtorType(Type));
223 } else {
224 auto *DD = dyn_cast<CXXDestructorDecl>(MD);
225 GD = GlobalDecl(DD, toCXXDtorType(Type));
226 }
John McCalld4324142010-02-19 01:32:20 +0000227
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000228 StringRef Name = getMangledName(GD);
229 if (llvm::GlobalValue *Existing = GetGlobalValue(Name))
230 return Existing;
John McCall46288ef2011-03-09 08:12:35 +0000231
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000232 if (!FnType) {
233 if (!FnInfo)
234 FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
235 FnType = getTypes().GetFunctionType(*FnInfo);
236 }
237
238 return cast<llvm::Function>(GetOrCreateLLVMFunction(Name, FnType, GD,
Rafael Espindola94abb8f2013-12-09 04:29:47 +0000239 /*ForVTable=*/false,
240 DontDefer));
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000241}
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000242
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000243static llvm::Value *BuildAppleKextVirtualCall(CodeGenFunction &CGF,
244 GlobalDecl GD,
245 llvm::Type *Ty,
246 const CXXRecordDecl *RD) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000247 assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
248 "No kext in Microsoft ABI");
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000249 GD = GD.getCanonicalDecl();
250 CodeGenModule &CGM = CGF.CGM;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000251 llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000252 Ty = Ty->getPointerTo()->getPointerTo();
253 VTable = CGF.Builder.CreateBitCast(VTable, Ty);
254 assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000255 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000256 uint64_t AddressPoint =
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000257 CGM.getItaniumVTableContext().getVTableLayout(RD)
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000258 .getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
259 VTableIndex += AddressPoint;
260 llvm::Value *VFuncPtr =
261 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
Anders Carlssone828c362009-11-13 04:45:41 +0000262 return CGF.Builder.CreateLoad(VFuncPtr);
263}
264
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000265/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000266/// indirect call to virtual functions. It makes the call through indexing
267/// into the vtable.
268llvm::Value *
269CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
270 NestedNameSpecifier *Qual,
Chris Lattner2192fe52011-07-18 04:24:23 +0000271 llvm::Type *Ty) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000272 assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
273 "BuildAppleKextVirtualCall - bad Qual kind");
274
275 const Type *QTy = Qual->getAsType();
276 QualType T = QualType(QTy, 0);
277 const RecordType *RT = T->getAs<RecordType>();
278 assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000279 const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
280
281 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000282 return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000283
284 return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000285}
286
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000287/// BuildVirtualCall - This routine makes indirect vtable call for
288/// call to virtual destructors. It returns 0 if it could not do it.
289llvm::Value *
290CodeGenFunction::BuildAppleKextVirtualDestructorCall(
291 const CXXDestructorDecl *DD,
292 CXXDtorType Type,
293 const CXXRecordDecl *RD) {
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000294 const auto *MD = cast<CXXMethodDecl>(DD);
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000295 // FIXME. Dtor_Base dtor is always direct!!
296 // It need be somehow inline expanded into the caller.
297 // -O does that. But need to support -O0 as well.
298 if (MD->isVirtual() && Type != Dtor_Base) {
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000299 // Compute the function type we're calling.
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000300 const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
301 DD, StructorType::Complete);
John McCalla729c622012-02-17 03:33:10 +0000302 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000303 return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000304 }
Craig Topper8a13c412014-05-21 05:09:00 +0000305 return nullptr;
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000306}