blob: adaeacfe868e091c7ab6376f01687833e6ecad76 [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//
Chandler Carruth2946cd72019-01-19 08:50:56 +00003// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
Anders Carlsson87fc5a52008-08-22 16:00:37 +00006//
7//===----------------------------------------------------------------------===//
8//
9// This contains code dealing with C++ code generation.
10//
11//===----------------------------------------------------------------------===//
12
Mike Stump11289f42009-09-09 15:08:12 +000013// We might split this into multiple files if it gets too unwieldy
Anders Carlsson87fc5a52008-08-22 16:00:37 +000014
Chandler Carruth3a022472012-12-04 09:13:33 +000015#include "CodeGenModule.h"
Charles Davis4e786dd2010-05-25 19:52:27 +000016#include "CGCXXABI.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000017#include "CodeGenFunction.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000018#include "clang/AST/ASTContext.h"
19#include "clang/AST/Decl.h"
Anders Carlssone5fd6f22009-04-03 22:50:24 +000020#include "clang/AST/DeclCXX.h"
Anders Carlsson131be8b2008-08-23 19:42:54 +000021#include "clang/AST/DeclObjC.h"
Peter Collingbourne0ff0b372011-01-13 18:57:25 +000022#include "clang/AST/Mangle.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000023#include "clang/AST/RecordLayout.h"
Anders Carlsson52d78a52009-09-27 18:58:34 +000024#include "clang/AST/StmtCXX.h"
Richard Trieu63688182018-12-11 03:18:39 +000025#include "clang/Basic/CodeGenOptions.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000026#include "llvm/ADT/StringExtras.h"
Anders Carlsson87fc5a52008-08-22 16:00:37 +000027using namespace clang;
28using namespace CodeGen;
29
John McCall7f416cc2015-09-08 08:05:57 +000030
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
Naomi Musgrave866af2d2015-09-03 23:02:30 +000042 // If sanitizing memory to check for use-after-dtor, do not emit as
43 // an alias, unless this class owns no members.
44 if (getCodeGenOpts().SanitizeMemoryUseAfterDtor &&
45 !D->getParent()->field_empty())
46 return true;
47
John McCallf8ff7b92010-02-23 00:48:20 +000048 // If the destructor doesn't have a trivial body, we have to emit it
49 // separately.
Anders Carlsson9bd7d162011-05-14 23:26:09 +000050 if (!D->hasTrivialBody())
John McCallf8ff7b92010-02-23 00:48:20 +000051 return true;
52
53 const CXXRecordDecl *Class = D->getParent();
54
Kostya Serebryany5f1b4e82014-10-31 19:01:02 +000055 // We are going to instrument this destructor, so give up even if it is
56 // currently empty.
57 if (Class->mayInsertExtraPadding())
58 return true;
59
John McCallf8ff7b92010-02-23 00:48:20 +000060 // If we need to manipulate a VTT parameter, give up.
61 if (Class->getNumVBases()) {
62 // Extra Credit: passing extra parameters is perfectly safe
63 // in many calling conventions, so only bail out if the ctor's
64 // calling convention is nonstandard.
65 return true;
66 }
67
John McCall2b3c5532011-02-13 00:46:43 +000068 // If any field has a non-trivial destructor, we have to emit the
69 // destructor separately.
Aaron Ballmane8a8bae2014-03-08 20:12:42 +000070 for (const auto *I : Class->fields())
David Blaikie2d7c57e2012-04-30 02:36:29 +000071 if (I->getType().isDestructedType())
John McCall2b3c5532011-02-13 00:46:43 +000072 return true;
John McCallf8ff7b92010-02-23 00:48:20 +000073
74 // Try to find a unique base class with a non-trivial destructor.
Craig Topper8a13c412014-05-21 05:09:00 +000075 const CXXRecordDecl *UniqueBase = nullptr;
Aaron Ballman574705e2014-03-13 15:41:46 +000076 for (const auto &I : Class->bases()) {
John McCallf8ff7b92010-02-23 00:48:20 +000077
78 // We're in the base destructor, so skip virtual bases.
Aaron Ballman574705e2014-03-13 15:41:46 +000079 if (I.isVirtual()) continue;
John McCallf8ff7b92010-02-23 00:48:20 +000080
81 // Skip base classes with trivial destructors.
Rafael Espindola2ae250c2014-05-09 00:08:36 +000082 const auto *Base =
83 cast<CXXRecordDecl>(I.getType()->getAs<RecordType>()->getDecl());
John McCallf8ff7b92010-02-23 00:48:20 +000084 if (Base->hasTrivialDestructor()) continue;
85
86 // If we've already found a base class with a non-trivial
87 // destructor, give up.
88 if (UniqueBase) return true;
89 UniqueBase = Base;
90 }
91
92 // If we didn't find any bases with a non-trivial destructor, then
93 // the base destructor is actually effectively trivial, which can
94 // happen if it was needlessly user-defined or if there are virtual
95 // bases with non-trivial destructors.
96 if (!UniqueBase)
97 return true;
98
99 // If the base is at a non-zero offset, give up.
100 const ASTRecordLayout &ClassLayout = Context.getASTRecordLayout(Class);
Benjamin Kramer2ef30312012-07-04 18:45:14 +0000101 if (!ClassLayout.getBaseClassOffset(UniqueBase).isZero())
John McCallf8ff7b92010-02-23 00:48:20 +0000102 return true;
103
Rafael Espindola191b9512014-03-05 21:04:41 +0000104 // Give up if the calling conventions don't match. We could update the call,
105 // but it is probably not worth it.
Rafael Espindola961ba212013-11-09 01:57:21 +0000106 const CXXDestructorDecl *BaseD = UniqueBase->getDestructor();
Rafael Espindola191b9512014-03-05 21:04:41 +0000107 if (BaseD->getType()->getAs<FunctionType>()->getCallConv() !=
108 D->getType()->getAs<FunctionType>()->getCallConv())
109 return true;
110
Peter Collingbourned914fd22018-06-18 20:58:54 +0000111 GlobalDecl AliasDecl(D, Dtor_Base);
112 GlobalDecl TargetDecl(BaseD, Dtor_Base);
John McCalld4324142010-02-19 01:32:20 +0000113
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.
David Blaikie2a791d72015-09-14 18:38:22 +0000134 llvm::Type *AliasValueType = getTypes().GetFunctionType(AliasDecl);
135 llvm::PointerType *AliasType = AliasValueType->getPointerTo();
John McCallf8ff7b92010-02-23 00:48:20 +0000136
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.
Reid Kleckner3da37e02017-10-13 00:53:02 +0000147 if (llvm::GlobalValue::isDiscardableIfUnused(Linkage) &&
148 !(TargetLinkage == llvm::GlobalValue::AvailableExternallyLinkage &&
149 TargetDecl.getDecl()->hasAttr<AlwaysInlineAttr>())) {
150 // FIXME: An extern template instantiation will create functions with
151 // 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.
Yaron Kerenf8adb382016-02-07 12:44:35 +0000155 addReplacement(MangledName, Aliasee);
Rafael Espindolae2ec6fa2013-11-08 22:59:46 +0000156 return false;
157 }
158
Reid Kleckner489cfe12015-11-10 22:23:58 +0000159 // If we have a weak, non-discardable alias (weak, weak_odr), like an extern
160 // template instantiation or a dllexported class, avoid forming it on COFF.
161 // A COFF weak external alias cannot satisfy a normal undefined symbol
162 // reference from another TU. The other TU must also mark the referenced
163 // symbol as weak, which we cannot rely on.
164 if (llvm::GlobalValue::isWeakForLinker(Linkage) &&
165 getTriple().isOSBinFormatCOFF()) {
166 return true;
167 }
168
Reid Kleckner3da37e02017-10-13 00:53:02 +0000169 // If we don't have a definition for the destructor yet or the definition is
170 // avaialable_externally, don't emit an alias. We can't emit aliases to
171 // declarations; that's just not how aliases work.
172 if (Ref->isDeclarationForLinker())
173 return true;
Rafael Espindola2e2995b2013-11-05 21:37:29 +0000174
Rafael Espindola129d3132013-11-12 22:06:46 +0000175 // Don't create an alias to a linker weak symbol. This avoids producing
176 // different COMDATs in different TUs. Another option would be to
177 // output the alias both for weak_odr and linkonce_odr, but that
178 // requires explicit comdat support in the IL.
179 if (llvm::GlobalValue::isWeakForLinker(TargetLinkage))
180 return true;
181
John McCalld4324142010-02-19 01:32:20 +0000182 // Create the alias with no name.
David Blaikie2a791d72015-09-14 18:38:22 +0000183 auto *Alias = llvm::GlobalAlias::create(AliasValueType, 0, Linkage, "",
184 Aliasee, &getModule());
John McCalld4324142010-02-19 01:32:20 +0000185
Peter Collingbourned914fd22018-06-18 20:58:54 +0000186 // Destructors are always unnamed_addr.
187 Alias->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
188
John McCallaea181d2010-02-24 20:32:01 +0000189 // Switch any previous uses to the alias.
John McCalld4324142010-02-19 01:32:20 +0000190 if (Entry) {
John McCallaea181d2010-02-24 20:32:01 +0000191 assert(Entry->getType() == AliasType &&
192 "declaration exists with different type");
John McCall7ec50432010-03-19 23:29:14 +0000193 Alias->takeName(Entry);
John McCalld4324142010-02-19 01:32:20 +0000194 Entry->replaceAllUsesWith(Alias);
195 Entry->eraseFromParent();
John McCall7ec50432010-03-19 23:29:14 +0000196 } else {
Anders Carlssonea836bc2010-06-22 16:16:50 +0000197 Alias->setName(MangledName);
John McCalld4324142010-02-19 01:32:20 +0000198 }
John McCalld4324142010-02-19 01:32:20 +0000199
200 // Finally, set up the alias with its proper name and attributes.
Rafael Espindolab7350042018-03-01 00:35:47 +0000201 SetCommonAttributes(AliasDecl, Alias);
John McCalld4324142010-02-19 01:32:20 +0000202
203 return false;
204}
Anders Carlssonbd7d11f2009-05-11 23:37:08 +0000205
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000206llvm::Function *CodeGenModule::codegenCXXStructor(GlobalDecl GD) {
207 const CGFunctionInfo &FnInfo = getTypes().arrangeCXXStructorDeclaration(GD);
Rafael Espindola53686182014-09-15 19:34:18 +0000208 auto *Fn = cast<llvm::Function>(
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000209 getAddrOfCXXStructor(GD, &FnInfo, /*FnType=*/nullptr,
John McCalld195d4c2016-11-30 23:25:13 +0000210 /*DontDefer=*/true, ForDefinition));
Rafael Espindola53686182014-09-15 19:34:18 +0000211
Rafael Espindola53686182014-09-15 19:34:18 +0000212 setFunctionLinkage(GD, Fn);
Hans Wennborgbb4f9622015-05-28 17:44:56 +0000213
Rafael Espindola53686182014-09-15 19:34:18 +0000214 CodeGenFunction(*this).GenerateCode(GD, Fn, FnInfo);
Rafael Espindolae4e78132018-03-01 00:00:02 +0000215 setNonAliasAttributes(GD, Fn);
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000216 SetLLVMFunctionAttributesForDefinition(cast<CXXMethodDecl>(GD.getDecl()), Fn);
Rafael Espindola53686182014-09-15 19:34:18 +0000217 return Fn;
218}
219
James Y Knightf7321542019-02-07 01:14:17 +0000220llvm::FunctionCallee CodeGenModule::getAddrAndTypeOfCXXStructor(
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000221 GlobalDecl GD, const CGFunctionInfo *FnInfo, llvm::FunctionType *FnType,
222 bool DontDefer, ForDefinition_t IsForDefinition) {
223 auto *MD = cast<CXXMethodDecl>(GD.getDecl());
James Y Knightf7321542019-02-07 01:14:17 +0000224
Simon Pilgrim1ba406c2019-03-23 16:16:46 +0000225 if (isa<CXXDestructorDecl>(MD)) {
Reid Klecknerae9b0702018-03-16 19:40:50 +0000226 // Always alias equivalent complete destructors to base destructors in the
227 // MS ABI.
228 if (getTarget().getCXXABI().isMicrosoft() &&
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000229 GD.getDtorType() == Dtor_Complete &&
230 MD->getParent()->getNumVBases() == 0)
231 GD = GD.getWithDtorType(Dtor_Base);
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000232 }
John McCalld4324142010-02-19 01:32:20 +0000233
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000234 if (!FnType) {
235 if (!FnInfo)
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000236 FnInfo = &getTypes().arrangeCXXStructorDeclaration(GD);
Rafael Espindola8d2a19b2014-09-08 16:01:27 +0000237 FnType = getTypes().GetFunctionType(*FnInfo);
238 }
239
James Y Knightf7321542019-02-07 01:14:17 +0000240 llvm::Constant *Ptr = GetOrCreateLLVMFunction(
Andrey Bokhankocab58582015-08-31 13:20:44 +0000241 getMangledName(GD), FnType, GD, /*ForVTable=*/false, DontDefer,
Reid Klecknerde864822017-03-21 16:57:30 +0000242 /*isThunk=*/false, /*ExtraAttrs=*/llvm::AttributeList(), IsForDefinition);
James Y Knightf7321542019-02-07 01:14:17 +0000243 return {FnType, Ptr};
Anders Carlssone8eeffd2009-04-16 23:57:24 +0000244}
Anders Carlssoneaa28f72009-04-17 01:58:57 +0000245
John McCallb92ab1a2016-10-26 23:46:34 +0000246static CGCallee BuildAppleKextVirtualCall(CodeGenFunction &CGF,
247 GlobalDecl GD,
248 llvm::Type *Ty,
249 const CXXRecordDecl *RD) {
Timur Iskhodzhanov88fd4392013-08-21 06:25:03 +0000250 assert(!CGF.CGM.getTarget().getCXXABI().isMicrosoft() &&
251 "No kext in Microsoft ABI");
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000252 CodeGenModule &CGM = CGF.CGM;
Timur Iskhodzhanov8b5987e2013-09-27 14:48:01 +0000253 llvm::Value *VTable = CGM.getCXXABI().getAddrOfVTable(RD, CharUnits());
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000254 Ty = Ty->getPointerTo()->getPointerTo();
255 VTable = CGF.Builder.CreateBitCast(VTable, Ty);
256 assert(VTable && "BuildVirtualCall = kext vtbl pointer is null");
Timur Iskhodzhanov58776632013-11-05 15:54:58 +0000257 uint64_t VTableIndex = CGM.getItaniumVTableContext().getMethodVTableIndex(GD);
Peter Collingbourne2849c4e2016-12-13 20:40:39 +0000258 const VTableLayout &VTLayout = CGM.getItaniumVTableContext().getVTableLayout(RD);
259 VTableLayout::AddressPointLocation AddressPoint =
260 VTLayout.getAddressPoint(BaseSubobject(RD, CharUnits::Zero()));
261 VTableIndex += VTLayout.getVTableOffset(AddressPoint.VTableIndex) +
262 AddressPoint.AddressPointIndex;
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000263 llvm::Value *VFuncPtr =
264 CGF.Builder.CreateConstInBoundsGEP1_64(VTable, VTableIndex, "vfnkxt");
John McCallb92ab1a2016-10-26 23:46:34 +0000265 llvm::Value *VFunc =
266 CGF.Builder.CreateAlignedLoad(VFuncPtr, CGF.PointerAlignInBytes);
Erich Keanede6480a32018-11-13 15:48:08 +0000267 CGCallee Callee(GD, VFunc);
John McCallb92ab1a2016-10-26 23:46:34 +0000268 return Callee;
Anders Carlssone828c362009-11-13 04:45:41 +0000269}
270
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000271/// BuildAppleKextVirtualCall - This routine is to support gcc's kext ABI making
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000272/// indirect call to virtual functions. It makes the call through indexing
273/// into the vtable.
John McCallb92ab1a2016-10-26 23:46:34 +0000274CGCallee
Fangrui Song6907ce22018-07-30 19:24:48 +0000275CodeGenFunction::BuildAppleKextVirtualCall(const CXXMethodDecl *MD,
John McCallb92ab1a2016-10-26 23:46:34 +0000276 NestedNameSpecifier *Qual,
277 llvm::Type *Ty) {
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000278 assert((Qual->getKind() == NestedNameSpecifier::TypeSpec) &&
279 "BuildAppleKextVirtualCall - bad Qual kind");
Fangrui Song6907ce22018-07-30 19:24:48 +0000280
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000281 const Type *QTy = Qual->getAsType();
282 QualType T = QualType(QTy, 0);
283 const RecordType *RT = T->getAs<RecordType>();
284 assert(RT && "BuildAppleKextVirtualCall - Qual type must be record");
Rafael Espindola2ae250c2014-05-09 00:08:36 +0000285 const auto *RD = cast<CXXRecordDecl>(RT->getDecl());
286
287 if (const auto *DD = dyn_cast<CXXDestructorDecl>(MD))
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000288 return BuildAppleKextVirtualDestructorCall(DD, Dtor_Complete, RD);
Timur Iskhodzhanov03e87462013-07-19 08:14:45 +0000289
290 return ::BuildAppleKextVirtualCall(*this, MD, Ty, RD);
Fariborz Jahanian47609b02011-01-20 17:19:02 +0000291}
292
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000293/// BuildVirtualCall - This routine makes indirect vtable call for
294/// call to virtual destructors. It returns 0 if it could not do it.
John McCallb92ab1a2016-10-26 23:46:34 +0000295CGCallee
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000296CodeGenFunction::BuildAppleKextVirtualDestructorCall(
297 const CXXDestructorDecl *DD,
298 CXXDtorType Type,
299 const CXXRecordDecl *RD) {
John McCallb92ab1a2016-10-26 23:46:34 +0000300 assert(DD->isVirtual() && Type != Dtor_Base);
301 // Compute the function type we're calling.
302 const CGFunctionInfo &FInfo = CGM.getTypes().arrangeCXXStructorDeclaration(
Peter Collingbourned1c5b282019-03-22 23:05:10 +0000303 GlobalDecl(DD, Dtor_Complete));
John McCallb92ab1a2016-10-26 23:46:34 +0000304 llvm::Type *Ty = CGM.getTypes().GetFunctionType(FInfo);
305 return ::BuildAppleKextVirtualCall(*this, GlobalDecl(DD, Type), Ty, RD);
Fariborz Jahanian265c3252011-02-01 23:22:34 +0000306}