blob: c43528866b024b78382177b74c0178e61318f970 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- CodeGenModule.cpp - Emit LLVM Code from ASTs for a Module --------===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This coordinates the per-module state used while generating code.
11//
12//===----------------------------------------------------------------------===//
13
14#include "CodeGenModule.h"
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000015#include "CGCUDARuntime.h"
John McCall4c40d982010-08-31 07:33:07 +000016#include "CGCXXABI.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000017#include "CGCall.h"
18#include "CGDebugInfo.h"
Daniel Dunbaraf2f62c2008-08-13 00:59:25 +000019#include "CGObjCRuntime.h"
Peter Collingbourne8c25fc52011-09-19 21:14:35 +000020#include "CGOpenCLRuntime.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000021#include "CodeGenFunction.h"
22#include "CodeGenTBAA.h"
Anton Korobeynikov82d0a412010-01-10 12:58:08 +000023#include "TargetInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000024#include "clang/AST/ASTContext.h"
Ken Dyck687cc4a2010-01-26 13:48:07 +000025#include "clang/AST/CharUnits.h"
Chris Lattner21ef7ae2008-11-04 16:51:42 +000026#include "clang/AST/DeclCXX.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000027#include "clang/AST/DeclObjC.h"
Douglas Gregoraf896892010-06-21 18:41:26 +000028#include "clang/AST/DeclTemplate.h"
Peter Collingbourne14110472011-01-13 18:57:25 +000029#include "clang/AST/Mangle.h"
Anders Carlsson1a5e0d72009-11-30 23:41:22 +000030#include "clang/AST/RecordLayout.h"
Rafael Espindolaa411d2f2011-10-26 20:41:06 +000031#include "clang/AST/RecursiveASTVisitor.h"
Rafael Espindolabcf6b982011-12-19 14:41:01 +000032#include "clang/Basic/Builtins.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000033#include "clang/Basic/ConvertUTF.h"
Chris Lattner2c8569d2007-12-02 07:19:18 +000034#include "clang/Basic/Diagnostic.h"
Douglas Gregorb6cbe512013-01-14 17:21:00 +000035#include "clang/Basic/Module.h"
Nate Begeman8bd4afe2008-04-19 04:17:09 +000036#include "clang/Basic/SourceManager.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000037#include "clang/Basic/TargetInfo.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000038#include "clang/Frontend/CodeGenOptions.h"
Sebastian Redl19b1a6e2012-02-25 20:51:20 +000039#include "llvm/ADT/APSInt.h"
John McCall6374c332010-03-06 00:35:14 +000040#include "llvm/ADT/Triple.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000041#include "llvm/IR/CallingConv.h"
42#include "llvm/IR/DataLayout.h"
43#include "llvm/IR/Intrinsics.h"
44#include "llvm/IR/LLVMContext.h"
45#include "llvm/IR/Module.h"
Gabor Greif6ba728d2010-04-10 02:56:12 +000046#include "llvm/Support/CallSite.h"
Chris Lattner78f7ece2009-11-07 09:22:46 +000047#include "llvm/Support/ErrorHandling.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000048#include "llvm/Target/Mangler.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000049using namespace clang;
50using namespace CodeGen;
51
Julien Lerouge77f68bb2011-09-09 22:41:49 +000052static const char AnnotationSection[] = "llvm.metadata";
53
John McCallf16aa102010-08-22 21:01:12 +000054static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +000055 switch (CGM.getContext().getTargetInfo().getCXXABI()) {
John McCallf16aa102010-08-22 21:01:12 +000056 case CXXABI_ARM: return *CreateARMCXXABI(CGM);
57 case CXXABI_Itanium: return *CreateItaniumCXXABI(CGM);
58 case CXXABI_Microsoft: return *CreateMicrosoftCXXABI(CGM);
59 }
60
61 llvm_unreachable("invalid C++ ABI kind");
John McCallf16aa102010-08-22 21:01:12 +000062}
63
Reid Spencer5f016e22007-07-11 17:01:13 +000064
Chandler Carruth2811ccf2009-11-12 17:24:48 +000065CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
Micah Villmow25a6a842012-10-08 16:25:52 +000066 llvm::Module &M, const llvm::DataLayout &TD,
David Blaikied6471f72011-09-25 23:23:43 +000067 DiagnosticsEngine &diags)
David Blaikie4e4d0842012-03-11 07:00:24 +000068 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
Micah Villmow25a6a842012-10-08 16:25:52 +000069 TheDataLayout(TD), TheTargetCodeGenInfo(0), Diags(diags),
John McCallf16aa102010-08-22 21:01:12 +000070 ABI(createCXXABI(*this)),
John McCallde5d3c72012-02-17 03:33:10 +000071 Types(*this),
Dan Gohman3d5aff52010-10-14 23:06:10 +000072 TBAA(0),
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000073 VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
Dan Gohmanb49bd272012-02-16 00:57:37 +000074 DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
75 RRData(0), CFConstantStringClassRef(0),
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000076 ConstantStringClassRef(0), NSConstantStringType(0),
Daniel Dunbar673431a2010-07-16 00:00:15 +000077 VMContext(M.getContext()),
78 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
John McCalld16c2cf2011-02-08 08:22:06 +000079 BlockObjectAssign(0), BlockObjectDispose(0),
80 BlockDescriptorType(0), GenericBlockLiteralType(0) {
Chris Lattner8b418682012-02-07 00:39:47 +000081
82 // Initialize the type cache.
83 llvm::LLVMContext &LLVMContext = M.getContext();
84 VoidTy = llvm::Type::getVoidTy(LLVMContext);
85 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
86 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
87 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
88 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
89 FloatTy = llvm::Type::getFloatTy(LLVMContext);
90 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
91 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
92 PointerAlignInBytes =
93 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
94 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
95 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
96 Int8PtrTy = Int8Ty->getPointerTo(0);
97 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
98
David Blaikie4e4d0842012-03-11 07:00:24 +000099 if (LangOpts.ObjC1)
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000100 createObjCRuntime();
David Blaikie4e4d0842012-03-11 07:00:24 +0000101 if (LangOpts.OpenCL)
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000102 createOpenCLRuntime();
David Blaikie4e4d0842012-03-11 07:00:24 +0000103 if (LangOpts.CUDA)
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000104 createCUDARuntime();
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000105
Kostya Serebryanyc9fe6052012-04-24 06:57:01 +0000106 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Richard Smithca1b62a2012-11-05 21:48:12 +0000107 if (LangOpts.SanitizeThread ||
Kostya Serebryanyc9fe6052012-04-24 06:57:01 +0000108 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
109 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
Dan Gohman0b5c4fc2010-10-15 20:23:12 +0000110 ABI.getMangleContext());
Dan Gohman3d5aff52010-10-14 23:06:10 +0000111
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000112 // If debug info or coverage generation is enabled, create the CGDebugInfo
113 // object.
Douglas Gregor4cdad312012-10-23 20:05:01 +0000114 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000115 CodeGenOpts.EmitGcovArcs ||
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000116 CodeGenOpts.EmitGcovNotes)
117 DebugInfo = new CGDebugInfo(*this);
John McCalld16c2cf2011-02-08 08:22:06 +0000118
119 Block.GlobalUniqueCount = 0;
John McCall5936e332011-02-15 09:22:45 +0000120
David Blaikie4e4d0842012-03-11 07:00:24 +0000121 if (C.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000122 ARCData = new ARCEntrypoints();
123 RRData = new RREntrypoints();
Chris Lattner2b94fe32008-03-01 08:45:05 +0000124}
125
126CodeGenModule::~CodeGenModule() {
Peter Collingbournee9265232011-07-27 20:29:46 +0000127 delete ObjCRuntime;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000128 delete OpenCLRuntime;
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000129 delete CUDARuntime;
Ted Kremenek0628b722011-10-08 05:28:26 +0000130 delete TheTargetCodeGenInfo;
John McCallf16aa102010-08-22 21:01:12 +0000131 delete &ABI;
Dan Gohman4376c852010-10-15 18:04:46 +0000132 delete TBAA;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000133 delete DebugInfo;
John McCallf85e1932011-06-15 23:02:42 +0000134 delete ARCData;
135 delete RRData;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000136}
137
David Chisnall0d13f6f2010-01-23 02:40:42 +0000138void CodeGenModule::createObjCRuntime() {
John McCall260611a2012-06-20 06:18:46 +0000139 // This is just isGNUFamily(), but we want to force implementors of
140 // new ABIs to decide how best to do this.
141 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnall11d3f4c2012-07-03 20:49:52 +0000142 case ObjCRuntime::GNUstep:
143 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000144 case ObjCRuntime::ObjFW:
Peter Collingbournee9265232011-07-27 20:29:46 +0000145 ObjCRuntime = CreateGNUObjCRuntime(*this);
John McCall260611a2012-06-20 06:18:46 +0000146 return;
147
148 case ObjCRuntime::FragileMacOSX:
149 case ObjCRuntime::MacOSX:
150 case ObjCRuntime::iOS:
Peter Collingbournee9265232011-07-27 20:29:46 +0000151 ObjCRuntime = CreateMacObjCRuntime(*this);
John McCall260611a2012-06-20 06:18:46 +0000152 return;
153 }
154 llvm_unreachable("bad runtime kind");
David Chisnall0d13f6f2010-01-23 02:40:42 +0000155}
156
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000157void CodeGenModule::createOpenCLRuntime() {
158 OpenCLRuntime = new CGOpenCLRuntime(*this);
159}
160
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000161void CodeGenModule::createCUDARuntime() {
162 CUDARuntime = CreateNVCUDARuntime(*this);
163}
164
Ted Kremenek815c78f2008-08-05 18:50:11 +0000165void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +0000166 EmitDeferred();
Eli Friedman6c6bda32010-01-08 00:50:11 +0000167 EmitCXXGlobalInitFunc();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000168 EmitCXXGlobalDtorFunc();
Peter Collingbournee9265232011-07-27 20:29:46 +0000169 if (ObjCRuntime)
170 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000171 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000172 EmitCtorList(GlobalCtors, "llvm.global_ctors");
173 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000174 EmitGlobalAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +0000175 EmitLLVMUsed();
Douglas Gregor5d75ea72013-01-14 18:28:43 +0000176
John McCallb2593832010-09-16 06:16:50 +0000177 SimplifyPersonality();
178
John McCall744016d2010-07-06 23:57:41 +0000179 if (getCodeGenOpts().EmitDeclMetadata)
180 EmitDeclMetadata();
Nick Lewycky5ea4f442011-05-04 20:46:58 +0000181
182 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky3dc05412011-05-05 00:08:20 +0000183 EmitCoverageFile();
Devang Patelf391dbe2011-08-16 20:58:22 +0000184
185 if (DebugInfo)
186 DebugInfo->finalize();
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000187}
188
Devang Patele80d5672011-03-23 16:29:39 +0000189void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
190 // Make sure that this type is translated.
191 Types.UpdateCompletedType(TD);
Devang Patele80d5672011-03-23 16:29:39 +0000192}
193
Dan Gohman3d5aff52010-10-14 23:06:10 +0000194llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
195 if (!TBAA)
196 return 0;
197 return TBAA->getTBAAInfo(QTy);
198}
199
Kostya Serebryany8cb4a072012-03-26 17:03:51 +0000200llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
201 if (!TBAA)
202 return 0;
203 return TBAA->getTBAAInfoForVTablePtr();
204}
205
Dan Gohmanb22c7dc2012-09-28 21:58:29 +0000206llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
207 if (!TBAA)
208 return 0;
209 return TBAA->getTBAAStructInfo(QTy);
210}
211
Dan Gohman3d5aff52010-10-14 23:06:10 +0000212void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
213 llvm::MDNode *TBAAInfo) {
214 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
215}
216
John McCall6374c332010-03-06 00:35:14 +0000217bool CodeGenModule::isTargetDarwin() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000218 return getContext().getTargetInfo().getTriple().isOSDarwin();
John McCall6374c332010-03-06 00:35:14 +0000219}
220
Chandler Carruth0f30a122012-03-30 19:44:53 +0000221void CodeGenModule::Error(SourceLocation loc, StringRef error) {
222 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
John McCall32096692011-03-18 02:56:14 +0000223 getDiags().Report(Context.getFullLoc(loc), diagID);
224}
225
Daniel Dunbar488e9932008-08-16 00:56:44 +0000226/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000227/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000228void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
229 bool OmitOnError) {
230 if (OmitOnError && getDiags().hasErrorOccurred())
231 return;
David Blaikied6471f72011-09-25 23:23:43 +0000232 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000233 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000234 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000235 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
236 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000237}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000238
Daniel Dunbar488e9932008-08-16 00:56:44 +0000239/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000240/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000241void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
242 bool OmitOnError) {
243 if (OmitOnError && getDiags().hasErrorOccurred())
244 return;
David Blaikied6471f72011-09-25 23:23:43 +0000245 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000246 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000247 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000248 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000249}
250
John McCallbc8d40d2011-06-24 21:55:10 +0000251llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
252 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
253}
254
Mike Stump1eb44332009-09-09 15:08:12 +0000255void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000256 const NamedDecl *D) const {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000257 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000258 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000259 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000260 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000261 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000262
John McCallaf146032010-10-30 11:50:40 +0000263 // Set visibility for definitions.
264 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000265 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
266 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
Dan Gohman4f8d1232008-05-22 00:50:06 +0000267}
268
Hans Wennborgde981f32012-06-28 08:01:44 +0000269static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
270 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
271 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
272 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
273 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
274 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
275}
276
277static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
278 CodeGenOptions::TLSModel M) {
279 switch (M) {
280 case CodeGenOptions::GeneralDynamicTLSModel:
281 return llvm::GlobalVariable::GeneralDynamicTLSModel;
282 case CodeGenOptions::LocalDynamicTLSModel:
283 return llvm::GlobalVariable::LocalDynamicTLSModel;
284 case CodeGenOptions::InitialExecTLSModel:
285 return llvm::GlobalVariable::InitialExecTLSModel;
286 case CodeGenOptions::LocalExecTLSModel:
287 return llvm::GlobalVariable::LocalExecTLSModel;
288 }
289 llvm_unreachable("Invalid TLS model!");
290}
291
292void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
293 const VarDecl &D) const {
294 assert(D.isThreadSpecified() && "setting TLS mode on non-TLS var!");
295
296 llvm::GlobalVariable::ThreadLocalMode TLM;
Douglas Gregor4cdad312012-10-23 20:05:01 +0000297 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgde981f32012-06-28 08:01:44 +0000298
299 // Override the TLS model if it is explicitly specified.
300 if (D.hasAttr<TLSModelAttr>()) {
301 const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
302 TLM = GetLLVMTLSModel(Attr->getModel());
303 }
304
305 GV->setThreadLocalMode(TLM);
306}
307
John McCallcbfe5022010-08-04 08:34:44 +0000308/// Set the symbol visibility of type information (vtable and RTTI)
309/// associated with the given type.
310void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
311 const CXXRecordDecl *RD,
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000312 TypeVisibilityKind TVK) const {
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000313 setGlobalVisibility(GV, RD);
John McCallcbfe5022010-08-04 08:34:44 +0000314
John McCall279b5eb2010-08-12 23:36:15 +0000315 if (!CodeGenOpts.HiddenWeakVTables)
316 return;
317
Anders Carlsson9a86a132011-01-29 20:36:11 +0000318 // We never want to drop the visibility for RTTI names.
319 if (TVK == TVK_ForRTTIName)
320 return;
321
John McCallcbfe5022010-08-04 08:34:44 +0000322 // We want to drop the visibility to hidden for weak type symbols.
323 // This isn't possible if there might be unresolved references
324 // elsewhere that rely on this symbol being visible.
325
John McCall7a536902010-08-05 20:39:18 +0000326 // This should be kept roughly in sync with setThunkVisibility
327 // in CGVTables.cpp.
328
John McCallcbfe5022010-08-04 08:34:44 +0000329 // Preconditions.
Anders Carlssonf502d932011-01-24 00:46:19 +0000330 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
John McCallcbfe5022010-08-04 08:34:44 +0000331 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
332 return;
333
334 // Don't override an explicit visibility attribute.
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000335 if (RD->getExplicitVisibility())
John McCallcbfe5022010-08-04 08:34:44 +0000336 return;
337
338 switch (RD->getTemplateSpecializationKind()) {
339 // We have to disable the optimization if this is an EI definition
340 // because there might be EI declarations in other shared objects.
341 case TSK_ExplicitInstantiationDefinition:
342 case TSK_ExplicitInstantiationDeclaration:
343 return;
344
John McCall7a536902010-08-05 20:39:18 +0000345 // Every use of a non-template class's type information has to emit it.
John McCallcbfe5022010-08-04 08:34:44 +0000346 case TSK_Undeclared:
347 break;
348
John McCall7a536902010-08-05 20:39:18 +0000349 // In theory, implicit instantiations can ignore the possibility of
350 // an explicit instantiation declaration because there necessarily
351 // must be an EI definition somewhere with default visibility. In
352 // practice, it's possible to have an explicit instantiation for
353 // an arbitrary template class, and linkers aren't necessarily able
354 // to deal with mixed-visibility symbols.
355 case TSK_ExplicitSpecialization:
John McCallcbfe5022010-08-04 08:34:44 +0000356 case TSK_ImplicitInstantiation:
Douglas Gregoraafd1112012-10-24 14:11:55 +0000357 return;
John McCallcbfe5022010-08-04 08:34:44 +0000358 }
359
360 // If there's a key function, there may be translation units
361 // that don't have the key function's definition. But ignore
362 // this if we're emitting RTTI under -fno-rtti.
David Blaikie4e4d0842012-03-11 07:00:24 +0000363 if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
John McCallcbfe5022010-08-04 08:34:44 +0000364 if (Context.getKeyFunction(RD))
365 return;
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000366 }
John McCallcbfe5022010-08-04 08:34:44 +0000367
368 // Otherwise, drop the visibility to hidden.
369 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindolab1c65ff2011-01-11 21:44:37 +0000370 GV->setUnnamedAddr(true);
John McCallcbfe5022010-08-04 08:34:44 +0000371}
372
Chris Lattner5f9e2722011-07-23 10:55:15 +0000373StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
Anders Carlsson793a9902010-06-22 16:05:32 +0000374 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
375
Chris Lattner5f9e2722011-07-23 10:55:15 +0000376 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
Anders Carlsson793a9902010-06-22 16:05:32 +0000377 if (!Str.empty())
378 return Str;
379
John McCall4c40d982010-08-31 07:33:07 +0000380 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson793a9902010-06-22 16:05:32 +0000381 IdentifierInfo *II = ND->getIdentifier();
382 assert(II && "Attempt to mangle unnamed decl.");
383
384 Str = II->getName();
385 return Str;
386 }
387
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000388 SmallString<256> Buffer;
Rafael Espindolac4850c22011-02-10 23:59:36 +0000389 llvm::raw_svector_ostream Out(Buffer);
Anders Carlsson793a9902010-06-22 16:05:32 +0000390 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000391 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000392 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000393 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000394 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000395 getCXXABI().getMangleContext().mangleBlock(BD, Out,
396 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()));
Anders Carlsson793a9902010-06-22 16:05:32 +0000397 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000398 getCXXABI().getMangleContext().mangleName(ND, Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000399
400 // Allocate space for the mangled name.
Rafael Espindolac4850c22011-02-10 23:59:36 +0000401 Out.flush();
Anders Carlsson793a9902010-06-22 16:05:32 +0000402 size_t Length = Buffer.size();
403 char *Name = MangledNamesAllocator.Allocate<char>(Length);
404 std::copy(Buffer.begin(), Buffer.end(), Name);
405
Chris Lattner5f9e2722011-07-23 10:55:15 +0000406 Str = StringRef(Name, Length);
Anders Carlsson793a9902010-06-22 16:05:32 +0000407
408 return Str;
409}
410
Peter Collingbourne14110472011-01-13 18:57:25 +0000411void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
412 const BlockDecl *BD) {
413 MangleContext &MangleCtx = getCXXABI().getMangleContext();
414 const Decl *D = GD.getDecl();
Rafael Espindolac4850c22011-02-10 23:59:36 +0000415 llvm::raw_svector_ostream Out(Buffer.getBuffer());
Peter Collingbourne14110472011-01-13 18:57:25 +0000416 if (D == 0)
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000417 MangleCtx.mangleGlobalBlock(BD,
418 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000419 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000420 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000421 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000422 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000423 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000424 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Anders Carlsson9a8822b2010-06-09 02:36:32 +0000425}
426
Chris Lattner5f9e2722011-07-23 10:55:15 +0000427llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCallf746aa62010-03-19 23:29:14 +0000428 return getModule().getNamedValue(Name);
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000429}
430
Chris Lattner6d397602008-03-14 17:18:18 +0000431/// AddGlobalCtor - Add a function to the list that will be called before
432/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000433void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000434 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000435 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000436}
437
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000438/// AddGlobalDtor - Add a function to the list that will be called
439/// when the module is unloaded.
440void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000441 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000442 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
443}
444
445void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
446 // Ctor function type is void()*.
John McCall0774cb82011-05-15 01:53:33 +0000447 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000448 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000449
450 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000451 llvm::StructType *CtorStructTy =
Chris Lattner8b418682012-02-07 00:39:47 +0000452 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000453
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000454 // Construct the constructor and destructor arrays.
Chris Lattner0b239712012-02-06 22:16:34 +0000455 SmallVector<llvm::Constant*, 8> Ctors;
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000456 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
Chris Lattner0b239712012-02-06 22:16:34 +0000457 llvm::Constant *S[] = {
458 llvm::ConstantInt::get(Int32Ty, I->second, false),
459 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
460 };
Owen Anderson08e25242009-07-27 22:29:56 +0000461 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000462 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000463
464 if (!Ctors.empty()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000465 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Anderson1c431b32009-07-08 19:05:04 +0000466 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000467 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000468 llvm::ConstantArray::get(AT, Ctors),
Owen Anderson1c431b32009-07-08 19:05:04 +0000469 GlobalName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000470 }
Chris Lattner6d397602008-03-14 17:18:18 +0000471}
472
John McCalld46f9852010-02-19 01:32:20 +0000473llvm::GlobalValue::LinkageTypes
474CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000475 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000476
Chris Lattnerf81530652010-06-30 16:58:07 +0000477 if (Linkage == GVA_Internal)
John McCalld46f9852010-02-19 01:32:20 +0000478 return llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000479
480 if (D->hasAttr<DLLExportAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000481 return llvm::Function::DLLExportLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000482
483 if (D->hasAttr<WeakAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000484 return llvm::Function::WeakAnyLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000485
486 // In C99 mode, 'inline' functions are guaranteed to have a strong
487 // definition somewhere else, so we can use available_externally linkage.
488 if (Linkage == GVA_C99Inline)
Fariborz Jahanianfd0f89d2011-02-04 00:08:13 +0000489 return llvm::Function::AvailableExternallyLinkage;
John McCall5584d912011-09-19 18:05:26 +0000490
491 // Note that Apple's kernel linker doesn't support symbol
492 // coalescing, so we need to avoid linkonce and weak linkages there.
493 // Normally, this means we just map to internal, but for explicit
494 // instantiations we'll map to external.
495
Chris Lattnerf81530652010-06-30 16:58:07 +0000496 // In C++, the compiler has to emit a definition in every translation unit
497 // that references the function. We should use linkonce_odr because
498 // a) if all references in this translation unit are optimized away, we
499 // don't need to codegen it. b) if the function persists, it needs to be
500 // merged with other definitions. c) C++ has the ODR, so we know the
501 // definition is dependable.
502 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
David Blaikie4e4d0842012-03-11 07:00:24 +0000503 return !Context.getLangOpts().AppleKext
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000504 ? llvm::Function::LinkOnceODRLinkage
505 : llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000506
507 // An explicit instantiation of a template has weak linkage, since
508 // explicit instantiations can occur in multiple translation units
509 // and must all be equivalent. However, we are not allowed to
510 // throw away these explicit instantiations.
511 if (Linkage == GVA_ExplicitTemplateInstantiation)
David Blaikie4e4d0842012-03-11 07:00:24 +0000512 return !Context.getLangOpts().AppleKext
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000513 ? llvm::Function::WeakODRLinkage
John McCall5584d912011-09-19 18:05:26 +0000514 : llvm::Function::ExternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000515
516 // Otherwise, we have strong external linkage.
517 assert(Linkage == GVA_StrongExternal);
518 return llvm::Function::ExternalLinkage;
John McCalld46f9852010-02-19 01:32:20 +0000519}
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000520
John McCalld46f9852010-02-19 01:32:20 +0000521
522/// SetFunctionDefinitionAttributes - Set attributes for a global.
523///
524/// FIXME: This is currently only done for aliases and functions, but not for
525/// variables (these details are set in EmitGlobalVarDefinition for variables).
526void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
527 llvm::GlobalValue *GV) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000528 SetCommonAttributes(D, GV);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000529}
530
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000531void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump1eb44332009-09-09 15:08:12 +0000532 const CGFunctionInfo &Info,
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000533 llvm::Function *F) {
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000534 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +0000535 AttributeListType AttributeList;
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000536 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Bill Wendling785b7782012-12-07 23:17:26 +0000537 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000538 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000539}
540
John McCalld1e40d52011-10-02 01:16:38 +0000541/// Determines whether the language options require us to model
542/// unwind exceptions. We treat -fexceptions as mandating this
543/// except under the fragile ObjC ABI with only ObjC exceptions
544/// enabled. This means, for example, that C with -fexceptions
545/// enables this.
David Blaikie4e4d0842012-03-11 07:00:24 +0000546static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCalld1e40d52011-10-02 01:16:38 +0000547 // If exceptions are completely disabled, obviously this is false.
David Blaikie4e4d0842012-03-11 07:00:24 +0000548 if (!LangOpts.Exceptions) return false;
John McCalld1e40d52011-10-02 01:16:38 +0000549
550 // If C++ exceptions are enabled, this is true.
David Blaikie4e4d0842012-03-11 07:00:24 +0000551 if (LangOpts.CXXExceptions) return true;
John McCalld1e40d52011-10-02 01:16:38 +0000552
553 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikie4e4d0842012-03-11 07:00:24 +0000554 if (LangOpts.ObjCExceptions) {
David Chisnall11d3f4c2012-07-03 20:49:52 +0000555 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCalld1e40d52011-10-02 01:16:38 +0000556 }
557
558 return true;
559}
560
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000561void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
562 llvm::Function *F) {
Rafael Espindolaabca5a12011-05-25 03:44:55 +0000563 if (CodeGenOpts.UnwindTables)
564 F->setHasUWTable();
565
David Blaikie4e4d0842012-03-11 07:00:24 +0000566 if (!hasUnwindExceptions(LangOpts))
Bill Wendling72390b32012-12-20 19:27:06 +0000567 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000568
Eli Friedman2873aee2011-08-22 23:55:33 +0000569 if (D->hasAttr<NakedAttr>()) {
570 // Naked implies noinline: we should not be inlining such functions.
Bill Wendling72390b32012-12-20 19:27:06 +0000571 F->addFnAttr(llvm::Attribute::Naked);
572 F->addFnAttr(llvm::Attribute::NoInline);
Eli Friedman2873aee2011-08-22 23:55:33 +0000573 }
Daniel Dunbardd0cb222010-09-29 18:20:25 +0000574
Mike Stump1feade82009-08-26 22:31:08 +0000575 if (D->hasAttr<NoInlineAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +0000576 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpf55314d2009-10-05 21:58:44 +0000577
Eli Friedman2873aee2011-08-22 23:55:33 +0000578 // (noinline wins over always_inline, and we can't specify both in IR)
Michael J. Spenceradc6cbf2012-06-18 07:00:48 +0000579 if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
Bill Wendling01ad9542012-12-30 10:32:17 +0000580 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
581 llvm::Attribute::NoInline))
Bill Wendling72390b32012-12-20 19:27:06 +0000582 F->addFnAttr(llvm::Attribute::AlwaysInline);
Eli Friedman2873aee2011-08-22 23:55:33 +0000583
Benjamin Krameree409a92012-05-12 21:10:52 +0000584 // FIXME: Communicate hot and cold attributes to LLVM more directly.
585 if (D->hasAttr<ColdAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +0000586 F->addFnAttr(llvm::Attribute::OptimizeForSize);
Benjamin Krameree409a92012-05-12 21:10:52 +0000587
Quentin Colombetaee56fa2012-11-01 23:55:47 +0000588 if (D->hasAttr<MinSizeAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +0000589 F->addFnAttr(llvm::Attribute::MinSize);
Quentin Colombetaee56fa2012-11-01 23:55:47 +0000590
Rafael Espindolac5f657f2011-01-11 00:26:26 +0000591 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
592 F->setUnnamedAddr(true);
593
Richard Smithef4d5ce2012-09-28 22:46:07 +0000594 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
595 if (MD->isVirtual())
596 F->setUnnamedAddr(true);
597
David Blaikie4e4d0842012-03-11 07:00:24 +0000598 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
Bill Wendling72390b32012-12-20 19:27:06 +0000599 F->addFnAttr(llvm::Attribute::StackProtect);
David Blaikie4e4d0842012-03-11 07:00:24 +0000600 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
Bill Wendling72390b32012-12-20 19:27:06 +0000601 F->addFnAttr(llvm::Attribute::StackProtectReq);
Anders Carlssonfd015352009-11-16 16:56:03 +0000602
Richard Smithca1b62a2012-11-05 21:48:12 +0000603 if (LangOpts.SanitizeAddress) {
Alexander Potapenko89651ea2012-02-02 11:49:28 +0000604 // When AddressSanitizer is enabled, set AddressSafety attribute
605 // unless __attribute__((no_address_safety_analysis)) is used.
606 if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +0000607 F->addFnAttr(llvm::Attribute::AddressSafety);
Alexander Potapenko89651ea2012-02-02 11:49:28 +0000608 }
609
Sean Huntcf807c42010-08-18 23:23:40 +0000610 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
611 if (alignment)
612 F->setAlignment(alignment);
613
Mike Stumpfb51ddf2009-10-05 22:49:20 +0000614 // C++ ABI requires 2-byte alignment for member functions.
Mike Stumpbd6dbd12009-10-05 23:08:21 +0000615 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
616 F->setAlignment(2);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000617}
618
Mike Stump1eb44332009-09-09 15:08:12 +0000619void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000620 llvm::GlobalValue *GV) {
Anders Carlsson934176f2011-01-29 19:41:00 +0000621 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
622 setGlobalVisibility(GV, ND);
John McCall1fb0caa2010-10-22 21:05:15 +0000623 else
624 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000625
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000626 if (D->hasAttr<UsedAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000627 AddUsedGlobal(GV);
628
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000629 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000630 GV->setSection(SA->getName());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000631
632 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000633}
634
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000635void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
636 llvm::Function *F,
637 const CGFunctionInfo &FI) {
638 SetLLVMFunctionAttributes(D, FI, F);
639 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000640
641 F->setLinkage(llvm::Function::InternalLinkage);
642
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000643 SetCommonAttributes(D, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000644}
645
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000646void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000647 llvm::Function *F,
648 bool IsIncompleteFunction) {
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +0000649 if (unsigned IID = F->getIntrinsicID()) {
650 // If this is an intrinsic function, set the function's attributes
651 // to the intrinsic's attributes.
Bill Wendling50e6b182012-10-15 04:47:45 +0000652 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
653 (llvm::Intrinsic::ID)IID));
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +0000654 return;
655 }
656
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000657 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
658
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000659 if (!IsIncompleteFunction)
John McCallde5d3c72012-02-17 03:33:10 +0000660 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump1eb44332009-09-09 15:08:12 +0000661
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000662 // Only a few attributes are set on declarations; these may later be
663 // overridden by a definition.
Mike Stump1eb44332009-09-09 15:08:12 +0000664
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000665 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000666 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump1eb44332009-09-09 15:08:12 +0000667 } else if (FD->hasAttr<WeakAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000668 FD->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000669 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump1eb44332009-09-09 15:08:12 +0000670 // separate linkage types for this.
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000671 F->setLinkage(llvm::Function::ExternalWeakLinkage);
672 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000673 F->setLinkage(llvm::Function::ExternalLinkage);
John McCallaf146032010-10-30 11:50:40 +0000674
675 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
676 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
677 F->setVisibility(GetLLVMVisibility(LV.visibility()));
678 }
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000679 }
680
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000681 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000682 F->setSection(SA->getName());
Daniel Dunbar219df662008-09-08 23:44:31 +0000683}
684
Daniel Dunbar02698712009-02-13 20:29:50 +0000685void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump1eb44332009-09-09 15:08:12 +0000686 assert(!GV->isDeclaration() &&
Daniel Dunbar02698712009-02-13 20:29:50 +0000687 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000688 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000689}
690
691void CodeGenModule::EmitLLVMUsed() {
692 // Don't create llvm.used if there is no need.
Chris Lattnerad64e022009-07-17 23:57:13 +0000693 if (LLVMUsed.empty())
Daniel Dunbar02698712009-02-13 20:29:50 +0000694 return;
695
Chris Lattner35f38a22009-03-31 22:37:52 +0000696 // Convert LLVMUsed to what ConstantArray needs.
Chris Lattner0b239712012-02-06 22:16:34 +0000697 SmallVector<llvm::Constant*, 8> UsedArray;
Chris Lattner35f38a22009-03-31 22:37:52 +0000698 UsedArray.resize(LLVMUsed.size());
699 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000700 UsedArray[i] =
701 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Chris Lattner0b239712012-02-06 22:16:34 +0000702 Int8PtrTy);
Chris Lattner35f38a22009-03-31 22:37:52 +0000703 }
Mike Stump1eb44332009-09-09 15:08:12 +0000704
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000705 if (UsedArray.empty())
706 return;
Chris Lattner0b239712012-02-06 22:16:34 +0000707 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000708
709 llvm::GlobalVariable *GV =
710 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar02698712009-02-13 20:29:50 +0000711 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000712 llvm::ConstantArray::get(ATy, UsedArray),
Owen Anderson1c431b32009-07-08 19:05:04 +0000713 "llvm.used");
Daniel Dunbar02698712009-02-13 20:29:50 +0000714
715 GV->setSection("llvm.metadata");
716}
717
718void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000719 // Emit code for any potentially referenced deferred decls. Since a
720 // previously unused static decl may become used during the generation of code
Nick Lewyckydce67a72011-07-18 05:26:13 +0000721 // for a static function, iterate until no changes are made.
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000722
Anders Carlsson046c2942010-04-17 20:15:18 +0000723 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
724 if (!DeferredVTables.empty()) {
725 const CXXRecordDecl *RD = DeferredVTables.back();
726 DeferredVTables.pop_back();
Charles Davis9ee494f2012-06-23 23:44:00 +0000727 getCXXABI().EmitVTables(RD);
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000728 continue;
729 }
730
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000731 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner67b00522009-03-21 09:44:56 +0000732 DeferredDeclsToEmit.pop_back();
733
John McCallc76702c2010-05-27 01:45:30 +0000734 // Check to see if we've already emitted this. This is necessary
735 // for a couple of reasons: first, decls can end up in the
736 // deferred-decls queue multiple times, and second, decls can end
737 // up with definitions in unusual ways (e.g. by an extern inline
738 // function acquiring a strong function redefinition). Just
739 // ignore these cases.
740 //
741 // TODO: That said, looking this up multiple times is very wasteful.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000742 StringRef Name = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +0000743 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner67b00522009-03-21 09:44:56 +0000744 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump1eb44332009-09-09 15:08:12 +0000745
Chris Lattner67b00522009-03-21 09:44:56 +0000746 if (!CGRef->isDeclaration())
747 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000748
John McCallc76702c2010-05-27 01:45:30 +0000749 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
750 // purposes an alias counts as a definition.
751 if (isa<llvm::GlobalAlias>(CGRef))
752 continue;
753
Chris Lattner67b00522009-03-21 09:44:56 +0000754 // Otherwise, emit the definition and move on to the next one.
755 EmitGlobalDefinition(D);
756 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000757}
758
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000759void CodeGenModule::EmitGlobalAnnotations() {
760 if (Annotations.empty())
761 return;
762
763 // Create a new global variable for the ConstantStruct in the Module.
764 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
765 Annotations[0]->getType(), Annotations.size()), Annotations);
766 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
767 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
768 "llvm.global.annotations");
769 gv->setSection(AnnotationSection);
770}
771
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000772llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000773 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
774 if (i != AnnotationStrings.end())
775 return i->second;
776
777 // Not found yet, create a new global.
Chris Lattner94010692012-02-05 02:30:40 +0000778 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000779 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
780 true, llvm::GlobalValue::PrivateLinkage, s, ".str");
781 gv->setSection(AnnotationSection);
782 gv->setUnnamedAddr(true);
783 AnnotationStrings[Str] = gv;
784 return gv;
785}
786
787llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
788 SourceManager &SM = getContext().getSourceManager();
789 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
790 if (PLoc.isValid())
791 return EmitAnnotationString(PLoc.getFilename());
792 return EmitAnnotationString(SM.getBufferName(Loc));
793}
794
795llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
796 SourceManager &SM = getContext().getSourceManager();
797 PresumedLoc PLoc = SM.getPresumedLoc(L);
798 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
799 SM.getExpansionLineNumber(L);
800 return llvm::ConstantInt::get(Int32Ty, LineNo);
801}
802
Mike Stump1eb44332009-09-09 15:08:12 +0000803llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000804 const AnnotateAttr *AA,
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000805 SourceLocation L) {
806 // Get the globals for file name, annotation, and the line number.
807 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
808 *UnitGV = EmitAnnotationUnit(L),
809 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000810
Daniel Dunbar57d5cee2009-04-14 22:41:13 +0000811 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000812 llvm::Constant *Fields[4] = {
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000813 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
814 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
815 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
816 LineNoCst
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000817 };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000818 return llvm::ConstantStruct::getAnon(Fields);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000819}
820
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000821void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
822 llvm::GlobalValue *GV) {
823 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
824 // Get the struct elements for these annotations.
825 for (specific_attr_iterator<AnnotateAttr>
826 ai = D->specific_attr_begin<AnnotateAttr>(),
827 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
828 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
829}
830
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000831bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000832 // Never defer when EmitAllDecls is specified.
David Blaikie4e4d0842012-03-11 07:00:24 +0000833 if (LangOpts.EmitAllDecls)
Daniel Dunbar73241df2009-02-13 21:18:01 +0000834 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000835
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +0000836 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar73241df2009-02-13 21:18:01 +0000837}
838
Nico Weberc5f80462012-10-11 10:13:44 +0000839llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
840 const CXXUuidofExpr* E) {
841 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
842 // well-formed.
843 StringRef Uuid;
844 if (E->isTypeOperand())
845 Uuid = CXXUuidofExpr::GetUuidAttrOfType(E->getTypeOperand())->getGuid();
846 else {
847 // Special case: __uuidof(0) means an all-zero GUID.
848 Expr *Op = E->getExprOperand();
849 if (!Op->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
850 Uuid = CXXUuidofExpr::GetUuidAttrOfType(Op->getType())->getGuid();
851 else
852 Uuid = "00000000-0000-0000-0000-000000000000";
853 }
854 std::string Name = "__uuid_" + Uuid.str();
855
856 // Look for an existing global.
857 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
858 return GV;
859
860 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
861 assert(Init && "failed to initialize as constant");
862
863 // GUIDs are assumed to be 16 bytes, spread over 4-2-2-8 bytes. However, the
864 // first field is declared as "long", which for many targets is 8 bytes.
865 // Those architectures are not supported. (With the MS abi, long is always 4
866 // bytes.)
867 llvm::Type *GuidType = getTypes().ConvertType(E->getType());
868 if (Init->getType() != GuidType) {
869 DiagnosticsEngine &Diags = getDiags();
870 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
871 "__uuidof codegen is not supported on this architecture");
872 Diags.Report(E->getExprLoc(), DiagID) << E->getSourceRange();
873 Init = llvm::UndefValue::get(GuidType);
874 }
875
876 llvm::GlobalVariable *GV = new llvm::GlobalVariable(getModule(), GuidType,
877 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Init, Name);
878 GV->setUnnamedAddr(true);
879 return GV;
880}
881
Rafael Espindola6a836702010-03-04 18:17:24 +0000882llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
883 const AliasAttr *AA = VD->getAttr<AliasAttr>();
884 assert(AA && "No alias?");
885
Chris Lattner2acc6e32011-07-18 04:24:23 +0000886 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola6a836702010-03-04 18:17:24 +0000887
Rafael Espindola6a836702010-03-04 18:17:24 +0000888 // See if there is already something with the target's name in the module.
John McCallf746aa62010-03-19 23:29:14 +0000889 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenberger4695f912012-10-16 17:45:27 +0000890 if (Entry) {
891 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
892 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
893 }
Rafael Espindola6a836702010-03-04 18:17:24 +0000894
895 llvm::Constant *Aliasee;
896 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergc857ce82012-10-05 23:12:53 +0000897 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
898 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson1faa89f2011-02-05 04:35:53 +0000899 /*ForVTable=*/false);
Rafael Espindola6a836702010-03-04 18:17:24 +0000900 else
John McCallf746aa62010-03-19 23:29:14 +0000901 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola6a836702010-03-04 18:17:24 +0000902 llvm::PointerType::getUnqual(DeclTy), 0);
Joerg Sonnenberger4695f912012-10-16 17:45:27 +0000903
904 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
905 F->setLinkage(llvm::Function::ExternalWeakLinkage);
906 WeakRefReferences.insert(F);
Rafael Espindola6a836702010-03-04 18:17:24 +0000907
908 return Aliasee;
909}
910
Chris Lattnerb4880ba2009-05-12 21:21:08 +0000911void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +0000912 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +0000913
Rafael Espindola6a836702010-03-04 18:17:24 +0000914 // Weak references don't produce any output by themselves.
915 if (Global->hasAttr<WeakRefAttr>())
916 return;
917
Chris Lattnerbd532712009-03-22 21:47:11 +0000918 // If this is an alias definition (which otherwise looks like a declaration)
919 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000920 if (Global->hasAttr<AliasAttr>())
John McCallf746aa62010-03-19 23:29:14 +0000921 return EmitAliasDefinition(GD);
Daniel Dunbar219df662008-09-08 23:44:31 +0000922
Peter Collingbourned51e43a2011-10-06 18:29:46 +0000923 // If this is CUDA, be selective about which declarations we emit.
David Blaikie4e4d0842012-03-11 07:00:24 +0000924 if (LangOpts.CUDA) {
Peter Collingbourned51e43a2011-10-06 18:29:46 +0000925 if (CodeGenOpts.CUDAIsDevice) {
926 if (!Global->hasAttr<CUDADeviceAttr>() &&
927 !Global->hasAttr<CUDAGlobalAttr>() &&
928 !Global->hasAttr<CUDAConstantAttr>() &&
929 !Global->hasAttr<CUDASharedAttr>())
930 return;
931 } else {
932 if (!Global->hasAttr<CUDAHostAttr>() && (
933 Global->hasAttr<CUDADeviceAttr>() ||
934 Global->hasAttr<CUDAConstantAttr>() ||
935 Global->hasAttr<CUDASharedAttr>()))
936 return;
937 }
938 }
939
Chris Lattner67b00522009-03-21 09:44:56 +0000940 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +0000941 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +0000942 // Forward declarations are emitted lazily on first use.
Nick Lewyckydce67a72011-07-18 05:26:13 +0000943 if (!FD->doesThisDeclarationHaveABody()) {
944 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
945 return;
946
947 const FunctionDecl *InlineDefinition = 0;
948 FD->getBody(InlineDefinition);
949
Chris Lattner5f9e2722011-07-23 10:55:15 +0000950 StringRef MangledName = getMangledName(GD);
Benjamin Kramer7e423922012-03-24 18:22:12 +0000951 DeferredDecls.erase(MangledName);
Nick Lewyckydce67a72011-07-18 05:26:13 +0000952 EmitGlobalDefinition(InlineDefinition);
Daniel Dunbar73241df2009-02-13 21:18:01 +0000953 return;
Nick Lewyckydce67a72011-07-18 05:26:13 +0000954 }
Daniel Dunbar02698712009-02-13 20:29:50 +0000955 } else {
956 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000957 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
958
Douglas Gregora9a55c02010-02-06 05:15:45 +0000959 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +0000960 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000961 }
962
Chris Lattner67b00522009-03-21 09:44:56 +0000963 // Defer code generation when possible if this is a static definition, inline
964 // function etc. These we only want to emit if they are used.
Chris Lattner4357a822010-04-13 17:39:09 +0000965 if (!MayDeferGeneration(Global)) {
966 // Emit the definition if it can't be deferred.
967 EmitGlobalDefinition(GD);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000968 return;
969 }
John McCallbf40cb52010-07-15 23:40:35 +0000970
971 // If we're deferring emission of a C++ variable with an
972 // initializer, remember the order in which it appeared in the file.
David Blaikie4e4d0842012-03-11 07:00:24 +0000973 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCallbf40cb52010-07-15 23:40:35 +0000974 cast<VarDecl>(Global)->hasInit()) {
975 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
976 CXXGlobalInits.push_back(0);
977 }
Chris Lattner4357a822010-04-13 17:39:09 +0000978
979 // If the value has already been used, add it directly to the
980 // DeferredDeclsToEmit list.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000981 StringRef MangledName = getMangledName(GD);
Chris Lattner4357a822010-04-13 17:39:09 +0000982 if (GetGlobalValue(MangledName))
983 DeferredDeclsToEmit.push_back(GD);
984 else {
985 // Otherwise, remember that we saw a deferred decl with this name. The
986 // first use of the mangled name will cause it to move into
987 // DeferredDeclsToEmit.
988 DeferredDecls[MangledName] = GD;
989 }
Nate Begeman4c13b7a2008-04-20 06:29:50 +0000990}
991
Rafael Espindolaa411d2f2011-10-26 20:41:06 +0000992namespace {
993 struct FunctionIsDirectlyRecursive :
994 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
995 const StringRef Name;
Rafael Espindolabcf6b982011-12-19 14:41:01 +0000996 const Builtin::Context &BI;
Rafael Espindolaa411d2f2011-10-26 20:41:06 +0000997 bool Result;
Rafael Espindolabcf6b982011-12-19 14:41:01 +0000998 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
999 Name(N), BI(C), Result(false) {
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001000 }
1001 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1002
1003 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001004 const FunctionDecl *FD = E->getDirectCallee();
1005 if (!FD)
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001006 return true;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001007 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1008 if (Attr && Name == Attr->getLabel()) {
1009 Result = true;
1010 return false;
1011 }
1012 unsigned BuiltinID = FD->getBuiltinID();
1013 if (!BuiltinID)
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001014 return true;
Nick Lewyckyf6b56372012-01-18 03:41:19 +00001015 StringRef BuiltinName = BI.GetName(BuiltinID);
1016 if (BuiltinName.startswith("__builtin_") &&
1017 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001018 Result = true;
1019 return false;
1020 }
1021 return true;
1022 }
1023 };
1024}
1025
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001026// isTriviallyRecursive - Check if this function calls another
1027// decl that, because of the asm attribute or the other decl being a builtin,
1028// ends up pointing to itself.
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001029bool
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001030CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1031 StringRef Name;
1032 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky22afacc2012-01-18 01:50:13 +00001033 // asm labels are a special kind of mangling we have to support.
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001034 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1035 if (!Attr)
1036 return false;
1037 Name = Attr->getLabel();
1038 } else {
1039 Name = FD->getName();
1040 }
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001041
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001042 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1043 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001044 return Walker.Result;
1045}
1046
1047bool
1048CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
1049 if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
1050 return true;
Rafael Espindolacc4889f2011-10-28 20:43:56 +00001051 if (CodeGenOpts.OptimizationLevel == 0 &&
Michael J. Spenceradc6cbf2012-06-18 07:00:48 +00001052 !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001053 return false;
1054 // PR9614. Avoid cases where the source code is lying to us. An available
1055 // externally function should have an equivalent function somewhere else,
1056 // but a function that calls itself is clearly not equivalent to the real
1057 // implementation.
1058 // This happens in glibc's btowc and in some configure checks.
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001059 return !isTriviallyRecursive(F);
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001060}
1061
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001062void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +00001063 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001064
Dan Gohmancb421fa2010-04-19 16:39:44 +00001065 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson8e2efcc2009-10-27 14:32:27 +00001066 Context.getSourceManager(),
1067 "Generating code for declaration");
1068
Douglas Gregor44eac332010-07-13 06:02:28 +00001069 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1070 // At -O0, don't generate IR for functions with available_externally
1071 // linkage.
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001072 if (!shouldEmitFunction(Function))
Douglas Gregor44eac332010-07-13 06:02:28 +00001073 return;
Anders Carlsson7270ee42010-03-23 04:31:31 +00001074
Douglas Gregor44eac332010-07-13 06:02:28 +00001075 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001076 // Make sure to emit the definition(s) before we emit the thunks.
1077 // This is necessary for the generation of certain thunks.
1078 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1079 EmitCXXConstructor(CD, GD.getCtorType());
1080 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1081 EmitCXXDestructor(DD, GD.getDtorType());
1082 else
1083 EmitGlobalFunctionDefinition(GD);
1084
Douglas Gregor44eac332010-07-13 06:02:28 +00001085 if (Method->isVirtual())
1086 getVTables().EmitThunks(GD);
1087
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001088 return;
Douglas Gregor44eac332010-07-13 06:02:28 +00001089 }
Chris Lattnerb5e81562010-04-13 17:57:11 +00001090
Chris Lattnerb5e81562010-04-13 17:57:11 +00001091 return EmitGlobalFunctionDefinition(GD);
Douglas Gregor44eac332010-07-13 06:02:28 +00001092 }
Chris Lattnerb5e81562010-04-13 17:57:11 +00001093
1094 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1095 return EmitGlobalVarDefinition(VD);
Chris Lattner4357a822010-04-13 17:39:09 +00001096
David Blaikieb219cfc2011-09-23 05:06:16 +00001097 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001098}
1099
Chris Lattner74391b42009-03-22 21:03:39 +00001100/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1101/// module, create and return an llvm Function with the specified type. If there
1102/// is something in the module with the specified name, return it potentially
1103/// bitcasted to the right type.
1104///
1105/// If D is non-null, it specifies a decl that correspond to this. This is used
1106/// to set the attributes on the function when it is first created.
John McCallf746aa62010-03-19 23:29:14 +00001107llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001108CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001109 llvm::Type *Ty,
John McCallf85e1932011-06-15 23:02:42 +00001110 GlobalDecl D, bool ForVTable,
Bill Wendling72390b32012-12-20 19:27:06 +00001111 llvm::Attribute ExtraAttrs) {
Chris Lattner0558e792009-03-21 09:25:43 +00001112 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +00001113 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner0558e792009-03-21 09:25:43 +00001114 if (Entry) {
Benjamin Kramerd48bcb22012-08-22 15:37:55 +00001115 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola6a836702010-03-04 18:17:24 +00001116 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
1117 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +00001118 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +00001119 }
1120
Chris Lattner0558e792009-03-21 09:25:43 +00001121 if (Entry->getType()->getElementType() == Ty)
1122 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +00001123
Chris Lattner0558e792009-03-21 09:25:43 +00001124 // Make sure the result is of the correct type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001125 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattner0558e792009-03-21 09:25:43 +00001126 }
Mike Stump1eb44332009-09-09 15:08:12 +00001127
Eli Friedman654ad402009-11-09 05:07:37 +00001128 // This function doesn't have a complete type (for example, the return
1129 // type is an incomplete struct). Use a fake type instead, and make
1130 // sure not to try to set attributes.
1131 bool IsIncompleteFunction = false;
John McCall784f2112010-04-28 00:00:30 +00001132
Chris Lattner2acc6e32011-07-18 04:24:23 +00001133 llvm::FunctionType *FTy;
John McCall784f2112010-04-28 00:00:30 +00001134 if (isa<llvm::FunctionType>(Ty)) {
1135 FTy = cast<llvm::FunctionType>(Ty);
1136 } else {
John McCall0774cb82011-05-15 01:53:33 +00001137 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedman654ad402009-11-09 05:07:37 +00001138 IsIncompleteFunction = true;
1139 }
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001140
John McCall784f2112010-04-28 00:00:30 +00001141 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedman654ad402009-11-09 05:07:37 +00001142 llvm::Function::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +00001143 MangledName, &getModule());
1144 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedman654ad402009-11-09 05:07:37 +00001145 if (D.getDecl())
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +00001146 SetFunctionAttributes(D, F, IsIncompleteFunction);
Bill Wendlingfac63102012-10-10 03:13:20 +00001147 if (ExtraAttrs.hasAttributes())
Bill Wendling785b7782012-12-07 23:17:26 +00001148 F->addAttribute(llvm::AttributeSet::FunctionIndex, ExtraAttrs);
Eli Friedman654ad402009-11-09 05:07:37 +00001149
Chris Lattner67b00522009-03-21 09:44:56 +00001150 // This is the first use or definition of a mangled name. If there is a
1151 // deferred decl with this name, remember that we need to emit it at the end
1152 // of the file.
John McCallf746aa62010-03-19 23:29:14 +00001153 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +00001154 if (DDI != DeferredDecls.end()) {
1155 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1156 // list, and remove it from DeferredDecls (since we don't need it anymore).
1157 DeferredDeclsToEmit.push_back(DDI->second);
1158 DeferredDecls.erase(DDI);
John McCallbfdcdc82010-12-15 04:00:32 +00001159
1160 // Otherwise, there are cases we have to worry about where we're
1161 // using a declaration for which we must emit a definition but where
1162 // we might not find a top-level definition:
1163 // - member functions defined inline in their classes
1164 // - friend functions defined inline in some class
1165 // - special member functions with implicit definitions
1166 // If we ever change our AST traversal to walk into class methods,
1167 // this will be unnecessary.
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001168 //
1169 // We also don't emit a definition for a function if it's going to be an entry
1170 // in a vtable, unless it's already marked as used.
David Blaikie4e4d0842012-03-11 07:00:24 +00001171 } else if (getLangOpts().CPlusPlus && D.getDecl()) {
John McCallbfdcdc82010-12-15 04:00:32 +00001172 // Look for a declaration that's lexically in a record.
1173 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
Eli Friedmanb135f0f2012-07-02 21:05:30 +00001174 FD = FD->getMostRecentDecl();
John McCallbfdcdc82010-12-15 04:00:32 +00001175 do {
1176 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001177 if (FD->isImplicit() && !ForVTable) {
John McCallbfdcdc82010-12-15 04:00:32 +00001178 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
Douglas Gregora29bf412011-02-09 02:03:05 +00001179 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +00001180 break;
Sean Hunt10620eb2011-05-06 20:44:56 +00001181 } else if (FD->doesThisDeclarationHaveABody()) {
Douglas Gregora29bf412011-02-09 02:03:05 +00001182 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +00001183 break;
1184 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00001185 }
Douglas Gregoref96ee02012-01-14 16:38:05 +00001186 FD = FD->getPreviousDecl();
John McCallbfdcdc82010-12-15 04:00:32 +00001187 } while (FD);
Chris Lattner67b00522009-03-21 09:44:56 +00001188 }
Mike Stump1eb44332009-09-09 15:08:12 +00001189
John McCall784f2112010-04-28 00:00:30 +00001190 // Make sure the result is of the requested type.
1191 if (!IsIncompleteFunction) {
1192 assert(F->getType()->getElementType() == Ty);
1193 return F;
1194 }
1195
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001196 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCall784f2112010-04-28 00:00:30 +00001197 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +00001198}
1199
Chris Lattner74391b42009-03-22 21:03:39 +00001200/// GetAddrOfFunction - Return the address of the given function. If Ty is
1201/// non-null, then this function will use the specified type if it has to
1202/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001203llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001204 llvm::Type *Ty,
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001205 bool ForVTable) {
Chris Lattner74391b42009-03-22 21:03:39 +00001206 // If there was no specific requested type, just convert it now.
1207 if (!Ty)
Anders Carlsson4a6835e2009-09-10 23:38:47 +00001208 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001209
Chris Lattner5f9e2722011-07-23 10:55:15 +00001210 StringRef MangledName = getMangledName(GD);
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001211 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
Chris Lattner74391b42009-03-22 21:03:39 +00001212}
Eli Friedman77ba7082008-05-30 19:50:47 +00001213
Chris Lattner74391b42009-03-22 21:03:39 +00001214/// CreateRuntimeFunction - Create a new runtime function with the specified
1215/// type and name.
1216llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001217CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001218 StringRef Name,
Bill Wendling72390b32012-12-20 19:27:06 +00001219 llvm::Attribute ExtraAttrs) {
John McCallf85e1932011-06-15 23:02:42 +00001220 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1221 ExtraAttrs);
Chris Lattner74391b42009-03-22 21:03:39 +00001222}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001223
Richard Smitha9b21d22012-02-17 06:48:11 +00001224/// isTypeConstant - Determine whether an object of this type can be emitted
1225/// as a constant.
1226///
1227/// If ExcludeCtor is true, the duration when the object's constructor runs
1228/// will not be considered. The caller will need to verify that the object is
1229/// not written to during its construction.
1230bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1231 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedman20e098b2009-12-11 21:23:03 +00001232 return false;
Richard Smitha9b21d22012-02-17 06:48:11 +00001233
David Blaikie4e4d0842012-03-11 07:00:24 +00001234 if (Context.getLangOpts().CPlusPlus) {
Richard Smitha9b21d22012-02-17 06:48:11 +00001235 if (const CXXRecordDecl *Record
1236 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1237 return ExcludeCtor && !Record->hasMutableFields() &&
1238 Record->hasTrivialDestructor();
Eli Friedman20e098b2009-12-11 21:23:03 +00001239 }
Richard Smitha9b21d22012-02-17 06:48:11 +00001240
Eli Friedman20e098b2009-12-11 21:23:03 +00001241 return true;
1242}
1243
Chris Lattner74391b42009-03-22 21:03:39 +00001244/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1245/// create and return an llvm GlobalVariable with the specified type. If there
1246/// is something in the module with the specified name, return it potentially
1247/// bitcasted to the right type.
1248///
1249/// If D is non-null, it specifies a decl that correspond to this. This is used
1250/// to set the attributes on the global when it is first created.
John McCallf746aa62010-03-19 23:29:14 +00001251llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001252CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001253 llvm::PointerType *Ty,
Rafael Espindolac532b502011-01-18 21:07:57 +00001254 const VarDecl *D,
1255 bool UnnamedAddr) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +00001256 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +00001257 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +00001258 if (Entry) {
Benjamin Kramerd48bcb22012-08-22 15:37:55 +00001259 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola6a836702010-03-04 18:17:24 +00001260 if (D && !D->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +00001261 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +00001262 }
1263
Rafael Espindolac532b502011-01-18 21:07:57 +00001264 if (UnnamedAddr)
1265 Entry->setUnnamedAddr(true);
1266
Chris Lattner74391b42009-03-22 21:03:39 +00001267 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +00001268 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +00001269
Chris Lattner99b53612009-03-21 08:03:33 +00001270 // Make sure the result is of the correct type.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001271 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +00001272 }
Mike Stump1eb44332009-09-09 15:08:12 +00001273
Chris Lattner67b00522009-03-21 09:44:56 +00001274 // This is the first use or definition of a mangled name. If there is a
1275 // deferred decl with this name, remember that we need to emit it at the end
1276 // of the file.
John McCallf746aa62010-03-19 23:29:14 +00001277 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +00001278 if (DDI != DeferredDecls.end()) {
1279 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1280 // list, and remove it from DeferredDecls (since we don't need it anymore).
1281 DeferredDeclsToEmit.push_back(DDI->second);
1282 DeferredDecls.erase(DDI);
1283 }
Mike Stump1eb44332009-09-09 15:08:12 +00001284
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001285 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
Mike Stump1eb44332009-09-09 15:08:12 +00001286 llvm::GlobalVariable *GV =
1287 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +00001288 llvm::GlobalValue::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +00001289 0, MangledName, 0,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +00001290 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
Chris Lattner99b53612009-03-21 08:03:33 +00001291
1292 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +00001293 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001294 // FIXME: This code is overly simple and should be merged with other global
1295 // handling.
Richard Smitha9b21d22012-02-17 06:48:11 +00001296 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner99b53612009-03-21 08:03:33 +00001297
John McCall110e8e52010-10-29 22:22:43 +00001298 // Set linkage and visibility in case we never see a definition.
John McCallaf146032010-10-30 11:50:40 +00001299 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1300 if (LV.linkage() != ExternalLinkage) {
John McCall15e310a2011-02-19 02:53:41 +00001301 // Don't set internal linkage on declarations.
John McCall110e8e52010-10-29 22:22:43 +00001302 } else {
1303 if (D->hasAttr<DLLImportAttr>())
1304 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001305 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
John McCall110e8e52010-10-29 22:22:43 +00001306 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner99b53612009-03-21 08:03:33 +00001307
John McCallaf146032010-10-30 11:50:40 +00001308 // Set visibility on a declaration only if it's explicit.
1309 if (LV.visibilityExplicit())
1310 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
John McCall110e8e52010-10-29 22:22:43 +00001311 }
Eli Friedman56ebe502009-04-19 21:05:03 +00001312
Hans Wennborgde981f32012-06-28 08:01:44 +00001313 if (D->isThreadSpecified())
1314 setTLSMode(GV, *D);
Chris Lattner74391b42009-03-22 21:03:39 +00001315 }
Mike Stump1eb44332009-09-09 15:08:12 +00001316
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001317 if (AddrSpace != Ty->getAddressSpace())
1318 return llvm::ConstantExpr::getBitCast(GV, Ty);
1319 else
1320 return GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001321}
1322
Chris Lattner74391b42009-03-22 21:03:39 +00001323
Anders Carlsson3bd62022011-01-29 18:20:20 +00001324llvm::GlobalVariable *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001325CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001326 llvm::Type *Ty,
Anders Carlsson3bd62022011-01-29 18:20:20 +00001327 llvm::GlobalValue::LinkageTypes Linkage) {
1328 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1329 llvm::GlobalVariable *OldGV = 0;
1330
1331
1332 if (GV) {
1333 // Check if the variable has the right type.
1334 if (GV->getType()->getElementType() == Ty)
1335 return GV;
1336
1337 // Because C++ name mangling, the only way we can end up with an already
1338 // existing global with the same name is if it has been declared extern "C".
Nico Weberc5f80462012-10-11 10:13:44 +00001339 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlsson3bd62022011-01-29 18:20:20 +00001340 OldGV = GV;
1341 }
1342
1343 // Create a new variable.
1344 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1345 Linkage, 0, Name);
1346
1347 if (OldGV) {
1348 // Replace occurrences of the old variable if needed.
1349 GV->takeName(OldGV);
1350
1351 if (!OldGV->use_empty()) {
1352 llvm::Constant *NewPtrForOldDecl =
1353 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1354 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1355 }
1356
1357 OldGV->eraseFromParent();
1358 }
1359
1360 return GV;
1361}
1362
Chris Lattner74391b42009-03-22 21:03:39 +00001363/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1364/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher0ff258b2012-04-16 23:55:04 +00001365/// then it will be created with the specified type instead of whatever the
Chris Lattner74391b42009-03-22 21:03:39 +00001366/// normal requested type would be.
1367llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001368 llvm::Type *Ty) {
Chris Lattner74391b42009-03-22 21:03:39 +00001369 assert(D->hasGlobalStorage() && "Not a global variable");
1370 QualType ASTTy = D->getType();
1371 if (Ty == 0)
1372 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001373
Chris Lattner2acc6e32011-07-18 04:24:23 +00001374 llvm::PointerType *PTy =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001375 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCallf746aa62010-03-19 23:29:14 +00001376
Chris Lattner5f9e2722011-07-23 10:55:15 +00001377 StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001378 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattner74391b42009-03-22 21:03:39 +00001379}
1380
1381/// CreateRuntimeVariable - Create a new runtime global variable with the
1382/// specified type and name.
1383llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001384CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001385 StringRef Name) {
John McCall1de4d4e2011-04-07 08:22:57 +00001386 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
Rafael Espindolac532b502011-01-18 21:07:57 +00001387 true);
Chris Lattner74391b42009-03-22 21:03:39 +00001388}
1389
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001390void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1391 assert(!D->getInit() && "Cannot emit definite definitions here!");
1392
Douglas Gregor7520bd12009-04-21 19:28:58 +00001393 if (MayDeferGeneration(D)) {
1394 // If we have not seen a reference to this variable yet, place it
1395 // into the deferred declarations table to be emitted if needed
1396 // later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001397 StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001398 if (!GetGlobalValue(MangledName)) {
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001399 DeferredDecls[MangledName] = D;
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001400 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +00001401 }
1402 }
1403
1404 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001405 EmitGlobalVarDefinition(D);
1406}
1407
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001408void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1409 if (DefinitionRequired)
Charles Davis9ee494f2012-06-23 23:44:00 +00001410 getCXXABI().EmitVTables(Class);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001411}
1412
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001413llvm::GlobalVariable::LinkageTypes
Anders Carlsson046c2942010-04-17 20:15:18 +00001414CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Eli Friedmancb5d2d02011-06-10 21:53:06 +00001415 if (RD->getLinkage() != ExternalLinkage)
Douglas Gregordffb8012010-01-06 22:00:56 +00001416 return llvm::GlobalVariable::InternalLinkage;
1417
1418 if (const CXXMethodDecl *KeyFunction
1419 = RD->getASTContext().getKeyFunction(RD)) {
1420 // If this class has a key function, use that to determine the linkage of
1421 // the vtable.
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001422 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001423 if (KeyFunction->hasBody(Def))
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001424 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregordffb8012010-01-06 22:00:56 +00001425
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001426 switch (KeyFunction->getTemplateSpecializationKind()) {
1427 case TSK_Undeclared:
1428 case TSK_ExplicitSpecialization:
Anders Carlsson6d7f8472011-01-30 20:45:54 +00001429 // When compiling with optimizations turned on, we emit all vtables,
1430 // even if the key function is not defined in the current translation
1431 // unit. If this is the case, use available_externally linkage.
1432 if (!Def && CodeGenOpts.OptimizationLevel)
1433 return llvm::GlobalVariable::AvailableExternallyLinkage;
1434
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001435 if (KeyFunction->isInlined())
David Blaikie4e4d0842012-03-11 07:00:24 +00001436 return !Context.getLangOpts().AppleKext ?
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001437 llvm::GlobalVariable::LinkOnceODRLinkage :
1438 llvm::Function::InternalLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001439
1440 return llvm::GlobalVariable::ExternalLinkage;
1441
1442 case TSK_ImplicitInstantiation:
David Blaikie4e4d0842012-03-11 07:00:24 +00001443 return !Context.getLangOpts().AppleKext ?
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001444 llvm::GlobalVariable::LinkOnceODRLinkage :
1445 llvm::Function::InternalLinkage;
Anders Carlssonf502d932011-01-24 00:46:19 +00001446
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001447 case TSK_ExplicitInstantiationDefinition:
David Blaikie4e4d0842012-03-11 07:00:24 +00001448 return !Context.getLangOpts().AppleKext ?
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001449 llvm::GlobalVariable::WeakODRLinkage :
1450 llvm::Function::InternalLinkage;
Anders Carlssonf502d932011-01-24 00:46:19 +00001451
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001452 case TSK_ExplicitInstantiationDeclaration:
1453 // FIXME: Use available_externally linkage. However, this currently
1454 // breaks LLVM's build due to undefined symbols.
1455 // return llvm::GlobalVariable::AvailableExternallyLinkage;
David Blaikie4e4d0842012-03-11 07:00:24 +00001456 return !Context.getLangOpts().AppleKext ?
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001457 llvm::GlobalVariable::LinkOnceODRLinkage :
1458 llvm::Function::InternalLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001459 }
Douglas Gregordffb8012010-01-06 22:00:56 +00001460 }
1461
David Blaikie4e4d0842012-03-11 07:00:24 +00001462 if (Context.getLangOpts().AppleKext)
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001463 return llvm::Function::InternalLinkage;
1464
Douglas Gregordffb8012010-01-06 22:00:56 +00001465 switch (RD->getTemplateSpecializationKind()) {
1466 case TSK_Undeclared:
1467 case TSK_ExplicitSpecialization:
1468 case TSK_ImplicitInstantiation:
Douglas Gregordffb8012010-01-06 22:00:56 +00001469 // FIXME: Use available_externally linkage. However, this currently
1470 // breaks LLVM's build due to undefined symbols.
1471 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001472 case TSK_ExplicitInstantiationDeclaration:
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001473 return llvm::GlobalVariable::LinkOnceODRLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001474
1475 case TSK_ExplicitInstantiationDefinition:
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001476 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001477 }
David Blaikie30263482012-01-20 21:50:17 +00001478
1479 llvm_unreachable("Invalid TemplateSpecializationKind!");
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001480}
1481
Chris Lattner2acc6e32011-07-18 04:24:23 +00001482CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Ken Dyck06f486e2011-01-18 02:01:14 +00001483 return Context.toCharUnitsFromBits(
Micah Villmow25a6a842012-10-08 16:25:52 +00001484 TheDataLayout.getTypeStoreSizeInBits(Ty));
Ken Dyck687cc4a2010-01-26 13:48:07 +00001485}
1486
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001487llvm::Constant *
1488CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
1489 const Expr *rawInit) {
1490 ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
1491 if (const ExprWithCleanups *withCleanups =
1492 dyn_cast<ExprWithCleanups>(rawInit)) {
1493 cleanups = withCleanups->getObjects();
1494 rawInit = withCleanups->getSubExpr();
1495 }
1496
1497 const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
1498 if (!init || !init->initializesStdInitializerList() ||
1499 init->getNumInits() == 0)
1500 return 0;
1501
1502 ASTContext &ctx = getContext();
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001503 unsigned numInits = init->getNumInits();
Sebastian Redl062a82c2012-02-27 23:20:01 +00001504 // FIXME: This check is here because we would otherwise silently miscompile
1505 // nested global std::initializer_lists. Better would be to have a real
1506 // implementation.
1507 for (unsigned i = 0; i < numInits; ++i) {
1508 const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1509 if (inner && inner->initializesStdInitializerList()) {
1510 ErrorUnsupported(inner, "nested global std::initializer_list");
1511 return 0;
1512 }
1513 }
1514
1515 // Synthesize a fake VarDecl for the array and initialize that.
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001516 QualType elementType = init->getInit(0)->getType();
1517 llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
1518 QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
1519 ArrayType::Normal, 0);
1520
1521 IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
1522 TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
1523 arrayType, D->getLocation());
1524 VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
1525 D->getDeclContext()),
1526 D->getLocStart(), D->getLocation(),
1527 name, arrayType, sourceInfo,
1528 SC_Static, SC_Static);
1529
1530 // Now clone the InitListExpr to initialize the array instead.
1531 // Incredible hack: we want to use the existing InitListExpr here, so we need
1532 // to tell it that it no longer initializes a std::initializer_list.
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001533 ArrayRef<Expr*> Inits(const_cast<InitListExpr*>(init)->getInits(),
1534 init->getNumInits());
1535 Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), Inits,
1536 init->getRBraceLoc());
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001537 arrayInit->setType(arrayType);
1538
1539 if (!cleanups.empty())
1540 arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
1541
1542 backingArray->setInit(arrayInit);
1543
1544 // Emit the definition of the array.
1545 EmitGlobalVarDefinition(backingArray);
1546
1547 // Inspect the initializer list to validate it and determine its type.
1548 // FIXME: doing this every time is probably inefficient; caching would be nice
1549 RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
1550 RecordDecl::field_iterator field = record->field_begin();
1551 if (field == record->field_end()) {
1552 ErrorUnsupported(D, "weird std::initializer_list");
1553 return 0;
1554 }
1555 QualType elementPtr = ctx.getPointerType(elementType.withConst());
1556 // Start pointer.
1557 if (!ctx.hasSameType(field->getType(), elementPtr)) {
1558 ErrorUnsupported(D, "weird std::initializer_list");
1559 return 0;
1560 }
1561 ++field;
1562 if (field == record->field_end()) {
1563 ErrorUnsupported(D, "weird std::initializer_list");
1564 return 0;
1565 }
1566 bool isStartEnd = false;
1567 if (ctx.hasSameType(field->getType(), elementPtr)) {
1568 // End pointer.
1569 isStartEnd = true;
1570 } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
1571 ErrorUnsupported(D, "weird std::initializer_list");
1572 return 0;
1573 }
1574
1575 // Now build an APValue representing the std::initializer_list.
1576 APValue initListValue(APValue::UninitStruct(), 0, 2);
1577 APValue &startField = initListValue.getStructField(0);
1578 APValue::LValuePathEntry startOffsetPathEntry;
1579 startOffsetPathEntry.ArrayIndex = 0;
1580 startField = APValue(APValue::LValueBase(backingArray),
1581 CharUnits::fromQuantity(0),
1582 llvm::makeArrayRef(startOffsetPathEntry),
1583 /*IsOnePastTheEnd=*/false, 0);
1584
1585 if (isStartEnd) {
1586 APValue &endField = initListValue.getStructField(1);
1587 APValue::LValuePathEntry endOffsetPathEntry;
1588 endOffsetPathEntry.ArrayIndex = numInits;
1589 endField = APValue(APValue::LValueBase(backingArray),
1590 ctx.getTypeSizeInChars(elementType) * numInits,
1591 llvm::makeArrayRef(endOffsetPathEntry),
1592 /*IsOnePastTheEnd=*/true, 0);
1593 } else {
1594 APValue &sizeField = initListValue.getStructField(1);
1595 sizeField = APValue(llvm::APSInt(numElements));
1596 }
1597
1598 // Emit the constant for the initializer_list.
Richard Smitha3ca41f2012-03-02 23:27:11 +00001599 llvm::Constant *llvmInit =
1600 EmitConstantValueForMemory(initListValue, D->getType());
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001601 assert(llvmInit && "failed to initialize as constant");
1602 return llvmInit;
1603}
1604
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001605unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1606 unsigned AddrSpace) {
1607 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1608 if (D->hasAttr<CUDAConstantAttr>())
1609 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1610 else if (D->hasAttr<CUDASharedAttr>())
1611 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1612 else
1613 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1614 }
1615
1616 return AddrSpace;
1617}
1618
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001619void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +00001620 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +00001621 QualType ASTTy = D->getType();
Richard Smith7ca48502012-02-13 22:16:19 +00001622 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1623 bool NeedsGlobalCtor = false;
1624 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump1eb44332009-09-09 15:08:12 +00001625
Richard Smith2d6a5672012-01-14 04:30:29 +00001626 const VarDecl *InitDecl;
1627 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001628
Anders Carlsson3bb92692010-01-26 17:43:42 +00001629 if (!InitExpr) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +00001630 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001631 // implicitly initialized with { 0 }.
1632 //
1633 // Note that tentative definitions are only emitted at the end of
1634 // a translation unit, so they should never have incomplete
1635 // type. In addition, EmitTentativeDefinition makes sure that we
1636 // never attempt to emit a tentative definition if a real one
1637 // exists. A use may still exists, however, so we still may need
1638 // to do a RAUW.
1639 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonb0d0ea02009-08-02 21:18:22 +00001640 Init = EmitNullConstant(D->getType());
Eli Friedman77ba7082008-05-30 19:50:47 +00001641 } else {
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001642 // If this is a std::initializer_list, emit the special initializer.
1643 Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
1644 // An empty init list will perform zero-initialization, which happens
1645 // to be exactly what we want.
1646 // FIXME: It does so in a global constructor, which is *not* what we
1647 // want.
1648
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001649 if (!Init) {
1650 initializedGlobalDecl = GlobalDecl(D);
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001651 Init = EmitConstantInit(*InitDecl);
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001652 }
Eli Friedman6e656f42009-02-20 01:18:21 +00001653 if (!Init) {
Anders Carlsson3bb92692010-01-26 17:43:42 +00001654 QualType T = InitExpr->getType();
Douglas Gregorc446d182010-05-05 20:15:55 +00001655 if (D->getType()->isReferenceType())
1656 T = D->getType();
Richard Smith2d6a5672012-01-14 04:30:29 +00001657
David Blaikie4e4d0842012-03-11 07:00:24 +00001658 if (getLangOpts().CPlusPlus) {
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001659 Init = EmitNullConstant(T);
Richard Smith7ca48502012-02-13 22:16:19 +00001660 NeedsGlobalCtor = true;
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001661 } else {
1662 ErrorUnsupported(D, "static initializer");
1663 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1664 }
John McCallbf40cb52010-07-15 23:40:35 +00001665 } else {
1666 // We don't need an initializer, so remove the entry for the delayed
Richard Smith7ca48502012-02-13 22:16:19 +00001667 // initializer position (just in case this entry was delayed) if we
1668 // also don't need to register a destructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00001669 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCallbf40cb52010-07-15 23:40:35 +00001670 DelayedCXXInitPosition.erase(D);
Eli Friedman6e656f42009-02-20 01:18:21 +00001671 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001672 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001673
Chris Lattner2acc6e32011-07-18 04:24:23 +00001674 llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +00001675 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump1eb44332009-09-09 15:08:12 +00001676
Chris Lattner570585c2009-03-21 09:16:30 +00001677 // Strip off a bitcast if we got one back.
1678 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001679 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1680 // all zero index gep.
1681 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner570585c2009-03-21 09:16:30 +00001682 Entry = CE->getOperand(0);
1683 }
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Chris Lattner570585c2009-03-21 09:16:30 +00001685 // Entry is now either a Function or GlobalVariable.
1686 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001687
Chris Lattner570585c2009-03-21 09:16:30 +00001688 // We have a definition after a declaration with the wrong type.
1689 // We must make a new GlobalVariable* and update everything that used OldGV
1690 // (a declaration or tentative definition) with the new GlobalVariable*
1691 // (which will be a definition).
1692 //
1693 // This happens if there is a prototype for a global (e.g.
1694 // "extern int x[];") and then a definition of a different type (e.g.
1695 // "int x[10];"). This also happens when an initializer has a different type
1696 // from the type of the global (this happens with unions).
Chris Lattner570585c2009-03-21 09:16:30 +00001697 if (GV == 0 ||
1698 GV->getType()->getElementType() != InitType ||
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001699 GV->getType()->getAddressSpace() !=
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001700 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001701
John McCallf746aa62010-03-19 23:29:14 +00001702 // Move the old entry aside so that we'll create a new one.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001703 Entry->setName(StringRef());
Daniel Dunbar232350d2009-02-19 05:36:41 +00001704
Chris Lattner570585c2009-03-21 09:16:30 +00001705 // Make a new global with the correct type, this is now guaranteed to work.
1706 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +00001707
Eli Friedman77ba7082008-05-30 19:50:47 +00001708 // Replace all uses of the old global with the new global
Mike Stump1eb44332009-09-09 15:08:12 +00001709 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001710 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner570585c2009-03-21 09:16:30 +00001711 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +00001712
1713 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +00001714 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +00001715 }
Devang Patel8e53e722007-10-26 16:31:40 +00001716
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001717 if (D->hasAttr<AnnotateAttr>())
1718 AddGlobalAnnotations(D, GV);
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001719
Chris Lattner88a69ad2007-07-13 05:13:43 +00001720 GV->setInitializer(Init);
Chris Lattnere78b86f2009-08-05 05:20:29 +00001721
1722 // If it is safe to mark the global 'constant', do so now.
Richard Smitha9b21d22012-02-17 06:48:11 +00001723 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1724 isTypeConstant(D->getType(), true));
Mike Stump1eb44332009-09-09 15:08:12 +00001725
Ken Dyck8b752f12010-01-27 17:10:57 +00001726 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smitha9b21d22012-02-17 06:48:11 +00001727
Chris Lattner88a69ad2007-07-13 05:13:43 +00001728 // Set the llvm linkage type as appropriate.
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001729 llvm::GlobalValue::LinkageTypes Linkage =
1730 GetLLVMLinkageVarDefinition(D, GV);
1731 GV->setLinkage(Linkage);
1732 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnere78b86f2009-08-05 05:20:29 +00001733 // common vars aren't constant even if declared const.
1734 GV->setConstant(false);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +00001735
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001736 SetCommonAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +00001737
John McCall3030eb82010-11-06 09:44:32 +00001738 // Emit the initializer function if necessary.
Richard Smith7ca48502012-02-13 22:16:19 +00001739 if (NeedsGlobalCtor || NeedsGlobalDtor)
1740 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCall3030eb82010-11-06 09:44:32 +00001741
Kostya Serebryany05c5ebc2012-08-21 06:53:28 +00001742 // If we are compiling with ASan, add metadata indicating dynamically
1743 // initialized globals.
Richard Smithca1b62a2012-11-05 21:48:12 +00001744 if (LangOpts.SanitizeAddress && NeedsGlobalCtor) {
Kostya Serebryany05c5ebc2012-08-21 06:53:28 +00001745 llvm::Module &M = getModule();
1746
1747 llvm::NamedMDNode *DynamicInitializers =
1748 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1749 llvm::Value *GlobalToAdd[] = { GV };
1750 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1751 DynamicInitializers->addOperand(ThisGlobal);
1752 }
1753
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001754 // Emit global variable debug information.
Eric Christopher73fb3502011-10-13 21:45:18 +00001755 if (CGDebugInfo *DI = getModuleDebugInfo())
Douglas Gregor4cdad312012-10-23 20:05:01 +00001756 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001757 DI->EmitGlobalVariable(GV, D);
Chris Lattner88a69ad2007-07-13 05:13:43 +00001758}
Reid Spencer5f016e22007-07-11 17:01:13 +00001759
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001760llvm::GlobalValue::LinkageTypes
1761CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1762 llvm::GlobalVariable *GV) {
1763 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1764 if (Linkage == GVA_Internal)
1765 return llvm::Function::InternalLinkage;
1766 else if (D->hasAttr<DLLImportAttr>())
1767 return llvm::Function::DLLImportLinkage;
1768 else if (D->hasAttr<DLLExportAttr>())
1769 return llvm::Function::DLLExportLinkage;
1770 else if (D->hasAttr<WeakAttr>()) {
1771 if (GV->isConstant())
1772 return llvm::GlobalVariable::WeakODRLinkage;
1773 else
1774 return llvm::GlobalVariable::WeakAnyLinkage;
1775 } else if (Linkage == GVA_TemplateInstantiation ||
1776 Linkage == GVA_ExplicitTemplateInstantiation)
John McCall99ace162011-04-12 01:46:54 +00001777 return llvm::GlobalVariable::WeakODRLinkage;
David Blaikie4e4d0842012-03-11 07:00:24 +00001778 else if (!getLangOpts().CPlusPlus &&
Eric Christophera6cf1e72010-12-02 02:45:55 +00001779 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1780 D->getAttr<CommonAttr>()) &&
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001781 !D->hasExternalStorage() && !D->getInit() &&
Fariborz Jahanianab27d6e2011-06-20 17:50:03 +00001782 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1783 !D->getAttr<WeakImportAttr>()) {
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001784 // Thread local vars aren't considered common linkage.
1785 return llvm::GlobalVariable::CommonLinkage;
1786 }
1787 return llvm::GlobalVariable::ExternalLinkage;
1788}
1789
John McCalla923c972012-12-12 22:21:47 +00001790/// Replace the uses of a function that was declared with a non-proto type.
1791/// We want to silently drop extra arguments from call sites
1792static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1793 llvm::Function *newFn) {
1794 // Fast path.
1795 if (old->use_empty()) return;
1796
1797 llvm::Type *newRetTy = newFn->getReturnType();
1798 SmallVector<llvm::Value*, 4> newArgs;
1799
1800 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1801 ui != ue; ) {
1802 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
1803 llvm::User *user = *use;
1804
1805 // Recognize and replace uses of bitcasts. Most calls to
1806 // unprototyped functions will use bitcasts.
1807 if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1808 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1809 replaceUsesOfNonProtoConstant(bitcast, newFn);
1810 continue;
1811 }
1812
1813 // Recognize calls to the function.
1814 llvm::CallSite callSite(user);
1815 if (!callSite) continue;
1816 if (!callSite.isCallee(use)) continue;
1817
1818 // If the return types don't match exactly, then we can't
1819 // transform this call unless it's dead.
1820 if (callSite->getType() != newRetTy && !callSite->use_empty())
1821 continue;
1822
1823 // Get the call site's attribute list.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001824 SmallVector<llvm::AttributeWithIndex, 8> newAttrs;
John McCalla923c972012-12-12 22:21:47 +00001825 llvm::AttributeSet oldAttrs = callSite.getAttributes();
1826
1827 // Collect any return attributes from the call.
Bill Wendling72390b32012-12-20 19:27:06 +00001828 llvm::Attribute returnAttrs = oldAttrs.getRetAttributes();
John McCalla923c972012-12-12 22:21:47 +00001829 if (returnAttrs.hasAttributes())
1830 newAttrs.push_back(llvm::AttributeWithIndex::get(
1831 llvm::AttributeSet::ReturnIndex, returnAttrs));
1832
1833 // If the function was passed too few arguments, don't transform.
1834 unsigned newNumArgs = newFn->arg_size();
1835 if (callSite.arg_size() < newNumArgs) continue;
1836
1837 // If extra arguments were passed, we silently drop them.
1838 // If any of the types mismatch, we don't transform.
1839 unsigned argNo = 0;
1840 bool dontTransform = false;
1841 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
1842 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
1843 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
1844 dontTransform = true;
1845 break;
1846 }
1847
1848 // Add any parameter attributes.
Bill Wendling72390b32012-12-20 19:27:06 +00001849 llvm::Attribute pAttrs = oldAttrs.getParamAttributes(argNo + 1);
John McCalla923c972012-12-12 22:21:47 +00001850 if (pAttrs.hasAttributes())
1851 newAttrs.push_back(llvm::AttributeWithIndex::get(argNo + 1, pAttrs));
1852 }
1853 if (dontTransform)
1854 continue;
1855
Bill Wendling72390b32012-12-20 19:27:06 +00001856 llvm::Attribute fnAttrs = oldAttrs.getFnAttributes();
John McCalla923c972012-12-12 22:21:47 +00001857 if (fnAttrs.hasAttributes())
1858 newAttrs.push_back(llvm::
1859 AttributeWithIndex::get(llvm::AttributeSet::FunctionIndex,
1860 fnAttrs));
1861
1862 // Okay, we can transform this. Create the new call instruction and copy
1863 // over the required information.
1864 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
1865
1866 llvm::CallSite newCall;
1867 if (callSite.isCall()) {
1868 newCall = llvm::CallInst::Create(newFn, newArgs, "",
1869 callSite.getInstruction());
1870 } else {
1871 llvm::InvokeInst *oldInvoke =
1872 cast<llvm::InvokeInst>(callSite.getInstruction());
1873 newCall = llvm::InvokeInst::Create(newFn,
1874 oldInvoke->getNormalDest(),
1875 oldInvoke->getUnwindDest(),
1876 newArgs, "",
1877 callSite.getInstruction());
1878 }
1879 newArgs.clear(); // for the next iteration
1880
1881 if (!newCall->getType()->isVoidTy())
1882 newCall->takeName(callSite.getInstruction());
1883 newCall.setAttributes(
1884 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
1885 newCall.setCallingConv(callSite.getCallingConv());
1886
1887 // Finally, remove the old call, replacing any uses with the new one.
1888 if (!callSite->use_empty())
1889 callSite->replaceAllUsesWith(newCall.getInstruction());
1890
1891 // Copy debug location attached to CI.
1892 if (!callSite->getDebugLoc().isUnknown())
1893 newCall->setDebugLoc(callSite->getDebugLoc());
1894 callSite->eraseFromParent();
1895 }
1896}
1897
Chris Lattnerbdb01322009-05-05 06:16:31 +00001898/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1899/// implement a function with no prototype, e.g. "int foo() {}". If there are
1900/// existing call uses of the old function in the module, this adjusts them to
1901/// call the new function directly.
1902///
1903/// This is not just a cleanup: the always_inline pass requires direct calls to
1904/// functions to be able to inline them. If there is a bitcast in the way, it
1905/// won't inline them. Instcombine normally deletes these calls, but it isn't
1906/// run at -O0.
1907static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1908 llvm::Function *NewFn) {
1909 // If we're redefining a global as a function, don't transform it.
John McCalla923c972012-12-12 22:21:47 +00001910 if (!isa<llvm::Function>(Old)) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001911
John McCalla923c972012-12-12 22:21:47 +00001912 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattnerbdb01322009-05-05 06:16:31 +00001913}
1914
Rafael Espindola02503932012-03-08 15:51:03 +00001915void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
1916 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
1917 // If we have a definition, this might be a deferred decl. If the
1918 // instantiation is explicit, make sure we emit it at the end.
1919 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
1920 GetAddrOfGlobalVar(VD);
Rafael Espindola234fe652012-03-05 10:54:55 +00001921}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001922
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001923void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001924 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCalld26bc762011-03-09 04:27:21 +00001925
John McCall1f6f9612011-03-09 08:12:35 +00001926 // Compute the function info and LLVM type.
John McCallde5d3c72012-02-17 03:33:10 +00001927 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1928 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalld26bc762011-03-09 04:27:21 +00001929
Chris Lattner9fa959d2009-05-12 20:58:15 +00001930 // Get or create the prototype for the function.
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001931 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001932
Chris Lattner0558e792009-03-21 09:25:43 +00001933 // Strip off a bitcast if we got one back.
1934 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1935 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1936 Entry = CE->getOperand(0);
1937 }
Mike Stump1eb44332009-09-09 15:08:12 +00001938
1939
Chris Lattner0558e792009-03-21 09:25:43 +00001940 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001941 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001942
Daniel Dunbar42745812009-03-09 23:53:08 +00001943 // If the types mismatch then we have to rewrite the definition.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001944 assert(OldFn->isDeclaration() &&
Chris Lattner0558e792009-03-21 09:25:43 +00001945 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +00001946
Chris Lattner62b33ea2009-03-21 08:38:50 +00001947 // F is the Function* for the one with the wrong type, we must make a new
1948 // Function* and update everything that used F (a declaration) with the new
1949 // Function* (which will be a definition).
1950 //
1951 // This happens if there is a prototype for a function
1952 // (e.g. "int f()") and then a definition of a different type
John McCallf746aa62010-03-19 23:29:14 +00001953 // (e.g. "int f(int x)"). Move the old function aside so that it
1954 // doesn't interfere with GetAddrOfFunction.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001955 OldFn->setName(StringRef());
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001956 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump1eb44332009-09-09 15:08:12 +00001957
John McCalla923c972012-12-12 22:21:47 +00001958 // This might be an implementation of a function without a
1959 // prototype, in which case, try to do special replacement of
1960 // calls which match the new prototype. The really key thing here
1961 // is that we also potentially drop arguments from the call site
1962 // so as to make a direct call, which makes the inliner happier
1963 // and suppresses a number of optimizer warnings (!) about
1964 // dropping arguments.
1965 if (!OldFn->use_empty()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00001966 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattner9fa959d2009-05-12 20:58:15 +00001967 OldFn->removeDeadConstantUsers();
1968 }
Mike Stump1eb44332009-09-09 15:08:12 +00001969
Chris Lattner62b33ea2009-03-21 08:38:50 +00001970 // Replace uses of F with the Function we will endow with a body.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001971 if (!Entry->use_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00001972 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001973 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattnerbdb01322009-05-05 06:16:31 +00001974 Entry->replaceAllUsesWith(NewPtrForOldDecl);
1975 }
Mike Stump1eb44332009-09-09 15:08:12 +00001976
Chris Lattner62b33ea2009-03-21 08:38:50 +00001977 // Ok, delete the old function now, which is dead.
Chris Lattnerbdb01322009-05-05 06:16:31 +00001978 OldFn->eraseFromParent();
Mike Stump1eb44332009-09-09 15:08:12 +00001979
Chris Lattner0558e792009-03-21 09:25:43 +00001980 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001981 }
Mike Stump1eb44332009-09-09 15:08:12 +00001982
John McCall112c9672010-11-02 21:04:24 +00001983 // We need to set linkage and visibility on the function before
1984 // generating code for it because various parts of IR generation
1985 // want to propagate this information down (e.g. to local static
1986 // declarations).
Chris Lattner0558e792009-03-21 09:25:43 +00001987 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall8b242332010-05-25 04:30:21 +00001988 setFunctionLinkage(D, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001989
John McCall112c9672010-11-02 21:04:24 +00001990 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlsson0ffeaad2011-01-29 19:39:23 +00001991 setGlobalVisibility(Fn, D);
John McCall112c9672010-11-02 21:04:24 +00001992
John McCalld26bc762011-03-09 04:27:21 +00001993 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00001994
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001995 SetFunctionDefinitionAttributes(D, Fn);
1996 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump1eb44332009-09-09 15:08:12 +00001997
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001998 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00001999 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002000 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00002001 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge77f68bb2011-09-09 22:41:49 +00002002 if (D->hasAttr<AnnotateAttr>())
2003 AddGlobalAnnotations(D, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002004}
2005
John McCallf746aa62010-03-19 23:29:14 +00002006void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2007 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002008 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00002009 assert(AA && "Not an alias?");
2010
Chris Lattner5f9e2722011-07-23 10:55:15 +00002011 StringRef MangledName = getMangledName(GD);
Mike Stump1eb44332009-09-09 15:08:12 +00002012
John McCallf746aa62010-03-19 23:29:14 +00002013 // If there is a definition in the module, then it wins over the alias.
2014 // This is dubious, but allow it to be safe. Just ignore the alias.
2015 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2016 if (Entry && !Entry->isDeclaration())
2017 return;
2018
Chris Lattner2acc6e32011-07-18 04:24:23 +00002019 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattnerbd532712009-03-22 21:47:11 +00002020
2021 // Create a reference to the named value. This ensures that it is emitted
2022 // if a deferred decl.
2023 llvm::Constant *Aliasee;
2024 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergc857ce82012-10-05 23:12:53 +00002025 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson1faa89f2011-02-05 04:35:53 +00002026 /*ForVTable=*/false);
Chris Lattnerbd532712009-03-22 21:47:11 +00002027 else
John McCallf746aa62010-03-19 23:29:14 +00002028 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson96e0fc72009-07-29 22:16:19 +00002029 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattnerbd532712009-03-22 21:47:11 +00002030
2031 // Create the new alias itself, but don't set a name yet.
Mike Stump1eb44332009-09-09 15:08:12 +00002032 llvm::GlobalValue *GA =
Chris Lattnerbd532712009-03-22 21:47:11 +00002033 new llvm::GlobalAlias(Aliasee->getType(),
2034 llvm::Function::ExternalLinkage,
2035 "", Aliasee, &getModule());
Mike Stump1eb44332009-09-09 15:08:12 +00002036
Chris Lattnerbd532712009-03-22 21:47:11 +00002037 if (Entry) {
John McCallf746aa62010-03-19 23:29:14 +00002038 assert(Entry->isDeclaration());
2039
Chris Lattnerbd532712009-03-22 21:47:11 +00002040 // If there is a declaration in the module, then we had an extern followed
2041 // by the alias, as in:
2042 // extern int test6();
2043 // ...
2044 // int test6() __attribute__((alias("test7")));
2045 //
2046 // Remove it and replace uses of it with the alias.
John McCallf746aa62010-03-19 23:29:14 +00002047 GA->takeName(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00002048
Owen Anderson3c4972d2009-07-29 18:54:39 +00002049 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattnerbd532712009-03-22 21:47:11 +00002050 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00002051 Entry->eraseFromParent();
John McCallf746aa62010-03-19 23:29:14 +00002052 } else {
Anders Carlsson9a20d552010-06-22 16:16:50 +00002053 GA->setName(MangledName);
Chris Lattnerbd532712009-03-22 21:47:11 +00002054 }
Mike Stump1eb44332009-09-09 15:08:12 +00002055
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002056 // Set attributes which are particular to an alias; this is a
2057 // specialization of the attributes which may be set on a global
2058 // variable/function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002059 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002060 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2061 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002062 if (FD->hasBody())
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002063 GA->setLinkage(llvm::Function::DLLExportLinkage);
2064 } else {
2065 GA->setLinkage(llvm::Function::DLLExportLinkage);
2066 }
Mike Stump1eb44332009-09-09 15:08:12 +00002067 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindola11e8ce72010-02-23 22:00:30 +00002068 D->hasAttr<WeakRefAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00002069 D->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002070 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2071 }
2072
2073 SetCommonAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00002074}
2075
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00002076llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00002077 ArrayRef<llvm::Type*> Tys) {
Jay Foaddf983a82011-07-12 14:06:48 +00002078 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00002079 Tys);
Chris Lattner7acda7c2007-12-18 00:25:38 +00002080}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00002081
Daniel Dunbar1d552912009-07-23 22:52:48 +00002082static llvm::StringMapEntry<llvm::Constant*> &
2083GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2084 const StringLiteral *Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002085 bool TargetIsLSB,
Daniel Dunbar1d552912009-07-23 22:52:48 +00002086 bool &IsUTF16,
2087 unsigned &StringLength) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002088 StringRef String = Literal->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002089 unsigned NumBytes = String.size();
Daniel Dunbar1d552912009-07-23 22:52:48 +00002090
Daniel Dunbarf015b032009-09-22 10:03:52 +00002091 // Check for simple case.
2092 if (!Literal->containsNonAsciiOrNull()) {
2093 StringLength = NumBytes;
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002094 return Map.GetOrCreateValue(String);
Daniel Dunbarf015b032009-09-22 10:03:52 +00002095 }
2096
Bill Wendling84392d02012-03-30 00:26:17 +00002097 // Otherwise, convert the UTF8 literals into a string of shorts.
2098 IsUTF16 = true;
2099
2100 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
Roman Divacky31ba6132012-09-06 15:59:27 +00002101 const UTF8 *FromPtr = (const UTF8 *)String.data();
Daniel Dunbar1d552912009-07-23 22:52:48 +00002102 UTF16 *ToPtr = &ToBuf[0];
Mike Stump1eb44332009-09-09 15:08:12 +00002103
Fariborz Jahaniane7ddfb92010-09-07 19:57:04 +00002104 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2105 &ToPtr, ToPtr + NumBytes,
2106 strictConversion);
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002108 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar1d552912009-07-23 22:52:48 +00002109 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002110
Bill Wendling84392d02012-03-30 00:26:17 +00002111 // Add an explicit null.
2112 *ToPtr = 0;
2113 return Map.
2114 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2115 (StringLength + 1) * 2));
Daniel Dunbar1d552912009-07-23 22:52:48 +00002116}
2117
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002118static llvm::StringMapEntry<llvm::Constant*> &
2119GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
Bill Wendling8322c232012-03-29 22:12:09 +00002120 const StringLiteral *Literal,
2121 unsigned &StringLength) {
2122 StringRef String = Literal->getString();
2123 StringLength = String.size();
2124 return Map.GetOrCreateValue(String);
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002125}
2126
Daniel Dunbar1d552912009-07-23 22:52:48 +00002127llvm::Constant *
2128CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2129 unsigned StringLength = 0;
2130 bool isUTF16 = false;
2131 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump1eb44332009-09-09 15:08:12 +00002132 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Micah Villmow25a6a842012-10-08 16:25:52 +00002133 getDataLayout().isLittleEndian(),
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002134 isUTF16, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00002135
Daniel Dunbar1d552912009-07-23 22:52:48 +00002136 if (llvm::Constant *C = Entry.getValue())
2137 return C;
Mike Stump1eb44332009-09-09 15:08:12 +00002138
Chris Lattner8b418682012-02-07 00:39:47 +00002139 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002140 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump1eb44332009-09-09 15:08:12 +00002141
Chris Lattner9d4a15f2009-07-16 16:48:25 +00002142 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonc9e20912007-08-21 00:21:21 +00002143 if (!CFConstantStringClassRef) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002144 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002145 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002146 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattner9d4a15f2009-07-16 16:48:25 +00002147 "__CFConstantStringClassReference");
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002148 // Decay array -> ptr
2149 CFConstantStringClassRef =
Jay Foada5c04342011-07-21 14:31:17 +00002150 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlssonc9e20912007-08-21 00:21:21 +00002151 }
Mike Stump1eb44332009-09-09 15:08:12 +00002152
Anders Carlssone3daa762008-11-15 18:54:24 +00002153 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002154
Chris Lattner2acc6e32011-07-18 04:24:23 +00002155 llvm::StructType *STy =
Anders Carlssone3daa762008-11-15 18:54:24 +00002156 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2157
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00002158 llvm::Constant *Fields[4];
Douglas Gregor44b43212008-12-11 16:49:14 +00002159
Anders Carlssonc9e20912007-08-21 00:21:21 +00002160 // Class pointer.
Anders Carlsson5add6832009-08-16 05:55:31 +00002161 Fields[0] = CFConstantStringClassRef;
Mike Stump1eb44332009-09-09 15:08:12 +00002162
Anders Carlssonc9e20912007-08-21 00:21:21 +00002163 // Flags.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002164 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002165 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson5add6832009-08-16 05:55:31 +00002166 llvm::ConstantInt::get(Ty, 0x07C8);
2167
Anders Carlssonc9e20912007-08-21 00:21:21 +00002168 // String pointer.
Bill Wendling84392d02012-03-30 00:26:17 +00002169 llvm::Constant *C = 0;
2170 if (isUTF16) {
2171 ArrayRef<uint16_t> Arr =
2172 llvm::makeArrayRef<uint16_t>((uint16_t*)Entry.getKey().data(),
2173 Entry.getKey().size() / 2);
2174 C = llvm::ConstantDataArray::get(VMContext, Arr);
2175 } else {
2176 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2177 }
Daniel Dunbara9668e02009-04-03 00:57:44 +00002178
Chris Lattner95b851e2009-07-16 05:03:48 +00002179 llvm::GlobalValue::LinkageTypes Linkage;
Bill Wendling1bf7a3f2012-01-10 08:46:39 +00002180 if (isUTF16)
Chris Lattner278b9f02009-10-14 05:55:45 +00002181 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner95b851e2009-07-16 05:03:48 +00002182 Linkage = llvm::GlobalValue::InternalLinkage;
Bill Wendling1bf7a3f2012-01-10 08:46:39 +00002183 else
Rafael Espindola584acf22011-03-14 17:55:00 +00002184 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2185 // when using private linkage. It is not clear if this is a bug in ld
2186 // or a reasonable new restriction.
Rafael Espindoladc0f1372011-03-14 21:08:19 +00002187 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00002188
Bill Wendling1bf7a3f2012-01-10 08:46:39 +00002189 // Note: -fwritable-strings doesn't make the backing store strings of
2190 // CFStrings writable. (See <rdar://problem/10657500>)
Mike Stump1eb44332009-09-09 15:08:12 +00002191 llvm::GlobalVariable *GV =
Bill Wendling1bf7a3f2012-01-10 08:46:39 +00002192 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2193 Linkage, C, ".str");
Rafael Espindolab266a1f2011-01-17 16:31:00 +00002194 GV->setUnnamedAddr(true);
Daniel Dunbara9668e02009-04-03 00:57:44 +00002195 if (isUTF16) {
Ken Dyck4da244c2010-01-26 18:46:23 +00002196 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2197 GV->setAlignment(Align.getQuantity());
Daniel Dunbarf7e903d2011-04-12 23:30:52 +00002198 } else {
2199 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2200 GV->setAlignment(Align.getQuantity());
Daniel Dunbara9668e02009-04-03 00:57:44 +00002201 }
Bill Wendling84392d02012-03-30 00:26:17 +00002202
2203 // String.
Jay Foada5c04342011-07-21 14:31:17 +00002204 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlsson5add6832009-08-16 05:55:31 +00002205
Bill Wendling84392d02012-03-30 00:26:17 +00002206 if (isUTF16)
2207 // Cast the UTF16 string to the correct type.
2208 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2209
Anders Carlssonc9e20912007-08-21 00:21:21 +00002210 // String length.
2211 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson5add6832009-08-16 05:55:31 +00002212 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00002213
Anders Carlssonc9e20912007-08-21 00:21:21 +00002214 // The struct.
Owen Anderson08e25242009-07-27 22:29:56 +00002215 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump1eb44332009-09-09 15:08:12 +00002216 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2217 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner95b851e2009-07-16 05:03:48 +00002218 "_unnamed_cfstring_");
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002219 if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00002220 GV->setSection(Sect);
Daniel Dunbar1d552912009-07-23 22:52:48 +00002221 Entry.setValue(GV);
Mike Stump1eb44332009-09-09 15:08:12 +00002222
Anders Carlsson0c678292007-11-01 00:41:52 +00002223 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00002224}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002225
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002226static RecordDecl *
2227CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2228 DeclContext *DC, IdentifierInfo *Id) {
2229 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00002230 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002231 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2232 else
2233 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2234}
2235
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00002236llvm::Constant *
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002237CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002238 unsigned StringLength = 0;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002239 llvm::StringMapEntry<llvm::Constant*> &Entry =
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002240 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002241
2242 if (llvm::Constant *C = Entry.getValue())
2243 return C;
2244
Chris Lattner812234b2012-02-06 22:47:00 +00002245 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002246 llvm::Constant *Zeros[] = { Zero, Zero };
2247
Fariborz Jahanianec951e02010-04-23 22:33:39 +00002248 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002249 if (!ConstantStringClassRef) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002250 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002251 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002252 llvm::Constant *GV;
John McCall260611a2012-06-20 06:18:46 +00002253 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00002254 std::string str =
2255 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2256 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00002257 GV = getObjCRuntime().GetClassGlobal(str);
2258 // Make sure the result is of the correct type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002259 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00002260 ConstantStringClassRef =
2261 llvm::ConstantExpr::getBitCast(GV, PTy);
2262 } else {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00002263 std::string str =
2264 StringClass.empty() ? "_NSConstantStringClassReference"
2265 : "_" + StringClass + "ClassReference";
Chris Lattner2acc6e32011-07-18 04:24:23 +00002266 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00002267 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00002268 // Decay array -> ptr
2269 ConstantStringClassRef =
Jay Foada5c04342011-07-21 14:31:17 +00002270 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002271 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002272 }
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002273
2274 if (!NSConstantStringType) {
2275 // Construct the type for a constant NSString.
2276 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2277 Context.getTranslationUnitDecl(),
2278 &Context.Idents.get("__builtin_NSString"));
2279 D->startDefinition();
2280
2281 QualType FieldTypes[3];
2282
2283 // const int *isa;
2284 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2285 // const char *str;
2286 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2287 // unsigned int length;
2288 FieldTypes[2] = Context.UnsignedIntTy;
2289
2290 // Create fields
2291 for (unsigned i = 0; i < 3; ++i) {
2292 FieldDecl *Field = FieldDecl::Create(Context, D,
2293 SourceLocation(),
2294 SourceLocation(), 0,
2295 FieldTypes[i], /*TInfo=*/0,
2296 /*BitWidth=*/0,
2297 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002298 ICIS_NoInit);
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002299 Field->setAccess(AS_public);
2300 D->addDecl(Field);
2301 }
2302
2303 D->completeDefinition();
2304 QualType NSTy = Context.getTagDeclType(D);
2305 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2306 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002307
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00002308 llvm::Constant *Fields[3];
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002309
2310 // Class pointer.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002311 Fields[0] = ConstantStringClassRef;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002312
2313 // String pointer.
Chris Lattner94010692012-02-05 02:30:40 +00002314 llvm::Constant *C =
2315 llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002316
2317 llvm::GlobalValue::LinkageTypes Linkage;
2318 bool isConstant;
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002319 Linkage = llvm::GlobalValue::PrivateLinkage;
David Blaikie4e4d0842012-03-11 07:00:24 +00002320 isConstant = !LangOpts.WritableStrings;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002321
2322 llvm::GlobalVariable *GV =
2323 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2324 ".str");
Rafael Espindola803d3072011-01-17 22:11:21 +00002325 GV->setUnnamedAddr(true);
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002326 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2327 GV->setAlignment(Align.getQuantity());
Jay Foada5c04342011-07-21 14:31:17 +00002328 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002329
2330 // String length.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002331 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002332 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2333
2334 // The struct.
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002335 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002336 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2337 llvm::GlobalVariable::PrivateLinkage, C,
2338 "_unnamed_nsstring_");
2339 // FIXME. Fix section.
Fariborz Jahanianec951e02010-04-23 22:33:39 +00002340 if (const char *Sect =
John McCall260611a2012-06-20 06:18:46 +00002341 LangOpts.ObjCRuntime.isNonFragile()
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002342 ? getContext().getTargetInfo().getNSStringNonFragileABISection()
2343 : getContext().getTargetInfo().getNSStringSection())
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002344 GV->setSection(Sect);
2345 Entry.setValue(GV);
2346
2347 return GV;
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00002348}
2349
Douglas Gregor0815b572011-08-09 17:23:49 +00002350QualType CodeGenModule::getObjCFastEnumerationStateType() {
2351 if (ObjCFastEnumerationStateType.isNull()) {
2352 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2353 Context.getTranslationUnitDecl(),
2354 &Context.Idents.get("__objcFastEnumerationState"));
2355 D->startDefinition();
2356
2357 QualType FieldTypes[] = {
2358 Context.UnsignedLongTy,
2359 Context.getPointerType(Context.getObjCIdType()),
2360 Context.getPointerType(Context.UnsignedLongTy),
2361 Context.getConstantArrayType(Context.UnsignedLongTy,
2362 llvm::APInt(32, 5), ArrayType::Normal, 0)
2363 };
2364
2365 for (size_t i = 0; i < 4; ++i) {
2366 FieldDecl *Field = FieldDecl::Create(Context,
2367 D,
2368 SourceLocation(),
2369 SourceLocation(), 0,
2370 FieldTypes[i], /*TInfo=*/0,
2371 /*BitWidth=*/0,
2372 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002373 ICIS_NoInit);
Douglas Gregor0815b572011-08-09 17:23:49 +00002374 Field->setAccess(AS_public);
2375 D->addDecl(Field);
2376 }
2377
2378 D->completeDefinition();
2379 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2380 }
2381
2382 return ObjCFastEnumerationStateType;
2383}
2384
Eli Friedman64f45a22011-11-01 02:23:42 +00002385llvm::Constant *
2386CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2387 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2388
2389 // Don't emit it as the address of the string, emit the string data itself
2390 // as an inline array.
Chris Lattner812234b2012-02-06 22:47:00 +00002391 if (E->getCharByteWidth() == 1) {
2392 SmallString<64> Str(E->getString());
2393
2394 // Resize the string to the right size, which is indicated by its type.
2395 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2396 Str.resize(CAT->getSize().getZExtValue());
2397 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2398 }
Chris Lattner94010692012-02-05 02:30:40 +00002399
2400 llvm::ArrayType *AType =
2401 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2402 llvm::Type *ElemTy = AType->getElementType();
2403 unsigned NumElements = AType->getNumElements();
Chris Lattnerd79ed432012-02-06 22:52:04 +00002404
2405 // Wide strings have either 2-byte or 4-byte elements.
2406 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2407 SmallVector<uint16_t, 32> Elements;
2408 Elements.reserve(NumElements);
2409
2410 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2411 Elements.push_back(E->getCodeUnit(i));
2412 Elements.resize(NumElements);
2413 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner94010692012-02-05 02:30:40 +00002414 }
2415
Chris Lattnerd79ed432012-02-06 22:52:04 +00002416 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2417 SmallVector<uint32_t, 32> Elements;
2418 Elements.reserve(NumElements);
2419
2420 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2421 Elements.push_back(E->getCodeUnit(i));
2422 Elements.resize(NumElements);
2423 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedman64f45a22011-11-01 02:23:42 +00002424}
2425
Daniel Dunbar61432932008-08-13 23:20:05 +00002426/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2427/// constant array for the given string literal.
2428llvm::Constant *
2429CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
John McCalla5e19c62011-08-04 01:03:22 +00002430 CharUnits Align = getContext().getTypeAlignInChars(S->getType());
Eli Friedman64f45a22011-11-01 02:23:42 +00002431 if (S->isAscii() || S->isUTF8()) {
Chris Lattner812234b2012-02-06 22:47:00 +00002432 SmallString<64> Str(S->getString());
2433
2434 // Resize the string to the right size, which is indicated by its type.
2435 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2436 Str.resize(CAT->getSize().getZExtValue());
2437 return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
Eli Friedman7eb79c12009-11-16 05:55:46 +00002438 }
Eli Friedman64f45a22011-11-01 02:23:42 +00002439
Chris Lattner812234b2012-02-06 22:47:00 +00002440 // FIXME: the following does not memoize wide strings.
Eli Friedman64f45a22011-11-01 02:23:42 +00002441 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2442 llvm::GlobalVariable *GV =
2443 new llvm::GlobalVariable(getModule(),C->getType(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002444 !LangOpts.WritableStrings,
Eli Friedman64f45a22011-11-01 02:23:42 +00002445 llvm::GlobalValue::PrivateLinkage,
2446 C,".str");
Seth Cantrell7d6a7c02012-01-18 12:11:32 +00002447
Eli Friedman64f45a22011-11-01 02:23:42 +00002448 GV->setAlignment(Align.getQuantity());
2449 GV->setUnnamedAddr(true);
Eli Friedman64f45a22011-11-01 02:23:42 +00002450 return GV;
Daniel Dunbar61432932008-08-13 23:20:05 +00002451}
2452
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002453/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2454/// array for the given ObjCEncodeExpr node.
2455llvm::Constant *
2456CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2457 std::string Str;
2458 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00002459
2460 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002461}
2462
2463
Chris Lattnera7ad98f2008-02-11 00:02:17 +00002464/// GenerateWritableString -- Creates storage for a string literal.
John McCalla5e19c62011-08-04 01:03:22 +00002465static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002466 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00002467 CodeGenModule &CGM,
John McCalla5e19c62011-08-04 01:03:22 +00002468 const char *GlobalName,
2469 unsigned Alignment) {
Daniel Dunbar61432932008-08-13 23:20:05 +00002470 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson0032b272009-08-13 21:57:51 +00002471 llvm::Constant *C =
Chris Lattner94010692012-02-05 02:30:40 +00002472 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002473
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002474 // Create a global variable for this string
Rafael Espindola1257bc62011-01-10 22:34:03 +00002475 llvm::GlobalVariable *GV =
2476 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2477 llvm::GlobalValue::PrivateLinkage,
2478 C, GlobalName);
John McCalla5e19c62011-08-04 01:03:22 +00002479 GV->setAlignment(Alignment);
Rafael Espindola1257bc62011-01-10 22:34:03 +00002480 GV->setUnnamedAddr(true);
2481 return GV;
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002482}
2483
Daniel Dunbar61432932008-08-13 23:20:05 +00002484/// GetAddrOfConstantString - Returns a pointer to a character array
2485/// containing the literal. This contents are exactly that of the
2486/// given string, i.e. it will not be null terminated automatically;
2487/// see GetAddrOfConstantCString. Note that whether the result is
2488/// actually a pointer to an LLVM constant depends on
2489/// Feature.WriteableStrings.
2490///
2491/// The result has pointer to array type.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002492llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
John McCalla5e19c62011-08-04 01:03:22 +00002493 const char *GlobalName,
2494 unsigned Alignment) {
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00002495 // Get the default prefix if a name wasn't specified.
2496 if (!GlobalName)
Chris Lattner95b851e2009-07-16 05:03:48 +00002497 GlobalName = ".str";
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00002498
2499 // Don't share any string literals if strings aren't constant.
David Blaikie4e4d0842012-03-11 07:00:24 +00002500 if (LangOpts.WritableStrings)
John McCalla5e19c62011-08-04 01:03:22 +00002501 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002502
John McCalla5e19c62011-08-04 01:03:22 +00002503 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
Benjamin Kramer9de43422011-03-05 13:45:23 +00002504 ConstantStringMap.GetOrCreateValue(Str);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002505
John McCalla5e19c62011-08-04 01:03:22 +00002506 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2507 if (Alignment > GV->getAlignment()) {
2508 GV->setAlignment(Alignment);
2509 }
2510 return GV;
2511 }
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002512
2513 // Create a global variable for this.
Chris Lattner812234b2012-02-06 22:47:00 +00002514 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2515 Alignment);
John McCalla5e19c62011-08-04 01:03:22 +00002516 Entry.setValue(GV);
2517 return GV;
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002518}
Daniel Dunbar61432932008-08-13 23:20:05 +00002519
2520/// GetAddrOfConstantCString - Returns a pointer to a character
Benjamin Kramer9de43422011-03-05 13:45:23 +00002521/// array containing the literal and a terminating '\0'
Daniel Dunbar61432932008-08-13 23:20:05 +00002522/// character. The result has pointer to array type.
Benjamin Kramer9de43422011-03-05 13:45:23 +00002523llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
John McCalla5e19c62011-08-04 01:03:22 +00002524 const char *GlobalName,
2525 unsigned Alignment) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002526 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCalla5e19c62011-08-04 01:03:22 +00002527 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
Daniel Dunbar61432932008-08-13 23:20:05 +00002528}
Daniel Dunbar41071de2008-08-15 23:26:23 +00002529
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002530/// EmitObjCPropertyImplementations - Emit information for synthesized
2531/// properties for an implementation.
Mike Stump1eb44332009-09-09 15:08:12 +00002532void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002533 ObjCImplementationDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00002534 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002535 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002536 ObjCPropertyImplDecl *PID = *i;
Mike Stump1eb44332009-09-09 15:08:12 +00002537
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002538 // Dynamic is just for type-checking.
2539 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2540 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2541
2542 // Determine which methods need to be implemented, some may have
Jordan Rose1e4691b2012-10-10 16:42:25 +00002543 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002544 // we want, that just indicates if the decl came from a
2545 // property. What we want to know is if the method is defined in
2546 // this implementation.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002547 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00002548 CodeGenFunction(*this).GenerateObjCGetter(
2549 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002550 if (!PD->isReadOnly() &&
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002551 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00002552 CodeGenFunction(*this).GenerateObjCSetter(
2553 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002554 }
2555 }
2556}
2557
John McCalle81ac692011-03-22 07:05:39 +00002558static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00002559 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2560 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00002561 ivar; ivar = ivar->getNextIvar())
2562 if (ivar->getType().isDestructedType())
2563 return true;
2564
2565 return false;
2566}
2567
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002568/// EmitObjCIvarInitializations - Emit information for ivar initialization
2569/// for an implementation.
2570void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCalle81ac692011-03-22 07:05:39 +00002571 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2572 if (needsDestructMethod(D)) {
2573 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2574 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2575 ObjCMethodDecl *DTORMethod =
2576 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002577 cxxSelector, getContext().VoidTy, 0, D,
2578 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rose1e4691b2012-10-10 16:42:25 +00002579 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002580 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCalle81ac692011-03-22 07:05:39 +00002581 D->addInstanceMethod(DTORMethod);
2582 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCallb03527a2012-10-17 04:53:31 +00002583 D->setHasDestructors(true);
John McCalle81ac692011-03-22 07:05:39 +00002584 }
2585
2586 // If the implementation doesn't have any ivar initializers, we don't need
2587 // a .cxx_construct.
David Chisnall827bbcc2011-03-17 14:19:08 +00002588 if (D->getNumIvarInitializers() == 0)
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002589 return;
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002590
John McCalle81ac692011-03-22 07:05:39 +00002591 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2592 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002593 // The constructor returns 'self'.
2594 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2595 D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00002596 D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00002597 cxxSelector,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002598 getContext().getObjCIdType(), 0,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002599 D, /*isInstance=*/true,
2600 /*isVariadic=*/false,
Jordan Rose1e4691b2012-10-10 16:42:25 +00002601 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002602 /*isImplicitlyDeclared=*/true,
2603 /*isDefined=*/false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002604 ObjCMethodDecl::Required);
2605 D->addInstanceMethod(CTORMethod);
2606 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCallb03527a2012-10-17 04:53:31 +00002607 D->setHasNonZeroConstructors(true);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002608}
2609
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002610/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00002611void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002612 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson984e0682009-04-01 00:58:25 +00002613 I != E; ++I)
2614 EmitTopLevelDecl(*I);
2615}
2616
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002617// EmitLinkageSpec - Emit all declarations in a linkage spec.
2618void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmanf976be82009-08-01 20:48:04 +00002619 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2620 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002621 ErrorUnsupported(LSD, "linkage spec");
2622 return;
2623 }
2624
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002625 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Fariborz Jahanianc1868e52012-10-26 20:22:11 +00002626 I != E; ++I) {
Fariborz Jahanian107dae42012-10-26 22:20:25 +00002627 // Meta-data for ObjC class includes references to implemented methods.
2628 // Generate class's method definitions first.
Fariborz Jahanianc1868e52012-10-26 20:22:11 +00002629 if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
2630 for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2631 MEnd = OID->meth_end();
2632 M != MEnd; ++M)
2633 EmitTopLevelDecl(*M);
2634 }
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002635 EmitTopLevelDecl(*I);
Fariborz Jahanianc1868e52012-10-26 20:22:11 +00002636 }
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002637}
2638
Daniel Dunbar41071de2008-08-15 23:26:23 +00002639/// EmitTopLevelDecl - Emit code for a single top level declaration.
2640void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2641 // If an error has occurred, stop code generation, but continue
2642 // parsing and semantic analysis (to ensure all warnings and errors
2643 // are emitted).
2644 if (Diags.hasErrorOccurred())
2645 return;
2646
Douglas Gregor16e8be22009-06-29 17:30:29 +00002647 // Ignore dependent declarations.
2648 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2649 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002650
Daniel Dunbar41071de2008-08-15 23:26:23 +00002651 switch (D->getKind()) {
Anders Carlsson293361a2009-08-25 13:14:46 +00002652 case Decl::CXXConversion:
Anders Carlsson2b77ba82009-04-04 20:47:02 +00002653 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00002654 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00002655 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00002656 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2657 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor16e8be22009-06-29 17:30:29 +00002658 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002659
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002660 EmitGlobal(cast<FunctionDecl>(D));
2661 break;
2662
Daniel Dunbar41071de2008-08-15 23:26:23 +00002663 case Decl::Var:
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002664 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002665 break;
2666
John McCall26fbc722011-04-12 01:01:22 +00002667 // Indirect fields from global anonymous structs and unions can be
2668 // ignored; only the actual variable requires IR gen support.
2669 case Decl::IndirectField:
2670 break;
2671
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002672 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00002673 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00002674 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002675 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002676 // No code generation needed.
John McCall9d0c6612009-11-17 09:33:40 +00002677 case Decl::UsingShadow:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002678 case Decl::Using:
Douglas Gregordd9967a2009-09-02 23:49:23 +00002679 case Decl::UsingDirective:
Douglas Gregor127102b2009-06-29 20:59:39 +00002680 case Decl::ClassTemplate:
2681 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +00002682 case Decl::TypeAliasTemplate:
Anders Carlsson018837b2009-09-23 19:19:16 +00002683 case Decl::NamespaceAlias:
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002684 case Decl::Block:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002685 break;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002686 case Decl::CXXConstructor:
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002687 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00002688 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2689 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002690 return;
2691
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002692 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2693 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002694 case Decl::CXXDestructor:
Francois Pichet8387e2a2011-04-22 22:18:13 +00002695 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2696 return;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002697 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2698 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00002699
2700 case Decl::StaticAssert:
2701 // Nothing to do.
2702 break;
2703
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002704 // Objective-C Decls
Mike Stump1eb44332009-09-09 15:08:12 +00002705
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00002706 // Forward declarations, no (immediate) code generation.
Chris Lattner285d0db2009-04-01 02:36:43 +00002707 case Decl::ObjCInterface:
Eric Christopherffb0c3a2012-07-19 22:22:55 +00002708 case Decl::ObjCCategory:
Chris Lattner285d0db2009-04-01 02:36:43 +00002709 break;
2710
Douglas Gregorbd9482d2012-01-01 21:23:57 +00002711 case Decl::ObjCProtocol: {
2712 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2713 if (Proto->isThisDeclarationADefinition())
2714 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbar41071de2008-08-15 23:26:23 +00002715 break;
Douglas Gregorbd9482d2012-01-01 21:23:57 +00002716 }
2717
Daniel Dunbar41071de2008-08-15 23:26:23 +00002718 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002719 // Categories have properties but don't support synthesize so we
2720 // can ignore them here.
Peter Collingbournee9265232011-07-27 20:29:46 +00002721 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002722 break;
2723
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002724 case Decl::ObjCImplementation: {
2725 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2726 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002727 EmitObjCIvarInitializations(OMD);
Peter Collingbournee9265232011-07-27 20:29:46 +00002728 ObjCRuntime->GenerateClass(OMD);
Eric Christopherbe6c6862012-04-11 05:56:05 +00002729 // Emit global variable debug information.
2730 if (CGDebugInfo *DI = getModuleDebugInfo())
Alexey Samsonov96a66392012-12-03 18:28:12 +00002731 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2732 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
2733 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002734 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002735 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00002736 case Decl::ObjCMethod: {
2737 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2738 // If this is not a prototype, emit the body.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002739 if (OMD->getBody())
Daniel Dunbar41071de2008-08-15 23:26:23 +00002740 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2741 break;
2742 }
Mike Stump1eb44332009-09-09 15:08:12 +00002743 case Decl::ObjCCompatibleAlias:
David Chisnall29254f42012-01-31 18:59:20 +00002744 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002745 break;
2746
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002747 case Decl::LinkageSpec:
2748 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002749 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00002750
2751 case Decl::FileScopeAsm: {
2752 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002753 StringRef AsmString = AD->getAsmString()->getString();
Mike Stump1eb44332009-09-09 15:08:12 +00002754
Daniel Dunbar41071de2008-08-15 23:26:23 +00002755 const std::string &S = getModule().getModuleInlineAsm();
2756 if (S.empty())
2757 getModule().setModuleInlineAsm(AsmString);
Joerg Sonnenberger8ce9cca2012-08-10 10:57:52 +00002758 else if (S.end()[-1] == '\n')
Chris Lattner9f5bff02011-07-23 20:04:25 +00002759 getModule().setModuleInlineAsm(S + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002760 else
Benjamin Kramer8d042582009-12-11 13:33:18 +00002761 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002762 break;
2763 }
Mike Stump1eb44332009-09-09 15:08:12 +00002764
Douglas Gregorb6cbe512013-01-14 17:21:00 +00002765 case Decl::Import: {
2766 ImportDecl *Import = cast<ImportDecl>(D);
2767
2768 // Ignore import declarations that come from imported modules.
2769 if (clang::Module *Owner = Import->getOwningModule()) {
2770 if (getLangOpts().CurrentModule.empty() ||
2771 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
2772 break;
2773 }
2774
2775 // Walk from this module up to its top-level module; we'll import all of
2776 // these modules and their non-explicit child modules.
2777 llvm::SmallVector<clang::Module *, 2> Stack;
2778 for (clang::Module *Mod = Import->getImportedModule(); Mod;
2779 Mod = Mod->Parent) {
2780 if (!ImportedModules.insert(Mod))
2781 break;
2782
2783 Stack.push_back(Mod);
2784 }
2785
Douglas Gregor5d75ea72013-01-14 18:28:43 +00002786 if (Stack.empty())
2787 break;
2788
2789 // Get/create metadata for the link options.
2790 llvm::NamedMDNode *Metadata
2791 = getModule().getOrInsertNamedMetadata("llvm.module.linkoptions");
2792
Douglas Gregorb6cbe512013-01-14 17:21:00 +00002793 // Find all of the non-explicit submodules of the modules we've imported and
2794 // import them.
2795 while (!Stack.empty()) {
2796 clang::Module *Mod = Stack.back();
2797 Stack.pop_back();
2798
Douglas Gregor5d75ea72013-01-14 18:28:43 +00002799 // Add linker options to link against the libraries/frameworks
2800 // described by this module.
2801 for (unsigned I = 0, N = Mod->LinkLibraries.size(); I != N; ++I) {
2802 // FIXME: -lfoo is Unix-centric and -framework Foo is Darwin-centric.
2803 // We need to know more about the linker to know how to encode these
2804 // options propertly.
2805
2806 // Link against a framework.
2807 if (Mod->LinkLibraries[I].IsFramework) {
2808 llvm::Value *Args[2] = {
2809 llvm::MDString::get(getLLVMContext(), "-framework"),
2810 llvm::MDString::get(getLLVMContext(),
2811 Mod->LinkLibraries[I].Library)
2812 };
2813
2814 Metadata->addOperand(llvm::MDNode::get(getLLVMContext(), Args));
2815 continue;
2816 }
2817
2818 // Link against a library.
2819 llvm::Value *OptString
2820 = llvm::MDString::get(getLLVMContext(),
2821 "-l" + Mod->LinkLibraries[I].Library);
2822 Metadata->addOperand(llvm::MDNode::get(getLLVMContext(), OptString));
2823 }
Douglas Gregorb6cbe512013-01-14 17:21:00 +00002824
2825 // We've imported this module; now import any of its children that haven't
2826 // already been imported.
2827 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
2828 SubEnd = Mod->submodule_end();
2829 Sub != SubEnd; ++Sub) {
2830 if ((*Sub)->IsExplicit)
2831 continue;
2832
2833 if (ImportedModules.insert(*Sub))
2834 Stack.push_back(*Sub);
2835 }
2836 }
2837 break;
2838 }
2839
Mike Stump1eb44332009-09-09 15:08:12 +00002840 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00002841 // Make sure we handled everything we should, every other kind is a
2842 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2843 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002844 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2845 }
2846}
John McCall744016d2010-07-06 23:57:41 +00002847
2848/// Turns the given pointer into a constant.
2849static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2850 const void *Ptr) {
2851 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002852 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall744016d2010-07-06 23:57:41 +00002853 return llvm::ConstantInt::get(i64, PtrInt);
2854}
2855
2856static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2857 llvm::NamedMDNode *&GlobalMetadata,
2858 GlobalDecl D,
2859 llvm::GlobalValue *Addr) {
2860 if (!GlobalMetadata)
2861 GlobalMetadata =
2862 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2863
2864 // TODO: should we report variant information for ctors/dtors?
2865 llvm::Value *Ops[] = {
2866 Addr,
2867 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2868 };
Jay Foad6f141652011-04-21 19:59:12 +00002869 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall744016d2010-07-06 23:57:41 +00002870}
2871
2872/// Emits metadata nodes associating all the global values in the
2873/// current module with the Decls they came from. This is useful for
2874/// projects using IR gen as a subroutine.
2875///
2876/// Since there's currently no way to associate an MDNode directly
2877/// with an llvm::GlobalValue, we create a global named metadata
2878/// with the name 'clang.global.decl.ptrs'.
2879void CodeGenModule::EmitDeclMetadata() {
2880 llvm::NamedMDNode *GlobalMetadata = 0;
2881
2882 // StaticLocalDeclMap
Chris Lattner5f9e2722011-07-23 10:55:15 +00002883 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
John McCall744016d2010-07-06 23:57:41 +00002884 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2885 I != E; ++I) {
2886 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2887 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2888 }
2889}
2890
2891/// Emits metadata nodes for all the local variables in the current
2892/// function.
2893void CodeGenFunction::EmitDeclMetadata() {
2894 if (LocalDeclMap.empty()) return;
2895
2896 llvm::LLVMContext &Context = getLLVMContext();
2897
2898 // Find the unique metadata ID for this name.
2899 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2900
2901 llvm::NamedMDNode *GlobalMetadata = 0;
2902
2903 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2904 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2905 const Decl *D = I->first;
2906 llvm::Value *Addr = I->second;
2907
2908 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2909 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Jay Foad6f141652011-04-21 19:59:12 +00002910 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
John McCall744016d2010-07-06 23:57:41 +00002911 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2912 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2913 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2914 }
2915 }
2916}
Daniel Dunbar673431a2010-07-16 00:00:15 +00002917
Nick Lewycky3dc05412011-05-05 00:08:20 +00002918void CodeGenModule::EmitCoverageFile() {
2919 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002920 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2921 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2922 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky3dc05412011-05-05 00:08:20 +00002923 llvm::MDString *CoverageFile =
2924 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002925 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2926 llvm::MDNode *CU = CUNode->getOperand(i);
Nick Lewycky3dc05412011-05-05 00:08:20 +00002927 llvm::Value *node[] = { CoverageFile, CU };
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002928 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2929 GCov->addOperand(N);
2930 }
2931 }
2932 }
2933}
Nico Weberc5f80462012-10-11 10:13:44 +00002934
2935llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
2936 QualType GuidType) {
2937 // Sema has checked that all uuid strings are of the form
2938 // "12345678-1234-1234-1234-1234567890ab".
2939 assert(Uuid.size() == 36);
2940 const char *Uuidstr = Uuid.data();
2941 for (int i = 0; i < 36; ++i) {
2942 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-');
2943 else assert(isxdigit(Uuidstr[i]));
2944 }
2945
2946 llvm::APInt Field0(32, StringRef(Uuidstr , 8), 16);
2947 llvm::APInt Field1(16, StringRef(Uuidstr + 9, 4), 16);
2948 llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16);
Nico Weber193646f2012-10-17 00:34:34 +00002949 static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Weberc5f80462012-10-11 10:13:44 +00002950
2951 APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4);
2952 InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0));
2953 InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1));
2954 InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2));
2955 APValue& Arr = InitStruct.getStructField(3);
2956 Arr = APValue(APValue::UninitArray(), 8, 8);
2957 for (int t = 0; t < 8; ++t)
Nico Weber43085812012-10-13 21:56:05 +00002958 Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt(
2959 llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16)));
Nico Weberc5f80462012-10-11 10:13:44 +00002960
2961 return EmitConstantValue(InitStruct, GuidType);
2962}