blob: 20d53ee81586140232b24637e7ac8c854bd626fb [file] [log] [blame]
Anders Carlssonbc49cfe2009-12-10 00:16:00 +00001//===--- CGDeclCXX.cpp - Emit LLVM Code for C++ 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 code generation of C++ declarations
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenFunction.h"
John McCall5d865c322010-08-31 07:33:07 +000015#include "CGCXXABI.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000016#include "CGObjCRuntime.h"
Chandler Carruth85098242010-06-15 23:19:56 +000017#include "clang/Frontend/CodeGenOptions.h"
Anton Korobeynikovabed7492012-11-06 22:44:45 +000018#include "llvm/ADT/StringExtras.h"
Chandler Carruthffd55512013-01-02 11:45:17 +000019#include "llvm/IR/Intrinsics.h"
Nico Weberbdc96982014-05-06 20:32:45 +000020#include "llvm/Support/Path.h"
Douglas Gregor51150ab2010-05-16 01:24:12 +000021
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000022using namespace clang;
23using namespace CodeGen;
24
Anders Carlsson364051c2009-12-10 00:57:45 +000025static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
26 llvm::Constant *DeclPtr) {
27 assert(D.hasGlobalStorage() && "VarDecl must have global storage!");
28 assert(!D.getType()->isReferenceType() &&
29 "Should not call EmitDeclInit on a reference!");
30
Anders Carlsson364051c2009-12-10 00:57:45 +000031 ASTContext &Context = CGF.getContext();
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000032
Eli Friedmana0544d62011-12-03 04:14:32 +000033 CharUnits alignment = Context.getDeclAlign(&D);
John McCall1553b192011-06-16 04:16:24 +000034 QualType type = D.getType();
35 LValue lv = CGF.MakeAddrLValue(DeclPtr, type, alignment);
36
37 const Expr *Init = D.getInit();
John McCall47fb9502013-03-07 21:37:08 +000038 switch (CGF.getEvaluationKind(type)) {
39 case TEK_Scalar: {
Fariborz Jahaniand1339792011-01-13 20:00:54 +000040 CodeGenModule &CGM = CGF.CGM;
John McCall1553b192011-06-16 04:16:24 +000041 if (lv.isObjCStrong())
John McCall31168b02011-06-15 23:02:42 +000042 CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
Richard Smithfd3834f2013-04-13 02:43:54 +000043 DeclPtr, D.getTLSKind());
John McCall1553b192011-06-16 04:16:24 +000044 else if (lv.isObjCWeak())
45 CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
46 DeclPtr);
Fariborz Jahaniand1339792011-01-13 20:00:54 +000047 else
John McCall1553b192011-06-16 04:16:24 +000048 CGF.EmitScalarInit(Init, &D, lv, false);
John McCall47fb9502013-03-07 21:37:08 +000049 return;
50 }
51 case TEK_Complex:
52 CGF.EmitComplexExprIntoLValue(Init, lv, /*isInit*/ true);
53 return;
54 case TEK_Aggregate:
Chad Rosier615ed1a2012-03-29 17:37:10 +000055 CGF.EmitAggExpr(Init, AggValueSlot::forLValue(lv,AggValueSlot::IsDestructed,
56 AggValueSlot::DoesNotNeedGCBarriers,
57 AggValueSlot::IsNotAliased));
John McCall47fb9502013-03-07 21:37:08 +000058 return;
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000059 }
John McCall47fb9502013-03-07 21:37:08 +000060 llvm_unreachable("bad evaluation kind");
Anders Carlssonbc49cfe2009-12-10 00:16:00 +000061}
62
John McCall68ff0372010-09-08 01:44:27 +000063/// Emit code to cause the destruction of the given variable with
64/// static storage duration.
Douglas Gregor370eadf2010-05-05 15:38:32 +000065static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
John McCall98de3d72011-07-13 03:01:35 +000066 llvm::Constant *addr) {
Douglas Gregor370eadf2010-05-05 15:38:32 +000067 CodeGenModule &CGM = CGF.CGM;
John McCall98de3d72011-07-13 03:01:35 +000068
69 // FIXME: __attribute__((cleanup)) ?
Douglas Gregor370eadf2010-05-05 15:38:32 +000070
John McCall98de3d72011-07-13 03:01:35 +000071 QualType type = D.getType();
72 QualType::DestructionKind dtorKind = type.isDestructedType();
73
74 switch (dtorKind) {
75 case QualType::DK_none:
Douglas Gregor370eadf2010-05-05 15:38:32 +000076 return;
John McCall98de3d72011-07-13 03:01:35 +000077
78 case QualType::DK_cxx_destructor:
79 break;
80
81 case QualType::DK_objc_strong_lifetime:
82 case QualType::DK_objc_weak_lifetime:
83 // We don't care about releasing objects during process teardown.
Richard Smithdbf74ba2013-04-14 23:01:42 +000084 assert(!D.getTLSKind() && "should have rejected this");
Douglas Gregor370eadf2010-05-05 15:38:32 +000085 return;
John McCall98de3d72011-07-13 03:01:35 +000086 }
87
88 llvm::Constant *function;
89 llvm::Constant *argument;
90
91 // Special-case non-array C++ destructors, where there's a function
92 // with the right signature that we can just call.
Craig Topper8a13c412014-05-21 05:09:00 +000093 const CXXRecordDecl *record = nullptr;
John McCall98de3d72011-07-13 03:01:35 +000094 if (dtorKind == QualType::DK_cxx_destructor &&
95 (record = type->getAsCXXRecordDecl())) {
96 assert(!record->hasTrivialDestructor());
97 CXXDestructorDecl *dtor = record->getDestructor();
98
Rafael Espindola1ac0ec82014-09-11 15:42:06 +000099 function = CGM.getAddrOfCXXStructor(dtor, StructorType::Complete);
Timur Iskhodzhanov40c585a2013-10-02 16:03:16 +0000100 argument = llvm::ConstantExpr::getBitCast(
101 addr, CGF.getTypes().ConvertType(type)->getPointerTo());
John McCall98de3d72011-07-13 03:01:35 +0000102
103 // Otherwise, the standard logic requires a helper function.
104 } else {
David Blaikieebe87e12013-08-27 23:57:18 +0000105 function = CodeGenFunction(CGM)
106 .generateDestroyHelper(addr, type, CGF.getDestroyer(dtorKind),
107 CGF.needsEHCleanup(dtorKind), &D);
John McCall98de3d72011-07-13 03:01:35 +0000108 argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
109 }
110
Richard Smithdbf74ba2013-04-14 23:01:42 +0000111 CGM.getCXXABI().registerGlobalDtor(CGF, D, function, argument);
Douglas Gregor370eadf2010-05-05 15:38:32 +0000112}
113
Richard Smith08a51442012-02-17 07:31:37 +0000114/// Emit code to cause the variable at the given address to be considered as
115/// constant from this point onwards.
Nick Lewycky45062042012-02-21 00:26:58 +0000116static void EmitDeclInvariant(CodeGenFunction &CGF, const VarDecl &D,
117 llvm::Constant *Addr) {
Richard Smith132bea92012-02-17 20:12:52 +0000118 // Don't emit the intrinsic if we're not optimizing.
119 if (!CGF.CGM.getCodeGenOpts().OptimizationLevel)
120 return;
121
Richard Smith08a51442012-02-17 07:31:37 +0000122 // Grab the llvm.invariant.start intrinsic.
123 llvm::Intrinsic::ID InvStartID = llvm::Intrinsic::invariant_start;
124 llvm::Constant *InvariantStart = CGF.CGM.getIntrinsic(InvStartID);
125
Nick Lewycky45062042012-02-21 00:26:58 +0000126 // Emit a call with the size in bytes of the object.
127 CharUnits WidthChars = CGF.getContext().getTypeSizeInChars(D.getType());
128 uint64_t Width = WidthChars.getQuantity();
129 llvm::Value *Args[2] = { llvm::ConstantInt::getSigned(CGF.Int64Ty, Width),
Richard Smith08a51442012-02-17 07:31:37 +0000130 llvm::ConstantExpr::getBitCast(Addr, CGF.Int8PtrTy)};
131 CGF.Builder.CreateCall(InvariantStart, Args);
132}
133
Anders Carlsson364051c2009-12-10 00:57:45 +0000134void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
Richard Smith6331c402012-02-13 22:16:19 +0000135 llvm::Constant *DeclPtr,
136 bool PerformInit) {
Anders Carlsson364051c2009-12-10 00:57:45 +0000137
138 const Expr *Init = D.getInit();
139 QualType T = D.getType();
140
141 if (!T->isReferenceType()) {
Richard Smith6331c402012-02-13 22:16:19 +0000142 if (PerformInit)
143 EmitDeclInit(*this, D, DeclPtr);
Richard Smith08a51442012-02-17 07:31:37 +0000144 if (CGM.isTypeConstant(D.getType(), true))
Nick Lewycky45062042012-02-21 00:26:58 +0000145 EmitDeclInvariant(*this, D, DeclPtr);
Richard Smith08a51442012-02-17 07:31:37 +0000146 else
147 EmitDeclDestroy(*this, D, DeclPtr);
Anders Carlsson364051c2009-12-10 00:57:45 +0000148 return;
149 }
Anders Carlsson3f48c602010-06-27 17:52:15 +0000150
Richard Smith6331c402012-02-13 22:16:19 +0000151 assert(PerformInit && "cannot have constant initializer which needs "
152 "destruction for reference");
Daniel Dunbar03816342010-08-21 02:24:36 +0000153 unsigned Alignment = getContext().getDeclAlign(&D).getQuantity();
Richard Smitha1c9d4d2013-06-12 23:38:09 +0000154 RValue RV = EmitReferenceBindingToExpr(Init);
Daniel Dunbar03816342010-08-21 02:24:36 +0000155 EmitStoreOfScalar(RV.getScalarVal(), DeclPtr, false, Alignment, T);
Anders Carlsson364051c2009-12-10 00:57:45 +0000156}
Anders Carlsson633c6f62009-12-10 00:30:05 +0000157
John McCall76cc43a2012-04-06 18:21:06 +0000158/// Create a stub function, suitable for being passed to atexit,
159/// which passes the given address to the given destructor function.
David Majnemerb3341ea2014-10-05 05:05:40 +0000160llvm::Constant *CodeGenFunction::createAtExitStub(const VarDecl &VD,
161 llvm::Constant *dtor,
162 llvm::Constant *addr) {
John McCall76cc43a2012-04-06 18:21:06 +0000163 // Get the destructor function type, void(*)(void).
164 llvm::FunctionType *ty = llvm::FunctionType::get(CGM.VoidTy, false);
Reid Klecknerd8110b62013-09-10 20:14:30 +0000165 SmallString<256> FnName;
166 {
167 llvm::raw_svector_ostream Out(FnName);
168 CGM.getCXXABI().getMangleContext().mangleDynamicAtExitDestructor(&VD, Out);
169 }
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000170 llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(ty, FnName.str(),
171 VD.getLocation());
John McCall76cc43a2012-04-06 18:21:06 +0000172
173 CodeGenFunction CGF(CGM);
174
David Blaikieebe87e12013-08-27 23:57:18 +0000175 CGF.StartFunction(&VD, CGM.getContext().VoidTy, fn,
Adrian Prantl22e66b42014-04-11 01:13:04 +0000176 CGM.getTypes().arrangeNullaryFunction(), FunctionArgList());
John McCall76cc43a2012-04-06 18:21:06 +0000177
178 llvm::CallInst *call = CGF.Builder.CreateCall(dtor, addr);
179
180 // Make sure the call and the callee agree on calling convention.
181 if (llvm::Function *dtorFn =
182 dyn_cast<llvm::Function>(dtor->stripPointerCasts()))
183 call->setCallingConv(dtorFn->getCallingConv());
184
185 CGF.FinishFunction();
186
187 return fn;
188}
189
John McCallc84ed6a2012-05-01 06:13:13 +0000190/// Register a global destructor using the C atexit runtime function.
David Blaikieebe87e12013-08-27 23:57:18 +0000191void CodeGenFunction::registerGlobalDtorWithAtExit(const VarDecl &VD,
192 llvm::Constant *dtor,
John McCallc84ed6a2012-05-01 06:13:13 +0000193 llvm::Constant *addr) {
John McCall76cc43a2012-04-06 18:21:06 +0000194 // Create a function which calls the destructor.
David Majnemerb3341ea2014-10-05 05:05:40 +0000195 llvm::Constant *dtorStub = createAtExitStub(VD, dtor, addr);
John McCall76cc43a2012-04-06 18:21:06 +0000196
197 // extern "C" int atexit(void (*f)(void));
198 llvm::FunctionType *atexitTy =
John McCallc84ed6a2012-05-01 06:13:13 +0000199 llvm::FunctionType::get(IntTy, dtorStub->getType(), false);
John McCall76cc43a2012-04-06 18:21:06 +0000200
201 llvm::Constant *atexit =
John McCallc84ed6a2012-05-01 06:13:13 +0000202 CGM.CreateRuntimeFunction(atexitTy, "atexit");
John McCall76cc43a2012-04-06 18:21:06 +0000203 if (llvm::Function *atexitFn = dyn_cast<llvm::Function>(atexit))
204 atexitFn->setDoesNotThrow();
205
John McCall882987f2013-02-28 19:01:20 +0000206 EmitNounwindRuntimeCall(atexit, dtorStub);
Anders Carlsson633c6f62009-12-10 00:30:05 +0000207}
208
John McCallcdf7ef52010-11-06 09:44:32 +0000209void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
Chandler Carruth84537952012-03-30 19:44:53 +0000210 llvm::GlobalVariable *DeclPtr,
Richard Smith6331c402012-02-13 22:16:19 +0000211 bool PerformInit) {
John McCall7ef5cb32011-03-18 02:56:14 +0000212 // If we've been asked to forbid guard variables, emit an error now.
213 // This diagnostic is hard-coded for Darwin's use case; we can find
214 // better phrasing if someone else needs it.
215 if (CGM.getCodeGenOpts().ForbidGuardVariables)
216 CGM.Error(D.getLocation(),
217 "this initialization requires a guard variable, which "
218 "the kernel does not support");
219
Chandler Carruth84537952012-03-30 19:44:53 +0000220 CGM.getCXXABI().EmitGuardedInit(*this, D, DeclPtr, PerformInit);
John McCall68ff0372010-09-08 01:44:27 +0000221}
222
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000223llvm::Function *CodeGenModule::CreateGlobalInitOrDestructFunction(
224 llvm::FunctionType *FTy, const Twine &Name, SourceLocation Loc, bool TLS) {
Anders Carlssonb2839e42010-06-08 22:40:05 +0000225 llvm::Function *Fn =
226 llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
David Majnemerb3341ea2014-10-05 05:05:40 +0000227 Name, &getModule());
228 if (!getLangOpts().AppleKext && !TLS) {
Fariborz Jahanian09948f12011-02-15 18:54:46 +0000229 // Set the section if needed.
David Majnemerb3341ea2014-10-05 05:05:40 +0000230 if (const char *Section = getTarget().getStaticInitSectionSpecifier())
Fariborz Jahanian09948f12011-02-15 18:54:46 +0000231 Fn->setSection(Section);
232 }
Anders Carlsson851318a2010-06-08 22:47:50 +0000233
David Majnemerb3341ea2014-10-05 05:05:40 +0000234 Fn->setCallingConv(getRuntimeCC());
John McCall882987f2013-02-28 19:01:20 +0000235
David Majnemerb3341ea2014-10-05 05:05:40 +0000236 if (!getLangOpts().Exceptions)
John McCall466e2212010-07-06 04:38:10 +0000237 Fn->setDoesNotThrow();
238
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000239 if (!isInSanitizerBlacklist(Fn, Loc)) {
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000240 if (getLangOpts().Sanitize.has(SanitizerKind::Address))
Alexey Samsonove7a8ccf2014-07-07 23:34:34 +0000241 Fn->addFnAttr(llvm::Attribute::SanitizeAddress);
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000242 if (getLangOpts().Sanitize.has(SanitizerKind::Thread))
Alexey Samsonove7a8ccf2014-07-07 23:34:34 +0000243 Fn->addFnAttr(llvm::Attribute::SanitizeThread);
Alexey Samsonovedf99a92014-11-07 22:29:38 +0000244 if (getLangOpts().Sanitize.has(SanitizerKind::Memory))
Alexey Samsonove7a8ccf2014-07-07 23:34:34 +0000245 Fn->addFnAttr(llvm::Attribute::SanitizeMemory);
246 }
Kostya Serebryanybf84b8f2012-06-26 08:56:33 +0000247
Anders Carlssonb2839e42010-06-08 22:40:05 +0000248 return Fn;
249}
250
Reid Kleckner1a711b12014-07-22 00:53:05 +0000251/// Create a global pointer to a function that will initialize a global
252/// variable. The user has requested that this pointer be emitted in a specific
253/// section.
254void CodeGenModule::EmitPointerToInitFunc(const VarDecl *D,
255 llvm::GlobalVariable *GV,
256 llvm::Function *InitFunc,
257 InitSegAttr *ISA) {
258 llvm::GlobalVariable *PtrArray = new llvm::GlobalVariable(
259 TheModule, InitFunc->getType(), /*isConstant=*/true,
260 llvm::GlobalValue::PrivateLinkage, InitFunc, "__cxx_init_fn_ptr");
261 PtrArray->setSection(ISA->getSection());
262 addUsedGlobal(PtrArray);
263
264 // If the GV is already in a comdat group, then we have to join it.
265 llvm::Comdat *C = GV->getComdat();
266
267 // LinkOnce and Weak linkage are lowered down to a single-member comdat group.
268 // Make an explicit group so we can join it.
269 if (!C && (GV->hasWeakLinkage() || GV->hasLinkOnceLinkage())) {
270 C = TheModule.getOrInsertComdat(GV->getName());
271 GV->setComdat(C);
272 }
273 if (C)
274 PtrArray->setComdat(C);
275}
276
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000277void
John McCallcdf7ef52010-11-06 09:44:32 +0000278CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
Richard Smith6331c402012-02-13 22:16:19 +0000279 llvm::GlobalVariable *Addr,
280 bool PerformInit) {
Chris Lattnerece04092012-02-07 00:39:47 +0000281 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Reid Kleckner1ece9fc2013-09-10 20:43:12 +0000282 SmallString<256> FnName;
283 {
284 llvm::raw_svector_ostream Out(FnName);
285 getCXXABI().getMangleContext().mangleDynamicInitializer(D, Out);
286 }
Eli Friedman5866fe32010-01-08 00:50:11 +0000287
288 // Create a variable initialization function.
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000289 llvm::Function *Fn =
290 CreateGlobalInitOrDestructFunction(FTy, FnName.str(), D->getLocation());
Eli Friedman5866fe32010-01-08 00:50:11 +0000291
Reid Kleckner1a711b12014-07-22 00:53:05 +0000292 auto *ISA = D->getAttr<InitSegAttr>();
Richard Smith6331c402012-02-13 22:16:19 +0000293 CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
294 PerformInit);
Rafael Espindola9f834732014-09-19 01:54:22 +0000295
Reid Kleckner72d03be2014-10-15 16:38:00 +0000296 llvm::GlobalVariable *COMDATKey =
297 supportsCOMDAT() && D->isExternallyVisible() ? Addr : nullptr;
Rafael Espindola9f834732014-09-19 01:54:22 +0000298
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000299 if (D->getTLSKind()) {
300 // FIXME: Should we support init_priority for thread_local?
301 // FIXME: Ideally, initialization of instantiated thread_local static data
302 // members of class templates should not trigger initialization of other
303 // entities in the TU.
304 // FIXME: We only need to register one __cxa_thread_atexit function for the
305 // entire TU.
306 CXXThreadLocalInits.push_back(Fn);
David Majnemerb3341ea2014-10-05 05:05:40 +0000307 CXXThreadLocalInitVars.push_back(Addr);
Reid Kleckner1a711b12014-07-22 00:53:05 +0000308 } else if (PerformInit && ISA) {
309 EmitPointerToInitFunc(D, Addr, Fn, ISA);
310 DelayedCXXInitPosition.erase(D);
311 } else if (auto *IPA = D->getAttr<InitPriorityAttr>()) {
Aaron Ballmane8d9f8d2013-12-19 03:02:49 +0000312 OrderGlobalInits Key(IPA->getPriority(), PrioritizedCXXGlobalInits.size());
Fariborz Jahanian89bdd142010-06-21 21:27:42 +0000313 PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
John McCall70013b62010-07-15 23:40:35 +0000314 DelayedCXXInitPosition.erase(D);
Reid Kleckner72d03be2014-10-15 16:38:00 +0000315 } else if (isTemplateInstantiation(D->getTemplateSpecializationKind())) {
Reid Kleckner37384452013-08-22 20:07:45 +0000316 // C++ [basic.start.init]p2:
Reid Kleckner27533242013-09-04 00:54:24 +0000317 // Definitions of explicitly specialized class template static data
318 // members have ordered initialization. Other class template static data
319 // members (i.e., implicitly or explicitly instantiated specializations)
320 // have unordered initialization.
Reid Kleckner37384452013-08-22 20:07:45 +0000321 //
322 // As a consequence, we can put them into their own llvm.global_ctors entry.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000323 //
Reid Kleckner72d03be2014-10-15 16:38:00 +0000324 // If the global is externally visible, put the initializer into a COMDAT
325 // group with the global being initialized. On most platforms, this is a
326 // minor startup time optimization. In the MS C++ ABI, there are no guard
327 // variables, so this COMDAT key is required for correctness.
328 AddGlobalCtor(Fn, 65535, COMDATKey);
Reid Kleckner37384452013-08-22 20:07:45 +0000329 DelayedCXXInitPosition.erase(D);
Hans Wennborg7b556ea2014-09-10 19:28:48 +0000330 } else if (D->hasAttr<SelectAnyAttr>()) {
331 // SelectAny globals will be comdat-folded. Put the initializer into a COMDAT
332 // group associated with the global, so the initializers get folded too.
Reid Kleckner72d03be2014-10-15 16:38:00 +0000333 AddGlobalCtor(Fn, 65535, COMDATKey);
Hans Wennborg7b556ea2014-09-10 19:28:48 +0000334 DelayedCXXInitPosition.erase(D);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000335 } else {
John McCall70013b62010-07-15 23:40:35 +0000336 llvm::DenseMap<const Decl *, unsigned>::iterator I =
337 DelayedCXXInitPosition.find(D);
338 if (I == DelayedCXXInitPosition.end()) {
339 CXXGlobalInits.push_back(Fn);
340 } else {
Craig Topper8a13c412014-05-21 05:09:00 +0000341 assert(CXXGlobalInits[I->second] == nullptr);
John McCall70013b62010-07-15 23:40:35 +0000342 CXXGlobalInits[I->second] = Fn;
343 DelayedCXXInitPosition.erase(I);
344 }
345 }
Eli Friedman5866fe32010-01-08 00:50:11 +0000346}
347
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000348void CodeGenModule::EmitCXXThreadLocalInitFunc() {
David Majnemerb3341ea2014-10-05 05:05:40 +0000349 getCXXABI().EmitThreadLocalInitFuncs(
350 *this, CXXThreadLocals, CXXThreadLocalInits, CXXThreadLocalInitVars);
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000351
352 CXXThreadLocalInits.clear();
David Majnemerb3341ea2014-10-05 05:05:40 +0000353 CXXThreadLocalInitVars.clear();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000354 CXXThreadLocals.clear();
355}
356
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000357void
358CodeGenModule::EmitCXXGlobalInitFunc() {
John McCall70013b62010-07-15 23:40:35 +0000359 while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
360 CXXGlobalInits.pop_back();
361
Fariborz Jahanian9f2a4ee2010-06-21 18:45:05 +0000362 if (CXXGlobalInits.empty() && PrioritizedCXXGlobalInits.empty())
Anders Carlsson633c6f62009-12-10 00:30:05 +0000363 return;
364
Chris Lattnerece04092012-02-07 00:39:47 +0000365 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Anders Carlsson633c6f62009-12-10 00:30:05 +0000366
Anders Carlsson633c6f62009-12-10 00:30:05 +0000367
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000368 // Create our global initialization function.
Fariborz Jahanian9f2a4ee2010-06-21 18:45:05 +0000369 if (!PrioritizedCXXGlobalInits.empty()) {
David Majnemerb3341ea2014-10-05 05:05:40 +0000370 SmallVector<llvm::Function *, 8> LocalCXXGlobalInits;
Fariborz Jahanian090e4e52010-06-21 19:49:38 +0000371 llvm::array_pod_sort(PrioritizedCXXGlobalInits.begin(),
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000372 PrioritizedCXXGlobalInits.end());
373 // Iterate over "chunks" of ctors with same priority and emit each chunk
374 // into separate function. Note - everything is sorted first by priority,
375 // second - by lex order, so we emit ctor functions in proper order.
376 for (SmallVectorImpl<GlobalInitData >::iterator
377 I = PrioritizedCXXGlobalInits.begin(),
378 E = PrioritizedCXXGlobalInits.end(); I != E; ) {
379 SmallVectorImpl<GlobalInitData >::iterator
380 PrioE = std::upper_bound(I + 1, E, *I, GlobalInitPriorityCmp());
381
382 LocalCXXGlobalInits.clear();
383 unsigned Priority = I->first.priority;
384 // Compute the function suffix from priority. Prepend with zeroes to make
385 // sure the function names are also ordered as priorities.
386 std::string PrioritySuffix = llvm::utostr(Priority);
Nico Weberbdc96982014-05-06 20:32:45 +0000387 // Priority is always <= 65535 (enforced by sema).
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000388 PrioritySuffix = std::string(6-PrioritySuffix.size(), '0')+PrioritySuffix;
David Majnemerb3341ea2014-10-05 05:05:40 +0000389 llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
390 FTy, "_GLOBAL__I_" + PrioritySuffix);
391
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000392 for (; I < PrioE; ++I)
393 LocalCXXGlobalInits.push_back(I->second);
394
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000395 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000396 AddGlobalCtor(Fn, Priority);
397 }
Fariborz Jahanian9f2a4ee2010-06-21 18:45:05 +0000398 }
Keno Fischer84778b22014-08-26 22:10:15 +0000399
400 SmallString<128> FileName;
Nico Weberbdc96982014-05-06 20:32:45 +0000401 SourceManager &SM = Context.getSourceManager();
Keno Fischer84778b22014-08-26 22:10:15 +0000402 if (const FileEntry *MainFile = SM.getFileEntryForID(SM.getMainFileID())) {
403 // Include the filename in the symbol name. Including "sub_" matches gcc and
404 // makes sure these symbols appear lexicographically behind the symbols with
405 // priority emitted above.
406 FileName = llvm::sys::path::filename(MainFile->getName());
407 } else {
408 FileName = SmallString<128>("<null>");
409 }
410
Nico Weberbdc96982014-05-06 20:32:45 +0000411 for (size_t i = 0; i < FileName.size(); ++i) {
412 // Replace everything that's not [a-zA-Z0-9._] with a _. This set happens
413 // to be the set of C preprocessing numbers.
414 if (!isPreprocessingNumberBody(FileName[i]))
415 FileName[i] = '_';
416 }
Keno Fischer84778b22014-08-26 22:10:15 +0000417
Nico Weberbdc96982014-05-06 20:32:45 +0000418 llvm::Function *Fn = CreateGlobalInitOrDestructFunction(
David Majnemerb3341ea2014-10-05 05:05:40 +0000419 FTy, llvm::Twine("_GLOBAL__sub_I_", FileName));
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000420
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000421 CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000422 AddGlobalCtor(Fn);
Anton Korobeynikovabed7492012-11-06 22:44:45 +0000423
Axel Naumannbd26a582011-05-06 15:24:04 +0000424 CXXGlobalInits.clear();
425 PrioritizedCXXGlobalInits.clear();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000426}
427
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000428void CodeGenModule::EmitCXXGlobalDtorFunc() {
429 if (CXXGlobalDtors.empty())
430 return;
431
Chris Lattnerece04092012-02-07 00:39:47 +0000432 llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000433
434 // Create our global destructor function.
David Majnemerb3341ea2014-10-05 05:05:40 +0000435 llvm::Function *Fn = CreateGlobalInitOrDestructFunction(FTy, "_GLOBAL__D_a");
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000436
John McCallee08c532012-04-06 18:21:03 +0000437 CodeGenFunction(*this).GenerateCXXGlobalDtorsFunc(Fn, CXXGlobalDtors);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000438 AddGlobalDtor(Fn);
439}
440
John McCallcdf7ef52010-11-06 09:44:32 +0000441/// Emit the code necessary to initialize the given global variable.
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000442void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
John McCallcdf7ef52010-11-06 09:44:32 +0000443 const VarDecl *D,
Richard Smith6331c402012-02-13 22:16:19 +0000444 llvm::GlobalVariable *Addr,
445 bool PerformInit) {
Alexey Samsonov38e24962012-10-16 07:22:28 +0000446 // Check if we need to emit debug info for variable initializer.
David Blaikie92848de2013-08-26 20:33:21 +0000447 if (D->hasAttr<NoDebugAttr>())
Craig Topper8a13c412014-05-21 05:09:00 +0000448 DebugInfo = nullptr; // disable debug info indefinitely for this function
Nick Lewycky08597072012-07-24 01:40:49 +0000449
450 StartFunction(GlobalDecl(D), getContext().VoidTy, Fn,
John McCalla729c622012-02-17 03:33:10 +0000451 getTypes().arrangeNullaryFunction(),
Adrian Prantl42d71b92014-04-10 23:21:53 +0000452 FunctionArgList(), D->getLocation(),
453 D->getInit()->getExprLoc());
Daniel Dunbar75722842010-03-20 04:15:29 +0000454
Douglas Gregorfa918f62011-07-01 21:54:36 +0000455 // Use guarded initialization if the global variable is weak. This
456 // occurs for, e.g., instantiated static data members and
457 // definitions explicitly marked weak.
Reid Kleckner563f0e82014-05-23 21:13:45 +0000458 if (Addr->hasWeakLinkage() || Addr->hasLinkOnceLinkage()) {
Richard Smith6331c402012-02-13 22:16:19 +0000459 EmitCXXGuardedInit(*D, Addr, PerformInit);
John McCallcdf7ef52010-11-06 09:44:32 +0000460 } else {
Richard Smith6331c402012-02-13 22:16:19 +0000461 EmitCXXGlobalVarDeclInit(*D, Addr, PerformInit);
Fariborz Jahanian67ca8c42010-10-26 22:47:47 +0000462 }
Daniel Dunbar75722842010-03-20 04:15:29 +0000463
464 FinishFunction();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000465}
Daniel Dunbar75722842010-03-20 04:15:29 +0000466
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000467void
468CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
David Majnemerb3341ea2014-10-05 05:05:40 +0000469 ArrayRef<llvm::Function *> Decls,
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000470 llvm::GlobalVariable *Guard) {
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000471 {
472 ArtificialLocation AL(*this, Builder);
473 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
474 getTypes().arrangeNullaryFunction(), FunctionArgList());
475 // Emit an artificial location for this function.
476 AL.Emit();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000477
Craig Topper8a13c412014-05-21 05:09:00 +0000478 llvm::BasicBlock *ExitBlock = nullptr;
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000479 if (Guard) {
480 // If we have a guard variable, check whether we've already performed
481 // these initializations. This happens for TLS initialization functions.
482 llvm::Value *GuardVal = Builder.CreateLoad(Guard);
483 llvm::Value *Uninit = Builder.CreateIsNull(GuardVal,
484 "guard.uninitialized");
485 // Mark as initialized before initializing anything else. If the
486 // initializers use previously-initialized thread_local vars, that's
487 // probably supposed to be OK, but the standard doesn't say.
488 Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(),1), Guard);
489 llvm::BasicBlock *InitBlock = createBasicBlock("init");
490 ExitBlock = createBasicBlock("exit");
491 Builder.CreateCondBr(Uninit, InitBlock, ExitBlock);
492 EmitBlock(InitBlock);
493 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000494
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000495 RunCleanupsScope Scope(*this);
John McCall31168b02011-06-15 23:02:42 +0000496
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000497 // When building in Objective-C++ ARC mode, create an autorelease pool
498 // around the global initializers.
499 if (getLangOpts().ObjCAutoRefCount && getLangOpts().CPlusPlus) {
500 llvm::Value *token = EmitObjCAutoreleasePoolPush();
501 EmitObjCAutoreleasePoolCleanup(token);
502 }
Benjamin Kramer139cfc22013-04-26 21:32:52 +0000503
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000504 for (unsigned i = 0, e = Decls.size(); i != e; ++i)
505 if (Decls[i])
506 EmitRuntimeCall(Decls[i]);
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000507
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000508 Scope.ForceCleanup();
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000509
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000510 if (ExitBlock) {
511 Builder.CreateBr(ExitBlock);
512 EmitBlock(ExitBlock);
513 }
Richard Smith2fd1d7a2013-04-19 16:42:07 +0000514 }
515
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000516 FinishFunction();
517}
518
John McCallee08c532012-04-06 18:21:03 +0000519void CodeGenFunction::GenerateCXXGlobalDtorsFunc(llvm::Function *Fn,
Chris Lattner87233f72010-06-19 05:52:45 +0000520 const std::vector<std::pair<llvm::WeakVH, llvm::Constant*> >
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000521 &DtorsAndObjects) {
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000522 {
523 ArtificialLocation AL(*this, Builder);
524 StartFunction(GlobalDecl(), getContext().VoidTy, Fn,
525 getTypes().arrangeNullaryFunction(), FunctionArgList());
526 // Emit an artificial location for this function.
527 AL.Emit();
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000528
Adrian Prantl0ce2b872014-04-11 23:45:01 +0000529 // Emit the dtors, in reverse order from construction.
530 for (unsigned i = 0, e = DtorsAndObjects.size(); i != e; ++i) {
531 llvm::Value *Callee = DtorsAndObjects[e - i - 1].first;
532 llvm::CallInst *CI = Builder.CreateCall(Callee,
533 DtorsAndObjects[e - i - 1].second);
534 // Make sure the call and the callee agree on calling convention.
535 if (llvm::Function *F = dyn_cast<llvm::Function>(Callee))
536 CI->setCallingConv(F->getCallingConv());
537 }
Chris Lattner5e8416a2010-04-26 20:35:54 +0000538 }
Daniel Dunbarfe06df42010-03-20 04:15:41 +0000539
540 FinishFunction();
Anders Carlsson633c6f62009-12-10 00:30:05 +0000541}
542
John McCall98de3d72011-07-13 03:01:35 +0000543/// generateDestroyHelper - Generates a helper function which, when
544/// invoked, destroys the given object.
David Blaikieebe87e12013-08-27 23:57:18 +0000545llvm::Function *CodeGenFunction::generateDestroyHelper(
546 llvm::Constant *addr, QualType type, Destroyer *destroyer,
547 bool useEHCleanupForArray, const VarDecl *VD) {
John McCalla738c252011-03-09 04:27:21 +0000548 FunctionArgList args;
Craig Topper8a13c412014-05-21 05:09:00 +0000549 ImplicitParamDecl dst(getContext(), nullptr, SourceLocation(), nullptr,
Richard Smith053f6c62014-05-16 23:01:30 +0000550 getContext().VoidPtrTy);
John McCalla738c252011-03-09 04:27:21 +0000551 args.push_back(&dst);
Reid Kleckner4982b822014-01-31 22:54:50 +0000552
553 const CGFunctionInfo &FI = CGM.getTypes().arrangeFreeFunctionDeclaration(
554 getContext().VoidTy, args, FunctionType::ExtInfo(), /*variadic=*/false);
John McCalla729c622012-02-17 03:33:10 +0000555 llvm::FunctionType *FTy = CGM.getTypes().GetFunctionType(FI);
Alexey Samsonov1444bb92014-10-17 00:20:19 +0000556 llvm::Function *fn = CGM.CreateGlobalInitOrDestructFunction(
557 FTy, "__cxx_global_array_dtor", VD->getLocation());
Anders Carlsson282bc102010-06-08 22:17:27 +0000558
Adrian Prantl22e66b42014-04-11 01:13:04 +0000559 StartFunction(VD, getContext().VoidTy, fn, FI, args);
Anders Carlsson282bc102010-06-08 22:17:27 +0000560
John McCall98de3d72011-07-13 03:01:35 +0000561 emitDestroy(addr, type, destroyer, useEHCleanupForArray);
Anders Carlsson282bc102010-06-08 22:17:27 +0000562
563 FinishFunction();
564
John McCall98de3d72011-07-13 03:01:35 +0000565 return fn;
Anders Carlsson282bc102010-06-08 22:17:27 +0000566}