blob: 0d4e0981d0bf12fe4f644d1813ea67ec1906ecf3 [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),
Will Dietz4f45bc02013-01-18 11:30:38 +000080 BlockDescriptorType(0), GenericBlockLiteralType(0),
81 SanitizerBlacklist(CGO.SanitizerBlacklistFile),
82 SanOpts(SanitizerBlacklist.isIn(M) ?
83 SanitizerOptions::Disabled : LangOpts.Sanitize) {
84
Chris Lattner8b418682012-02-07 00:39:47 +000085 // Initialize the type cache.
86 llvm::LLVMContext &LLVMContext = M.getContext();
87 VoidTy = llvm::Type::getVoidTy(LLVMContext);
88 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
89 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
90 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
91 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
92 FloatTy = llvm::Type::getFloatTy(LLVMContext);
93 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
94 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
95 PointerAlignInBytes =
96 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
97 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
98 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
99 Int8PtrTy = Int8Ty->getPointerTo(0);
100 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
101
David Blaikie4e4d0842012-03-11 07:00:24 +0000102 if (LangOpts.ObjC1)
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000103 createObjCRuntime();
David Blaikie4e4d0842012-03-11 07:00:24 +0000104 if (LangOpts.OpenCL)
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000105 createOpenCLRuntime();
David Blaikie4e4d0842012-03-11 07:00:24 +0000106 if (LangOpts.CUDA)
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000107 createCUDARuntime();
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000108
Kostya Serebryanyc9fe6052012-04-24 06:57:01 +0000109 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Will Dietz4f45bc02013-01-18 11:30:38 +0000110 if (SanOpts.Thread ||
Kostya Serebryanyc9fe6052012-04-24 06:57:01 +0000111 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
112 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
Dan Gohman0b5c4fc2010-10-15 20:23:12 +0000113 ABI.getMangleContext());
Dan Gohman3d5aff52010-10-14 23:06:10 +0000114
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000115 // If debug info or coverage generation is enabled, create the CGDebugInfo
116 // object.
Douglas Gregor4cdad312012-10-23 20:05:01 +0000117 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000118 CodeGenOpts.EmitGcovArcs ||
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000119 CodeGenOpts.EmitGcovNotes)
120 DebugInfo = new CGDebugInfo(*this);
John McCalld16c2cf2011-02-08 08:22:06 +0000121
122 Block.GlobalUniqueCount = 0;
John McCall5936e332011-02-15 09:22:45 +0000123
David Blaikie4e4d0842012-03-11 07:00:24 +0000124 if (C.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000125 ARCData = new ARCEntrypoints();
126 RRData = new RREntrypoints();
Chris Lattner2b94fe32008-03-01 08:45:05 +0000127}
128
129CodeGenModule::~CodeGenModule() {
Peter Collingbournee9265232011-07-27 20:29:46 +0000130 delete ObjCRuntime;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000131 delete OpenCLRuntime;
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000132 delete CUDARuntime;
Ted Kremenek0628b722011-10-08 05:28:26 +0000133 delete TheTargetCodeGenInfo;
John McCallf16aa102010-08-22 21:01:12 +0000134 delete &ABI;
Dan Gohman4376c852010-10-15 18:04:46 +0000135 delete TBAA;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000136 delete DebugInfo;
John McCallf85e1932011-06-15 23:02:42 +0000137 delete ARCData;
138 delete RRData;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000139}
140
David Chisnall0d13f6f2010-01-23 02:40:42 +0000141void CodeGenModule::createObjCRuntime() {
John McCall260611a2012-06-20 06:18:46 +0000142 // This is just isGNUFamily(), but we want to force implementors of
143 // new ABIs to decide how best to do this.
144 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnall11d3f4c2012-07-03 20:49:52 +0000145 case ObjCRuntime::GNUstep:
146 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000147 case ObjCRuntime::ObjFW:
Peter Collingbournee9265232011-07-27 20:29:46 +0000148 ObjCRuntime = CreateGNUObjCRuntime(*this);
John McCall260611a2012-06-20 06:18:46 +0000149 return;
150
151 case ObjCRuntime::FragileMacOSX:
152 case ObjCRuntime::MacOSX:
153 case ObjCRuntime::iOS:
Peter Collingbournee9265232011-07-27 20:29:46 +0000154 ObjCRuntime = CreateMacObjCRuntime(*this);
John McCall260611a2012-06-20 06:18:46 +0000155 return;
156 }
157 llvm_unreachable("bad runtime kind");
David Chisnall0d13f6f2010-01-23 02:40:42 +0000158}
159
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000160void CodeGenModule::createOpenCLRuntime() {
161 OpenCLRuntime = new CGOpenCLRuntime(*this);
162}
163
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000164void CodeGenModule::createCUDARuntime() {
165 CUDARuntime = CreateNVCUDARuntime(*this);
166}
167
Ted Kremenek815c78f2008-08-05 18:50:11 +0000168void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +0000169 EmitDeferred();
Eli Friedman6c6bda32010-01-08 00:50:11 +0000170 EmitCXXGlobalInitFunc();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000171 EmitCXXGlobalDtorFunc();
Peter Collingbournee9265232011-07-27 20:29:46 +0000172 if (ObjCRuntime)
173 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000174 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000175 EmitCtorList(GlobalCtors, "llvm.global_ctors");
176 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000177 EmitGlobalAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +0000178 EmitLLVMUsed();
Douglas Gregorf43b7212013-01-16 01:23:41 +0000179
180 if (CodeGenOpts.ModulesAutolink) {
181 EmitModuleLinkOptions();
182 }
Douglas Gregor5d75ea72013-01-14 18:28:43 +0000183
John McCallb2593832010-09-16 06:16:50 +0000184 SimplifyPersonality();
185
John McCall744016d2010-07-06 23:57:41 +0000186 if (getCodeGenOpts().EmitDeclMetadata)
187 EmitDeclMetadata();
Nick Lewycky5ea4f442011-05-04 20:46:58 +0000188
189 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky3dc05412011-05-05 00:08:20 +0000190 EmitCoverageFile();
Devang Patelf391dbe2011-08-16 20:58:22 +0000191
192 if (DebugInfo)
193 DebugInfo->finalize();
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000194}
195
Devang Patele80d5672011-03-23 16:29:39 +0000196void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
197 // Make sure that this type is translated.
198 Types.UpdateCompletedType(TD);
Devang Patele80d5672011-03-23 16:29:39 +0000199}
200
Dan Gohman3d5aff52010-10-14 23:06:10 +0000201llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
202 if (!TBAA)
203 return 0;
204 return TBAA->getTBAAInfo(QTy);
205}
206
Kostya Serebryany8cb4a072012-03-26 17:03:51 +0000207llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
208 if (!TBAA)
209 return 0;
210 return TBAA->getTBAAInfoForVTablePtr();
211}
212
Dan Gohmanb22c7dc2012-09-28 21:58:29 +0000213llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
214 if (!TBAA)
215 return 0;
216 return TBAA->getTBAAStructInfo(QTy);
217}
218
Dan Gohman3d5aff52010-10-14 23:06:10 +0000219void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
220 llvm::MDNode *TBAAInfo) {
221 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
222}
223
John McCall6374c332010-03-06 00:35:14 +0000224bool CodeGenModule::isTargetDarwin() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000225 return getContext().getTargetInfo().getTriple().isOSDarwin();
John McCall6374c332010-03-06 00:35:14 +0000226}
227
Chandler Carruth0f30a122012-03-30 19:44:53 +0000228void CodeGenModule::Error(SourceLocation loc, StringRef error) {
229 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
John McCall32096692011-03-18 02:56:14 +0000230 getDiags().Report(Context.getFullLoc(loc), diagID);
231}
232
Daniel Dunbar488e9932008-08-16 00:56:44 +0000233/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000234/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000235void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
236 bool OmitOnError) {
237 if (OmitOnError && getDiags().hasErrorOccurred())
238 return;
David Blaikied6471f72011-09-25 23:23:43 +0000239 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000240 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000241 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000242 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
243 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000244}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000245
Daniel Dunbar488e9932008-08-16 00:56:44 +0000246/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000247/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000248void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
249 bool OmitOnError) {
250 if (OmitOnError && getDiags().hasErrorOccurred())
251 return;
David Blaikied6471f72011-09-25 23:23:43 +0000252 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000253 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000254 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000255 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000256}
257
John McCallbc8d40d2011-06-24 21:55:10 +0000258llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
259 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
260}
261
Mike Stump1eb44332009-09-09 15:08:12 +0000262void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000263 const NamedDecl *D) const {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000264 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000265 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000266 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000267 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000268 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000269
John McCallaf146032010-10-30 11:50:40 +0000270 // Set visibility for definitions.
271 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000272 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
273 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
Dan Gohman4f8d1232008-05-22 00:50:06 +0000274}
275
Hans Wennborgde981f32012-06-28 08:01:44 +0000276static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
277 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
278 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
279 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
280 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
281 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
282}
283
284static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
285 CodeGenOptions::TLSModel M) {
286 switch (M) {
287 case CodeGenOptions::GeneralDynamicTLSModel:
288 return llvm::GlobalVariable::GeneralDynamicTLSModel;
289 case CodeGenOptions::LocalDynamicTLSModel:
290 return llvm::GlobalVariable::LocalDynamicTLSModel;
291 case CodeGenOptions::InitialExecTLSModel:
292 return llvm::GlobalVariable::InitialExecTLSModel;
293 case CodeGenOptions::LocalExecTLSModel:
294 return llvm::GlobalVariable::LocalExecTLSModel;
295 }
296 llvm_unreachable("Invalid TLS model!");
297}
298
299void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
300 const VarDecl &D) const {
301 assert(D.isThreadSpecified() && "setting TLS mode on non-TLS var!");
302
303 llvm::GlobalVariable::ThreadLocalMode TLM;
Douglas Gregor4cdad312012-10-23 20:05:01 +0000304 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgde981f32012-06-28 08:01:44 +0000305
306 // Override the TLS model if it is explicitly specified.
307 if (D.hasAttr<TLSModelAttr>()) {
308 const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
309 TLM = GetLLVMTLSModel(Attr->getModel());
310 }
311
312 GV->setThreadLocalMode(TLM);
313}
314
John McCallcbfe5022010-08-04 08:34:44 +0000315/// Set the symbol visibility of type information (vtable and RTTI)
316/// associated with the given type.
317void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
318 const CXXRecordDecl *RD,
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000319 TypeVisibilityKind TVK) const {
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000320 setGlobalVisibility(GV, RD);
John McCallcbfe5022010-08-04 08:34:44 +0000321
John McCall279b5eb2010-08-12 23:36:15 +0000322 if (!CodeGenOpts.HiddenWeakVTables)
323 return;
324
Anders Carlsson9a86a132011-01-29 20:36:11 +0000325 // We never want to drop the visibility for RTTI names.
326 if (TVK == TVK_ForRTTIName)
327 return;
328
John McCallcbfe5022010-08-04 08:34:44 +0000329 // We want to drop the visibility to hidden for weak type symbols.
330 // This isn't possible if there might be unresolved references
331 // elsewhere that rely on this symbol being visible.
332
John McCall7a536902010-08-05 20:39:18 +0000333 // This should be kept roughly in sync with setThunkVisibility
334 // in CGVTables.cpp.
335
John McCallcbfe5022010-08-04 08:34:44 +0000336 // Preconditions.
Anders Carlssonf502d932011-01-24 00:46:19 +0000337 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
John McCallcbfe5022010-08-04 08:34:44 +0000338 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
339 return;
340
341 // Don't override an explicit visibility attribute.
Douglas Gregor4421d2b2011-03-26 12:10:19 +0000342 if (RD->getExplicitVisibility())
John McCallcbfe5022010-08-04 08:34:44 +0000343 return;
344
345 switch (RD->getTemplateSpecializationKind()) {
346 // We have to disable the optimization if this is an EI definition
347 // because there might be EI declarations in other shared objects.
348 case TSK_ExplicitInstantiationDefinition:
349 case TSK_ExplicitInstantiationDeclaration:
350 return;
351
John McCall7a536902010-08-05 20:39:18 +0000352 // Every use of a non-template class's type information has to emit it.
John McCallcbfe5022010-08-04 08:34:44 +0000353 case TSK_Undeclared:
354 break;
355
John McCall7a536902010-08-05 20:39:18 +0000356 // In theory, implicit instantiations can ignore the possibility of
357 // an explicit instantiation declaration because there necessarily
358 // must be an EI definition somewhere with default visibility. In
359 // practice, it's possible to have an explicit instantiation for
360 // an arbitrary template class, and linkers aren't necessarily able
361 // to deal with mixed-visibility symbols.
362 case TSK_ExplicitSpecialization:
John McCallcbfe5022010-08-04 08:34:44 +0000363 case TSK_ImplicitInstantiation:
Douglas Gregoraafd1112012-10-24 14:11:55 +0000364 return;
John McCallcbfe5022010-08-04 08:34:44 +0000365 }
366
367 // If there's a key function, there may be translation units
368 // that don't have the key function's definition. But ignore
369 // this if we're emitting RTTI under -fno-rtti.
David Blaikie4e4d0842012-03-11 07:00:24 +0000370 if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
John McCallcbfe5022010-08-04 08:34:44 +0000371 if (Context.getKeyFunction(RD))
372 return;
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000373 }
John McCallcbfe5022010-08-04 08:34:44 +0000374
375 // Otherwise, drop the visibility to hidden.
376 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindolab1c65ff2011-01-11 21:44:37 +0000377 GV->setUnnamedAddr(true);
John McCallcbfe5022010-08-04 08:34:44 +0000378}
379
Chris Lattner5f9e2722011-07-23 10:55:15 +0000380StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
Anders Carlsson793a9902010-06-22 16:05:32 +0000381 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
382
Chris Lattner5f9e2722011-07-23 10:55:15 +0000383 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
Anders Carlsson793a9902010-06-22 16:05:32 +0000384 if (!Str.empty())
385 return Str;
386
John McCall4c40d982010-08-31 07:33:07 +0000387 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson793a9902010-06-22 16:05:32 +0000388 IdentifierInfo *II = ND->getIdentifier();
389 assert(II && "Attempt to mangle unnamed decl.");
390
391 Str = II->getName();
392 return Str;
393 }
394
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000395 SmallString<256> Buffer;
Rafael Espindolac4850c22011-02-10 23:59:36 +0000396 llvm::raw_svector_ostream Out(Buffer);
Anders Carlsson793a9902010-06-22 16:05:32 +0000397 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000398 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000399 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000400 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000401 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000402 getCXXABI().getMangleContext().mangleBlock(BD, Out,
403 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()));
Anders Carlsson793a9902010-06-22 16:05:32 +0000404 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000405 getCXXABI().getMangleContext().mangleName(ND, Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000406
407 // Allocate space for the mangled name.
Rafael Espindolac4850c22011-02-10 23:59:36 +0000408 Out.flush();
Anders Carlsson793a9902010-06-22 16:05:32 +0000409 size_t Length = Buffer.size();
410 char *Name = MangledNamesAllocator.Allocate<char>(Length);
411 std::copy(Buffer.begin(), Buffer.end(), Name);
412
Chris Lattner5f9e2722011-07-23 10:55:15 +0000413 Str = StringRef(Name, Length);
Anders Carlsson793a9902010-06-22 16:05:32 +0000414
415 return Str;
416}
417
Peter Collingbourne14110472011-01-13 18:57:25 +0000418void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
419 const BlockDecl *BD) {
420 MangleContext &MangleCtx = getCXXABI().getMangleContext();
421 const Decl *D = GD.getDecl();
Rafael Espindolac4850c22011-02-10 23:59:36 +0000422 llvm::raw_svector_ostream Out(Buffer.getBuffer());
Peter Collingbourne14110472011-01-13 18:57:25 +0000423 if (D == 0)
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000424 MangleCtx.mangleGlobalBlock(BD,
425 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000426 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000427 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000428 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000429 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000430 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000431 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Anders Carlsson9a8822b2010-06-09 02:36:32 +0000432}
433
Chris Lattner5f9e2722011-07-23 10:55:15 +0000434llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCallf746aa62010-03-19 23:29:14 +0000435 return getModule().getNamedValue(Name);
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000436}
437
Chris Lattner6d397602008-03-14 17:18:18 +0000438/// AddGlobalCtor - Add a function to the list that will be called before
439/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000440void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000441 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000442 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000443}
444
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000445/// AddGlobalDtor - Add a function to the list that will be called
446/// when the module is unloaded.
447void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000448 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000449 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
450}
451
452void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
453 // Ctor function type is void()*.
John McCall0774cb82011-05-15 01:53:33 +0000454 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000455 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000456
457 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000458 llvm::StructType *CtorStructTy =
Chris Lattner8b418682012-02-07 00:39:47 +0000459 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000460
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000461 // Construct the constructor and destructor arrays.
Chris Lattner0b239712012-02-06 22:16:34 +0000462 SmallVector<llvm::Constant*, 8> Ctors;
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000463 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
Chris Lattner0b239712012-02-06 22:16:34 +0000464 llvm::Constant *S[] = {
465 llvm::ConstantInt::get(Int32Ty, I->second, false),
466 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
467 };
Owen Anderson08e25242009-07-27 22:29:56 +0000468 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000469 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000470
471 if (!Ctors.empty()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000472 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Anderson1c431b32009-07-08 19:05:04 +0000473 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000474 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000475 llvm::ConstantArray::get(AT, Ctors),
Owen Anderson1c431b32009-07-08 19:05:04 +0000476 GlobalName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000477 }
Chris Lattner6d397602008-03-14 17:18:18 +0000478}
479
John McCalld46f9852010-02-19 01:32:20 +0000480llvm::GlobalValue::LinkageTypes
481CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000482 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000483
Chris Lattnerf81530652010-06-30 16:58:07 +0000484 if (Linkage == GVA_Internal)
John McCalld46f9852010-02-19 01:32:20 +0000485 return llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000486
487 if (D->hasAttr<DLLExportAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000488 return llvm::Function::DLLExportLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000489
490 if (D->hasAttr<WeakAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000491 return llvm::Function::WeakAnyLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000492
493 // In C99 mode, 'inline' functions are guaranteed to have a strong
494 // definition somewhere else, so we can use available_externally linkage.
495 if (Linkage == GVA_C99Inline)
Fariborz Jahanianfd0f89d2011-02-04 00:08:13 +0000496 return llvm::Function::AvailableExternallyLinkage;
John McCall5584d912011-09-19 18:05:26 +0000497
498 // Note that Apple's kernel linker doesn't support symbol
499 // coalescing, so we need to avoid linkonce and weak linkages there.
500 // Normally, this means we just map to internal, but for explicit
501 // instantiations we'll map to external.
502
Chris Lattnerf81530652010-06-30 16:58:07 +0000503 // In C++, the compiler has to emit a definition in every translation unit
504 // that references the function. We should use linkonce_odr because
505 // a) if all references in this translation unit are optimized away, we
506 // don't need to codegen it. b) if the function persists, it needs to be
507 // merged with other definitions. c) C++ has the ODR, so we know the
508 // definition is dependable.
509 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
David Blaikie4e4d0842012-03-11 07:00:24 +0000510 return !Context.getLangOpts().AppleKext
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000511 ? llvm::Function::LinkOnceODRLinkage
512 : llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000513
514 // An explicit instantiation of a template has weak linkage, since
515 // explicit instantiations can occur in multiple translation units
516 // and must all be equivalent. However, we are not allowed to
517 // throw away these explicit instantiations.
518 if (Linkage == GVA_ExplicitTemplateInstantiation)
David Blaikie4e4d0842012-03-11 07:00:24 +0000519 return !Context.getLangOpts().AppleKext
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000520 ? llvm::Function::WeakODRLinkage
John McCall5584d912011-09-19 18:05:26 +0000521 : llvm::Function::ExternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000522
523 // Otherwise, we have strong external linkage.
524 assert(Linkage == GVA_StrongExternal);
525 return llvm::Function::ExternalLinkage;
John McCalld46f9852010-02-19 01:32:20 +0000526}
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000527
John McCalld46f9852010-02-19 01:32:20 +0000528
529/// SetFunctionDefinitionAttributes - Set attributes for a global.
530///
531/// FIXME: This is currently only done for aliases and functions, but not for
532/// variables (these details are set in EmitGlobalVarDefinition for variables).
533void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
534 llvm::GlobalValue *GV) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000535 SetCommonAttributes(D, GV);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000536}
537
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000538void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump1eb44332009-09-09 15:08:12 +0000539 const CGFunctionInfo &Info,
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000540 llvm::Function *F) {
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000541 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +0000542 AttributeListType AttributeList;
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000543 ConstructAttributeList(Info, D, AttributeList, CallingConv);
Bill Wendling785b7782012-12-07 23:17:26 +0000544 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000545 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000546}
547
John McCalld1e40d52011-10-02 01:16:38 +0000548/// Determines whether the language options require us to model
549/// unwind exceptions. We treat -fexceptions as mandating this
550/// except under the fragile ObjC ABI with only ObjC exceptions
551/// enabled. This means, for example, that C with -fexceptions
552/// enables this.
David Blaikie4e4d0842012-03-11 07:00:24 +0000553static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCalld1e40d52011-10-02 01:16:38 +0000554 // If exceptions are completely disabled, obviously this is false.
David Blaikie4e4d0842012-03-11 07:00:24 +0000555 if (!LangOpts.Exceptions) return false;
John McCalld1e40d52011-10-02 01:16:38 +0000556
557 // If C++ exceptions are enabled, this is true.
David Blaikie4e4d0842012-03-11 07:00:24 +0000558 if (LangOpts.CXXExceptions) return true;
John McCalld1e40d52011-10-02 01:16:38 +0000559
560 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikie4e4d0842012-03-11 07:00:24 +0000561 if (LangOpts.ObjCExceptions) {
David Chisnall11d3f4c2012-07-03 20:49:52 +0000562 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCalld1e40d52011-10-02 01:16:38 +0000563 }
564
565 return true;
566}
567
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000568void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
569 llvm::Function *F) {
Rafael Espindolaabca5a12011-05-25 03:44:55 +0000570 if (CodeGenOpts.UnwindTables)
571 F->setHasUWTable();
572
David Blaikie4e4d0842012-03-11 07:00:24 +0000573 if (!hasUnwindExceptions(LangOpts))
Bill Wendling72390b32012-12-20 19:27:06 +0000574 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000575
Eli Friedman2873aee2011-08-22 23:55:33 +0000576 if (D->hasAttr<NakedAttr>()) {
577 // Naked implies noinline: we should not be inlining such functions.
Bill Wendling72390b32012-12-20 19:27:06 +0000578 F->addFnAttr(llvm::Attribute::Naked);
579 F->addFnAttr(llvm::Attribute::NoInline);
Eli Friedman2873aee2011-08-22 23:55:33 +0000580 }
Daniel Dunbardd0cb222010-09-29 18:20:25 +0000581
Mike Stump1feade82009-08-26 22:31:08 +0000582 if (D->hasAttr<NoInlineAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +0000583 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpf55314d2009-10-05 21:58:44 +0000584
Eli Friedman2873aee2011-08-22 23:55:33 +0000585 // (noinline wins over always_inline, and we can't specify both in IR)
Michael J. Spenceradc6cbf2012-06-18 07:00:48 +0000586 if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
Bill Wendling01ad9542012-12-30 10:32:17 +0000587 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
588 llvm::Attribute::NoInline))
Bill Wendling72390b32012-12-20 19:27:06 +0000589 F->addFnAttr(llvm::Attribute::AlwaysInline);
Eli Friedman2873aee2011-08-22 23:55:33 +0000590
Benjamin Krameree409a92012-05-12 21:10:52 +0000591 // FIXME: Communicate hot and cold attributes to LLVM more directly.
592 if (D->hasAttr<ColdAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +0000593 F->addFnAttr(llvm::Attribute::OptimizeForSize);
Benjamin Krameree409a92012-05-12 21:10:52 +0000594
Quentin Colombetaee56fa2012-11-01 23:55:47 +0000595 if (D->hasAttr<MinSizeAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +0000596 F->addFnAttr(llvm::Attribute::MinSize);
Quentin Colombetaee56fa2012-11-01 23:55:47 +0000597
Rafael Espindolac5f657f2011-01-11 00:26:26 +0000598 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
599 F->setUnnamedAddr(true);
600
Richard Smithef4d5ce2012-09-28 22:46:07 +0000601 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
602 if (MD->isVirtual())
603 F->setUnnamedAddr(true);
604
David Blaikie4e4d0842012-03-11 07:00:24 +0000605 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
Bill Wendling72390b32012-12-20 19:27:06 +0000606 F->addFnAttr(llvm::Attribute::StackProtect);
David Blaikie4e4d0842012-03-11 07:00:24 +0000607 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
Bill Wendling72390b32012-12-20 19:27:06 +0000608 F->addFnAttr(llvm::Attribute::StackProtectReq);
Will Dietz4f45bc02013-01-18 11:30:38 +0000609
610 if (SanOpts.Address) {
Alexander Potapenko89651ea2012-02-02 11:49:28 +0000611 // When AddressSanitizer is enabled, set AddressSafety attribute
612 // unless __attribute__((no_address_safety_analysis)) is used.
613 if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +0000614 F->addFnAttr(llvm::Attribute::AddressSafety);
Alexander Potapenko89651ea2012-02-02 11:49:28 +0000615 }
616
Sean Huntcf807c42010-08-18 23:23:40 +0000617 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
618 if (alignment)
619 F->setAlignment(alignment);
620
Mike Stumpfb51ddf2009-10-05 22:49:20 +0000621 // C++ ABI requires 2-byte alignment for member functions.
Mike Stumpbd6dbd12009-10-05 23:08:21 +0000622 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
623 F->setAlignment(2);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000624}
625
Mike Stump1eb44332009-09-09 15:08:12 +0000626void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000627 llvm::GlobalValue *GV) {
Anders Carlsson934176f2011-01-29 19:41:00 +0000628 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
629 setGlobalVisibility(GV, ND);
John McCall1fb0caa2010-10-22 21:05:15 +0000630 else
631 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000632
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000633 if (D->hasAttr<UsedAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000634 AddUsedGlobal(GV);
635
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000636 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000637 GV->setSection(SA->getName());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000638
639 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000640}
641
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000642void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
643 llvm::Function *F,
644 const CGFunctionInfo &FI) {
645 SetLLVMFunctionAttributes(D, FI, F);
646 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000647
648 F->setLinkage(llvm::Function::InternalLinkage);
649
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000650 SetCommonAttributes(D, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000651}
652
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000653void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000654 llvm::Function *F,
655 bool IsIncompleteFunction) {
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +0000656 if (unsigned IID = F->getIntrinsicID()) {
657 // If this is an intrinsic function, set the function's attributes
658 // to the intrinsic's attributes.
Bill Wendling50e6b182012-10-15 04:47:45 +0000659 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
660 (llvm::Intrinsic::ID)IID));
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +0000661 return;
662 }
663
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000664 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
665
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000666 if (!IsIncompleteFunction)
John McCallde5d3c72012-02-17 03:33:10 +0000667 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump1eb44332009-09-09 15:08:12 +0000668
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000669 // Only a few attributes are set on declarations; these may later be
670 // overridden by a definition.
Mike Stump1eb44332009-09-09 15:08:12 +0000671
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000672 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000673 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump1eb44332009-09-09 15:08:12 +0000674 } else if (FD->hasAttr<WeakAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000675 FD->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000676 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump1eb44332009-09-09 15:08:12 +0000677 // separate linkage types for this.
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000678 F->setLinkage(llvm::Function::ExternalWeakLinkage);
679 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000680 F->setLinkage(llvm::Function::ExternalLinkage);
John McCallaf146032010-10-30 11:50:40 +0000681
682 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
683 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
684 F->setVisibility(GetLLVMVisibility(LV.visibility()));
685 }
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000686 }
687
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000688 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000689 F->setSection(SA->getName());
Daniel Dunbar219df662008-09-08 23:44:31 +0000690}
691
Daniel Dunbar02698712009-02-13 20:29:50 +0000692void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump1eb44332009-09-09 15:08:12 +0000693 assert(!GV->isDeclaration() &&
Daniel Dunbar02698712009-02-13 20:29:50 +0000694 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000695 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000696}
697
698void CodeGenModule::EmitLLVMUsed() {
699 // Don't create llvm.used if there is no need.
Chris Lattnerad64e022009-07-17 23:57:13 +0000700 if (LLVMUsed.empty())
Daniel Dunbar02698712009-02-13 20:29:50 +0000701 return;
702
Chris Lattner35f38a22009-03-31 22:37:52 +0000703 // Convert LLVMUsed to what ConstantArray needs.
Chris Lattner0b239712012-02-06 22:16:34 +0000704 SmallVector<llvm::Constant*, 8> UsedArray;
Chris Lattner35f38a22009-03-31 22:37:52 +0000705 UsedArray.resize(LLVMUsed.size());
706 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000707 UsedArray[i] =
708 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Chris Lattner0b239712012-02-06 22:16:34 +0000709 Int8PtrTy);
Chris Lattner35f38a22009-03-31 22:37:52 +0000710 }
Mike Stump1eb44332009-09-09 15:08:12 +0000711
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000712 if (UsedArray.empty())
713 return;
Chris Lattner0b239712012-02-06 22:16:34 +0000714 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000715
716 llvm::GlobalVariable *GV =
717 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar02698712009-02-13 20:29:50 +0000718 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000719 llvm::ConstantArray::get(ATy, UsedArray),
Owen Anderson1c431b32009-07-08 19:05:04 +0000720 "llvm.used");
Daniel Dunbar02698712009-02-13 20:29:50 +0000721
722 GV->setSection("llvm.metadata");
723}
724
Douglas Gregor858afb32013-01-14 20:53:57 +0000725/// \brief Add link options implied by the given module, including modules
726/// it depends on, using a postorder walk.
727static void addLinkOptionsPostorder(llvm::LLVMContext &Context,
728 Module *Mod,
Daniel Dunbarf9d03c12013-01-17 01:35:06 +0000729 SmallVectorImpl<llvm::Value *> &Metadata,
Douglas Gregor858afb32013-01-14 20:53:57 +0000730 llvm::SmallPtrSet<Module *, 16> &Visited) {
731 // Import this module's parent.
732 if (Mod->Parent && Visited.insert(Mod->Parent)) {
733 addLinkOptionsPostorder(Context, Mod->Parent, Metadata, Visited);
734 }
735
736 // Import this module's dependencies.
737 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
738 if (Visited.insert(Mod->Imports[I-1]))
739 addLinkOptionsPostorder(Context, Mod->Imports[I-1], Metadata, Visited);
740 }
741
742 // Add linker options to link against the libraries/frameworks
743 // described by this module.
744 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
745 // FIXME: -lfoo is Unix-centric and -framework Foo is Darwin-centric.
746 // We need to know more about the linker to know how to encode these
747 // options propertly.
748
749 // Link against a framework.
750 if (Mod->LinkLibraries[I-1].IsFramework) {
751 llvm::Value *Args[2] = {
752 llvm::MDString::get(Context, "-framework"),
753 llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
754 };
755
756 Metadata.push_back(llvm::MDNode::get(Context, Args));
757 continue;
758 }
759
760 // Link against a library.
761 llvm::Value *OptString
762 = llvm::MDString::get(Context,
763 "-l" + Mod->LinkLibraries[I-1].Library);
764 Metadata.push_back(llvm::MDNode::get(Context, OptString));
765 }
766}
767
768void CodeGenModule::EmitModuleLinkOptions() {
769 // Collect the set of all of the modules we want to visit to emit link
770 // options, which is essentially the imported modules and all of their
771 // non-explicit child modules.
772 llvm::SetVector<clang::Module *> LinkModules;
773 llvm::SmallPtrSet<clang::Module *, 16> Visited;
774 SmallVector<clang::Module *, 16> Stack;
775
776 // Seed the stack with imported modules.
777 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
778 MEnd = ImportedModules.end();
779 M != MEnd; ++M) {
780 if (Visited.insert(*M))
781 Stack.push_back(*M);
782 }
783
784 // Find all of the modules to import, making a little effort to prune
785 // non-leaf modules.
786 while (!Stack.empty()) {
787 clang::Module *Mod = Stack.back();
788 Stack.pop_back();
789
790 bool AnyChildren = false;
791
792 // Visit the submodules of this module.
793 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
794 SubEnd = Mod->submodule_end();
795 Sub != SubEnd; ++Sub) {
796 // Skip explicit children; they need to be explicitly imported to be
797 // linked against.
798 if ((*Sub)->IsExplicit)
799 continue;
800
801 if (Visited.insert(*Sub)) {
802 Stack.push_back(*Sub);
803 AnyChildren = true;
804 }
805 }
806
807 // We didn't find any children, so add this module to the list of
808 // modules to link against.
809 if (!AnyChildren) {
810 LinkModules.insert(Mod);
811 }
812 }
813
814 // Add link options for all of the imported modules in reverse topological
815 // order.
Daniel Dunbarf9d03c12013-01-17 01:35:06 +0000816 SmallVector<llvm::Value *, 16> MetadataArgs;
Douglas Gregor858afb32013-01-14 20:53:57 +0000817 Visited.clear();
818 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
819 MEnd = LinkModules.end();
820 M != MEnd; ++M) {
821 if (Visited.insert(*M))
822 addLinkOptionsPostorder(getLLVMContext(), *M, MetadataArgs, Visited);
823 }
Daniel Dunbarf9d03c12013-01-17 01:35:06 +0000824 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregor858afb32013-01-14 20:53:57 +0000825
Daniel Dunbarf9d03c12013-01-17 01:35:06 +0000826 // Add the linker options metadata flag.
827 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
828 llvm::MDNode::get(getLLVMContext(), MetadataArgs));
Douglas Gregor858afb32013-01-14 20:53:57 +0000829}
830
Daniel Dunbar02698712009-02-13 20:29:50 +0000831void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000832 // Emit code for any potentially referenced deferred decls. Since a
833 // previously unused static decl may become used during the generation of code
Nick Lewyckydce67a72011-07-18 05:26:13 +0000834 // for a static function, iterate until no changes are made.
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000835
Anders Carlsson046c2942010-04-17 20:15:18 +0000836 while (!DeferredDeclsToEmit.empty() || !DeferredVTables.empty()) {
837 if (!DeferredVTables.empty()) {
838 const CXXRecordDecl *RD = DeferredVTables.back();
839 DeferredVTables.pop_back();
Charles Davis9ee494f2012-06-23 23:44:00 +0000840 getCXXABI().EmitVTables(RD);
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000841 continue;
842 }
843
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000844 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner67b00522009-03-21 09:44:56 +0000845 DeferredDeclsToEmit.pop_back();
846
John McCallc76702c2010-05-27 01:45:30 +0000847 // Check to see if we've already emitted this. This is necessary
848 // for a couple of reasons: first, decls can end up in the
849 // deferred-decls queue multiple times, and second, decls can end
850 // up with definitions in unusual ways (e.g. by an extern inline
851 // function acquiring a strong function redefinition). Just
852 // ignore these cases.
853 //
854 // TODO: That said, looking this up multiple times is very wasteful.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000855 StringRef Name = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +0000856 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner67b00522009-03-21 09:44:56 +0000857 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump1eb44332009-09-09 15:08:12 +0000858
Chris Lattner67b00522009-03-21 09:44:56 +0000859 if (!CGRef->isDeclaration())
860 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000861
John McCallc76702c2010-05-27 01:45:30 +0000862 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
863 // purposes an alias counts as a definition.
864 if (isa<llvm::GlobalAlias>(CGRef))
865 continue;
866
Chris Lattner67b00522009-03-21 09:44:56 +0000867 // Otherwise, emit the definition and move on to the next one.
868 EmitGlobalDefinition(D);
869 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000870}
871
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000872void CodeGenModule::EmitGlobalAnnotations() {
873 if (Annotations.empty())
874 return;
875
876 // Create a new global variable for the ConstantStruct in the Module.
877 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
878 Annotations[0]->getType(), Annotations.size()), Annotations);
879 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
880 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
881 "llvm.global.annotations");
882 gv->setSection(AnnotationSection);
883}
884
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000885llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000886 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
887 if (i != AnnotationStrings.end())
888 return i->second;
889
890 // Not found yet, create a new global.
Chris Lattner94010692012-02-05 02:30:40 +0000891 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000892 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
893 true, llvm::GlobalValue::PrivateLinkage, s, ".str");
894 gv->setSection(AnnotationSection);
895 gv->setUnnamedAddr(true);
896 AnnotationStrings[Str] = gv;
897 return gv;
898}
899
900llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
901 SourceManager &SM = getContext().getSourceManager();
902 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
903 if (PLoc.isValid())
904 return EmitAnnotationString(PLoc.getFilename());
905 return EmitAnnotationString(SM.getBufferName(Loc));
906}
907
908llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
909 SourceManager &SM = getContext().getSourceManager();
910 PresumedLoc PLoc = SM.getPresumedLoc(L);
911 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
912 SM.getExpansionLineNumber(L);
913 return llvm::ConstantInt::get(Int32Ty, LineNo);
914}
915
Mike Stump1eb44332009-09-09 15:08:12 +0000916llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000917 const AnnotateAttr *AA,
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000918 SourceLocation L) {
919 // Get the globals for file name, annotation, and the line number.
920 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
921 *UnitGV = EmitAnnotationUnit(L),
922 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000923
Daniel Dunbar57d5cee2009-04-14 22:41:13 +0000924 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000925 llvm::Constant *Fields[4] = {
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000926 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
927 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
928 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
929 LineNoCst
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000930 };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000931 return llvm::ConstantStruct::getAnon(Fields);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000932}
933
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000934void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
935 llvm::GlobalValue *GV) {
936 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
937 // Get the struct elements for these annotations.
938 for (specific_attr_iterator<AnnotateAttr>
939 ai = D->specific_attr_begin<AnnotateAttr>(),
940 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
941 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
942}
943
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000944bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000945 // Never defer when EmitAllDecls is specified.
David Blaikie4e4d0842012-03-11 07:00:24 +0000946 if (LangOpts.EmitAllDecls)
Daniel Dunbar73241df2009-02-13 21:18:01 +0000947 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000948
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +0000949 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar73241df2009-02-13 21:18:01 +0000950}
951
Nico Weberc5f80462012-10-11 10:13:44 +0000952llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
953 const CXXUuidofExpr* E) {
954 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
955 // well-formed.
956 StringRef Uuid;
957 if (E->isTypeOperand())
958 Uuid = CXXUuidofExpr::GetUuidAttrOfType(E->getTypeOperand())->getGuid();
959 else {
960 // Special case: __uuidof(0) means an all-zero GUID.
961 Expr *Op = E->getExprOperand();
962 if (!Op->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
963 Uuid = CXXUuidofExpr::GetUuidAttrOfType(Op->getType())->getGuid();
964 else
965 Uuid = "00000000-0000-0000-0000-000000000000";
966 }
967 std::string Name = "__uuid_" + Uuid.str();
968
969 // Look for an existing global.
970 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
971 return GV;
972
973 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
974 assert(Init && "failed to initialize as constant");
975
976 // GUIDs are assumed to be 16 bytes, spread over 4-2-2-8 bytes. However, the
977 // first field is declared as "long", which for many targets is 8 bytes.
978 // Those architectures are not supported. (With the MS abi, long is always 4
979 // bytes.)
980 llvm::Type *GuidType = getTypes().ConvertType(E->getType());
981 if (Init->getType() != GuidType) {
982 DiagnosticsEngine &Diags = getDiags();
983 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
984 "__uuidof codegen is not supported on this architecture");
985 Diags.Report(E->getExprLoc(), DiagID) << E->getSourceRange();
986 Init = llvm::UndefValue::get(GuidType);
987 }
988
989 llvm::GlobalVariable *GV = new llvm::GlobalVariable(getModule(), GuidType,
990 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Init, Name);
991 GV->setUnnamedAddr(true);
992 return GV;
993}
994
Rafael Espindola6a836702010-03-04 18:17:24 +0000995llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
996 const AliasAttr *AA = VD->getAttr<AliasAttr>();
997 assert(AA && "No alias?");
998
Chris Lattner2acc6e32011-07-18 04:24:23 +0000999 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola6a836702010-03-04 18:17:24 +00001000
Rafael Espindola6a836702010-03-04 18:17:24 +00001001 // See if there is already something with the target's name in the module.
John McCallf746aa62010-03-19 23:29:14 +00001002 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenberger4695f912012-10-16 17:45:27 +00001003 if (Entry) {
1004 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1005 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1006 }
Rafael Espindola6a836702010-03-04 18:17:24 +00001007
1008 llvm::Constant *Aliasee;
1009 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergc857ce82012-10-05 23:12:53 +00001010 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1011 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001012 /*ForVTable=*/false);
Rafael Espindola6a836702010-03-04 18:17:24 +00001013 else
John McCallf746aa62010-03-19 23:29:14 +00001014 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola6a836702010-03-04 18:17:24 +00001015 llvm::PointerType::getUnqual(DeclTy), 0);
Joerg Sonnenberger4695f912012-10-16 17:45:27 +00001016
1017 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
1018 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1019 WeakRefReferences.insert(F);
Rafael Espindola6a836702010-03-04 18:17:24 +00001020
1021 return Aliasee;
1022}
1023
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001024void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +00001025 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001026
Rafael Espindola6a836702010-03-04 18:17:24 +00001027 // Weak references don't produce any output by themselves.
1028 if (Global->hasAttr<WeakRefAttr>())
1029 return;
1030
Chris Lattnerbd532712009-03-22 21:47:11 +00001031 // If this is an alias definition (which otherwise looks like a declaration)
1032 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001033 if (Global->hasAttr<AliasAttr>())
John McCallf746aa62010-03-19 23:29:14 +00001034 return EmitAliasDefinition(GD);
Daniel Dunbar219df662008-09-08 23:44:31 +00001035
Peter Collingbourned51e43a2011-10-06 18:29:46 +00001036 // If this is CUDA, be selective about which declarations we emit.
David Blaikie4e4d0842012-03-11 07:00:24 +00001037 if (LangOpts.CUDA) {
Peter Collingbourned51e43a2011-10-06 18:29:46 +00001038 if (CodeGenOpts.CUDAIsDevice) {
1039 if (!Global->hasAttr<CUDADeviceAttr>() &&
1040 !Global->hasAttr<CUDAGlobalAttr>() &&
1041 !Global->hasAttr<CUDAConstantAttr>() &&
1042 !Global->hasAttr<CUDASharedAttr>())
1043 return;
1044 } else {
1045 if (!Global->hasAttr<CUDAHostAttr>() && (
1046 Global->hasAttr<CUDADeviceAttr>() ||
1047 Global->hasAttr<CUDAConstantAttr>() ||
1048 Global->hasAttr<CUDASharedAttr>()))
1049 return;
1050 }
1051 }
1052
Chris Lattner67b00522009-03-21 09:44:56 +00001053 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +00001054 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +00001055 // Forward declarations are emitted lazily on first use.
Nick Lewyckydce67a72011-07-18 05:26:13 +00001056 if (!FD->doesThisDeclarationHaveABody()) {
1057 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1058 return;
1059
1060 const FunctionDecl *InlineDefinition = 0;
1061 FD->getBody(InlineDefinition);
1062
Chris Lattner5f9e2722011-07-23 10:55:15 +00001063 StringRef MangledName = getMangledName(GD);
Benjamin Kramer7e423922012-03-24 18:22:12 +00001064 DeferredDecls.erase(MangledName);
Nick Lewyckydce67a72011-07-18 05:26:13 +00001065 EmitGlobalDefinition(InlineDefinition);
Daniel Dunbar73241df2009-02-13 21:18:01 +00001066 return;
Nick Lewyckydce67a72011-07-18 05:26:13 +00001067 }
Daniel Dunbar02698712009-02-13 20:29:50 +00001068 } else {
1069 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001070 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1071
Douglas Gregora9a55c02010-02-06 05:15:45 +00001072 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00001073 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +00001074 }
1075
Chris Lattner67b00522009-03-21 09:44:56 +00001076 // Defer code generation when possible if this is a static definition, inline
1077 // function etc. These we only want to emit if they are used.
Chris Lattner4357a822010-04-13 17:39:09 +00001078 if (!MayDeferGeneration(Global)) {
1079 // Emit the definition if it can't be deferred.
1080 EmitGlobalDefinition(GD);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001081 return;
1082 }
John McCallbf40cb52010-07-15 23:40:35 +00001083
1084 // If we're deferring emission of a C++ variable with an
1085 // initializer, remember the order in which it appeared in the file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001086 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCallbf40cb52010-07-15 23:40:35 +00001087 cast<VarDecl>(Global)->hasInit()) {
1088 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1089 CXXGlobalInits.push_back(0);
1090 }
Chris Lattner4357a822010-04-13 17:39:09 +00001091
1092 // If the value has already been used, add it directly to the
1093 // DeferredDeclsToEmit list.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001094 StringRef MangledName = getMangledName(GD);
Chris Lattner4357a822010-04-13 17:39:09 +00001095 if (GetGlobalValue(MangledName))
1096 DeferredDeclsToEmit.push_back(GD);
1097 else {
1098 // Otherwise, remember that we saw a deferred decl with this name. The
1099 // first use of the mangled name will cause it to move into
1100 // DeferredDeclsToEmit.
1101 DeferredDecls[MangledName] = GD;
1102 }
Nate Begeman4c13b7a2008-04-20 06:29:50 +00001103}
1104
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001105namespace {
1106 struct FunctionIsDirectlyRecursive :
1107 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1108 const StringRef Name;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001109 const Builtin::Context &BI;
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001110 bool Result;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001111 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1112 Name(N), BI(C), Result(false) {
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001113 }
1114 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1115
1116 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001117 const FunctionDecl *FD = E->getDirectCallee();
1118 if (!FD)
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001119 return true;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001120 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1121 if (Attr && Name == Attr->getLabel()) {
1122 Result = true;
1123 return false;
1124 }
1125 unsigned BuiltinID = FD->getBuiltinID();
1126 if (!BuiltinID)
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001127 return true;
Nick Lewyckyf6b56372012-01-18 03:41:19 +00001128 StringRef BuiltinName = BI.GetName(BuiltinID);
1129 if (BuiltinName.startswith("__builtin_") &&
1130 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001131 Result = true;
1132 return false;
1133 }
1134 return true;
1135 }
1136 };
1137}
1138
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001139// isTriviallyRecursive - Check if this function calls another
1140// decl that, because of the asm attribute or the other decl being a builtin,
1141// ends up pointing to itself.
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001142bool
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001143CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1144 StringRef Name;
1145 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky22afacc2012-01-18 01:50:13 +00001146 // asm labels are a special kind of mangling we have to support.
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001147 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1148 if (!Attr)
1149 return false;
1150 Name = Attr->getLabel();
1151 } else {
1152 Name = FD->getName();
1153 }
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001154
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001155 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1156 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001157 return Walker.Result;
1158}
1159
1160bool
1161CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
1162 if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
1163 return true;
Rafael Espindolacc4889f2011-10-28 20:43:56 +00001164 if (CodeGenOpts.OptimizationLevel == 0 &&
Michael J. Spenceradc6cbf2012-06-18 07:00:48 +00001165 !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001166 return false;
1167 // PR9614. Avoid cases where the source code is lying to us. An available
1168 // externally function should have an equivalent function somewhere else,
1169 // but a function that calls itself is clearly not equivalent to the real
1170 // implementation.
1171 // This happens in glibc's btowc and in some configure checks.
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001172 return !isTriviallyRecursive(F);
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001173}
1174
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001175void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +00001176 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001177
Dan Gohmancb421fa2010-04-19 16:39:44 +00001178 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson8e2efcc2009-10-27 14:32:27 +00001179 Context.getSourceManager(),
1180 "Generating code for declaration");
1181
Douglas Gregor44eac332010-07-13 06:02:28 +00001182 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1183 // At -O0, don't generate IR for functions with available_externally
1184 // linkage.
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001185 if (!shouldEmitFunction(Function))
Douglas Gregor44eac332010-07-13 06:02:28 +00001186 return;
Anders Carlsson7270ee42010-03-23 04:31:31 +00001187
Douglas Gregor44eac332010-07-13 06:02:28 +00001188 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001189 // Make sure to emit the definition(s) before we emit the thunks.
1190 // This is necessary for the generation of certain thunks.
1191 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1192 EmitCXXConstructor(CD, GD.getCtorType());
1193 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1194 EmitCXXDestructor(DD, GD.getDtorType());
1195 else
1196 EmitGlobalFunctionDefinition(GD);
1197
Douglas Gregor44eac332010-07-13 06:02:28 +00001198 if (Method->isVirtual())
1199 getVTables().EmitThunks(GD);
1200
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001201 return;
Douglas Gregor44eac332010-07-13 06:02:28 +00001202 }
Chris Lattnerb5e81562010-04-13 17:57:11 +00001203
Chris Lattnerb5e81562010-04-13 17:57:11 +00001204 return EmitGlobalFunctionDefinition(GD);
Douglas Gregor44eac332010-07-13 06:02:28 +00001205 }
Chris Lattnerb5e81562010-04-13 17:57:11 +00001206
1207 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1208 return EmitGlobalVarDefinition(VD);
Chris Lattner4357a822010-04-13 17:39:09 +00001209
David Blaikieb219cfc2011-09-23 05:06:16 +00001210 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001211}
1212
Chris Lattner74391b42009-03-22 21:03:39 +00001213/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1214/// module, create and return an llvm Function with the specified type. If there
1215/// is something in the module with the specified name, return it potentially
1216/// bitcasted to the right type.
1217///
1218/// If D is non-null, it specifies a decl that correspond to this. This is used
1219/// to set the attributes on the function when it is first created.
John McCallf746aa62010-03-19 23:29:14 +00001220llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001221CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001222 llvm::Type *Ty,
John McCallf85e1932011-06-15 23:02:42 +00001223 GlobalDecl D, bool ForVTable,
Bill Wendling72390b32012-12-20 19:27:06 +00001224 llvm::Attribute ExtraAttrs) {
Chris Lattner0558e792009-03-21 09:25:43 +00001225 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +00001226 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner0558e792009-03-21 09:25:43 +00001227 if (Entry) {
Benjamin Kramerd48bcb22012-08-22 15:37:55 +00001228 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola6a836702010-03-04 18:17:24 +00001229 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
1230 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +00001231 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +00001232 }
1233
Chris Lattner0558e792009-03-21 09:25:43 +00001234 if (Entry->getType()->getElementType() == Ty)
1235 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +00001236
Chris Lattner0558e792009-03-21 09:25:43 +00001237 // Make sure the result is of the correct type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001238 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattner0558e792009-03-21 09:25:43 +00001239 }
Mike Stump1eb44332009-09-09 15:08:12 +00001240
Eli Friedman654ad402009-11-09 05:07:37 +00001241 // This function doesn't have a complete type (for example, the return
1242 // type is an incomplete struct). Use a fake type instead, and make
1243 // sure not to try to set attributes.
1244 bool IsIncompleteFunction = false;
John McCall784f2112010-04-28 00:00:30 +00001245
Chris Lattner2acc6e32011-07-18 04:24:23 +00001246 llvm::FunctionType *FTy;
John McCall784f2112010-04-28 00:00:30 +00001247 if (isa<llvm::FunctionType>(Ty)) {
1248 FTy = cast<llvm::FunctionType>(Ty);
1249 } else {
John McCall0774cb82011-05-15 01:53:33 +00001250 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedman654ad402009-11-09 05:07:37 +00001251 IsIncompleteFunction = true;
1252 }
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001253
John McCall784f2112010-04-28 00:00:30 +00001254 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedman654ad402009-11-09 05:07:37 +00001255 llvm::Function::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +00001256 MangledName, &getModule());
1257 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedman654ad402009-11-09 05:07:37 +00001258 if (D.getDecl())
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +00001259 SetFunctionAttributes(D, F, IsIncompleteFunction);
Bill Wendling909b6de2013-01-23 00:21:06 +00001260 if (ExtraAttrs.hasAttributes()) {
1261 llvm::AttrBuilder B(ExtraAttrs);
1262 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1263 llvm::AttributeSet::get(VMContext,
1264 llvm::AttributeSet::FunctionIndex,
1265 B));
1266 }
Eli Friedman654ad402009-11-09 05:07:37 +00001267
Chris Lattner67b00522009-03-21 09:44:56 +00001268 // This is the first use or definition of a mangled name. If there is a
1269 // deferred decl with this name, remember that we need to emit it at the end
1270 // of the file.
John McCallf746aa62010-03-19 23:29:14 +00001271 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +00001272 if (DDI != DeferredDecls.end()) {
1273 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1274 // list, and remove it from DeferredDecls (since we don't need it anymore).
1275 DeferredDeclsToEmit.push_back(DDI->second);
1276 DeferredDecls.erase(DDI);
John McCallbfdcdc82010-12-15 04:00:32 +00001277
1278 // Otherwise, there are cases we have to worry about where we're
1279 // using a declaration for which we must emit a definition but where
1280 // we might not find a top-level definition:
1281 // - member functions defined inline in their classes
1282 // - friend functions defined inline in some class
1283 // - special member functions with implicit definitions
1284 // If we ever change our AST traversal to walk into class methods,
1285 // this will be unnecessary.
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001286 //
1287 // We also don't emit a definition for a function if it's going to be an entry
1288 // in a vtable, unless it's already marked as used.
David Blaikie4e4d0842012-03-11 07:00:24 +00001289 } else if (getLangOpts().CPlusPlus && D.getDecl()) {
John McCallbfdcdc82010-12-15 04:00:32 +00001290 // Look for a declaration that's lexically in a record.
1291 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
Eli Friedmanb135f0f2012-07-02 21:05:30 +00001292 FD = FD->getMostRecentDecl();
John McCallbfdcdc82010-12-15 04:00:32 +00001293 do {
1294 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001295 if (FD->isImplicit() && !ForVTable) {
John McCallbfdcdc82010-12-15 04:00:32 +00001296 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
Douglas Gregora29bf412011-02-09 02:03:05 +00001297 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +00001298 break;
Sean Hunt10620eb2011-05-06 20:44:56 +00001299 } else if (FD->doesThisDeclarationHaveABody()) {
Douglas Gregora29bf412011-02-09 02:03:05 +00001300 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +00001301 break;
1302 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00001303 }
Douglas Gregoref96ee02012-01-14 16:38:05 +00001304 FD = FD->getPreviousDecl();
John McCallbfdcdc82010-12-15 04:00:32 +00001305 } while (FD);
Chris Lattner67b00522009-03-21 09:44:56 +00001306 }
Mike Stump1eb44332009-09-09 15:08:12 +00001307
John McCall784f2112010-04-28 00:00:30 +00001308 // Make sure the result is of the requested type.
1309 if (!IsIncompleteFunction) {
1310 assert(F->getType()->getElementType() == Ty);
1311 return F;
1312 }
1313
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001314 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCall784f2112010-04-28 00:00:30 +00001315 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +00001316}
1317
Chris Lattner74391b42009-03-22 21:03:39 +00001318/// GetAddrOfFunction - Return the address of the given function. If Ty is
1319/// non-null, then this function will use the specified type if it has to
1320/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001321llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001322 llvm::Type *Ty,
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001323 bool ForVTable) {
Chris Lattner74391b42009-03-22 21:03:39 +00001324 // If there was no specific requested type, just convert it now.
1325 if (!Ty)
Anders Carlsson4a6835e2009-09-10 23:38:47 +00001326 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001327
Chris Lattner5f9e2722011-07-23 10:55:15 +00001328 StringRef MangledName = getMangledName(GD);
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001329 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
Chris Lattner74391b42009-03-22 21:03:39 +00001330}
Eli Friedman77ba7082008-05-30 19:50:47 +00001331
Chris Lattner74391b42009-03-22 21:03:39 +00001332/// CreateRuntimeFunction - Create a new runtime function with the specified
1333/// type and name.
1334llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001335CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001336 StringRef Name,
Bill Wendling72390b32012-12-20 19:27:06 +00001337 llvm::Attribute ExtraAttrs) {
John McCallf85e1932011-06-15 23:02:42 +00001338 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1339 ExtraAttrs);
Chris Lattner74391b42009-03-22 21:03:39 +00001340}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001341
Richard Smitha9b21d22012-02-17 06:48:11 +00001342/// isTypeConstant - Determine whether an object of this type can be emitted
1343/// as a constant.
1344///
1345/// If ExcludeCtor is true, the duration when the object's constructor runs
1346/// will not be considered. The caller will need to verify that the object is
1347/// not written to during its construction.
1348bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1349 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedman20e098b2009-12-11 21:23:03 +00001350 return false;
Richard Smitha9b21d22012-02-17 06:48:11 +00001351
David Blaikie4e4d0842012-03-11 07:00:24 +00001352 if (Context.getLangOpts().CPlusPlus) {
Richard Smitha9b21d22012-02-17 06:48:11 +00001353 if (const CXXRecordDecl *Record
1354 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1355 return ExcludeCtor && !Record->hasMutableFields() &&
1356 Record->hasTrivialDestructor();
Eli Friedman20e098b2009-12-11 21:23:03 +00001357 }
Richard Smitha9b21d22012-02-17 06:48:11 +00001358
Eli Friedman20e098b2009-12-11 21:23:03 +00001359 return true;
1360}
1361
Chris Lattner74391b42009-03-22 21:03:39 +00001362/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1363/// create and return an llvm GlobalVariable with the specified type. If there
1364/// is something in the module with the specified name, return it potentially
1365/// bitcasted to the right type.
1366///
1367/// If D is non-null, it specifies a decl that correspond to this. This is used
1368/// to set the attributes on the global when it is first created.
John McCallf746aa62010-03-19 23:29:14 +00001369llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001370CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001371 llvm::PointerType *Ty,
Rafael Espindolac532b502011-01-18 21:07:57 +00001372 const VarDecl *D,
1373 bool UnnamedAddr) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +00001374 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +00001375 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +00001376 if (Entry) {
Benjamin Kramerd48bcb22012-08-22 15:37:55 +00001377 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola6a836702010-03-04 18:17:24 +00001378 if (D && !D->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +00001379 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +00001380 }
1381
Rafael Espindolac532b502011-01-18 21:07:57 +00001382 if (UnnamedAddr)
1383 Entry->setUnnamedAddr(true);
1384
Chris Lattner74391b42009-03-22 21:03:39 +00001385 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +00001386 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +00001387
Chris Lattner99b53612009-03-21 08:03:33 +00001388 // Make sure the result is of the correct type.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001389 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +00001390 }
Mike Stump1eb44332009-09-09 15:08:12 +00001391
Chris Lattner67b00522009-03-21 09:44:56 +00001392 // This is the first use or definition of a mangled name. If there is a
1393 // deferred decl with this name, remember that we need to emit it at the end
1394 // of the file.
John McCallf746aa62010-03-19 23:29:14 +00001395 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +00001396 if (DDI != DeferredDecls.end()) {
1397 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1398 // list, and remove it from DeferredDecls (since we don't need it anymore).
1399 DeferredDeclsToEmit.push_back(DDI->second);
1400 DeferredDecls.erase(DDI);
1401 }
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001403 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
Mike Stump1eb44332009-09-09 15:08:12 +00001404 llvm::GlobalVariable *GV =
1405 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +00001406 llvm::GlobalValue::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +00001407 0, MangledName, 0,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +00001408 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
Chris Lattner99b53612009-03-21 08:03:33 +00001409
1410 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +00001411 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001412 // FIXME: This code is overly simple and should be merged with other global
1413 // handling.
Richard Smitha9b21d22012-02-17 06:48:11 +00001414 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner99b53612009-03-21 08:03:33 +00001415
John McCall110e8e52010-10-29 22:22:43 +00001416 // Set linkage and visibility in case we never see a definition.
John McCallaf146032010-10-30 11:50:40 +00001417 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1418 if (LV.linkage() != ExternalLinkage) {
John McCall15e310a2011-02-19 02:53:41 +00001419 // Don't set internal linkage on declarations.
John McCall110e8e52010-10-29 22:22:43 +00001420 } else {
1421 if (D->hasAttr<DLLImportAttr>())
1422 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001423 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
John McCall110e8e52010-10-29 22:22:43 +00001424 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner99b53612009-03-21 08:03:33 +00001425
John McCallaf146032010-10-30 11:50:40 +00001426 // Set visibility on a declaration only if it's explicit.
1427 if (LV.visibilityExplicit())
1428 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
John McCall110e8e52010-10-29 22:22:43 +00001429 }
Eli Friedman56ebe502009-04-19 21:05:03 +00001430
Hans Wennborgde981f32012-06-28 08:01:44 +00001431 if (D->isThreadSpecified())
1432 setTLSMode(GV, *D);
Chris Lattner74391b42009-03-22 21:03:39 +00001433 }
Mike Stump1eb44332009-09-09 15:08:12 +00001434
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001435 if (AddrSpace != Ty->getAddressSpace())
1436 return llvm::ConstantExpr::getBitCast(GV, Ty);
1437 else
1438 return GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001439}
1440
Chris Lattner74391b42009-03-22 21:03:39 +00001441
Anders Carlsson3bd62022011-01-29 18:20:20 +00001442llvm::GlobalVariable *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001443CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001444 llvm::Type *Ty,
Anders Carlsson3bd62022011-01-29 18:20:20 +00001445 llvm::GlobalValue::LinkageTypes Linkage) {
1446 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1447 llvm::GlobalVariable *OldGV = 0;
1448
1449
1450 if (GV) {
1451 // Check if the variable has the right type.
1452 if (GV->getType()->getElementType() == Ty)
1453 return GV;
1454
1455 // Because C++ name mangling, the only way we can end up with an already
1456 // existing global with the same name is if it has been declared extern "C".
Nico Weberc5f80462012-10-11 10:13:44 +00001457 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlsson3bd62022011-01-29 18:20:20 +00001458 OldGV = GV;
1459 }
1460
1461 // Create a new variable.
1462 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1463 Linkage, 0, Name);
1464
1465 if (OldGV) {
1466 // Replace occurrences of the old variable if needed.
1467 GV->takeName(OldGV);
1468
1469 if (!OldGV->use_empty()) {
1470 llvm::Constant *NewPtrForOldDecl =
1471 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1472 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1473 }
1474
1475 OldGV->eraseFromParent();
1476 }
1477
1478 return GV;
1479}
1480
Chris Lattner74391b42009-03-22 21:03:39 +00001481/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1482/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher0ff258b2012-04-16 23:55:04 +00001483/// then it will be created with the specified type instead of whatever the
Chris Lattner74391b42009-03-22 21:03:39 +00001484/// normal requested type would be.
1485llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001486 llvm::Type *Ty) {
Chris Lattner74391b42009-03-22 21:03:39 +00001487 assert(D->hasGlobalStorage() && "Not a global variable");
1488 QualType ASTTy = D->getType();
1489 if (Ty == 0)
1490 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001491
Chris Lattner2acc6e32011-07-18 04:24:23 +00001492 llvm::PointerType *PTy =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001493 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCallf746aa62010-03-19 23:29:14 +00001494
Chris Lattner5f9e2722011-07-23 10:55:15 +00001495 StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001496 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattner74391b42009-03-22 21:03:39 +00001497}
1498
1499/// CreateRuntimeVariable - Create a new runtime global variable with the
1500/// specified type and name.
1501llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001502CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001503 StringRef Name) {
John McCall1de4d4e2011-04-07 08:22:57 +00001504 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
Rafael Espindolac532b502011-01-18 21:07:57 +00001505 true);
Chris Lattner74391b42009-03-22 21:03:39 +00001506}
1507
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001508void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1509 assert(!D->getInit() && "Cannot emit definite definitions here!");
1510
Douglas Gregor7520bd12009-04-21 19:28:58 +00001511 if (MayDeferGeneration(D)) {
1512 // If we have not seen a reference to this variable yet, place it
1513 // into the deferred declarations table to be emitted if needed
1514 // later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001515 StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001516 if (!GetGlobalValue(MangledName)) {
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001517 DeferredDecls[MangledName] = D;
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001518 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +00001519 }
1520 }
1521
1522 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001523 EmitGlobalVarDefinition(D);
1524}
1525
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001526void CodeGenModule::EmitVTable(CXXRecordDecl *Class, bool DefinitionRequired) {
1527 if (DefinitionRequired)
Charles Davis9ee494f2012-06-23 23:44:00 +00001528 getCXXABI().EmitVTables(Class);
Douglas Gregor6fb745b2010-05-13 16:44:06 +00001529}
1530
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001531llvm::GlobalVariable::LinkageTypes
Anders Carlsson046c2942010-04-17 20:15:18 +00001532CodeGenModule::getVTableLinkage(const CXXRecordDecl *RD) {
Eli Friedmancb5d2d02011-06-10 21:53:06 +00001533 if (RD->getLinkage() != ExternalLinkage)
Douglas Gregordffb8012010-01-06 22:00:56 +00001534 return llvm::GlobalVariable::InternalLinkage;
1535
1536 if (const CXXMethodDecl *KeyFunction
1537 = RD->getASTContext().getKeyFunction(RD)) {
1538 // If this class has a key function, use that to determine the linkage of
1539 // the vtable.
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001540 const FunctionDecl *Def = 0;
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00001541 if (KeyFunction->hasBody(Def))
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001542 KeyFunction = cast<CXXMethodDecl>(Def);
Douglas Gregordffb8012010-01-06 22:00:56 +00001543
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001544 switch (KeyFunction->getTemplateSpecializationKind()) {
1545 case TSK_Undeclared:
1546 case TSK_ExplicitSpecialization:
Anders Carlsson6d7f8472011-01-30 20:45:54 +00001547 // When compiling with optimizations turned on, we emit all vtables,
1548 // even if the key function is not defined in the current translation
1549 // unit. If this is the case, use available_externally linkage.
1550 if (!Def && CodeGenOpts.OptimizationLevel)
1551 return llvm::GlobalVariable::AvailableExternallyLinkage;
1552
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001553 if (KeyFunction->isInlined())
David Blaikie4e4d0842012-03-11 07:00:24 +00001554 return !Context.getLangOpts().AppleKext ?
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001555 llvm::GlobalVariable::LinkOnceODRLinkage :
1556 llvm::Function::InternalLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001557
1558 return llvm::GlobalVariable::ExternalLinkage;
1559
1560 case TSK_ImplicitInstantiation:
David Blaikie4e4d0842012-03-11 07:00:24 +00001561 return !Context.getLangOpts().AppleKext ?
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001562 llvm::GlobalVariable::LinkOnceODRLinkage :
1563 llvm::Function::InternalLinkage;
Anders Carlssonf502d932011-01-24 00:46:19 +00001564
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001565 case TSK_ExplicitInstantiationDefinition:
David Blaikie4e4d0842012-03-11 07:00:24 +00001566 return !Context.getLangOpts().AppleKext ?
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001567 llvm::GlobalVariable::WeakODRLinkage :
1568 llvm::Function::InternalLinkage;
Anders Carlssonf502d932011-01-24 00:46:19 +00001569
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001570 case TSK_ExplicitInstantiationDeclaration:
1571 // FIXME: Use available_externally linkage. However, this currently
1572 // breaks LLVM's build due to undefined symbols.
1573 // return llvm::GlobalVariable::AvailableExternallyLinkage;
David Blaikie4e4d0842012-03-11 07:00:24 +00001574 return !Context.getLangOpts().AppleKext ?
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001575 llvm::GlobalVariable::LinkOnceODRLinkage :
1576 llvm::Function::InternalLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001577 }
Douglas Gregordffb8012010-01-06 22:00:56 +00001578 }
1579
David Blaikie4e4d0842012-03-11 07:00:24 +00001580 if (Context.getLangOpts().AppleKext)
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001581 return llvm::Function::InternalLinkage;
1582
Douglas Gregordffb8012010-01-06 22:00:56 +00001583 switch (RD->getTemplateSpecializationKind()) {
1584 case TSK_Undeclared:
1585 case TSK_ExplicitSpecialization:
1586 case TSK_ImplicitInstantiation:
Douglas Gregordffb8012010-01-06 22:00:56 +00001587 // FIXME: Use available_externally linkage. However, this currently
1588 // breaks LLVM's build due to undefined symbols.
1589 // return llvm::GlobalVariable::AvailableExternallyLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001590 case TSK_ExplicitInstantiationDeclaration:
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001591 return llvm::GlobalVariable::LinkOnceODRLinkage;
Fariborz Jahanian142f9e92011-02-04 00:01:24 +00001592
1593 case TSK_ExplicitInstantiationDefinition:
Fariborz Jahanian53bad4e2011-02-04 00:32:39 +00001594 return llvm::GlobalVariable::WeakODRLinkage;
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001595 }
David Blaikie30263482012-01-20 21:50:17 +00001596
1597 llvm_unreachable("Invalid TemplateSpecializationKind!");
Douglas Gregor4b0f21c2010-01-06 20:27:16 +00001598}
1599
Chris Lattner2acc6e32011-07-18 04:24:23 +00001600CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Ken Dyck06f486e2011-01-18 02:01:14 +00001601 return Context.toCharUnitsFromBits(
Micah Villmow25a6a842012-10-08 16:25:52 +00001602 TheDataLayout.getTypeStoreSizeInBits(Ty));
Ken Dyck687cc4a2010-01-26 13:48:07 +00001603}
1604
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001605llvm::Constant *
1606CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
1607 const Expr *rawInit) {
1608 ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
1609 if (const ExprWithCleanups *withCleanups =
1610 dyn_cast<ExprWithCleanups>(rawInit)) {
1611 cleanups = withCleanups->getObjects();
1612 rawInit = withCleanups->getSubExpr();
1613 }
1614
1615 const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
1616 if (!init || !init->initializesStdInitializerList() ||
1617 init->getNumInits() == 0)
1618 return 0;
1619
1620 ASTContext &ctx = getContext();
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001621 unsigned numInits = init->getNumInits();
Sebastian Redl062a82c2012-02-27 23:20:01 +00001622 // FIXME: This check is here because we would otherwise silently miscompile
1623 // nested global std::initializer_lists. Better would be to have a real
1624 // implementation.
1625 for (unsigned i = 0; i < numInits; ++i) {
1626 const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1627 if (inner && inner->initializesStdInitializerList()) {
1628 ErrorUnsupported(inner, "nested global std::initializer_list");
1629 return 0;
1630 }
1631 }
1632
1633 // Synthesize a fake VarDecl for the array and initialize that.
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001634 QualType elementType = init->getInit(0)->getType();
1635 llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
1636 QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
1637 ArrayType::Normal, 0);
1638
1639 IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
1640 TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
1641 arrayType, D->getLocation());
1642 VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
1643 D->getDeclContext()),
1644 D->getLocStart(), D->getLocation(),
1645 name, arrayType, sourceInfo,
1646 SC_Static, SC_Static);
1647
1648 // Now clone the InitListExpr to initialize the array instead.
1649 // Incredible hack: we want to use the existing InitListExpr here, so we need
1650 // to tell it that it no longer initializes a std::initializer_list.
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001651 ArrayRef<Expr*> Inits(const_cast<InitListExpr*>(init)->getInits(),
1652 init->getNumInits());
1653 Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), Inits,
1654 init->getRBraceLoc());
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001655 arrayInit->setType(arrayType);
1656
1657 if (!cleanups.empty())
1658 arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
1659
1660 backingArray->setInit(arrayInit);
1661
1662 // Emit the definition of the array.
1663 EmitGlobalVarDefinition(backingArray);
1664
1665 // Inspect the initializer list to validate it and determine its type.
1666 // FIXME: doing this every time is probably inefficient; caching would be nice
1667 RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
1668 RecordDecl::field_iterator field = record->field_begin();
1669 if (field == record->field_end()) {
1670 ErrorUnsupported(D, "weird std::initializer_list");
1671 return 0;
1672 }
1673 QualType elementPtr = ctx.getPointerType(elementType.withConst());
1674 // Start pointer.
1675 if (!ctx.hasSameType(field->getType(), elementPtr)) {
1676 ErrorUnsupported(D, "weird std::initializer_list");
1677 return 0;
1678 }
1679 ++field;
1680 if (field == record->field_end()) {
1681 ErrorUnsupported(D, "weird std::initializer_list");
1682 return 0;
1683 }
1684 bool isStartEnd = false;
1685 if (ctx.hasSameType(field->getType(), elementPtr)) {
1686 // End pointer.
1687 isStartEnd = true;
1688 } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
1689 ErrorUnsupported(D, "weird std::initializer_list");
1690 return 0;
1691 }
1692
1693 // Now build an APValue representing the std::initializer_list.
1694 APValue initListValue(APValue::UninitStruct(), 0, 2);
1695 APValue &startField = initListValue.getStructField(0);
1696 APValue::LValuePathEntry startOffsetPathEntry;
1697 startOffsetPathEntry.ArrayIndex = 0;
1698 startField = APValue(APValue::LValueBase(backingArray),
1699 CharUnits::fromQuantity(0),
1700 llvm::makeArrayRef(startOffsetPathEntry),
1701 /*IsOnePastTheEnd=*/false, 0);
1702
1703 if (isStartEnd) {
1704 APValue &endField = initListValue.getStructField(1);
1705 APValue::LValuePathEntry endOffsetPathEntry;
1706 endOffsetPathEntry.ArrayIndex = numInits;
1707 endField = APValue(APValue::LValueBase(backingArray),
1708 ctx.getTypeSizeInChars(elementType) * numInits,
1709 llvm::makeArrayRef(endOffsetPathEntry),
1710 /*IsOnePastTheEnd=*/true, 0);
1711 } else {
1712 APValue &sizeField = initListValue.getStructField(1);
1713 sizeField = APValue(llvm::APSInt(numElements));
1714 }
1715
1716 // Emit the constant for the initializer_list.
Richard Smitha3ca41f2012-03-02 23:27:11 +00001717 llvm::Constant *llvmInit =
1718 EmitConstantValueForMemory(initListValue, D->getType());
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001719 assert(llvmInit && "failed to initialize as constant");
1720 return llvmInit;
1721}
1722
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001723unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1724 unsigned AddrSpace) {
1725 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1726 if (D->hasAttr<CUDAConstantAttr>())
1727 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1728 else if (D->hasAttr<CUDASharedAttr>())
1729 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1730 else
1731 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1732 }
1733
1734 return AddrSpace;
1735}
1736
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001737void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +00001738 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +00001739 QualType ASTTy = D->getType();
Richard Smith7ca48502012-02-13 22:16:19 +00001740 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1741 bool NeedsGlobalCtor = false;
1742 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Richard Smith2d6a5672012-01-14 04:30:29 +00001744 const VarDecl *InitDecl;
1745 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001746
Anders Carlsson3bb92692010-01-26 17:43:42 +00001747 if (!InitExpr) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +00001748 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001749 // implicitly initialized with { 0 }.
1750 //
1751 // Note that tentative definitions are only emitted at the end of
1752 // a translation unit, so they should never have incomplete
1753 // type. In addition, EmitTentativeDefinition makes sure that we
1754 // never attempt to emit a tentative definition if a real one
1755 // exists. A use may still exists, however, so we still may need
1756 // to do a RAUW.
1757 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonb0d0ea02009-08-02 21:18:22 +00001758 Init = EmitNullConstant(D->getType());
Eli Friedman77ba7082008-05-30 19:50:47 +00001759 } else {
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001760 // If this is a std::initializer_list, emit the special initializer.
1761 Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
1762 // An empty init list will perform zero-initialization, which happens
1763 // to be exactly what we want.
1764 // FIXME: It does so in a global constructor, which is *not* what we
1765 // want.
1766
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001767 if (!Init) {
1768 initializedGlobalDecl = GlobalDecl(D);
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001769 Init = EmitConstantInit(*InitDecl);
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001770 }
Eli Friedman6e656f42009-02-20 01:18:21 +00001771 if (!Init) {
Anders Carlsson3bb92692010-01-26 17:43:42 +00001772 QualType T = InitExpr->getType();
Douglas Gregorc446d182010-05-05 20:15:55 +00001773 if (D->getType()->isReferenceType())
1774 T = D->getType();
Richard Smith2d6a5672012-01-14 04:30:29 +00001775
David Blaikie4e4d0842012-03-11 07:00:24 +00001776 if (getLangOpts().CPlusPlus) {
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001777 Init = EmitNullConstant(T);
Richard Smith7ca48502012-02-13 22:16:19 +00001778 NeedsGlobalCtor = true;
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001779 } else {
1780 ErrorUnsupported(D, "static initializer");
1781 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1782 }
John McCallbf40cb52010-07-15 23:40:35 +00001783 } else {
1784 // We don't need an initializer, so remove the entry for the delayed
Richard Smith7ca48502012-02-13 22:16:19 +00001785 // initializer position (just in case this entry was delayed) if we
1786 // also don't need to register a destructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00001787 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCallbf40cb52010-07-15 23:40:35 +00001788 DelayedCXXInitPosition.erase(D);
Eli Friedman6e656f42009-02-20 01:18:21 +00001789 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001790 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001791
Chris Lattner2acc6e32011-07-18 04:24:23 +00001792 llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +00001793 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump1eb44332009-09-09 15:08:12 +00001794
Chris Lattner570585c2009-03-21 09:16:30 +00001795 // Strip off a bitcast if we got one back.
1796 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001797 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1798 // all zero index gep.
1799 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner570585c2009-03-21 09:16:30 +00001800 Entry = CE->getOperand(0);
1801 }
Mike Stump1eb44332009-09-09 15:08:12 +00001802
Chris Lattner570585c2009-03-21 09:16:30 +00001803 // Entry is now either a Function or GlobalVariable.
1804 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001805
Chris Lattner570585c2009-03-21 09:16:30 +00001806 // We have a definition after a declaration with the wrong type.
1807 // We must make a new GlobalVariable* and update everything that used OldGV
1808 // (a declaration or tentative definition) with the new GlobalVariable*
1809 // (which will be a definition).
1810 //
1811 // This happens if there is a prototype for a global (e.g.
1812 // "extern int x[];") and then a definition of a different type (e.g.
1813 // "int x[10];"). This also happens when an initializer has a different type
1814 // from the type of the global (this happens with unions).
Chris Lattner570585c2009-03-21 09:16:30 +00001815 if (GV == 0 ||
1816 GV->getType()->getElementType() != InitType ||
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001817 GV->getType()->getAddressSpace() !=
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001818 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001819
John McCallf746aa62010-03-19 23:29:14 +00001820 // Move the old entry aside so that we'll create a new one.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001821 Entry->setName(StringRef());
Daniel Dunbar232350d2009-02-19 05:36:41 +00001822
Chris Lattner570585c2009-03-21 09:16:30 +00001823 // Make a new global with the correct type, this is now guaranteed to work.
1824 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +00001825
Eli Friedman77ba7082008-05-30 19:50:47 +00001826 // Replace all uses of the old global with the new global
Mike Stump1eb44332009-09-09 15:08:12 +00001827 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001828 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner570585c2009-03-21 09:16:30 +00001829 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +00001830
1831 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +00001832 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +00001833 }
Devang Patel8e53e722007-10-26 16:31:40 +00001834
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001835 if (D->hasAttr<AnnotateAttr>())
1836 AddGlobalAnnotations(D, GV);
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001837
Chris Lattner88a69ad2007-07-13 05:13:43 +00001838 GV->setInitializer(Init);
Chris Lattnere78b86f2009-08-05 05:20:29 +00001839
1840 // If it is safe to mark the global 'constant', do so now.
Richard Smitha9b21d22012-02-17 06:48:11 +00001841 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1842 isTypeConstant(D->getType(), true));
Mike Stump1eb44332009-09-09 15:08:12 +00001843
Ken Dyck8b752f12010-01-27 17:10:57 +00001844 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smitha9b21d22012-02-17 06:48:11 +00001845
Chris Lattner88a69ad2007-07-13 05:13:43 +00001846 // Set the llvm linkage type as appropriate.
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001847 llvm::GlobalValue::LinkageTypes Linkage =
1848 GetLLVMLinkageVarDefinition(D, GV);
1849 GV->setLinkage(Linkage);
1850 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnere78b86f2009-08-05 05:20:29 +00001851 // common vars aren't constant even if declared const.
1852 GV->setConstant(false);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +00001853
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001854 SetCommonAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +00001855
John McCall3030eb82010-11-06 09:44:32 +00001856 // Emit the initializer function if necessary.
Richard Smith7ca48502012-02-13 22:16:19 +00001857 if (NeedsGlobalCtor || NeedsGlobalDtor)
1858 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCall3030eb82010-11-06 09:44:32 +00001859
Kostya Serebryany05c5ebc2012-08-21 06:53:28 +00001860 // If we are compiling with ASan, add metadata indicating dynamically
1861 // initialized globals.
Will Dietz4f45bc02013-01-18 11:30:38 +00001862 if (SanOpts.Address && NeedsGlobalCtor) {
Kostya Serebryany05c5ebc2012-08-21 06:53:28 +00001863 llvm::Module &M = getModule();
1864
1865 llvm::NamedMDNode *DynamicInitializers =
1866 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1867 llvm::Value *GlobalToAdd[] = { GV };
1868 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1869 DynamicInitializers->addOperand(ThisGlobal);
1870 }
1871
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001872 // Emit global variable debug information.
Eric Christopher73fb3502011-10-13 21:45:18 +00001873 if (CGDebugInfo *DI = getModuleDebugInfo())
Douglas Gregor4cdad312012-10-23 20:05:01 +00001874 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001875 DI->EmitGlobalVariable(GV, D);
Chris Lattner88a69ad2007-07-13 05:13:43 +00001876}
Reid Spencer5f016e22007-07-11 17:01:13 +00001877
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001878llvm::GlobalValue::LinkageTypes
1879CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1880 llvm::GlobalVariable *GV) {
1881 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1882 if (Linkage == GVA_Internal)
1883 return llvm::Function::InternalLinkage;
1884 else if (D->hasAttr<DLLImportAttr>())
1885 return llvm::Function::DLLImportLinkage;
1886 else if (D->hasAttr<DLLExportAttr>())
1887 return llvm::Function::DLLExportLinkage;
1888 else if (D->hasAttr<WeakAttr>()) {
1889 if (GV->isConstant())
1890 return llvm::GlobalVariable::WeakODRLinkage;
1891 else
1892 return llvm::GlobalVariable::WeakAnyLinkage;
1893 } else if (Linkage == GVA_TemplateInstantiation ||
1894 Linkage == GVA_ExplicitTemplateInstantiation)
John McCall99ace162011-04-12 01:46:54 +00001895 return llvm::GlobalVariable::WeakODRLinkage;
David Blaikie4e4d0842012-03-11 07:00:24 +00001896 else if (!getLangOpts().CPlusPlus &&
Eric Christophera6cf1e72010-12-02 02:45:55 +00001897 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1898 D->getAttr<CommonAttr>()) &&
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001899 !D->hasExternalStorage() && !D->getInit() &&
Fariborz Jahanianab27d6e2011-06-20 17:50:03 +00001900 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1901 !D->getAttr<WeakImportAttr>()) {
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001902 // Thread local vars aren't considered common linkage.
1903 return llvm::GlobalVariable::CommonLinkage;
1904 }
1905 return llvm::GlobalVariable::ExternalLinkage;
1906}
1907
John McCalla923c972012-12-12 22:21:47 +00001908/// Replace the uses of a function that was declared with a non-proto type.
1909/// We want to silently drop extra arguments from call sites
1910static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1911 llvm::Function *newFn) {
1912 // Fast path.
1913 if (old->use_empty()) return;
1914
1915 llvm::Type *newRetTy = newFn->getReturnType();
1916 SmallVector<llvm::Value*, 4> newArgs;
1917
1918 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1919 ui != ue; ) {
1920 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
1921 llvm::User *user = *use;
1922
1923 // Recognize and replace uses of bitcasts. Most calls to
1924 // unprototyped functions will use bitcasts.
1925 if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1926 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1927 replaceUsesOfNonProtoConstant(bitcast, newFn);
1928 continue;
1929 }
1930
1931 // Recognize calls to the function.
1932 llvm::CallSite callSite(user);
1933 if (!callSite) continue;
1934 if (!callSite.isCallee(use)) continue;
1935
1936 // If the return types don't match exactly, then we can't
1937 // transform this call unless it's dead.
1938 if (callSite->getType() != newRetTy && !callSite->use_empty())
1939 continue;
1940
1941 // Get the call site's attribute list.
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +00001942 SmallVector<llvm::AttributeWithIndex, 8> newAttrs;
John McCalla923c972012-12-12 22:21:47 +00001943 llvm::AttributeSet oldAttrs = callSite.getAttributes();
1944
1945 // Collect any return attributes from the call.
Bill Wendlinga37ce612013-01-21 21:57:40 +00001946 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
Bill Wendlinged01f842013-01-21 22:45:00 +00001947 newAttrs.push_back(
1948 llvm::AttributeWithIndex::get(newFn->getContext(),
1949 llvm::AttributeSet::ReturnIndex,
1950 oldAttrs.getRetAttributes()));
John McCalla923c972012-12-12 22:21:47 +00001951
1952 // If the function was passed too few arguments, don't transform.
1953 unsigned newNumArgs = newFn->arg_size();
1954 if (callSite.arg_size() < newNumArgs) continue;
1955
1956 // If extra arguments were passed, we silently drop them.
1957 // If any of the types mismatch, we don't transform.
1958 unsigned argNo = 0;
1959 bool dontTransform = false;
1960 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
1961 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
1962 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
1963 dontTransform = true;
1964 break;
1965 }
1966
1967 // Add any parameter attributes.
Bill Wendling72390b32012-12-20 19:27:06 +00001968 llvm::Attribute pAttrs = oldAttrs.getParamAttributes(argNo + 1);
John McCalla923c972012-12-12 22:21:47 +00001969 if (pAttrs.hasAttributes())
1970 newAttrs.push_back(llvm::AttributeWithIndex::get(argNo + 1, pAttrs));
1971 }
1972 if (dontTransform)
1973 continue;
1974
Bill Wendlinge67e4c92013-01-18 21:26:07 +00001975 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
John McCalla923c972012-12-12 22:21:47 +00001976 newAttrs.push_back(llvm::
Bill Wendlinga37ce612013-01-21 21:57:40 +00001977 AttributeWithIndex::get(newFn->getContext(),
1978 llvm::AttributeSet::FunctionIndex,
1979 oldAttrs.getFnAttributes()));
John McCalla923c972012-12-12 22:21:47 +00001980
1981 // Okay, we can transform this. Create the new call instruction and copy
1982 // over the required information.
1983 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
1984
1985 llvm::CallSite newCall;
1986 if (callSite.isCall()) {
1987 newCall = llvm::CallInst::Create(newFn, newArgs, "",
1988 callSite.getInstruction());
1989 } else {
1990 llvm::InvokeInst *oldInvoke =
1991 cast<llvm::InvokeInst>(callSite.getInstruction());
1992 newCall = llvm::InvokeInst::Create(newFn,
1993 oldInvoke->getNormalDest(),
1994 oldInvoke->getUnwindDest(),
1995 newArgs, "",
1996 callSite.getInstruction());
1997 }
1998 newArgs.clear(); // for the next iteration
1999
2000 if (!newCall->getType()->isVoidTy())
2001 newCall->takeName(callSite.getInstruction());
2002 newCall.setAttributes(
2003 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
2004 newCall.setCallingConv(callSite.getCallingConv());
2005
2006 // Finally, remove the old call, replacing any uses with the new one.
2007 if (!callSite->use_empty())
2008 callSite->replaceAllUsesWith(newCall.getInstruction());
2009
2010 // Copy debug location attached to CI.
2011 if (!callSite->getDebugLoc().isUnknown())
2012 newCall->setDebugLoc(callSite->getDebugLoc());
2013 callSite->eraseFromParent();
2014 }
2015}
2016
Chris Lattnerbdb01322009-05-05 06:16:31 +00002017/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
2018/// implement a function with no prototype, e.g. "int foo() {}". If there are
2019/// existing call uses of the old function in the module, this adjusts them to
2020/// call the new function directly.
2021///
2022/// This is not just a cleanup: the always_inline pass requires direct calls to
2023/// functions to be able to inline them. If there is a bitcast in the way, it
2024/// won't inline them. Instcombine normally deletes these calls, but it isn't
2025/// run at -O0.
2026static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
2027 llvm::Function *NewFn) {
2028 // If we're redefining a global as a function, don't transform it.
John McCalla923c972012-12-12 22:21:47 +00002029 if (!isa<llvm::Function>(Old)) return;
Mike Stump1eb44332009-09-09 15:08:12 +00002030
John McCalla923c972012-12-12 22:21:47 +00002031 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattnerbdb01322009-05-05 06:16:31 +00002032}
2033
Rafael Espindola02503932012-03-08 15:51:03 +00002034void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
2035 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
2036 // If we have a definition, this might be a deferred decl. If the
2037 // instantiation is explicit, make sure we emit it at the end.
2038 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
2039 GetAddrOfGlobalVar(VD);
Rafael Espindola234fe652012-03-05 10:54:55 +00002040}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002041
Chris Lattnerb4880ba2009-05-12 21:21:08 +00002042void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnerb4880ba2009-05-12 21:21:08 +00002043 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCalld26bc762011-03-09 04:27:21 +00002044
John McCall1f6f9612011-03-09 08:12:35 +00002045 // Compute the function info and LLVM type.
John McCallde5d3c72012-02-17 03:33:10 +00002046 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
2047 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalld26bc762011-03-09 04:27:21 +00002048
Chris Lattner9fa959d2009-05-12 20:58:15 +00002049 // Get or create the prototype for the function.
Chris Lattnerb4880ba2009-05-12 21:21:08 +00002050 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00002051
Chris Lattner0558e792009-03-21 09:25:43 +00002052 // Strip off a bitcast if we got one back.
2053 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
2054 assert(CE->getOpcode() == llvm::Instruction::BitCast);
2055 Entry = CE->getOperand(0);
2056 }
Mike Stump1eb44332009-09-09 15:08:12 +00002057
2058
Chris Lattner0558e792009-03-21 09:25:43 +00002059 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00002060 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00002061
Daniel Dunbar42745812009-03-09 23:53:08 +00002062 // If the types mismatch then we have to rewrite the definition.
Chris Lattnerbdb01322009-05-05 06:16:31 +00002063 assert(OldFn->isDeclaration() &&
Chris Lattner0558e792009-03-21 09:25:43 +00002064 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +00002065
Chris Lattner62b33ea2009-03-21 08:38:50 +00002066 // F is the Function* for the one with the wrong type, we must make a new
2067 // Function* and update everything that used F (a declaration) with the new
2068 // Function* (which will be a definition).
2069 //
2070 // This happens if there is a prototype for a function
2071 // (e.g. "int f()") and then a definition of a different type
John McCallf746aa62010-03-19 23:29:14 +00002072 // (e.g. "int f(int x)"). Move the old function aside so that it
2073 // doesn't interfere with GetAddrOfFunction.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002074 OldFn->setName(StringRef());
Chris Lattnerb4880ba2009-05-12 21:21:08 +00002075 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump1eb44332009-09-09 15:08:12 +00002076
John McCalla923c972012-12-12 22:21:47 +00002077 // This might be an implementation of a function without a
2078 // prototype, in which case, try to do special replacement of
2079 // calls which match the new prototype. The really key thing here
2080 // is that we also potentially drop arguments from the call site
2081 // so as to make a direct call, which makes the inliner happier
2082 // and suppresses a number of optimizer warnings (!) about
2083 // dropping arguments.
2084 if (!OldFn->use_empty()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00002085 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattner9fa959d2009-05-12 20:58:15 +00002086 OldFn->removeDeadConstantUsers();
2087 }
Mike Stump1eb44332009-09-09 15:08:12 +00002088
Chris Lattner62b33ea2009-03-21 08:38:50 +00002089 // Replace uses of F with the Function we will endow with a body.
Chris Lattnerbdb01322009-05-05 06:16:31 +00002090 if (!Entry->use_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002091 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00002092 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattnerbdb01322009-05-05 06:16:31 +00002093 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2094 }
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Chris Lattner62b33ea2009-03-21 08:38:50 +00002096 // Ok, delete the old function now, which is dead.
Chris Lattnerbdb01322009-05-05 06:16:31 +00002097 OldFn->eraseFromParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002098
Chris Lattner0558e792009-03-21 09:25:43 +00002099 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002100 }
Mike Stump1eb44332009-09-09 15:08:12 +00002101
John McCall112c9672010-11-02 21:04:24 +00002102 // We need to set linkage and visibility on the function before
2103 // generating code for it because various parts of IR generation
2104 // want to propagate this information down (e.g. to local static
2105 // declarations).
Chris Lattner0558e792009-03-21 09:25:43 +00002106 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall8b242332010-05-25 04:30:21 +00002107 setFunctionLinkage(D, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002108
John McCall112c9672010-11-02 21:04:24 +00002109 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlsson0ffeaad2011-01-29 19:39:23 +00002110 setGlobalVisibility(Fn, D);
John McCall112c9672010-11-02 21:04:24 +00002111
John McCalld26bc762011-03-09 04:27:21 +00002112 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00002113
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002114 SetFunctionDefinitionAttributes(D, Fn);
2115 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump1eb44332009-09-09 15:08:12 +00002116
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002117 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00002118 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002119 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00002120 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge77f68bb2011-09-09 22:41:49 +00002121 if (D->hasAttr<AnnotateAttr>())
2122 AddGlobalAnnotations(D, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002123}
2124
John McCallf746aa62010-03-19 23:29:14 +00002125void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2126 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002127 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00002128 assert(AA && "Not an alias?");
2129
Chris Lattner5f9e2722011-07-23 10:55:15 +00002130 StringRef MangledName = getMangledName(GD);
Mike Stump1eb44332009-09-09 15:08:12 +00002131
John McCallf746aa62010-03-19 23:29:14 +00002132 // If there is a definition in the module, then it wins over the alias.
2133 // This is dubious, but allow it to be safe. Just ignore the alias.
2134 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2135 if (Entry && !Entry->isDeclaration())
2136 return;
2137
Chris Lattner2acc6e32011-07-18 04:24:23 +00002138 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattnerbd532712009-03-22 21:47:11 +00002139
2140 // Create a reference to the named value. This ensures that it is emitted
2141 // if a deferred decl.
2142 llvm::Constant *Aliasee;
2143 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergc857ce82012-10-05 23:12:53 +00002144 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson1faa89f2011-02-05 04:35:53 +00002145 /*ForVTable=*/false);
Chris Lattnerbd532712009-03-22 21:47:11 +00002146 else
John McCallf746aa62010-03-19 23:29:14 +00002147 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson96e0fc72009-07-29 22:16:19 +00002148 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattnerbd532712009-03-22 21:47:11 +00002149
2150 // Create the new alias itself, but don't set a name yet.
Mike Stump1eb44332009-09-09 15:08:12 +00002151 llvm::GlobalValue *GA =
Chris Lattnerbd532712009-03-22 21:47:11 +00002152 new llvm::GlobalAlias(Aliasee->getType(),
2153 llvm::Function::ExternalLinkage,
2154 "", Aliasee, &getModule());
Mike Stump1eb44332009-09-09 15:08:12 +00002155
Chris Lattnerbd532712009-03-22 21:47:11 +00002156 if (Entry) {
John McCallf746aa62010-03-19 23:29:14 +00002157 assert(Entry->isDeclaration());
2158
Chris Lattnerbd532712009-03-22 21:47:11 +00002159 // If there is a declaration in the module, then we had an extern followed
2160 // by the alias, as in:
2161 // extern int test6();
2162 // ...
2163 // int test6() __attribute__((alias("test7")));
2164 //
2165 // Remove it and replace uses of it with the alias.
John McCallf746aa62010-03-19 23:29:14 +00002166 GA->takeName(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00002167
Owen Anderson3c4972d2009-07-29 18:54:39 +00002168 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattnerbd532712009-03-22 21:47:11 +00002169 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00002170 Entry->eraseFromParent();
John McCallf746aa62010-03-19 23:29:14 +00002171 } else {
Anders Carlsson9a20d552010-06-22 16:16:50 +00002172 GA->setName(MangledName);
Chris Lattnerbd532712009-03-22 21:47:11 +00002173 }
Mike Stump1eb44332009-09-09 15:08:12 +00002174
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002175 // Set attributes which are particular to an alias; this is a
2176 // specialization of the attributes which may be set on a global
2177 // variable/function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002178 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002179 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2180 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002181 if (FD->hasBody())
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002182 GA->setLinkage(llvm::Function::DLLExportLinkage);
2183 } else {
2184 GA->setLinkage(llvm::Function::DLLExportLinkage);
2185 }
Mike Stump1eb44332009-09-09 15:08:12 +00002186 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindola11e8ce72010-02-23 22:00:30 +00002187 D->hasAttr<WeakRefAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00002188 D->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002189 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2190 }
2191
2192 SetCommonAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00002193}
2194
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00002195llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00002196 ArrayRef<llvm::Type*> Tys) {
Jay Foaddf983a82011-07-12 14:06:48 +00002197 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00002198 Tys);
Chris Lattner7acda7c2007-12-18 00:25:38 +00002199}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00002200
Daniel Dunbar1d552912009-07-23 22:52:48 +00002201static llvm::StringMapEntry<llvm::Constant*> &
2202GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2203 const StringLiteral *Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002204 bool TargetIsLSB,
Daniel Dunbar1d552912009-07-23 22:52:48 +00002205 bool &IsUTF16,
2206 unsigned &StringLength) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002207 StringRef String = Literal->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002208 unsigned NumBytes = String.size();
Daniel Dunbar1d552912009-07-23 22:52:48 +00002209
Daniel Dunbarf015b032009-09-22 10:03:52 +00002210 // Check for simple case.
2211 if (!Literal->containsNonAsciiOrNull()) {
2212 StringLength = NumBytes;
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002213 return Map.GetOrCreateValue(String);
Daniel Dunbarf015b032009-09-22 10:03:52 +00002214 }
2215
Bill Wendling84392d02012-03-30 00:26:17 +00002216 // Otherwise, convert the UTF8 literals into a string of shorts.
2217 IsUTF16 = true;
2218
2219 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
Roman Divacky31ba6132012-09-06 15:59:27 +00002220 const UTF8 *FromPtr = (const UTF8 *)String.data();
Daniel Dunbar1d552912009-07-23 22:52:48 +00002221 UTF16 *ToPtr = &ToBuf[0];
Mike Stump1eb44332009-09-09 15:08:12 +00002222
Fariborz Jahaniane7ddfb92010-09-07 19:57:04 +00002223 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2224 &ToPtr, ToPtr + NumBytes,
2225 strictConversion);
Mike Stump1eb44332009-09-09 15:08:12 +00002226
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002227 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar1d552912009-07-23 22:52:48 +00002228 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002229
Bill Wendling84392d02012-03-30 00:26:17 +00002230 // Add an explicit null.
2231 *ToPtr = 0;
2232 return Map.
2233 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2234 (StringLength + 1) * 2));
Daniel Dunbar1d552912009-07-23 22:52:48 +00002235}
2236
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002237static llvm::StringMapEntry<llvm::Constant*> &
2238GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
Bill Wendling8322c232012-03-29 22:12:09 +00002239 const StringLiteral *Literal,
2240 unsigned &StringLength) {
2241 StringRef String = Literal->getString();
2242 StringLength = String.size();
2243 return Map.GetOrCreateValue(String);
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002244}
2245
Daniel Dunbar1d552912009-07-23 22:52:48 +00002246llvm::Constant *
2247CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2248 unsigned StringLength = 0;
2249 bool isUTF16 = false;
2250 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump1eb44332009-09-09 15:08:12 +00002251 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Micah Villmow25a6a842012-10-08 16:25:52 +00002252 getDataLayout().isLittleEndian(),
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002253 isUTF16, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00002254
Daniel Dunbar1d552912009-07-23 22:52:48 +00002255 if (llvm::Constant *C = Entry.getValue())
2256 return C;
Mike Stump1eb44332009-09-09 15:08:12 +00002257
Chris Lattner8b418682012-02-07 00:39:47 +00002258 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002259 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump1eb44332009-09-09 15:08:12 +00002260
Chris Lattner9d4a15f2009-07-16 16:48:25 +00002261 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonc9e20912007-08-21 00:21:21 +00002262 if (!CFConstantStringClassRef) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002263 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002264 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002265 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattner9d4a15f2009-07-16 16:48:25 +00002266 "__CFConstantStringClassReference");
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002267 // Decay array -> ptr
2268 CFConstantStringClassRef =
Jay Foada5c04342011-07-21 14:31:17 +00002269 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlssonc9e20912007-08-21 00:21:21 +00002270 }
Mike Stump1eb44332009-09-09 15:08:12 +00002271
Anders Carlssone3daa762008-11-15 18:54:24 +00002272 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002273
Chris Lattner2acc6e32011-07-18 04:24:23 +00002274 llvm::StructType *STy =
Anders Carlssone3daa762008-11-15 18:54:24 +00002275 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2276
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00002277 llvm::Constant *Fields[4];
Douglas Gregor44b43212008-12-11 16:49:14 +00002278
Anders Carlssonc9e20912007-08-21 00:21:21 +00002279 // Class pointer.
Anders Carlsson5add6832009-08-16 05:55:31 +00002280 Fields[0] = CFConstantStringClassRef;
Mike Stump1eb44332009-09-09 15:08:12 +00002281
Anders Carlssonc9e20912007-08-21 00:21:21 +00002282 // Flags.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002283 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002284 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson5add6832009-08-16 05:55:31 +00002285 llvm::ConstantInt::get(Ty, 0x07C8);
2286
Anders Carlssonc9e20912007-08-21 00:21:21 +00002287 // String pointer.
Bill Wendling84392d02012-03-30 00:26:17 +00002288 llvm::Constant *C = 0;
2289 if (isUTF16) {
2290 ArrayRef<uint16_t> Arr =
David Greene5ba58a12013-01-15 22:09:41 +00002291 llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2292 const_cast<char *>(Entry.getKey().data())),
Bill Wendling84392d02012-03-30 00:26:17 +00002293 Entry.getKey().size() / 2);
2294 C = llvm::ConstantDataArray::get(VMContext, Arr);
2295 } else {
2296 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2297 }
Daniel Dunbara9668e02009-04-03 00:57:44 +00002298
Chris Lattner95b851e2009-07-16 05:03:48 +00002299 llvm::GlobalValue::LinkageTypes Linkage;
Bill Wendling1bf7a3f2012-01-10 08:46:39 +00002300 if (isUTF16)
Chris Lattner278b9f02009-10-14 05:55:45 +00002301 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner95b851e2009-07-16 05:03:48 +00002302 Linkage = llvm::GlobalValue::InternalLinkage;
Bill Wendling1bf7a3f2012-01-10 08:46:39 +00002303 else
Rafael Espindola584acf22011-03-14 17:55:00 +00002304 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2305 // when using private linkage. It is not clear if this is a bug in ld
2306 // or a reasonable new restriction.
Rafael Espindoladc0f1372011-03-14 21:08:19 +00002307 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00002308
Bill Wendling1bf7a3f2012-01-10 08:46:39 +00002309 // Note: -fwritable-strings doesn't make the backing store strings of
2310 // CFStrings writable. (See <rdar://problem/10657500>)
Mike Stump1eb44332009-09-09 15:08:12 +00002311 llvm::GlobalVariable *GV =
Bill Wendling1bf7a3f2012-01-10 08:46:39 +00002312 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2313 Linkage, C, ".str");
Rafael Espindolab266a1f2011-01-17 16:31:00 +00002314 GV->setUnnamedAddr(true);
Daniel Dunbara9668e02009-04-03 00:57:44 +00002315 if (isUTF16) {
Ken Dyck4da244c2010-01-26 18:46:23 +00002316 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2317 GV->setAlignment(Align.getQuantity());
Daniel Dunbarf7e903d2011-04-12 23:30:52 +00002318 } else {
2319 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2320 GV->setAlignment(Align.getQuantity());
Daniel Dunbara9668e02009-04-03 00:57:44 +00002321 }
Bill Wendling84392d02012-03-30 00:26:17 +00002322
2323 // String.
Jay Foada5c04342011-07-21 14:31:17 +00002324 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlsson5add6832009-08-16 05:55:31 +00002325
Bill Wendling84392d02012-03-30 00:26:17 +00002326 if (isUTF16)
2327 // Cast the UTF16 string to the correct type.
2328 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2329
Anders Carlssonc9e20912007-08-21 00:21:21 +00002330 // String length.
2331 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson5add6832009-08-16 05:55:31 +00002332 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00002333
Anders Carlssonc9e20912007-08-21 00:21:21 +00002334 // The struct.
Owen Anderson08e25242009-07-27 22:29:56 +00002335 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump1eb44332009-09-09 15:08:12 +00002336 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2337 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner95b851e2009-07-16 05:03:48 +00002338 "_unnamed_cfstring_");
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002339 if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00002340 GV->setSection(Sect);
Daniel Dunbar1d552912009-07-23 22:52:48 +00002341 Entry.setValue(GV);
Mike Stump1eb44332009-09-09 15:08:12 +00002342
Anders Carlsson0c678292007-11-01 00:41:52 +00002343 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00002344}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002345
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002346static RecordDecl *
2347CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2348 DeclContext *DC, IdentifierInfo *Id) {
2349 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00002350 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002351 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2352 else
2353 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2354}
2355
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00002356llvm::Constant *
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002357CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002358 unsigned StringLength = 0;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002359 llvm::StringMapEntry<llvm::Constant*> &Entry =
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002360 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002361
2362 if (llvm::Constant *C = Entry.getValue())
2363 return C;
2364
Chris Lattner812234b2012-02-06 22:47:00 +00002365 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002366 llvm::Constant *Zeros[] = { Zero, Zero };
2367
Fariborz Jahanianec951e02010-04-23 22:33:39 +00002368 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002369 if (!ConstantStringClassRef) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002370 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002371 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002372 llvm::Constant *GV;
John McCall260611a2012-06-20 06:18:46 +00002373 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00002374 std::string str =
2375 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2376 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00002377 GV = getObjCRuntime().GetClassGlobal(str);
2378 // Make sure the result is of the correct type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002379 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00002380 ConstantStringClassRef =
2381 llvm::ConstantExpr::getBitCast(GV, PTy);
2382 } else {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00002383 std::string str =
2384 StringClass.empty() ? "_NSConstantStringClassReference"
2385 : "_" + StringClass + "ClassReference";
Chris Lattner2acc6e32011-07-18 04:24:23 +00002386 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00002387 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00002388 // Decay array -> ptr
2389 ConstantStringClassRef =
Jay Foada5c04342011-07-21 14:31:17 +00002390 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002391 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002392 }
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002393
2394 if (!NSConstantStringType) {
2395 // Construct the type for a constant NSString.
2396 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2397 Context.getTranslationUnitDecl(),
2398 &Context.Idents.get("__builtin_NSString"));
2399 D->startDefinition();
2400
2401 QualType FieldTypes[3];
2402
2403 // const int *isa;
2404 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2405 // const char *str;
2406 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2407 // unsigned int length;
2408 FieldTypes[2] = Context.UnsignedIntTy;
2409
2410 // Create fields
2411 for (unsigned i = 0; i < 3; ++i) {
2412 FieldDecl *Field = FieldDecl::Create(Context, D,
2413 SourceLocation(),
2414 SourceLocation(), 0,
2415 FieldTypes[i], /*TInfo=*/0,
2416 /*BitWidth=*/0,
2417 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002418 ICIS_NoInit);
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002419 Field->setAccess(AS_public);
2420 D->addDecl(Field);
2421 }
2422
2423 D->completeDefinition();
2424 QualType NSTy = Context.getTagDeclType(D);
2425 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2426 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002427
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00002428 llvm::Constant *Fields[3];
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002429
2430 // Class pointer.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002431 Fields[0] = ConstantStringClassRef;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002432
2433 // String pointer.
Chris Lattner94010692012-02-05 02:30:40 +00002434 llvm::Constant *C =
2435 llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002436
2437 llvm::GlobalValue::LinkageTypes Linkage;
2438 bool isConstant;
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002439 Linkage = llvm::GlobalValue::PrivateLinkage;
David Blaikie4e4d0842012-03-11 07:00:24 +00002440 isConstant = !LangOpts.WritableStrings;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002441
2442 llvm::GlobalVariable *GV =
2443 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2444 ".str");
Rafael Espindola803d3072011-01-17 22:11:21 +00002445 GV->setUnnamedAddr(true);
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002446 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2447 GV->setAlignment(Align.getQuantity());
Jay Foada5c04342011-07-21 14:31:17 +00002448 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002449
2450 // String length.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002451 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002452 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2453
2454 // The struct.
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002455 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002456 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2457 llvm::GlobalVariable::PrivateLinkage, C,
2458 "_unnamed_nsstring_");
2459 // FIXME. Fix section.
Fariborz Jahanianec951e02010-04-23 22:33:39 +00002460 if (const char *Sect =
John McCall260611a2012-06-20 06:18:46 +00002461 LangOpts.ObjCRuntime.isNonFragile()
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002462 ? getContext().getTargetInfo().getNSStringNonFragileABISection()
2463 : getContext().getTargetInfo().getNSStringSection())
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002464 GV->setSection(Sect);
2465 Entry.setValue(GV);
2466
2467 return GV;
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00002468}
2469
Douglas Gregor0815b572011-08-09 17:23:49 +00002470QualType CodeGenModule::getObjCFastEnumerationStateType() {
2471 if (ObjCFastEnumerationStateType.isNull()) {
2472 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2473 Context.getTranslationUnitDecl(),
2474 &Context.Idents.get("__objcFastEnumerationState"));
2475 D->startDefinition();
2476
2477 QualType FieldTypes[] = {
2478 Context.UnsignedLongTy,
2479 Context.getPointerType(Context.getObjCIdType()),
2480 Context.getPointerType(Context.UnsignedLongTy),
2481 Context.getConstantArrayType(Context.UnsignedLongTy,
2482 llvm::APInt(32, 5), ArrayType::Normal, 0)
2483 };
2484
2485 for (size_t i = 0; i < 4; ++i) {
2486 FieldDecl *Field = FieldDecl::Create(Context,
2487 D,
2488 SourceLocation(),
2489 SourceLocation(), 0,
2490 FieldTypes[i], /*TInfo=*/0,
2491 /*BitWidth=*/0,
2492 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002493 ICIS_NoInit);
Douglas Gregor0815b572011-08-09 17:23:49 +00002494 Field->setAccess(AS_public);
2495 D->addDecl(Field);
2496 }
2497
2498 D->completeDefinition();
2499 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2500 }
2501
2502 return ObjCFastEnumerationStateType;
2503}
2504
Eli Friedman64f45a22011-11-01 02:23:42 +00002505llvm::Constant *
2506CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2507 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2508
2509 // Don't emit it as the address of the string, emit the string data itself
2510 // as an inline array.
Chris Lattner812234b2012-02-06 22:47:00 +00002511 if (E->getCharByteWidth() == 1) {
2512 SmallString<64> Str(E->getString());
2513
2514 // Resize the string to the right size, which is indicated by its type.
2515 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2516 Str.resize(CAT->getSize().getZExtValue());
2517 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2518 }
Chris Lattner94010692012-02-05 02:30:40 +00002519
2520 llvm::ArrayType *AType =
2521 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2522 llvm::Type *ElemTy = AType->getElementType();
2523 unsigned NumElements = AType->getNumElements();
Chris Lattnerd79ed432012-02-06 22:52:04 +00002524
2525 // Wide strings have either 2-byte or 4-byte elements.
2526 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2527 SmallVector<uint16_t, 32> Elements;
2528 Elements.reserve(NumElements);
2529
2530 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2531 Elements.push_back(E->getCodeUnit(i));
2532 Elements.resize(NumElements);
2533 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner94010692012-02-05 02:30:40 +00002534 }
2535
Chris Lattnerd79ed432012-02-06 22:52:04 +00002536 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2537 SmallVector<uint32_t, 32> Elements;
2538 Elements.reserve(NumElements);
2539
2540 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2541 Elements.push_back(E->getCodeUnit(i));
2542 Elements.resize(NumElements);
2543 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedman64f45a22011-11-01 02:23:42 +00002544}
2545
Daniel Dunbar61432932008-08-13 23:20:05 +00002546/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2547/// constant array for the given string literal.
2548llvm::Constant *
2549CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
John McCalla5e19c62011-08-04 01:03:22 +00002550 CharUnits Align = getContext().getTypeAlignInChars(S->getType());
Eli Friedman64f45a22011-11-01 02:23:42 +00002551 if (S->isAscii() || S->isUTF8()) {
Chris Lattner812234b2012-02-06 22:47:00 +00002552 SmallString<64> Str(S->getString());
2553
2554 // Resize the string to the right size, which is indicated by its type.
2555 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2556 Str.resize(CAT->getSize().getZExtValue());
2557 return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
Eli Friedman7eb79c12009-11-16 05:55:46 +00002558 }
Eli Friedman64f45a22011-11-01 02:23:42 +00002559
Chris Lattner812234b2012-02-06 22:47:00 +00002560 // FIXME: the following does not memoize wide strings.
Eli Friedman64f45a22011-11-01 02:23:42 +00002561 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2562 llvm::GlobalVariable *GV =
2563 new llvm::GlobalVariable(getModule(),C->getType(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002564 !LangOpts.WritableStrings,
Eli Friedman64f45a22011-11-01 02:23:42 +00002565 llvm::GlobalValue::PrivateLinkage,
2566 C,".str");
Seth Cantrell7d6a7c02012-01-18 12:11:32 +00002567
Eli Friedman64f45a22011-11-01 02:23:42 +00002568 GV->setAlignment(Align.getQuantity());
2569 GV->setUnnamedAddr(true);
Eli Friedman64f45a22011-11-01 02:23:42 +00002570 return GV;
Daniel Dunbar61432932008-08-13 23:20:05 +00002571}
2572
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002573/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2574/// array for the given ObjCEncodeExpr node.
2575llvm::Constant *
2576CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2577 std::string Str;
2578 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00002579
2580 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002581}
2582
2583
Chris Lattnera7ad98f2008-02-11 00:02:17 +00002584/// GenerateWritableString -- Creates storage for a string literal.
John McCalla5e19c62011-08-04 01:03:22 +00002585static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002586 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00002587 CodeGenModule &CGM,
John McCalla5e19c62011-08-04 01:03:22 +00002588 const char *GlobalName,
2589 unsigned Alignment) {
Daniel Dunbar61432932008-08-13 23:20:05 +00002590 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson0032b272009-08-13 21:57:51 +00002591 llvm::Constant *C =
Chris Lattner94010692012-02-05 02:30:40 +00002592 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002593
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002594 // Create a global variable for this string
Rafael Espindola1257bc62011-01-10 22:34:03 +00002595 llvm::GlobalVariable *GV =
2596 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2597 llvm::GlobalValue::PrivateLinkage,
2598 C, GlobalName);
John McCalla5e19c62011-08-04 01:03:22 +00002599 GV->setAlignment(Alignment);
Rafael Espindola1257bc62011-01-10 22:34:03 +00002600 GV->setUnnamedAddr(true);
2601 return GV;
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002602}
2603
Daniel Dunbar61432932008-08-13 23:20:05 +00002604/// GetAddrOfConstantString - Returns a pointer to a character array
2605/// containing the literal. This contents are exactly that of the
2606/// given string, i.e. it will not be null terminated automatically;
2607/// see GetAddrOfConstantCString. Note that whether the result is
2608/// actually a pointer to an LLVM constant depends on
2609/// Feature.WriteableStrings.
2610///
2611/// The result has pointer to array type.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002612llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
John McCalla5e19c62011-08-04 01:03:22 +00002613 const char *GlobalName,
2614 unsigned Alignment) {
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00002615 // Get the default prefix if a name wasn't specified.
2616 if (!GlobalName)
Chris Lattner95b851e2009-07-16 05:03:48 +00002617 GlobalName = ".str";
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00002618
2619 // Don't share any string literals if strings aren't constant.
David Blaikie4e4d0842012-03-11 07:00:24 +00002620 if (LangOpts.WritableStrings)
John McCalla5e19c62011-08-04 01:03:22 +00002621 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002622
John McCalla5e19c62011-08-04 01:03:22 +00002623 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
Benjamin Kramer9de43422011-03-05 13:45:23 +00002624 ConstantStringMap.GetOrCreateValue(Str);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002625
John McCalla5e19c62011-08-04 01:03:22 +00002626 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2627 if (Alignment > GV->getAlignment()) {
2628 GV->setAlignment(Alignment);
2629 }
2630 return GV;
2631 }
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002632
2633 // Create a global variable for this.
Chris Lattner812234b2012-02-06 22:47:00 +00002634 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2635 Alignment);
John McCalla5e19c62011-08-04 01:03:22 +00002636 Entry.setValue(GV);
2637 return GV;
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002638}
Daniel Dunbar61432932008-08-13 23:20:05 +00002639
2640/// GetAddrOfConstantCString - Returns a pointer to a character
Benjamin Kramer9de43422011-03-05 13:45:23 +00002641/// array containing the literal and a terminating '\0'
Daniel Dunbar61432932008-08-13 23:20:05 +00002642/// character. The result has pointer to array type.
Benjamin Kramer9de43422011-03-05 13:45:23 +00002643llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
John McCalla5e19c62011-08-04 01:03:22 +00002644 const char *GlobalName,
2645 unsigned Alignment) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002646 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCalla5e19c62011-08-04 01:03:22 +00002647 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
Daniel Dunbar61432932008-08-13 23:20:05 +00002648}
Daniel Dunbar41071de2008-08-15 23:26:23 +00002649
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002650/// EmitObjCPropertyImplementations - Emit information for synthesized
2651/// properties for an implementation.
Mike Stump1eb44332009-09-09 15:08:12 +00002652void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002653 ObjCImplementationDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00002654 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002655 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002656 ObjCPropertyImplDecl *PID = *i;
Mike Stump1eb44332009-09-09 15:08:12 +00002657
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002658 // Dynamic is just for type-checking.
2659 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2660 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2661
2662 // Determine which methods need to be implemented, some may have
Jordan Rose1e4691b2012-10-10 16:42:25 +00002663 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002664 // we want, that just indicates if the decl came from a
2665 // property. What we want to know is if the method is defined in
2666 // this implementation.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002667 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00002668 CodeGenFunction(*this).GenerateObjCGetter(
2669 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002670 if (!PD->isReadOnly() &&
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002671 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00002672 CodeGenFunction(*this).GenerateObjCSetter(
2673 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002674 }
2675 }
2676}
2677
John McCalle81ac692011-03-22 07:05:39 +00002678static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00002679 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2680 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00002681 ivar; ivar = ivar->getNextIvar())
2682 if (ivar->getType().isDestructedType())
2683 return true;
2684
2685 return false;
2686}
2687
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002688/// EmitObjCIvarInitializations - Emit information for ivar initialization
2689/// for an implementation.
2690void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCalle81ac692011-03-22 07:05:39 +00002691 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2692 if (needsDestructMethod(D)) {
2693 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2694 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2695 ObjCMethodDecl *DTORMethod =
2696 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002697 cxxSelector, getContext().VoidTy, 0, D,
2698 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rose1e4691b2012-10-10 16:42:25 +00002699 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002700 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCalle81ac692011-03-22 07:05:39 +00002701 D->addInstanceMethod(DTORMethod);
2702 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCallb03527a2012-10-17 04:53:31 +00002703 D->setHasDestructors(true);
John McCalle81ac692011-03-22 07:05:39 +00002704 }
2705
2706 // If the implementation doesn't have any ivar initializers, we don't need
2707 // a .cxx_construct.
David Chisnall827bbcc2011-03-17 14:19:08 +00002708 if (D->getNumIvarInitializers() == 0)
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002709 return;
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002710
John McCalle81ac692011-03-22 07:05:39 +00002711 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2712 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002713 // The constructor returns 'self'.
2714 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2715 D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00002716 D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00002717 cxxSelector,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002718 getContext().getObjCIdType(), 0,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002719 D, /*isInstance=*/true,
2720 /*isVariadic=*/false,
Jordan Rose1e4691b2012-10-10 16:42:25 +00002721 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002722 /*isImplicitlyDeclared=*/true,
2723 /*isDefined=*/false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002724 ObjCMethodDecl::Required);
2725 D->addInstanceMethod(CTORMethod);
2726 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCallb03527a2012-10-17 04:53:31 +00002727 D->setHasNonZeroConstructors(true);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002728}
2729
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002730/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00002731void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002732 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson984e0682009-04-01 00:58:25 +00002733 I != E; ++I)
2734 EmitTopLevelDecl(*I);
2735}
2736
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002737// EmitLinkageSpec - Emit all declarations in a linkage spec.
2738void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmanf976be82009-08-01 20:48:04 +00002739 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2740 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002741 ErrorUnsupported(LSD, "linkage spec");
2742 return;
2743 }
2744
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002745 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Fariborz Jahanianc1868e52012-10-26 20:22:11 +00002746 I != E; ++I) {
Fariborz Jahanian107dae42012-10-26 22:20:25 +00002747 // Meta-data for ObjC class includes references to implemented methods.
2748 // Generate class's method definitions first.
Fariborz Jahanianc1868e52012-10-26 20:22:11 +00002749 if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
2750 for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2751 MEnd = OID->meth_end();
2752 M != MEnd; ++M)
2753 EmitTopLevelDecl(*M);
2754 }
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002755 EmitTopLevelDecl(*I);
Fariborz Jahanianc1868e52012-10-26 20:22:11 +00002756 }
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002757}
2758
Daniel Dunbar41071de2008-08-15 23:26:23 +00002759/// EmitTopLevelDecl - Emit code for a single top level declaration.
2760void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2761 // If an error has occurred, stop code generation, but continue
2762 // parsing and semantic analysis (to ensure all warnings and errors
2763 // are emitted).
2764 if (Diags.hasErrorOccurred())
2765 return;
2766
Douglas Gregor16e8be22009-06-29 17:30:29 +00002767 // Ignore dependent declarations.
2768 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2769 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002770
Daniel Dunbar41071de2008-08-15 23:26:23 +00002771 switch (D->getKind()) {
Anders Carlsson293361a2009-08-25 13:14:46 +00002772 case Decl::CXXConversion:
Anders Carlsson2b77ba82009-04-04 20:47:02 +00002773 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00002774 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00002775 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00002776 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2777 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor16e8be22009-06-29 17:30:29 +00002778 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002779
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002780 EmitGlobal(cast<FunctionDecl>(D));
2781 break;
2782
Daniel Dunbar41071de2008-08-15 23:26:23 +00002783 case Decl::Var:
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002784 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002785 break;
2786
John McCall26fbc722011-04-12 01:01:22 +00002787 // Indirect fields from global anonymous structs and unions can be
2788 // ignored; only the actual variable requires IR gen support.
2789 case Decl::IndirectField:
2790 break;
2791
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002792 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00002793 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00002794 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002795 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002796 // No code generation needed.
John McCall9d0c6612009-11-17 09:33:40 +00002797 case Decl::UsingShadow:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002798 case Decl::Using:
Douglas Gregordd9967a2009-09-02 23:49:23 +00002799 case Decl::UsingDirective:
Douglas Gregor127102b2009-06-29 20:59:39 +00002800 case Decl::ClassTemplate:
2801 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +00002802 case Decl::TypeAliasTemplate:
Anders Carlsson018837b2009-09-23 19:19:16 +00002803 case Decl::NamespaceAlias:
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002804 case Decl::Block:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002805 break;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002806 case Decl::CXXConstructor:
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002807 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00002808 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2809 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002810 return;
2811
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002812 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2813 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002814 case Decl::CXXDestructor:
Francois Pichet8387e2a2011-04-22 22:18:13 +00002815 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2816 return;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002817 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2818 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00002819
2820 case Decl::StaticAssert:
2821 // Nothing to do.
2822 break;
2823
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002824 // Objective-C Decls
Mike Stump1eb44332009-09-09 15:08:12 +00002825
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00002826 // Forward declarations, no (immediate) code generation.
Chris Lattner285d0db2009-04-01 02:36:43 +00002827 case Decl::ObjCInterface:
Eric Christopherffb0c3a2012-07-19 22:22:55 +00002828 case Decl::ObjCCategory:
Chris Lattner285d0db2009-04-01 02:36:43 +00002829 break;
2830
Douglas Gregorbd9482d2012-01-01 21:23:57 +00002831 case Decl::ObjCProtocol: {
2832 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2833 if (Proto->isThisDeclarationADefinition())
2834 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbar41071de2008-08-15 23:26:23 +00002835 break;
Douglas Gregorbd9482d2012-01-01 21:23:57 +00002836 }
2837
Daniel Dunbar41071de2008-08-15 23:26:23 +00002838 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002839 // Categories have properties but don't support synthesize so we
2840 // can ignore them here.
Peter Collingbournee9265232011-07-27 20:29:46 +00002841 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002842 break;
2843
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002844 case Decl::ObjCImplementation: {
2845 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2846 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002847 EmitObjCIvarInitializations(OMD);
Peter Collingbournee9265232011-07-27 20:29:46 +00002848 ObjCRuntime->GenerateClass(OMD);
Eric Christopherbe6c6862012-04-11 05:56:05 +00002849 // Emit global variable debug information.
2850 if (CGDebugInfo *DI = getModuleDebugInfo())
Alexey Samsonov96a66392012-12-03 18:28:12 +00002851 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2852 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
2853 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002854 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002855 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00002856 case Decl::ObjCMethod: {
2857 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2858 // If this is not a prototype, emit the body.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002859 if (OMD->getBody())
Daniel Dunbar41071de2008-08-15 23:26:23 +00002860 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2861 break;
2862 }
Mike Stump1eb44332009-09-09 15:08:12 +00002863 case Decl::ObjCCompatibleAlias:
David Chisnall29254f42012-01-31 18:59:20 +00002864 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002865 break;
2866
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002867 case Decl::LinkageSpec:
2868 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002869 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00002870
2871 case Decl::FileScopeAsm: {
2872 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002873 StringRef AsmString = AD->getAsmString()->getString();
Mike Stump1eb44332009-09-09 15:08:12 +00002874
Daniel Dunbar41071de2008-08-15 23:26:23 +00002875 const std::string &S = getModule().getModuleInlineAsm();
2876 if (S.empty())
2877 getModule().setModuleInlineAsm(AsmString);
Joerg Sonnenberger8ce9cca2012-08-10 10:57:52 +00002878 else if (S.end()[-1] == '\n')
Chris Lattner9f5bff02011-07-23 20:04:25 +00002879 getModule().setModuleInlineAsm(S + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002880 else
Benjamin Kramer8d042582009-12-11 13:33:18 +00002881 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002882 break;
2883 }
Mike Stump1eb44332009-09-09 15:08:12 +00002884
Douglas Gregorb6cbe512013-01-14 17:21:00 +00002885 case Decl::Import: {
2886 ImportDecl *Import = cast<ImportDecl>(D);
2887
2888 // Ignore import declarations that come from imported modules.
2889 if (clang::Module *Owner = Import->getOwningModule()) {
2890 if (getLangOpts().CurrentModule.empty() ||
2891 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
2892 break;
2893 }
2894
Douglas Gregor858afb32013-01-14 20:53:57 +00002895 ImportedModules.insert(Import->getImportedModule());
Douglas Gregorb6cbe512013-01-14 17:21:00 +00002896 break;
2897 }
2898
Mike Stump1eb44332009-09-09 15:08:12 +00002899 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00002900 // Make sure we handled everything we should, every other kind is a
2901 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2902 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002903 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2904 }
2905}
John McCall744016d2010-07-06 23:57:41 +00002906
2907/// Turns the given pointer into a constant.
2908static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2909 const void *Ptr) {
2910 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002911 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall744016d2010-07-06 23:57:41 +00002912 return llvm::ConstantInt::get(i64, PtrInt);
2913}
2914
2915static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2916 llvm::NamedMDNode *&GlobalMetadata,
2917 GlobalDecl D,
2918 llvm::GlobalValue *Addr) {
2919 if (!GlobalMetadata)
2920 GlobalMetadata =
2921 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2922
2923 // TODO: should we report variant information for ctors/dtors?
2924 llvm::Value *Ops[] = {
2925 Addr,
2926 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2927 };
Jay Foad6f141652011-04-21 19:59:12 +00002928 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall744016d2010-07-06 23:57:41 +00002929}
2930
2931/// Emits metadata nodes associating all the global values in the
2932/// current module with the Decls they came from. This is useful for
2933/// projects using IR gen as a subroutine.
2934///
2935/// Since there's currently no way to associate an MDNode directly
2936/// with an llvm::GlobalValue, we create a global named metadata
2937/// with the name 'clang.global.decl.ptrs'.
2938void CodeGenModule::EmitDeclMetadata() {
2939 llvm::NamedMDNode *GlobalMetadata = 0;
2940
2941 // StaticLocalDeclMap
Chris Lattner5f9e2722011-07-23 10:55:15 +00002942 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
John McCall744016d2010-07-06 23:57:41 +00002943 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2944 I != E; ++I) {
2945 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2946 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2947 }
2948}
2949
2950/// Emits metadata nodes for all the local variables in the current
2951/// function.
2952void CodeGenFunction::EmitDeclMetadata() {
2953 if (LocalDeclMap.empty()) return;
2954
2955 llvm::LLVMContext &Context = getLLVMContext();
2956
2957 // Find the unique metadata ID for this name.
2958 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2959
2960 llvm::NamedMDNode *GlobalMetadata = 0;
2961
2962 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2963 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2964 const Decl *D = I->first;
2965 llvm::Value *Addr = I->second;
2966
2967 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2968 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Jay Foad6f141652011-04-21 19:59:12 +00002969 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
John McCall744016d2010-07-06 23:57:41 +00002970 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2971 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2972 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2973 }
2974 }
2975}
Daniel Dunbar673431a2010-07-16 00:00:15 +00002976
Nick Lewycky3dc05412011-05-05 00:08:20 +00002977void CodeGenModule::EmitCoverageFile() {
2978 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002979 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2980 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2981 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky3dc05412011-05-05 00:08:20 +00002982 llvm::MDString *CoverageFile =
2983 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002984 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2985 llvm::MDNode *CU = CUNode->getOperand(i);
Nick Lewycky3dc05412011-05-05 00:08:20 +00002986 llvm::Value *node[] = { CoverageFile, CU };
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002987 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2988 GCov->addOperand(N);
2989 }
2990 }
2991 }
2992}
Nico Weberc5f80462012-10-11 10:13:44 +00002993
2994llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
2995 QualType GuidType) {
2996 // Sema has checked that all uuid strings are of the form
2997 // "12345678-1234-1234-1234-1234567890ab".
2998 assert(Uuid.size() == 36);
2999 const char *Uuidstr = Uuid.data();
3000 for (int i = 0; i < 36; ++i) {
3001 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-');
3002 else assert(isxdigit(Uuidstr[i]));
3003 }
3004
3005 llvm::APInt Field0(32, StringRef(Uuidstr , 8), 16);
3006 llvm::APInt Field1(16, StringRef(Uuidstr + 9, 4), 16);
3007 llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16);
Nico Weber193646f2012-10-17 00:34:34 +00003008 static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Weberc5f80462012-10-11 10:13:44 +00003009
3010 APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4);
3011 InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0));
3012 InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1));
3013 InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2));
3014 APValue& Arr = InitStruct.getStructField(3);
3015 Arr = APValue(APValue::UninitArray(), 8, 8);
3016 for (int t = 0; t < 8; ++t)
Nico Weber43085812012-10-13 21:56:05 +00003017 Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt(
3018 llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16)));
Nico Weberc5f80462012-10-11 10:13:44 +00003019
3020 return EmitConstantValue(InitStruct, GuidType);
3021}