blob: 0f3141ab76d0d277dbd114f2907a6c0ed50c1e97 [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"
Saleem Abdulrasool10a49722016-04-08 16:52:00 +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 McCall7f416cc2015-09-08 08:05:57 +000031
John McCallf8ff7b92010-02-23 00:48:20 +000032/// Try to emit a base destructor as an alias to its primary
33/// base-class destructor.
34bool CodeGenModule::TryEmitBaseDestructorAsAlias(const CXXDestructorDecl *D) {
35 if (!getCodeGenOpts().CXXCtorDtorAliases)
36 return true;
37
Rafael Espindolad967bad2013-11-13 23:20:45 +000038 // Producing an alias to a base class ctor/dtor can degrade debug quality
Alp Tokerf6a24ce2013-12-05 16:25:25 +000039 // as the debugger cannot tell them apart.
Rafael Espindolad967bad2013-11-13 23:20:45 +000040 if (getCodeGenOpts().OptimizationLevel == 0)
41 return true;
42
Naomi Musgrave866af2d2015-09-03 23:02:30 +000043 // If sanitizing memory to check for use-after-dtor, do not emit as
44 // an alias, unless this class owns no members.
45 if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
46 !D->getParent()->field_empty())
47 return true;
48
John McCallf8ff7b92010-02-23 00:48:20 +000049 // If the destructor doesn't have a trivial body, we have to emit it
50 // separately.
Anders Carlsson9bd7d162011-05-14 23:26:09 +000051 if (!D->hasTrivialBody())
John McCallf8ff7b92010-02-23 00:48:20 +000052 return true;
53
54 const CXXRecordDecl *Class = D->getParent();
55
Kostya Serebryany5f1b4e82014-10-31 19:01:02 +000056 // We are going to instrument this destructor, so give up even if it is
57 // currently empty.
58 if (Class->mayInsertExtraPadding())
59 return true;
60
John McCallf8ff7b92010-02-23 00:48:20 +000061 // If we need to manipulate a VTT parameter, give up.
62 if (Class->getNumVBases()) {
63 // Extra Credit: passing extra parameters is perfectly safe
64 // in many calling conventions, so only bail out if the ctor's
65 // calling convention is nonstandard.
66 return true;
67 }
68
John McCall2b3c5532011-02-13 00:46:43 +000069 // If any field has a non-trivial destructor, we have to emit the
70 // destructor separately.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000071 for (const auto *I : Class->fields())
David Blaikie2d7c57e2012-04-30 02:36:29 +000072 if (I->getType().isDestructedType())
John McCall2b3c5532011-02-13 00:46:43 +000073 return true;
John McCallf8ff7b92010-02-23 00:48:20 +000074
75 // Try to find a unique base class with a non-trivial destructor.
Craig Topper8a13c412014-05-21 05:09:00 +000076 const CXXRecordDecl *UniqueBase = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +000077 for (const auto &I : Class->bases()) {
John McCallf8ff7b92010-02-23 00:48:20 +000078
79 // We're in the base destructor, so skip virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +000080 if (I.isVirtual()) continue;
John McCallf8ff7b92010-02-23 00:48:20 +000081
82 // Skip base classes with trivial destructors.
Rafael Espindola2ae250c2014-05-09 00:08:36 +000083 const auto *Base =
84 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
John McCallf8ff7b92010-02-23 00:48:20 +000085 if (Base->hasTrivialDestructor()) continue;
86
87 // If we've already found a base class with a non-trivial
88 // destructor, give up.
89 if (UniqueBase) return true;
90 UniqueBase = Base;
91 }
92
93 // If we didn't find any bases with a non-trivial destructor, then
94 // the base destructor is actually effectively trivial, which can
95 // happen if it was needlessly user-defined or if there are virtual
96 // bases with non-trivial destructors.
97 if (!UniqueBase)
98 return true;
99
100 // If the base is at a non-zero offset, give up.
101 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000102 if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
John McCallf8ff7b92010-02-23 00:48:20 +0000103 return true;
104
Rafael Espindola191b9512014-03-05 21:04:41 +0000105 // Give up if the calling conventions don't match. We could update the call,
106 // but it is probably not worth it.
Rafael Espindola961ba212013-11-09 01:57:21 +0000107 const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
Rafael Espindola191b9512014-03-05 21:04:41 +0000108 if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
109 D->getType()->getAs<FunctionType>()->getCallConv())
110 return true;
111
John McCallf8ff7b92010-02-23 00:48:20 +0000112 return TryEmitDefinitionAsAlias(GlobalDecl(D, Dtor_Base),
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000113 GlobalDecl(BaseD, Dtor_Base),
114 false);
John McCallf8ff7b92010-02-23 00:48:20 +0000115}
116
John McCalld4324142010-02-19 01:32:20 +0000117/// Try to emit a definition as a global alias for another definition.
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000118/// If \p InEveryTU is true, we know that an equivalent alias can be produced
119/// in every translation unit.
John McCalld4324142010-02-19 01:32:20 +0000120bool CodeGenModule::TryEmitDefinitionAsAlias(GlobalDecl AliasDecl,
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000121 GlobalDecl TargetDecl,
122 bool InEveryTU) {
John McCalld4324142010-02-19 01:32:20 +0000123 if (!getCodeGenOpts().CXXCtorDtorAliases)
124 return true;
125
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000126 // The alias will use the linkage of the referent. If we can't
John McCalld4324142010-02-19 01:32:20 +0000127 // support aliases with that linkage, fail.
Peter Collingbourne4d90dba2013-06-05 17:49:37 +0000128 llvm::GlobalValue::LinkageTypes Linkage = getFunctionLinkage(AliasDecl);
John McCalld4324142010-02-19 01:32:20 +0000129
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000130 // We can't use an alias if the linkage is not valid for one.
131 if (!llvm::GlobalAlias::isValidLinkage(Linkage))
Rafael Espindola4c489c72010-03-05 01:21:10 +0000132 return true;
133
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000134 llvm::GlobalValue::LinkageTypes TargetLinkage =
135 getFunctionLinkage(TargetDecl);
136
Aditya Kumare84372b2016-10-02 03:06:36 +0000137 // available_externally definitions aren't real definitions, so we cannot
138 // create an alias to one.
139 if (TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage)
140 return true;
141
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000142 // Check if we have it already.
143 StringRef MangledName = getMangledName(AliasDecl);
144 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
145 if (Entry && !Entry->isDeclaration())
146 return false;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000147 if (Replacements.count(MangledName))
148 return false;
Rafael Espindola3f643bd2013-11-04 18:38:59 +0000149
John McCallf8ff7b92010-02-23 00:48:20 +0000150 // Derive the type for the alias.
David Blaikie2a791d72015-09-14 18:38:22 +0000151 llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
152 llvm::PointerType *AliasType = AliasValueType->getPointerTo();
John McCallf8ff7b92010-02-23 00:48:20 +0000153
Alp Tokerf6a24ce2013-12-05 16:25:25 +0000154 // Find the referent. Some aliases might require a bitcast, in
John McCallf8ff7b92010-02-23 00:48:20 +0000155 // which case the caller is responsible for ensuring the soundness
156 // of these semantics.
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000157 auto *Ref = cast<llvm::GlobalValue>(GetAddrOfGlobal(TargetDecl));
Rafael Espindola27c60b52014-06-03 02:42:01 +0000158 llvm::Constant *Aliasee = Ref;
159 if (Ref->getType() != AliasType)
160 Aliasee = llvm::ConstantExpr::getBitCast(Ref, AliasType);
John McCallf8ff7b92010-02-23 00:48:20 +0000161
Rafael Espindolae2ec6fa2013-11-08 22:59:46 +0000162 // Instead of creating as alias to a linkonce_odr, replace all of the uses
Rafael Espindolab2633b92014-05-16 19:35:48 +0000163 // of the aliasee.
Aditya Kumare84372b2016-10-02 03:06:36 +0000164 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage)) {
Yaron Kerenf8adb382016-02-07 12:44:35 +0000165 addReplacement(MangledName, Aliasee);
Rafael Espindolae2ec6fa2013-11-08 22:59:46 +0000166 return false;
167 }
168
Reid Kleckner489cfe12015-11-10 22:23:58 +0000169 // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
170 // template instantiation or a dllexported class, avoid forming it on COFF.
171 // A COFF weak external alias cannot satisfy a normal undefined symbol
172 // reference from another TU. The other TU must also mark the referenced
173 // symbol as weak, which we cannot rely on.
174 if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
175 getTriple().isOSBinFormatCOFF()) {
176 return true;
177 }
178
Rafael Espindola961ba212013-11-09 01:57:21 +0000179 if (!InEveryTU) {
Nico Weberf867c172015-01-12 21:22:27 +0000180 // If we don't have a definition for the destructor yet, don't
181 // emit. We can't emit aliases to declarations; that's just not
182 // how aliases work.
Rafael Espindola27c60b52014-06-03 02:42:01 +0000183 if (Ref->isDeclaration())
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000184 return true;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000185 }
186
Rafael Espindola129d3132013-11-12 22:06:46 +0000187 // Don't create an alias to a linker weak symbol. This avoids producing
188 // different COMDATs in different TUs. Another option would be to
189 // output the alias both for weak_odr and linkonce_odr, but that
190 // requires explicit comdat support in the IL.
191 if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
192 return true;
193
John McCalld4324142010-02-19 01:32:20 +0000194 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +0000195 auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
196 Aliasee, &getModule());
John McCalld4324142010-02-19 01:32:20 +0000197
John McCallaea181d2010-02-24 20:32:01 +0000198 // Switch any previous uses to the alias.
John McCalld4324142010-02-19 01:32:20 +0000199 if (Entry) {
John McCallaea181d2010-02-24 20:32:01 +0000200 assert(Entry->getType() == AliasType &&
201 "declaration exists with different type");
John McCall7ec50432010-03-19 23:29:14 +0000202 Alias->takeName(Entry);
John McCalld4324142010-02-19 01:32:20 +0000203 Entry->replaceAllUsesWith(Alias);
204 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +0000205 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +0000206 Alias->setName(MangledName);
John McCalld4324142010-02-19 01:32:20 +0000207 }
John McCalld4324142010-02-19 01:32:20 +0000208
209 // Finally, set up the alias with its proper name and attributes.
Rafael Espindolae04a17d2014-10-07 13:34:42 +0000210 setAliasAttributes(cast<NamedDecl>(AliasDecl.getDecl()), Alias);
John McCalld4324142010-02-19 01:32:20 +0000211
212 return false;
213}
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000214
Rafael Espindola53686182014-09-15 19:34:18 +0000215llvm::Function *CodeGenModule::codegenCXXStructor(const CXXMethodDecl *MD,
216 StructorType Type) {
217 const CGFunctionInfo &FnInfo =
218 getTypes().arrangeCXXStructorDeclaration(MD, Type);
219 auto *Fn = cast<llvm::Function>(
Andrey Bokhankocab58582015-08-31 13:20:44 +0000220 getAddrOfCXXStructor(MD, Type, &FnInfo, /*FnType=*/nullptr,
John McCalld195d4c2016-11-30 23:25:13 +0000221 /*DontDefer=*/true, ForDefinition));
Rafael Espindola53686182014-09-15 19:34:18 +0000222
223 GlobalDecl GD;
224 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD)) {
225 GD = GlobalDecl(DD, toCXXDtorType(Type));
226 } else {
227 const auto *CD = cast<CXXConstructorDecl>(MD);
228 GD = GlobalDecl(CD, toCXXCtorType(Type));
229 }
230
231 setFunctionLinkage(GD, Fn);
Hans Wennborgbb4f9622015-05-28 17:44:56 +0000232 setFunctionDLLStorageClass(GD, Fn);
233
Rafael Espindola53686182014-09-15 19:34:18 +0000234 CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
235 setFunctionDefinitionAttributes(MD, Fn);
236 SetLLVMFunctionAttributesForDefinition(MD, Fn);
237 return Fn;
238}
239
Andrey Bokhankocab58582015-08-31 13:20:44 +0000240llvm::Constant *CodeGenModule::getAddrOfCXXStructor(
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000241 const CXXMethodDecl *MD, StructorType Type, const CGFunctionInfo *FnInfo,
John McCalld195d4c2016-11-30 23:25:13 +0000242 llvm::FunctionType *FnType, bool DontDefer,
243 ForDefinition_t IsForDefinition) {
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000244 GlobalDecl GD;
245 if (auto *CD = dyn_cast<CXXConstructorDecl>(MD)) {
246 GD = GlobalDecl(CD, toCXXCtorType(Type));
247 } else {
Duncan P. N. Exon Smithd6616ac2015-05-06 22:18:39 +0000248 GD = GlobalDecl(cast<CXXDestructorDecl>(MD), toCXXDtorType(Type));
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000249 }
John McCalld4324142010-02-19 01:32:20 +0000250
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000251 if (!FnType) {
252 if (!FnInfo)
253 FnInfo = &getTypes().arrangeCXXStructorDeclaration(MD, Type);
254 FnType = getTypes().GetFunctionType(*FnInfo);
255 }
256
Andrey Bokhankocab58582015-08-31 13:20:44 +0000257 return GetOrCreateLLVMFunction(
258 getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
Reid Klecknerde864822017-03-21 16:57:30 +0000259 /*isThunk=*/false, /*ExtraAttrs=*/llvm::AttributeList(), IsForDefinition);
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000260}
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000261
John McCallb92ab1a2016-10-26 23:46:34 +0000262static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF,
263 GlobalDecl GD,
264 llvm::Type *Ty,
265 const CXXRecordDecl *RD) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000266 assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
267 "No kext in Microsoft ABI");
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000268 GD = GD.getCanonicalDecl();
269 CodeGenModule &CGM = CGF.CGM;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000270 llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000271 Ty = Ty->getPointerTo()->getPointerTo();
272 VTable = CGF.Builder.CreateBitCast(VTable, Ty);
273 assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000274 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000275 const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD);
276 VTableLayout::AddressPointLocation AddressPoint =
277 VTLayout.getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
278 VTableIndex += VTLayout.getVTableOffset(AddressPoint.VTableIndex) +
279 AddressPoint.AddressPointIndex;
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000280 llvm::Value *VFuncPtr =
281 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
John McCallb92ab1a2016-10-26 23:46:34 +0000282 llvm::Value *VFunc =
283 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.PointerAlignInBytes);
284 CGCallee Callee(GD.getDecl(), VFunc);
285 return Callee;
Anders Carlssone828c362009-11-13 04:45:41 +0000286}
287
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000288/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000289/// indirect call to virtual functions. It makes the call through indexing
290/// into the vtable.
John McCallb92ab1a2016-10-26 23:46:34 +0000291CGCallee
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000292CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
John McCallb92ab1a2016-10-26 23:46:34 +0000293 NestedNameSpecifier *Qual,
294 llvm::Type *Ty) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000295 assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
296 "BuildAppleKextVirtualCall - bad Qual kind");
297
298 const Type *QTy = Qual->getAsType();
299 QualType T = QualType(QTy, 0);
300 const RecordType *RT = T->getAs<RecordType>();
301 assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000302 const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
303
304 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000305 return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000306
307 return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000308}
309
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000310/// BuildVirtualCall - This routine makes indirect vtable call for
311/// call to virtual destructors. It returns 0 if it could not do it.
John McCallb92ab1a2016-10-26 23:46:34 +0000312CGCallee
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000313CodeGenFunction::BuildAppleKextVirtualDestructorCall(
314 const CXXDestructorDecl *DD,
315 CXXDtorType Type,
316 const CXXRecordDecl *RD) {
John McCallb92ab1a2016-10-26 23:46:34 +0000317 assert(DD->isVirtual() && Type != Dtor_Base);
318 // Compute the function type we're calling.
319 const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
320 DD, StructorType::Complete);
321 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
322 return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000323}