blob: 6442f04070dc0d6486c7e8c5c3c45fc7e1b6f8e7 [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"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000033#include "clang/Basic/CharInfo.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"
Bill Wendlinge1092df2013-02-14 08:09:20 +000038#include "clang/Basic/TargetOptions.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000039#include "clang/Frontend/CodeGenOptions.h"
Sebastian Redl19b1a6e2012-02-25 20:51:20 +000040#include "llvm/ADT/APSInt.h"
John McCall6374c332010-03-06 00:35:14 +000041#include "llvm/ADT/Triple.h"
Chandler Carruth3b844ba2013-01-02 11:45:17 +000042#include "llvm/IR/CallingConv.h"
43#include "llvm/IR/DataLayout.h"
44#include "llvm/IR/Intrinsics.h"
45#include "llvm/IR/LLVMContext.h"
46#include "llvm/IR/Module.h"
Gabor Greif6ba728d2010-04-10 02:56:12 +000047#include "llvm/Support/CallSite.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000048#include "llvm/Support/ConvertUTF.h"
Chris Lattner78f7ece2009-11-07 09:22:46 +000049#include "llvm/Support/ErrorHandling.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000050#include "llvm/Target/Mangler.h"
Dmitri Gribenkocb5620c2013-01-30 12:06:08 +000051
Reid Spencer5f016e22007-07-11 17:01:13 +000052using namespace clang;
53using namespace CodeGen;
54
Julien Lerouge77f68bb2011-09-09 22:41:49 +000055static const char AnnotationSection[] = "llvm.metadata";
56
John McCallf16aa102010-08-22 21:01:12 +000057static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
John McCallb8b2c9d2013-01-25 22:30:49 +000058 switch (CGM.getContext().getTargetInfo().getCXXABI().getKind()) {
Tim Northoverc264e162013-01-31 12:13:10 +000059 case TargetCXXABI::GenericAArch64:
John McCall96fcde02013-01-25 23:36:14 +000060 case TargetCXXABI::GenericARM:
61 case TargetCXXABI::iOS:
62 case TargetCXXABI::GenericItanium:
63 return *CreateItaniumCXXABI(CGM);
64 case TargetCXXABI::Microsoft:
65 return *CreateMicrosoftCXXABI(CGM);
John McCallf16aa102010-08-22 21:01:12 +000066 }
67
68 llvm_unreachable("invalid C++ ABI kind");
John McCallf16aa102010-08-22 21:01:12 +000069}
70
Reid Spencer5f016e22007-07-11 17:01:13 +000071
Chandler Carruth2811ccf2009-11-12 17:24:48 +000072CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
Bill Wendlinge1092df2013-02-14 08:09:20 +000073 const TargetOptions &TO, llvm::Module &M,
74 const llvm::DataLayout &TD,
David Blaikied6471f72011-09-25 23:23:43 +000075 DiagnosticsEngine &diags)
Bill Wendlinge1092df2013-02-14 08:09:20 +000076 : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TargetOpts(TO),
77 TheModule(M), TheDataLayout(TD), TheTargetCodeGenInfo(0), Diags(diags),
John McCallf16aa102010-08-22 21:01:12 +000078 ABI(createCXXABI(*this)),
John McCallde5d3c72012-02-17 03:33:10 +000079 Types(*this),
Dan Gohman3d5aff52010-10-14 23:06:10 +000080 TBAA(0),
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000081 VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
Dan Gohmanb49bd272012-02-16 00:57:37 +000082 DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
83 RRData(0), CFConstantStringClassRef(0),
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +000084 ConstantStringClassRef(0), NSConstantStringType(0),
Daniel Dunbar673431a2010-07-16 00:00:15 +000085 VMContext(M.getContext()),
86 NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
John McCalld16c2cf2011-02-08 08:22:06 +000087 BlockObjectAssign(0), BlockObjectDispose(0),
Will Dietz4f45bc02013-01-18 11:30:38 +000088 BlockDescriptorType(0), GenericBlockLiteralType(0),
89 SanitizerBlacklist(CGO.SanitizerBlacklistFile),
90 SanOpts(SanitizerBlacklist.isIn(M) ?
91 SanitizerOptions::Disabled : LangOpts.Sanitize) {
92
Chris Lattner8b418682012-02-07 00:39:47 +000093 // Initialize the type cache.
94 llvm::LLVMContext &LLVMContext = M.getContext();
95 VoidTy = llvm::Type::getVoidTy(LLVMContext);
96 Int8Ty = llvm::Type::getInt8Ty(LLVMContext);
97 Int16Ty = llvm::Type::getInt16Ty(LLVMContext);
98 Int32Ty = llvm::Type::getInt32Ty(LLVMContext);
99 Int64Ty = llvm::Type::getInt64Ty(LLVMContext);
100 FloatTy = llvm::Type::getFloatTy(LLVMContext);
101 DoubleTy = llvm::Type::getDoubleTy(LLVMContext);
102 PointerWidthInBits = C.getTargetInfo().getPointerWidth(0);
103 PointerAlignInBytes =
104 C.toCharUnitsFromBits(C.getTargetInfo().getPointerAlign(0)).getQuantity();
105 IntTy = llvm::IntegerType::get(LLVMContext, C.getTargetInfo().getIntWidth());
106 IntPtrTy = llvm::IntegerType::get(LLVMContext, PointerWidthInBits);
107 Int8PtrTy = Int8Ty->getPointerTo(0);
108 Int8PtrPtrTy = Int8PtrTy->getPointerTo(0);
109
David Blaikie4e4d0842012-03-11 07:00:24 +0000110 if (LangOpts.ObjC1)
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000111 createObjCRuntime();
David Blaikie4e4d0842012-03-11 07:00:24 +0000112 if (LangOpts.OpenCL)
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000113 createOpenCLRuntime();
David Blaikie4e4d0842012-03-11 07:00:24 +0000114 if (LangOpts.CUDA)
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000115 createCUDARuntime();
Sanjiv Guptae8b9f5b2008-05-08 08:54:20 +0000116
Kostya Serebryanyc9fe6052012-04-24 06:57:01 +0000117 // Enable TBAA unless it's suppressed. ThreadSanitizer needs TBAA even at O0.
Will Dietz4f45bc02013-01-18 11:30:38 +0000118 if (SanOpts.Thread ||
Kostya Serebryanyc9fe6052012-04-24 06:57:01 +0000119 (!CodeGenOpts.RelaxedAliasing && CodeGenOpts.OptimizationLevel > 0))
120 TBAA = new CodeGenTBAA(Context, VMContext, CodeGenOpts, getLangOpts(),
Dan Gohman0b5c4fc2010-10-15 20:23:12 +0000121 ABI.getMangleContext());
Dan Gohman3d5aff52010-10-14 23:06:10 +0000122
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000123 // If debug info or coverage generation is enabled, create the CGDebugInfo
124 // object.
Douglas Gregor4cdad312012-10-23 20:05:01 +0000125 if (CodeGenOpts.getDebugInfo() != CodeGenOptions::NoDebugInfo ||
Alexey Samsonov3a70cd62012-04-27 07:24:20 +0000126 CodeGenOpts.EmitGcovArcs ||
Nick Lewyckye8ba8d72011-04-21 23:44:07 +0000127 CodeGenOpts.EmitGcovNotes)
128 DebugInfo = new CGDebugInfo(*this);
John McCalld16c2cf2011-02-08 08:22:06 +0000129
130 Block.GlobalUniqueCount = 0;
John McCall5936e332011-02-15 09:22:45 +0000131
David Blaikie4e4d0842012-03-11 07:00:24 +0000132 if (C.getLangOpts().ObjCAutoRefCount)
John McCallf85e1932011-06-15 23:02:42 +0000133 ARCData = new ARCEntrypoints();
134 RRData = new RREntrypoints();
Chris Lattner2b94fe32008-03-01 08:45:05 +0000135}
136
137CodeGenModule::~CodeGenModule() {
Peter Collingbournee9265232011-07-27 20:29:46 +0000138 delete ObjCRuntime;
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000139 delete OpenCLRuntime;
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000140 delete CUDARuntime;
Ted Kremenek0628b722011-10-08 05:28:26 +0000141 delete TheTargetCodeGenInfo;
John McCallf16aa102010-08-22 21:01:12 +0000142 delete &ABI;
Dan Gohman4376c852010-10-15 18:04:46 +0000143 delete TBAA;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000144 delete DebugInfo;
John McCallf85e1932011-06-15 23:02:42 +0000145 delete ARCData;
146 delete RRData;
Ted Kremenek815c78f2008-08-05 18:50:11 +0000147}
148
David Chisnall0d13f6f2010-01-23 02:40:42 +0000149void CodeGenModule::createObjCRuntime() {
John McCall260611a2012-06-20 06:18:46 +0000150 // This is just isGNUFamily(), but we want to force implementors of
151 // new ABIs to decide how best to do this.
152 switch (LangOpts.ObjCRuntime.getKind()) {
David Chisnall11d3f4c2012-07-03 20:49:52 +0000153 case ObjCRuntime::GNUstep:
154 case ObjCRuntime::GCC:
John McCallf7226fb2012-07-12 02:07:58 +0000155 case ObjCRuntime::ObjFW:
Peter Collingbournee9265232011-07-27 20:29:46 +0000156 ObjCRuntime = CreateGNUObjCRuntime(*this);
John McCall260611a2012-06-20 06:18:46 +0000157 return;
158
159 case ObjCRuntime::FragileMacOSX:
160 case ObjCRuntime::MacOSX:
161 case ObjCRuntime::iOS:
Peter Collingbournee9265232011-07-27 20:29:46 +0000162 ObjCRuntime = CreateMacObjCRuntime(*this);
John McCall260611a2012-06-20 06:18:46 +0000163 return;
164 }
165 llvm_unreachable("bad runtime kind");
David Chisnall0d13f6f2010-01-23 02:40:42 +0000166}
167
Peter Collingbourne8c25fc52011-09-19 21:14:35 +0000168void CodeGenModule::createOpenCLRuntime() {
169 OpenCLRuntime = new CGOpenCLRuntime(*this);
170}
171
Peter Collingbourne6c0aa5f2011-10-06 18:29:37 +0000172void CodeGenModule::createCUDARuntime() {
173 CUDARuntime = CreateNVCUDARuntime(*this);
174}
175
Ted Kremenek815c78f2008-08-05 18:50:11 +0000176void CodeGenModule::Release() {
Chris Lattner82227ff2009-03-22 21:21:57 +0000177 EmitDeferred();
Eli Friedman6c6bda32010-01-08 00:50:11 +0000178 EmitCXXGlobalInitFunc();
Daniel Dunbarefb0fa92010-03-20 04:15:41 +0000179 EmitCXXGlobalDtorFunc();
Peter Collingbournee9265232011-07-27 20:29:46 +0000180 if (ObjCRuntime)
181 if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
Daniel Dunbar208ff5e2008-08-11 18:12:00 +0000182 AddGlobalCtor(ObjCInitFunction);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000183 EmitCtorList(GlobalCtors, "llvm.global_ctors");
184 EmitCtorList(GlobalDtors, "llvm.global_dtors");
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000185 EmitGlobalAnnotations();
Daniel Dunbar02698712009-02-13 20:29:50 +0000186 EmitLLVMUsed();
Douglas Gregorf43b7212013-01-16 01:23:41 +0000187
188 if (CodeGenOpts.ModulesAutolink) {
189 EmitModuleLinkOptions();
190 }
Douglas Gregor5d75ea72013-01-14 18:28:43 +0000191
John McCallb2593832010-09-16 06:16:50 +0000192 SimplifyPersonality();
193
John McCall744016d2010-07-06 23:57:41 +0000194 if (getCodeGenOpts().EmitDeclMetadata)
195 EmitDeclMetadata();
Nick Lewycky5ea4f442011-05-04 20:46:58 +0000196
197 if (getCodeGenOpts().EmitGcovArcs || getCodeGenOpts().EmitGcovNotes)
Nick Lewycky3dc05412011-05-05 00:08:20 +0000198 EmitCoverageFile();
Devang Patelf391dbe2011-08-16 20:58:22 +0000199
200 if (DebugInfo)
201 DebugInfo->finalize();
Daniel Dunbarf1968f22008-10-01 00:49:24 +0000202}
203
Devang Patele80d5672011-03-23 16:29:39 +0000204void CodeGenModule::UpdateCompletedType(const TagDecl *TD) {
205 // Make sure that this type is translated.
206 Types.UpdateCompletedType(TD);
Devang Patele80d5672011-03-23 16:29:39 +0000207}
208
Dan Gohman3d5aff52010-10-14 23:06:10 +0000209llvm::MDNode *CodeGenModule::getTBAAInfo(QualType QTy) {
210 if (!TBAA)
211 return 0;
212 return TBAA->getTBAAInfo(QTy);
213}
214
Kostya Serebryany8cb4a072012-03-26 17:03:51 +0000215llvm::MDNode *CodeGenModule::getTBAAInfoForVTablePtr() {
216 if (!TBAA)
217 return 0;
218 return TBAA->getTBAAInfoForVTablePtr();
219}
220
Dan Gohmanb22c7dc2012-09-28 21:58:29 +0000221llvm::MDNode *CodeGenModule::getTBAAStructInfo(QualType QTy) {
222 if (!TBAA)
223 return 0;
224 return TBAA->getTBAAStructInfo(QTy);
225}
226
Dan Gohman3d5aff52010-10-14 23:06:10 +0000227void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
228 llvm::MDNode *TBAAInfo) {
229 Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
230}
231
John McCall6374c332010-03-06 00:35:14 +0000232bool CodeGenModule::isTargetDarwin() const {
Douglas Gregorbcfd1f52011-09-02 00:18:52 +0000233 return getContext().getTargetInfo().getTriple().isOSDarwin();
John McCall6374c332010-03-06 00:35:14 +0000234}
235
Chandler Carruth0f30a122012-03-30 19:44:53 +0000236void CodeGenModule::Error(SourceLocation loc, StringRef error) {
237 unsigned diagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error, error);
John McCall32096692011-03-18 02:56:14 +0000238 getDiags().Report(Context.getFullLoc(loc), diagID);
239}
240
Daniel Dunbar488e9932008-08-16 00:56:44 +0000241/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattner2c8569d2007-12-02 07:19:18 +0000242/// specified stmt yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000243void CodeGenModule::ErrorUnsupported(const Stmt *S, const char *Type,
244 bool OmitOnError) {
245 if (OmitOnError && getDiags().hasErrorOccurred())
246 return;
David Blaikied6471f72011-09-25 23:23:43 +0000247 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000248 "cannot compile this %0 yet");
Chris Lattner2c8569d2007-12-02 07:19:18 +0000249 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000250 getDiags().Report(Context.getFullLoc(S->getLocStart()), DiagID)
251 << Msg << S->getSourceRange();
Chris Lattner2c8569d2007-12-02 07:19:18 +0000252}
Chris Lattner58c3f9e2007-12-02 06:27:33 +0000253
Daniel Dunbar488e9932008-08-16 00:56:44 +0000254/// ErrorUnsupported - Print out an error that codegen doesn't support the
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000255/// specified decl yet.
Daniel Dunbar90df4b62008-09-04 03:43:08 +0000256void CodeGenModule::ErrorUnsupported(const Decl *D, const char *Type,
257 bool OmitOnError) {
258 if (OmitOnError && getDiags().hasErrorOccurred())
259 return;
David Blaikied6471f72011-09-25 23:23:43 +0000260 unsigned DiagID = getDiags().getCustomDiagID(DiagnosticsEngine::Error,
Daniel Dunbar56b80012009-02-06 19:18:03 +0000261 "cannot compile this %0 yet");
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000262 std::string Msg = Type;
Chris Lattner0a14eee2008-11-18 07:04:44 +0000263 getDiags().Report(Context.getFullLoc(D->getLocation()), DiagID) << Msg;
Chris Lattnerc6fdc342008-01-12 07:05:38 +0000264}
265
John McCallbc8d40d2011-06-24 21:55:10 +0000266llvm::ConstantInt *CodeGenModule::getSize(CharUnits size) {
267 return llvm::ConstantInt::get(SizeTy, size.getQuantity());
268}
269
Mike Stump1eb44332009-09-09 15:08:12 +0000270void CodeGenModule::setGlobalVisibility(llvm::GlobalValue *GV,
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000271 const NamedDecl *D) const {
Daniel Dunbar04d40782009-04-14 06:00:08 +0000272 // Internal definitions always have default visibility.
Chris Lattnerdf102fc2009-04-14 05:27:13 +0000273 if (GV->hasLocalLinkage()) {
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000274 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000275 return;
Daniel Dunbar7e714cd2009-04-10 20:26:50 +0000276 }
Daniel Dunbar6ab187a2009-04-07 05:48:37 +0000277
John McCallaf146032010-10-30 11:50:40 +0000278 // Set visibility for definitions.
279 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
Fariborz Jahanianc7c90582011-06-16 20:14:50 +0000280 if (LV.visibilityExplicit() || !GV->hasAvailableExternallyLinkage())
281 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
Dan Gohman4f8d1232008-05-22 00:50:06 +0000282}
283
Hans Wennborgde981f32012-06-28 08:01:44 +0000284static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(StringRef S) {
285 return llvm::StringSwitch<llvm::GlobalVariable::ThreadLocalMode>(S)
286 .Case("global-dynamic", llvm::GlobalVariable::GeneralDynamicTLSModel)
287 .Case("local-dynamic", llvm::GlobalVariable::LocalDynamicTLSModel)
288 .Case("initial-exec", llvm::GlobalVariable::InitialExecTLSModel)
289 .Case("local-exec", llvm::GlobalVariable::LocalExecTLSModel);
290}
291
292static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
293 CodeGenOptions::TLSModel M) {
294 switch (M) {
295 case CodeGenOptions::GeneralDynamicTLSModel:
296 return llvm::GlobalVariable::GeneralDynamicTLSModel;
297 case CodeGenOptions::LocalDynamicTLSModel:
298 return llvm::GlobalVariable::LocalDynamicTLSModel;
299 case CodeGenOptions::InitialExecTLSModel:
300 return llvm::GlobalVariable::InitialExecTLSModel;
301 case CodeGenOptions::LocalExecTLSModel:
302 return llvm::GlobalVariable::LocalExecTLSModel;
303 }
304 llvm_unreachable("Invalid TLS model!");
305}
306
307void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
308 const VarDecl &D) const {
309 assert(D.isThreadSpecified() && "setting TLS mode on non-TLS var!");
310
311 llvm::GlobalVariable::ThreadLocalMode TLM;
Douglas Gregor4cdad312012-10-23 20:05:01 +0000312 TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
Hans Wennborgde981f32012-06-28 08:01:44 +0000313
314 // Override the TLS model if it is explicitly specified.
315 if (D.hasAttr<TLSModelAttr>()) {
316 const TLSModelAttr *Attr = D.getAttr<TLSModelAttr>();
317 TLM = GetLLVMTLSModel(Attr->getModel());
318 }
319
320 GV->setThreadLocalMode(TLM);
321}
322
John McCallcbfe5022010-08-04 08:34:44 +0000323/// Set the symbol visibility of type information (vtable and RTTI)
324/// associated with the given type.
325void CodeGenModule::setTypeVisibility(llvm::GlobalValue *GV,
326 const CXXRecordDecl *RD,
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000327 TypeVisibilityKind TVK) const {
Anders Carlsson0ffeaad2011-01-29 19:39:23 +0000328 setGlobalVisibility(GV, RD);
John McCallcbfe5022010-08-04 08:34:44 +0000329
John McCall279b5eb2010-08-12 23:36:15 +0000330 if (!CodeGenOpts.HiddenWeakVTables)
331 return;
332
Anders Carlsson9a86a132011-01-29 20:36:11 +0000333 // We never want to drop the visibility for RTTI names.
334 if (TVK == TVK_ForRTTIName)
335 return;
336
John McCallcbfe5022010-08-04 08:34:44 +0000337 // We want to drop the visibility to hidden for weak type symbols.
338 // This isn't possible if there might be unresolved references
339 // elsewhere that rely on this symbol being visible.
340
John McCall7a536902010-08-05 20:39:18 +0000341 // This should be kept roughly in sync with setThunkVisibility
342 // in CGVTables.cpp.
343
John McCallcbfe5022010-08-04 08:34:44 +0000344 // Preconditions.
Anders Carlssonf502d932011-01-24 00:46:19 +0000345 if (GV->getLinkage() != llvm::GlobalVariable::LinkOnceODRLinkage ||
John McCallcbfe5022010-08-04 08:34:44 +0000346 GV->getVisibility() != llvm::GlobalVariable::DefaultVisibility)
347 return;
348
349 // Don't override an explicit visibility attribute.
John McCalld4c3d662013-02-20 01:54:26 +0000350 if (RD->getExplicitVisibility(NamedDecl::VisibilityForType))
John McCallcbfe5022010-08-04 08:34:44 +0000351 return;
352
353 switch (RD->getTemplateSpecializationKind()) {
354 // We have to disable the optimization if this is an EI definition
355 // because there might be EI declarations in other shared objects.
356 case TSK_ExplicitInstantiationDefinition:
357 case TSK_ExplicitInstantiationDeclaration:
358 return;
359
John McCall7a536902010-08-05 20:39:18 +0000360 // Every use of a non-template class's type information has to emit it.
John McCallcbfe5022010-08-04 08:34:44 +0000361 case TSK_Undeclared:
362 break;
363
John McCall7a536902010-08-05 20:39:18 +0000364 // In theory, implicit instantiations can ignore the possibility of
365 // an explicit instantiation declaration because there necessarily
366 // must be an EI definition somewhere with default visibility. In
367 // practice, it's possible to have an explicit instantiation for
368 // an arbitrary template class, and linkers aren't necessarily able
369 // to deal with mixed-visibility symbols.
370 case TSK_ExplicitSpecialization:
John McCallcbfe5022010-08-04 08:34:44 +0000371 case TSK_ImplicitInstantiation:
Douglas Gregoraafd1112012-10-24 14:11:55 +0000372 return;
John McCallcbfe5022010-08-04 08:34:44 +0000373 }
374
375 // If there's a key function, there may be translation units
376 // that don't have the key function's definition. But ignore
377 // this if we're emitting RTTI under -fno-rtti.
David Blaikie4e4d0842012-03-11 07:00:24 +0000378 if (!(TVK != TVK_ForRTTI) || LangOpts.RTTI) {
John McCalld5617ee2013-01-25 22:31:03 +0000379 // FIXME: what should we do if we "lose" the key function during
380 // the emission of the file?
381 if (Context.getCurrentKeyFunction(RD))
John McCallcbfe5022010-08-04 08:34:44 +0000382 return;
Anders Carlssonfa2e99f2011-01-29 20:24:48 +0000383 }
John McCallcbfe5022010-08-04 08:34:44 +0000384
385 // Otherwise, drop the visibility to hidden.
386 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
Rafael Espindolab1c65ff2011-01-11 21:44:37 +0000387 GV->setUnnamedAddr(true);
John McCallcbfe5022010-08-04 08:34:44 +0000388}
389
Chris Lattner5f9e2722011-07-23 10:55:15 +0000390StringRef CodeGenModule::getMangledName(GlobalDecl GD) {
Anders Carlsson793a9902010-06-22 16:05:32 +0000391 const NamedDecl *ND = cast<NamedDecl>(GD.getDecl());
392
Chris Lattner5f9e2722011-07-23 10:55:15 +0000393 StringRef &Str = MangledDeclNames[GD.getCanonicalDecl()];
Anders Carlsson793a9902010-06-22 16:05:32 +0000394 if (!Str.empty())
395 return Str;
396
John McCall4c40d982010-08-31 07:33:07 +0000397 if (!getCXXABI().getMangleContext().shouldMangleDeclName(ND)) {
Anders Carlsson793a9902010-06-22 16:05:32 +0000398 IdentifierInfo *II = ND->getIdentifier();
399 assert(II && "Attempt to mangle unnamed decl.");
400
401 Str = II->getName();
402 return Str;
403 }
404
Dylan Noblesmithf7ccbad2012-02-05 02:13:05 +0000405 SmallString<256> Buffer;
Rafael Espindolac4850c22011-02-10 23:59:36 +0000406 llvm::raw_svector_ostream Out(Buffer);
Anders Carlsson793a9902010-06-22 16:05:32 +0000407 if (const CXXConstructorDecl *D = dyn_cast<CXXConstructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000408 getCXXABI().getMangleContext().mangleCXXCtor(D, GD.getCtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000409 else if (const CXXDestructorDecl *D = dyn_cast<CXXDestructorDecl>(ND))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000410 getCXXABI().getMangleContext().mangleCXXDtor(D, GD.getDtorType(), Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000411 else if (const BlockDecl *BD = dyn_cast<BlockDecl>(ND))
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000412 getCXXABI().getMangleContext().mangleBlock(BD, Out,
413 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()));
Anders Carlsson793a9902010-06-22 16:05:32 +0000414 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000415 getCXXABI().getMangleContext().mangleName(ND, Out);
Anders Carlsson793a9902010-06-22 16:05:32 +0000416
417 // Allocate space for the mangled name.
Rafael Espindolac4850c22011-02-10 23:59:36 +0000418 Out.flush();
Anders Carlsson793a9902010-06-22 16:05:32 +0000419 size_t Length = Buffer.size();
420 char *Name = MangledNamesAllocator.Allocate<char>(Length);
421 std::copy(Buffer.begin(), Buffer.end(), Name);
422
Chris Lattner5f9e2722011-07-23 10:55:15 +0000423 Str = StringRef(Name, Length);
Anders Carlsson793a9902010-06-22 16:05:32 +0000424
425 return Str;
426}
427
Peter Collingbourne14110472011-01-13 18:57:25 +0000428void CodeGenModule::getBlockMangledName(GlobalDecl GD, MangleBuffer &Buffer,
429 const BlockDecl *BD) {
430 MangleContext &MangleCtx = getCXXABI().getMangleContext();
431 const Decl *D = GD.getDecl();
Rafael Espindolac4850c22011-02-10 23:59:36 +0000432 llvm::raw_svector_ostream Out(Buffer.getBuffer());
Peter Collingbourne14110472011-01-13 18:57:25 +0000433 if (D == 0)
Fariborz Jahanian4904bf42012-06-26 16:06:38 +0000434 MangleCtx.mangleGlobalBlock(BD,
435 dyn_cast_or_null<VarDecl>(initializedGlobalDecl.getDecl()), Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000436 else if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000437 MangleCtx.mangleCtorBlock(CD, GD.getCtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000438 else if (const CXXDestructorDecl *DD = dyn_cast<CXXDestructorDecl>(D))
Rafael Espindolac4850c22011-02-10 23:59:36 +0000439 MangleCtx.mangleDtorBlock(DD, GD.getDtorType(), BD, Out);
Peter Collingbourne14110472011-01-13 18:57:25 +0000440 else
Rafael Espindolac4850c22011-02-10 23:59:36 +0000441 MangleCtx.mangleBlock(cast<DeclContext>(D), BD, Out);
Anders Carlsson9a8822b2010-06-09 02:36:32 +0000442}
443
Chris Lattner5f9e2722011-07-23 10:55:15 +0000444llvm::GlobalValue *CodeGenModule::GetGlobalValue(StringRef Name) {
John McCallf746aa62010-03-19 23:29:14 +0000445 return getModule().getNamedValue(Name);
Douglas Gregor5f2bfd42009-02-13 00:10:09 +0000446}
447
Chris Lattner6d397602008-03-14 17:18:18 +0000448/// AddGlobalCtor - Add a function to the list that will be called before
449/// main() runs.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000450void CodeGenModule::AddGlobalCtor(llvm::Function * Ctor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000451 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000452 GlobalCtors.push_back(std::make_pair(Ctor, Priority));
Chris Lattner6d397602008-03-14 17:18:18 +0000453}
454
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000455/// AddGlobalDtor - Add a function to the list that will be called
456/// when the module is unloaded.
457void CodeGenModule::AddGlobalDtor(llvm::Function * Dtor, int Priority) {
Daniel Dunbar49988882009-01-13 02:25:00 +0000458 // FIXME: Type coercion of void()* types.
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000459 GlobalDtors.push_back(std::make_pair(Dtor, Priority));
460}
461
462void CodeGenModule::EmitCtorList(const CtorList &Fns, const char *GlobalName) {
463 // Ctor function type is void()*.
John McCall0774cb82011-05-15 01:53:33 +0000464 llvm::FunctionType* CtorFTy = llvm::FunctionType::get(VoidTy, false);
Owen Anderson96e0fc72009-07-29 22:16:19 +0000465 llvm::Type *CtorPFTy = llvm::PointerType::getUnqual(CtorFTy);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000466
467 // Get the type of a ctor entry, { i32, void ()* }.
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000468 llvm::StructType *CtorStructTy =
Chris Lattner8b418682012-02-07 00:39:47 +0000469 llvm::StructType::get(Int32Ty, llvm::PointerType::getUnqual(CtorFTy), NULL);
Chris Lattner6d397602008-03-14 17:18:18 +0000470
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000471 // Construct the constructor and destructor arrays.
Chris Lattner0b239712012-02-06 22:16:34 +0000472 SmallVector<llvm::Constant*, 8> Ctors;
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000473 for (CtorList::const_iterator I = Fns.begin(), E = Fns.end(); I != E; ++I) {
Chris Lattner0b239712012-02-06 22:16:34 +0000474 llvm::Constant *S[] = {
475 llvm::ConstantInt::get(Int32Ty, I->second, false),
476 llvm::ConstantExpr::getBitCast(I->first, CtorPFTy)
477 };
Owen Anderson08e25242009-07-27 22:29:56 +0000478 Ctors.push_back(llvm::ConstantStruct::get(CtorStructTy, S));
Chris Lattner6d397602008-03-14 17:18:18 +0000479 }
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000480
481 if (!Ctors.empty()) {
Owen Anderson96e0fc72009-07-29 22:16:19 +0000482 llvm::ArrayType *AT = llvm::ArrayType::get(CtorStructTy, Ctors.size());
Owen Anderson1c431b32009-07-08 19:05:04 +0000483 new llvm::GlobalVariable(TheModule, AT, false,
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000484 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000485 llvm::ConstantArray::get(AT, Ctors),
Owen Anderson1c431b32009-07-08 19:05:04 +0000486 GlobalName);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +0000487 }
Chris Lattner6d397602008-03-14 17:18:18 +0000488}
489
John McCalld46f9852010-02-19 01:32:20 +0000490llvm::GlobalValue::LinkageTypes
491CodeGenModule::getFunctionLinkage(const FunctionDecl *D) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000492 GVALinkage Linkage = getContext().GetGVALinkageForFunction(D);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000493
Chris Lattnerf81530652010-06-30 16:58:07 +0000494 if (Linkage == GVA_Internal)
John McCalld46f9852010-02-19 01:32:20 +0000495 return llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000496
497 if (D->hasAttr<DLLExportAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000498 return llvm::Function::DLLExportLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000499
500 if (D->hasAttr<WeakAttr>())
John McCalld46f9852010-02-19 01:32:20 +0000501 return llvm::Function::WeakAnyLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000502
503 // In C99 mode, 'inline' functions are guaranteed to have a strong
504 // definition somewhere else, so we can use available_externally linkage.
505 if (Linkage == GVA_C99Inline)
Fariborz Jahanianfd0f89d2011-02-04 00:08:13 +0000506 return llvm::Function::AvailableExternallyLinkage;
John McCall5584d912011-09-19 18:05:26 +0000507
508 // Note that Apple's kernel linker doesn't support symbol
509 // coalescing, so we need to avoid linkonce and weak linkages there.
510 // Normally, this means we just map to internal, but for explicit
511 // instantiations we'll map to external.
512
Chris Lattnerf81530652010-06-30 16:58:07 +0000513 // In C++, the compiler has to emit a definition in every translation unit
514 // that references the function. We should use linkonce_odr because
515 // a) if all references in this translation unit are optimized away, we
516 // don't need to codegen it. b) if the function persists, it needs to be
517 // merged with other definitions. c) C++ has the ODR, so we know the
518 // definition is dependable.
519 if (Linkage == GVA_CXXInline || Linkage == GVA_TemplateInstantiation)
David Blaikie4e4d0842012-03-11 07:00:24 +0000520 return !Context.getLangOpts().AppleKext
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000521 ? llvm::Function::LinkOnceODRLinkage
522 : llvm::Function::InternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000523
524 // An explicit instantiation of a template has weak linkage, since
525 // explicit instantiations can occur in multiple translation units
526 // and must all be equivalent. However, we are not allowed to
527 // throw away these explicit instantiations.
528 if (Linkage == GVA_ExplicitTemplateInstantiation)
David Blaikie4e4d0842012-03-11 07:00:24 +0000529 return !Context.getLangOpts().AppleKext
Fariborz Jahanian142f9e92011-02-04 00:01:24 +0000530 ? llvm::Function::WeakODRLinkage
John McCall5584d912011-09-19 18:05:26 +0000531 : llvm::Function::ExternalLinkage;
Chris Lattnerf81530652010-06-30 16:58:07 +0000532
533 // Otherwise, we have strong external linkage.
534 assert(Linkage == GVA_StrongExternal);
535 return llvm::Function::ExternalLinkage;
John McCalld46f9852010-02-19 01:32:20 +0000536}
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000537
John McCalld46f9852010-02-19 01:32:20 +0000538
539/// SetFunctionDefinitionAttributes - Set attributes for a global.
540///
541/// FIXME: This is currently only done for aliases and functions, but not for
542/// variables (these details are set in EmitGlobalVarDefinition for variables).
543void CodeGenModule::SetFunctionDefinitionAttributes(const FunctionDecl *D,
544 llvm::GlobalValue *GV) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000545 SetCommonAttributes(D, GV);
Nuno Lopesd4cbda62008-06-08 15:45:52 +0000546}
547
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000548void CodeGenModule::SetLLVMFunctionAttributes(const Decl *D,
Mike Stump1eb44332009-09-09 15:08:12 +0000549 const CGFunctionInfo &Info,
Daniel Dunbar7dbd8192009-04-14 07:08:30 +0000550 llvm::Function *F) {
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000551 unsigned CallingConv;
Devang Patel761d7f72008-09-25 21:02:23 +0000552 AttributeListType AttributeList;
Bill Wendling94236e72013-02-22 00:13:35 +0000553 ConstructAttributeList(Info, D, AttributeList, CallingConv, false);
Bill Wendling785b7782012-12-07 23:17:26 +0000554 F->setAttributes(llvm::AttributeSet::get(getLLVMContext(), AttributeList));
Daniel Dunbarca6408c2009-09-12 00:59:20 +0000555 F->setCallingConv(static_cast<llvm::CallingConv::ID>(CallingConv));
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000556}
557
John McCalld1e40d52011-10-02 01:16:38 +0000558/// Determines whether the language options require us to model
559/// unwind exceptions. We treat -fexceptions as mandating this
560/// except under the fragile ObjC ABI with only ObjC exceptions
561/// enabled. This means, for example, that C with -fexceptions
562/// enables this.
David Blaikie4e4d0842012-03-11 07:00:24 +0000563static bool hasUnwindExceptions(const LangOptions &LangOpts) {
John McCalld1e40d52011-10-02 01:16:38 +0000564 // If exceptions are completely disabled, obviously this is false.
David Blaikie4e4d0842012-03-11 07:00:24 +0000565 if (!LangOpts.Exceptions) return false;
John McCalld1e40d52011-10-02 01:16:38 +0000566
567 // If C++ exceptions are enabled, this is true.
David Blaikie4e4d0842012-03-11 07:00:24 +0000568 if (LangOpts.CXXExceptions) return true;
John McCalld1e40d52011-10-02 01:16:38 +0000569
570 // If ObjC exceptions are enabled, this depends on the ABI.
David Blaikie4e4d0842012-03-11 07:00:24 +0000571 if (LangOpts.ObjCExceptions) {
David Chisnall11d3f4c2012-07-03 20:49:52 +0000572 return LangOpts.ObjCRuntime.hasUnwindExceptions();
John McCalld1e40d52011-10-02 01:16:38 +0000573 }
574
575 return true;
576}
577
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000578void CodeGenModule::SetLLVMFunctionAttributesForDefinition(const Decl *D,
579 llvm::Function *F) {
Rafael Espindolaabca5a12011-05-25 03:44:55 +0000580 if (CodeGenOpts.UnwindTables)
581 F->setHasUWTable();
582
David Blaikie4e4d0842012-03-11 07:00:24 +0000583 if (!hasUnwindExceptions(LangOpts))
Bill Wendling72390b32012-12-20 19:27:06 +0000584 F->addFnAttr(llvm::Attribute::NoUnwind);
Daniel Dunbaraf668b02008-10-28 00:17:57 +0000585
Eli Friedman2873aee2011-08-22 23:55:33 +0000586 if (D->hasAttr<NakedAttr>()) {
587 // Naked implies noinline: we should not be inlining such functions.
Bill Wendling72390b32012-12-20 19:27:06 +0000588 F->addFnAttr(llvm::Attribute::Naked);
589 F->addFnAttr(llvm::Attribute::NoInline);
Eli Friedman2873aee2011-08-22 23:55:33 +0000590 }
Daniel Dunbardd0cb222010-09-29 18:20:25 +0000591
Mike Stump1feade82009-08-26 22:31:08 +0000592 if (D->hasAttr<NoInlineAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +0000593 F->addFnAttr(llvm::Attribute::NoInline);
Mike Stumpf55314d2009-10-05 21:58:44 +0000594
Eli Friedman2873aee2011-08-22 23:55:33 +0000595 // (noinline wins over always_inline, and we can't specify both in IR)
Michael J. Spenceradc6cbf2012-06-18 07:00:48 +0000596 if ((D->hasAttr<AlwaysInlineAttr>() || D->hasAttr<ForceInlineAttr>()) &&
Bill Wendling01ad9542012-12-30 10:32:17 +0000597 !F->getAttributes().hasAttribute(llvm::AttributeSet::FunctionIndex,
598 llvm::Attribute::NoInline))
Bill Wendling72390b32012-12-20 19:27:06 +0000599 F->addFnAttr(llvm::Attribute::AlwaysInline);
Eli Friedman2873aee2011-08-22 23:55:33 +0000600
Benjamin Krameree409a92012-05-12 21:10:52 +0000601 // FIXME: Communicate hot and cold attributes to LLVM more directly.
602 if (D->hasAttr<ColdAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +0000603 F->addFnAttr(llvm::Attribute::OptimizeForSize);
Benjamin Krameree409a92012-05-12 21:10:52 +0000604
Quentin Colombetaee56fa2012-11-01 23:55:47 +0000605 if (D->hasAttr<MinSizeAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +0000606 F->addFnAttr(llvm::Attribute::MinSize);
Quentin Colombetaee56fa2012-11-01 23:55:47 +0000607
Rafael Espindolac5f657f2011-01-11 00:26:26 +0000608 if (isa<CXXConstructorDecl>(D) || isa<CXXDestructorDecl>(D))
609 F->setUnnamedAddr(true);
610
Richard Smithef4d5ce2012-09-28 22:46:07 +0000611 if (const CXXMethodDecl *MD = dyn_cast<CXXMethodDecl>(D))
612 if (MD->isVirtual())
613 F->setUnnamedAddr(true);
614
David Blaikie4e4d0842012-03-11 07:00:24 +0000615 if (LangOpts.getStackProtector() == LangOptions::SSPOn)
Bill Wendling72390b32012-12-20 19:27:06 +0000616 F->addFnAttr(llvm::Attribute::StackProtect);
David Blaikie4e4d0842012-03-11 07:00:24 +0000617 else if (LangOpts.getStackProtector() == LangOptions::SSPReq)
Bill Wendling72390b32012-12-20 19:27:06 +0000618 F->addFnAttr(llvm::Attribute::StackProtectReq);
Will Dietz4f45bc02013-01-18 11:30:38 +0000619
620 if (SanOpts.Address) {
Alexander Potapenko89651ea2012-02-02 11:49:28 +0000621 // When AddressSanitizer is enabled, set AddressSafety attribute
622 // unless __attribute__((no_address_safety_analysis)) is used.
623 if (!D->hasAttr<NoAddressSafetyAnalysisAttr>())
Bill Wendling72390b32012-12-20 19:27:06 +0000624 F->addFnAttr(llvm::Attribute::AddressSafety);
Alexander Potapenko89651ea2012-02-02 11:49:28 +0000625 }
626
Sean Huntcf807c42010-08-18 23:23:40 +0000627 unsigned alignment = D->getMaxAlignment() / Context.getCharWidth();
628 if (alignment)
629 F->setAlignment(alignment);
630
Mike Stumpfb51ddf2009-10-05 22:49:20 +0000631 // C++ ABI requires 2-byte alignment for member functions.
Mike Stumpbd6dbd12009-10-05 23:08:21 +0000632 if (F->getAlignment() < 2 && isa<CXXMethodDecl>(D))
633 F->setAlignment(2);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000634}
635
Mike Stump1eb44332009-09-09 15:08:12 +0000636void CodeGenModule::SetCommonAttributes(const Decl *D,
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000637 llvm::GlobalValue *GV) {
Anders Carlsson934176f2011-01-29 19:41:00 +0000638 if (const NamedDecl *ND = dyn_cast<NamedDecl>(D))
639 setGlobalVisibility(GV, ND);
John McCall1fb0caa2010-10-22 21:05:15 +0000640 else
641 GV->setVisibility(llvm::GlobalValue::DefaultVisibility);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000642
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000643 if (D->hasAttr<UsedAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000644 AddUsedGlobal(GV);
645
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000646 if (const SectionAttr *SA = D->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000647 GV->setSection(SA->getName());
Anton Korobeynikov82d0a412010-01-10 12:58:08 +0000648
649 getTargetCodeGenInfo().SetTargetAttributes(D, GV, *this);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000650}
651
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000652void CodeGenModule::SetInternalFunctionAttributes(const Decl *D,
653 llvm::Function *F,
654 const CGFunctionInfo &FI) {
655 SetLLVMFunctionAttributes(D, FI, F);
656 SetLLVMFunctionAttributesForDefinition(D, F);
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000657
658 F->setLinkage(llvm::Function::InternalLinkage);
659
Daniel Dunbar0e4f40e2009-04-17 00:48:04 +0000660 SetCommonAttributes(D, F);
Daniel Dunbarf80519b2008-09-04 23:41:35 +0000661}
662
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000663void CodeGenModule::SetFunctionAttributes(GlobalDecl GD,
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000664 llvm::Function *F,
665 bool IsIncompleteFunction) {
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +0000666 if (unsigned IID = F->getIntrinsicID()) {
667 // If this is an intrinsic function, set the function's attributes
668 // to the intrinsic's attributes.
Bill Wendling50e6b182012-10-15 04:47:45 +0000669 F->setAttributes(llvm::Intrinsic::getAttributes(getLLVMContext(),
670 (llvm::Intrinsic::ID)IID));
Peter Collingbourne0ac2cf42011-04-06 12:29:04 +0000671 return;
672 }
673
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +0000674 const FunctionDecl *FD = cast<FunctionDecl>(GD.getDecl());
675
Eli Friedmanc6c14d12009-05-26 01:22:57 +0000676 if (!IsIncompleteFunction)
John McCallde5d3c72012-02-17 03:33:10 +0000677 SetLLVMFunctionAttributes(FD, getTypes().arrangeGlobalDeclaration(GD), F);
Mike Stump1eb44332009-09-09 15:08:12 +0000678
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000679 // Only a few attributes are set on declarations; these may later be
680 // overridden by a definition.
Mike Stump1eb44332009-09-09 15:08:12 +0000681
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000682 if (FD->hasAttr<DLLImportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000683 F->setLinkage(llvm::Function::DLLImportLinkage);
Mike Stump1eb44332009-09-09 15:08:12 +0000684 } else if (FD->hasAttr<WeakAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +0000685 FD->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000686 // "extern_weak" is overloaded in LLVM; we probably should have
Mike Stump1eb44332009-09-09 15:08:12 +0000687 // separate linkage types for this.
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000688 F->setLinkage(llvm::Function::ExternalWeakLinkage);
689 } else {
Mike Stump1eb44332009-09-09 15:08:12 +0000690 F->setLinkage(llvm::Function::ExternalLinkage);
John McCallaf146032010-10-30 11:50:40 +0000691
692 NamedDecl::LinkageInfo LV = FD->getLinkageAndVisibility();
693 if (LV.linkage() == ExternalLinkage && LV.visibilityExplicit()) {
694 F->setVisibility(GetLLVMVisibility(LV.visibility()));
695 }
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000696 }
697
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +0000698 if (const SectionAttr *SA = FD->getAttr<SectionAttr>())
Daniel Dunbar7c65e992009-04-14 08:05:55 +0000699 F->setSection(SA->getName());
Daniel Dunbar219df662008-09-08 23:44:31 +0000700}
701
Daniel Dunbar02698712009-02-13 20:29:50 +0000702void CodeGenModule::AddUsedGlobal(llvm::GlobalValue *GV) {
Mike Stump1eb44332009-09-09 15:08:12 +0000703 assert(!GV->isDeclaration() &&
Daniel Dunbar02698712009-02-13 20:29:50 +0000704 "Only globals with definition can force usage.");
Chris Lattner35f38a22009-03-31 22:37:52 +0000705 LLVMUsed.push_back(GV);
Daniel Dunbar02698712009-02-13 20:29:50 +0000706}
707
708void CodeGenModule::EmitLLVMUsed() {
709 // Don't create llvm.used if there is no need.
Chris Lattnerad64e022009-07-17 23:57:13 +0000710 if (LLVMUsed.empty())
Daniel Dunbar02698712009-02-13 20:29:50 +0000711 return;
712
Chris Lattner35f38a22009-03-31 22:37:52 +0000713 // Convert LLVMUsed to what ConstantArray needs.
Chris Lattner0b239712012-02-06 22:16:34 +0000714 SmallVector<llvm::Constant*, 8> UsedArray;
Chris Lattner35f38a22009-03-31 22:37:52 +0000715 UsedArray.resize(LLVMUsed.size());
716 for (unsigned i = 0, e = LLVMUsed.size(); i != e; ++i) {
Mike Stump1eb44332009-09-09 15:08:12 +0000717 UsedArray[i] =
718 llvm::ConstantExpr::getBitCast(cast<llvm::Constant>(&*LLVMUsed[i]),
Chris Lattner0b239712012-02-06 22:16:34 +0000719 Int8PtrTy);
Chris Lattner35f38a22009-03-31 22:37:52 +0000720 }
Mike Stump1eb44332009-09-09 15:08:12 +0000721
Fariborz Jahanianc38e9af2009-06-23 21:47:46 +0000722 if (UsedArray.empty())
723 return;
Chris Lattner0b239712012-02-06 22:16:34 +0000724 llvm::ArrayType *ATy = llvm::ArrayType::get(Int8PtrTy, UsedArray.size());
Mike Stump1eb44332009-09-09 15:08:12 +0000725
726 llvm::GlobalVariable *GV =
727 new llvm::GlobalVariable(getModule(), ATy, false,
Daniel Dunbar02698712009-02-13 20:29:50 +0000728 llvm::GlobalValue::AppendingLinkage,
Owen Anderson7db6d832009-07-28 18:33:04 +0000729 llvm::ConstantArray::get(ATy, UsedArray),
Owen Anderson1c431b32009-07-08 19:05:04 +0000730 "llvm.used");
Daniel Dunbar02698712009-02-13 20:29:50 +0000731
732 GV->setSection("llvm.metadata");
733}
734
Douglas Gregor858afb32013-01-14 20:53:57 +0000735/// \brief Add link options implied by the given module, including modules
736/// it depends on, using a postorder walk.
737static void addLinkOptionsPostorder(llvm::LLVMContext &Context,
738 Module *Mod,
Daniel Dunbarf9d03c12013-01-17 01:35:06 +0000739 SmallVectorImpl<llvm::Value *> &Metadata,
Douglas Gregor858afb32013-01-14 20:53:57 +0000740 llvm::SmallPtrSet<Module *, 16> &Visited) {
741 // Import this module's parent.
742 if (Mod->Parent && Visited.insert(Mod->Parent)) {
743 addLinkOptionsPostorder(Context, Mod->Parent, Metadata, Visited);
744 }
745
746 // Import this module's dependencies.
747 for (unsigned I = Mod->Imports.size(); I > 0; --I) {
748 if (Visited.insert(Mod->Imports[I-1]))
749 addLinkOptionsPostorder(Context, Mod->Imports[I-1], Metadata, Visited);
750 }
751
752 // Add linker options to link against the libraries/frameworks
753 // described by this module.
754 for (unsigned I = Mod->LinkLibraries.size(); I > 0; --I) {
755 // FIXME: -lfoo is Unix-centric and -framework Foo is Darwin-centric.
756 // We need to know more about the linker to know how to encode these
757 // options propertly.
758
759 // Link against a framework.
760 if (Mod->LinkLibraries[I-1].IsFramework) {
761 llvm::Value *Args[2] = {
762 llvm::MDString::get(Context, "-framework"),
763 llvm::MDString::get(Context, Mod->LinkLibraries[I-1].Library)
764 };
765
766 Metadata.push_back(llvm::MDNode::get(Context, Args));
767 continue;
768 }
769
770 // Link against a library.
771 llvm::Value *OptString
772 = llvm::MDString::get(Context,
773 "-l" + Mod->LinkLibraries[I-1].Library);
774 Metadata.push_back(llvm::MDNode::get(Context, OptString));
775 }
776}
777
778void CodeGenModule::EmitModuleLinkOptions() {
779 // Collect the set of all of the modules we want to visit to emit link
780 // options, which is essentially the imported modules and all of their
781 // non-explicit child modules.
782 llvm::SetVector<clang::Module *> LinkModules;
783 llvm::SmallPtrSet<clang::Module *, 16> Visited;
784 SmallVector<clang::Module *, 16> Stack;
785
786 // Seed the stack with imported modules.
787 for (llvm::SetVector<clang::Module *>::iterator M = ImportedModules.begin(),
788 MEnd = ImportedModules.end();
789 M != MEnd; ++M) {
790 if (Visited.insert(*M))
791 Stack.push_back(*M);
792 }
793
794 // Find all of the modules to import, making a little effort to prune
795 // non-leaf modules.
796 while (!Stack.empty()) {
797 clang::Module *Mod = Stack.back();
798 Stack.pop_back();
799
800 bool AnyChildren = false;
801
802 // Visit the submodules of this module.
803 for (clang::Module::submodule_iterator Sub = Mod->submodule_begin(),
804 SubEnd = Mod->submodule_end();
805 Sub != SubEnd; ++Sub) {
806 // Skip explicit children; they need to be explicitly imported to be
807 // linked against.
808 if ((*Sub)->IsExplicit)
809 continue;
810
811 if (Visited.insert(*Sub)) {
812 Stack.push_back(*Sub);
813 AnyChildren = true;
814 }
815 }
816
817 // We didn't find any children, so add this module to the list of
818 // modules to link against.
819 if (!AnyChildren) {
820 LinkModules.insert(Mod);
821 }
822 }
823
824 // Add link options for all of the imported modules in reverse topological
825 // order.
Daniel Dunbarf9d03c12013-01-17 01:35:06 +0000826 SmallVector<llvm::Value *, 16> MetadataArgs;
Douglas Gregor858afb32013-01-14 20:53:57 +0000827 Visited.clear();
828 for (llvm::SetVector<clang::Module *>::iterator M = LinkModules.begin(),
829 MEnd = LinkModules.end();
830 M != MEnd; ++M) {
831 if (Visited.insert(*M))
832 addLinkOptionsPostorder(getLLVMContext(), *M, MetadataArgs, Visited);
833 }
Daniel Dunbarf9d03c12013-01-17 01:35:06 +0000834 std::reverse(MetadataArgs.begin(), MetadataArgs.end());
Douglas Gregor858afb32013-01-14 20:53:57 +0000835
Daniel Dunbarf9d03c12013-01-17 01:35:06 +0000836 // Add the linker options metadata flag.
837 getModule().addModuleFlag(llvm::Module::AppendUnique, "Linker Options",
838 llvm::MDNode::get(getLLVMContext(), MetadataArgs));
Douglas Gregor858afb32013-01-14 20:53:57 +0000839}
840
Daniel Dunbar02698712009-02-13 20:29:50 +0000841void CodeGenModule::EmitDeferred() {
Chris Lattner67b00522009-03-21 09:44:56 +0000842 // Emit code for any potentially referenced deferred decls. Since a
843 // previously unused static decl may become used during the generation of code
Nick Lewyckydce67a72011-07-18 05:26:13 +0000844 // for a static function, iterate until no changes are made.
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000845
John McCalld5617ee2013-01-25 22:31:03 +0000846 while (true) {
Anders Carlsson046c2942010-04-17 20:15:18 +0000847 if (!DeferredVTables.empty()) {
John McCalld5617ee2013-01-25 22:31:03 +0000848 EmitDeferredVTables();
849
850 // Emitting a v-table doesn't directly cause more v-tables to
851 // become deferred, although it can cause functions to be
852 // emitted that then need those v-tables.
853 assert(DeferredVTables.empty());
Rafael Espindolabbf58bb2010-03-10 02:19:29 +0000854 }
855
John McCalld5617ee2013-01-25 22:31:03 +0000856 // Stop if we're out of both deferred v-tables and deferred declarations.
857 if (DeferredDeclsToEmit.empty()) break;
858
Anders Carlsson2a131fb2009-05-05 04:44:02 +0000859 GlobalDecl D = DeferredDeclsToEmit.back();
Chris Lattner67b00522009-03-21 09:44:56 +0000860 DeferredDeclsToEmit.pop_back();
861
John McCallc76702c2010-05-27 01:45:30 +0000862 // Check to see if we've already emitted this. This is necessary
863 // for a couple of reasons: first, decls can end up in the
864 // deferred-decls queue multiple times, and second, decls can end
865 // up with definitions in unusual ways (e.g. by an extern inline
866 // function acquiring a strong function redefinition). Just
867 // ignore these cases.
868 //
869 // TODO: That said, looking this up multiple times is very wasteful.
Chris Lattner5f9e2722011-07-23 10:55:15 +0000870 StringRef Name = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +0000871 llvm::GlobalValue *CGRef = GetGlobalValue(Name);
Chris Lattner67b00522009-03-21 09:44:56 +0000872 assert(CGRef && "Deferred decl wasn't referenced?");
Mike Stump1eb44332009-09-09 15:08:12 +0000873
Chris Lattner67b00522009-03-21 09:44:56 +0000874 if (!CGRef->isDeclaration())
875 continue;
Mike Stump1eb44332009-09-09 15:08:12 +0000876
John McCallc76702c2010-05-27 01:45:30 +0000877 // GlobalAlias::isDeclaration() defers to the aliasee, but for our
878 // purposes an alias counts as a definition.
879 if (isa<llvm::GlobalAlias>(CGRef))
880 continue;
881
Chris Lattner67b00522009-03-21 09:44:56 +0000882 // Otherwise, emit the definition and move on to the next one.
883 EmitGlobalDefinition(D);
884 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000885}
886
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000887void CodeGenModule::EmitGlobalAnnotations() {
888 if (Annotations.empty())
889 return;
890
891 // Create a new global variable for the ConstantStruct in the Module.
892 llvm::Constant *Array = llvm::ConstantArray::get(llvm::ArrayType::get(
893 Annotations[0]->getType(), Annotations.size()), Annotations);
894 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(),
895 Array->getType(), false, llvm::GlobalValue::AppendingLinkage, Array,
896 "llvm.global.annotations");
897 gv->setSection(AnnotationSection);
898}
899
Dmitri Gribenkocfa88f82013-01-12 19:30:44 +0000900llvm::Constant *CodeGenModule::EmitAnnotationString(StringRef Str) {
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000901 llvm::StringMap<llvm::Constant*>::iterator i = AnnotationStrings.find(Str);
902 if (i != AnnotationStrings.end())
903 return i->second;
904
905 // Not found yet, create a new global.
Chris Lattner94010692012-02-05 02:30:40 +0000906 llvm::Constant *s = llvm::ConstantDataArray::getString(getLLVMContext(), Str);
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000907 llvm::GlobalValue *gv = new llvm::GlobalVariable(getModule(), s->getType(),
908 true, llvm::GlobalValue::PrivateLinkage, s, ".str");
909 gv->setSection(AnnotationSection);
910 gv->setUnnamedAddr(true);
911 AnnotationStrings[Str] = gv;
912 return gv;
913}
914
915llvm::Constant *CodeGenModule::EmitAnnotationUnit(SourceLocation Loc) {
916 SourceManager &SM = getContext().getSourceManager();
917 PresumedLoc PLoc = SM.getPresumedLoc(Loc);
918 if (PLoc.isValid())
919 return EmitAnnotationString(PLoc.getFilename());
920 return EmitAnnotationString(SM.getBufferName(Loc));
921}
922
923llvm::Constant *CodeGenModule::EmitAnnotationLineNo(SourceLocation L) {
924 SourceManager &SM = getContext().getSourceManager();
925 PresumedLoc PLoc = SM.getPresumedLoc(L);
926 unsigned LineNo = PLoc.isValid() ? PLoc.getLine() :
927 SM.getExpansionLineNumber(L);
928 return llvm::ConstantInt::get(Int32Ty, LineNo);
929}
930
Mike Stump1eb44332009-09-09 15:08:12 +0000931llvm::Constant *CodeGenModule::EmitAnnotateAttr(llvm::GlobalValue *GV,
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000932 const AnnotateAttr *AA,
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000933 SourceLocation L) {
934 // Get the globals for file name, annotation, and the line number.
935 llvm::Constant *AnnoGV = EmitAnnotationString(AA->getAnnotation()),
936 *UnitGV = EmitAnnotationUnit(L),
937 *LineNoCst = EmitAnnotationLineNo(L);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000938
Daniel Dunbar57d5cee2009-04-14 22:41:13 +0000939 // Create the ConstantStruct for the global annotation.
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000940 llvm::Constant *Fields[4] = {
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000941 llvm::ConstantExpr::getBitCast(GV, Int8PtrTy),
942 llvm::ConstantExpr::getBitCast(AnnoGV, Int8PtrTy),
943 llvm::ConstantExpr::getBitCast(UnitGV, Int8PtrTy),
944 LineNoCst
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000945 };
Chris Lattnerc5cbb902011-06-20 04:01:35 +0000946 return llvm::ConstantStruct::getAnon(Fields);
Nate Begeman8bd4afe2008-04-19 04:17:09 +0000947}
948
Julien Lerouge77f68bb2011-09-09 22:41:49 +0000949void CodeGenModule::AddGlobalAnnotations(const ValueDecl *D,
950 llvm::GlobalValue *GV) {
951 assert(D->hasAttr<AnnotateAttr>() && "no annotate attribute");
952 // Get the struct elements for these annotations.
953 for (specific_attr_iterator<AnnotateAttr>
954 ai = D->specific_attr_begin<AnnotateAttr>(),
955 ae = D->specific_attr_end<AnnotateAttr>(); ai != ae; ++ai)
956 Annotations.push_back(EmitAnnotateAttr(GV, *ai, D->getLocation()));
957}
958
Argyrios Kyrtzidisa6d6af32010-07-27 22:37:14 +0000959bool CodeGenModule::MayDeferGeneration(const ValueDecl *Global) {
Argyrios Kyrtzidis90e99a82010-07-29 18:15:58 +0000960 // Never defer when EmitAllDecls is specified.
David Blaikie4e4d0842012-03-11 07:00:24 +0000961 if (LangOpts.EmitAllDecls)
Daniel Dunbar73241df2009-02-13 21:18:01 +0000962 return false;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +0000963
Argyrios Kyrtzidis4ac7c0b2010-07-29 20:08:05 +0000964 return !getContext().DeclMustBeEmitted(Global);
Daniel Dunbar73241df2009-02-13 21:18:01 +0000965}
966
Nico Weberc5f80462012-10-11 10:13:44 +0000967llvm::Constant *CodeGenModule::GetAddrOfUuidDescriptor(
968 const CXXUuidofExpr* E) {
969 // Sema has verified that IIDSource has a __declspec(uuid()), and that its
970 // well-formed.
971 StringRef Uuid;
972 if (E->isTypeOperand())
973 Uuid = CXXUuidofExpr::GetUuidAttrOfType(E->getTypeOperand())->getGuid();
974 else {
975 // Special case: __uuidof(0) means an all-zero GUID.
976 Expr *Op = E->getExprOperand();
977 if (!Op->isNullPointerConstant(Context, Expr::NPC_ValueDependentIsNull))
978 Uuid = CXXUuidofExpr::GetUuidAttrOfType(Op->getType())->getGuid();
979 else
980 Uuid = "00000000-0000-0000-0000-000000000000";
981 }
982 std::string Name = "__uuid_" + Uuid.str();
983
984 // Look for an existing global.
985 if (llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name))
986 return GV;
987
988 llvm::Constant *Init = EmitUuidofInitializer(Uuid, E->getType());
989 assert(Init && "failed to initialize as constant");
990
991 // GUIDs are assumed to be 16 bytes, spread over 4-2-2-8 bytes. However, the
992 // first field is declared as "long", which for many targets is 8 bytes.
993 // Those architectures are not supported. (With the MS abi, long is always 4
994 // bytes.)
995 llvm::Type *GuidType = getTypes().ConvertType(E->getType());
996 if (Init->getType() != GuidType) {
997 DiagnosticsEngine &Diags = getDiags();
998 unsigned DiagID = Diags.getCustomDiagID(DiagnosticsEngine::Error,
999 "__uuidof codegen is not supported on this architecture");
1000 Diags.Report(E->getExprLoc(), DiagID) << E->getSourceRange();
1001 Init = llvm::UndefValue::get(GuidType);
1002 }
1003
1004 llvm::GlobalVariable *GV = new llvm::GlobalVariable(getModule(), GuidType,
1005 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, Init, Name);
1006 GV->setUnnamedAddr(true);
1007 return GV;
1008}
1009
Rafael Espindola6a836702010-03-04 18:17:24 +00001010llvm::Constant *CodeGenModule::GetWeakRefReference(const ValueDecl *VD) {
1011 const AliasAttr *AA = VD->getAttr<AliasAttr>();
1012 assert(AA && "No alias?");
1013
Chris Lattner2acc6e32011-07-18 04:24:23 +00001014 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(VD->getType());
Rafael Espindola6a836702010-03-04 18:17:24 +00001015
Rafael Espindola6a836702010-03-04 18:17:24 +00001016 // See if there is already something with the target's name in the module.
John McCallf746aa62010-03-19 23:29:14 +00001017 llvm::GlobalValue *Entry = GetGlobalValue(AA->getAliasee());
Joerg Sonnenberger4695f912012-10-16 17:45:27 +00001018 if (Entry) {
1019 unsigned AS = getContext().getTargetAddressSpace(VD->getType());
1020 return llvm::ConstantExpr::getBitCast(Entry, DeclTy->getPointerTo(AS));
1021 }
Rafael Espindola6a836702010-03-04 18:17:24 +00001022
1023 llvm::Constant *Aliasee;
1024 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergc857ce82012-10-05 23:12:53 +00001025 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy,
1026 GlobalDecl(cast<FunctionDecl>(VD)),
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001027 /*ForVTable=*/false);
Rafael Espindola6a836702010-03-04 18:17:24 +00001028 else
John McCallf746aa62010-03-19 23:29:14 +00001029 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Rafael Espindola6a836702010-03-04 18:17:24 +00001030 llvm::PointerType::getUnqual(DeclTy), 0);
Joerg Sonnenberger4695f912012-10-16 17:45:27 +00001031
1032 llvm::GlobalValue* F = cast<llvm::GlobalValue>(Aliasee);
1033 F->setLinkage(llvm::Function::ExternalWeakLinkage);
1034 WeakRefReferences.insert(F);
Rafael Espindola6a836702010-03-04 18:17:24 +00001035
1036 return Aliasee;
1037}
1038
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001039void CodeGenModule::EmitGlobal(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +00001040 const ValueDecl *Global = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001041
Rafael Espindola6a836702010-03-04 18:17:24 +00001042 // Weak references don't produce any output by themselves.
1043 if (Global->hasAttr<WeakRefAttr>())
1044 return;
1045
Chris Lattnerbd532712009-03-22 21:47:11 +00001046 // If this is an alias definition (which otherwise looks like a declaration)
1047 // emit it now.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00001048 if (Global->hasAttr<AliasAttr>())
John McCallf746aa62010-03-19 23:29:14 +00001049 return EmitAliasDefinition(GD);
Daniel Dunbar219df662008-09-08 23:44:31 +00001050
Peter Collingbourned51e43a2011-10-06 18:29:46 +00001051 // If this is CUDA, be selective about which declarations we emit.
David Blaikie4e4d0842012-03-11 07:00:24 +00001052 if (LangOpts.CUDA) {
Peter Collingbourned51e43a2011-10-06 18:29:46 +00001053 if (CodeGenOpts.CUDAIsDevice) {
1054 if (!Global->hasAttr<CUDADeviceAttr>() &&
1055 !Global->hasAttr<CUDAGlobalAttr>() &&
1056 !Global->hasAttr<CUDAConstantAttr>() &&
1057 !Global->hasAttr<CUDASharedAttr>())
1058 return;
1059 } else {
1060 if (!Global->hasAttr<CUDAHostAttr>() && (
1061 Global->hasAttr<CUDADeviceAttr>() ||
1062 Global->hasAttr<CUDAConstantAttr>() ||
1063 Global->hasAttr<CUDASharedAttr>()))
1064 return;
1065 }
1066 }
1067
Chris Lattner67b00522009-03-21 09:44:56 +00001068 // Ignore declarations, they will be emitted on their first use.
Daniel Dunbar5e1e1f92009-03-19 08:27:24 +00001069 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(Global)) {
Daniel Dunbar73241df2009-02-13 21:18:01 +00001070 // Forward declarations are emitted lazily on first use.
Nick Lewyckydce67a72011-07-18 05:26:13 +00001071 if (!FD->doesThisDeclarationHaveABody()) {
1072 if (!FD->doesDeclarationForceExternallyVisibleDefinition())
1073 return;
1074
1075 const FunctionDecl *InlineDefinition = 0;
1076 FD->getBody(InlineDefinition);
1077
Chris Lattner5f9e2722011-07-23 10:55:15 +00001078 StringRef MangledName = getMangledName(GD);
Benjamin Kramer7e423922012-03-24 18:22:12 +00001079 DeferredDecls.erase(MangledName);
Nick Lewyckydce67a72011-07-18 05:26:13 +00001080 EmitGlobalDefinition(InlineDefinition);
Daniel Dunbar73241df2009-02-13 21:18:01 +00001081 return;
Nick Lewyckydce67a72011-07-18 05:26:13 +00001082 }
Daniel Dunbar02698712009-02-13 20:29:50 +00001083 } else {
1084 const VarDecl *VD = cast<VarDecl>(Global);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001085 assert(VD->isFileVarDecl() && "Cannot emit local var decl as global.");
1086
Douglas Gregora9a55c02010-02-06 05:15:45 +00001087 if (VD->isThisDeclarationADefinition() != VarDecl::Definition)
Douglas Gregorb6c8c8b2009-04-21 17:11:58 +00001088 return;
Nate Begeman4c13b7a2008-04-20 06:29:50 +00001089 }
1090
Chris Lattner67b00522009-03-21 09:44:56 +00001091 // Defer code generation when possible if this is a static definition, inline
1092 // function etc. These we only want to emit if they are used.
Chris Lattner4357a822010-04-13 17:39:09 +00001093 if (!MayDeferGeneration(Global)) {
1094 // Emit the definition if it can't be deferred.
1095 EmitGlobalDefinition(GD);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001096 return;
1097 }
John McCallbf40cb52010-07-15 23:40:35 +00001098
1099 // If we're deferring emission of a C++ variable with an
1100 // initializer, remember the order in which it appeared in the file.
David Blaikie4e4d0842012-03-11 07:00:24 +00001101 if (getLangOpts().CPlusPlus && isa<VarDecl>(Global) &&
John McCallbf40cb52010-07-15 23:40:35 +00001102 cast<VarDecl>(Global)->hasInit()) {
1103 DelayedCXXInitPosition[Global] = CXXGlobalInits.size();
1104 CXXGlobalInits.push_back(0);
1105 }
Chris Lattner4357a822010-04-13 17:39:09 +00001106
1107 // If the value has already been used, add it directly to the
1108 // DeferredDeclsToEmit list.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001109 StringRef MangledName = getMangledName(GD);
Chris Lattner4357a822010-04-13 17:39:09 +00001110 if (GetGlobalValue(MangledName))
1111 DeferredDeclsToEmit.push_back(GD);
1112 else {
1113 // Otherwise, remember that we saw a deferred decl with this name. The
1114 // first use of the mangled name will cause it to move into
1115 // DeferredDeclsToEmit.
1116 DeferredDecls[MangledName] = GD;
1117 }
Nate Begeman4c13b7a2008-04-20 06:29:50 +00001118}
1119
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001120namespace {
1121 struct FunctionIsDirectlyRecursive :
1122 public RecursiveASTVisitor<FunctionIsDirectlyRecursive> {
1123 const StringRef Name;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001124 const Builtin::Context &BI;
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001125 bool Result;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001126 FunctionIsDirectlyRecursive(StringRef N, const Builtin::Context &C) :
1127 Name(N), BI(C), Result(false) {
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001128 }
1129 typedef RecursiveASTVisitor<FunctionIsDirectlyRecursive> Base;
1130
1131 bool TraverseCallExpr(CallExpr *E) {
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001132 const FunctionDecl *FD = E->getDirectCallee();
1133 if (!FD)
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001134 return true;
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001135 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1136 if (Attr && Name == Attr->getLabel()) {
1137 Result = true;
1138 return false;
1139 }
1140 unsigned BuiltinID = FD->getBuiltinID();
1141 if (!BuiltinID)
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001142 return true;
Nick Lewyckyf6b56372012-01-18 03:41:19 +00001143 StringRef BuiltinName = BI.GetName(BuiltinID);
1144 if (BuiltinName.startswith("__builtin_") &&
1145 Name == BuiltinName.slice(strlen("__builtin_"), StringRef::npos)) {
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001146 Result = true;
1147 return false;
1148 }
1149 return true;
1150 }
1151 };
1152}
1153
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001154// isTriviallyRecursive - Check if this function calls another
1155// decl that, because of the asm attribute or the other decl being a builtin,
1156// ends up pointing to itself.
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001157bool
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001158CodeGenModule::isTriviallyRecursive(const FunctionDecl *FD) {
1159 StringRef Name;
1160 if (getCXXABI().getMangleContext().shouldMangleDeclName(FD)) {
Nick Lewycky22afacc2012-01-18 01:50:13 +00001161 // asm labels are a special kind of mangling we have to support.
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001162 AsmLabelAttr *Attr = FD->getAttr<AsmLabelAttr>();
1163 if (!Attr)
1164 return false;
1165 Name = Attr->getLabel();
1166 } else {
1167 Name = FD->getName();
1168 }
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001169
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001170 FunctionIsDirectlyRecursive Walker(Name, Context.BuiltinInfo);
1171 Walker.TraverseFunctionDecl(const_cast<FunctionDecl*>(FD));
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001172 return Walker.Result;
1173}
1174
1175bool
1176CodeGenModule::shouldEmitFunction(const FunctionDecl *F) {
1177 if (getFunctionLinkage(F) != llvm::Function::AvailableExternallyLinkage)
1178 return true;
Rafael Espindolacc4889f2011-10-28 20:43:56 +00001179 if (CodeGenOpts.OptimizationLevel == 0 &&
Michael J. Spenceradc6cbf2012-06-18 07:00:48 +00001180 !F->hasAttr<AlwaysInlineAttr>() && !F->hasAttr<ForceInlineAttr>())
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001181 return false;
1182 // PR9614. Avoid cases where the source code is lying to us. An available
1183 // externally function should have an equivalent function somewhere else,
1184 // but a function that calls itself is clearly not equivalent to the real
1185 // implementation.
1186 // This happens in glibc's btowc and in some configure checks.
Rafael Espindolabcf6b982011-12-19 14:41:01 +00001187 return !isTriviallyRecursive(F);
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001188}
1189
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001190void CodeGenModule::EmitGlobalDefinition(GlobalDecl GD) {
Anders Carlsson4a6835e2009-09-10 23:38:47 +00001191 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Mike Stump1eb44332009-09-09 15:08:12 +00001192
Dan Gohmancb421fa2010-04-19 16:39:44 +00001193 PrettyStackTraceDecl CrashInfo(const_cast<ValueDecl *>(D), D->getLocation(),
Anders Carlsson8e2efcc2009-10-27 14:32:27 +00001194 Context.getSourceManager(),
1195 "Generating code for declaration");
1196
Douglas Gregor44eac332010-07-13 06:02:28 +00001197 if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
1198 // At -O0, don't generate IR for functions with available_externally
1199 // linkage.
Rafael Espindolaa411d2f2011-10-26 20:41:06 +00001200 if (!shouldEmitFunction(Function))
Douglas Gregor44eac332010-07-13 06:02:28 +00001201 return;
Anders Carlsson7270ee42010-03-23 04:31:31 +00001202
Douglas Gregor44eac332010-07-13 06:02:28 +00001203 if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(D)) {
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001204 // Make sure to emit the definition(s) before we emit the thunks.
1205 // This is necessary for the generation of certain thunks.
1206 if (const CXXConstructorDecl *CD = dyn_cast<CXXConstructorDecl>(Method))
1207 EmitCXXConstructor(CD, GD.getCtorType());
1208 else if (const CXXDestructorDecl *DD =dyn_cast<CXXDestructorDecl>(Method))
1209 EmitCXXDestructor(DD, GD.getDtorType());
1210 else
1211 EmitGlobalFunctionDefinition(GD);
1212
Douglas Gregor44eac332010-07-13 06:02:28 +00001213 if (Method->isVirtual())
1214 getVTables().EmitThunks(GD);
1215
Eli Friedman7dcdf5b2011-05-06 17:27:27 +00001216 return;
Douglas Gregor44eac332010-07-13 06:02:28 +00001217 }
Chris Lattnerb5e81562010-04-13 17:57:11 +00001218
Chris Lattnerb5e81562010-04-13 17:57:11 +00001219 return EmitGlobalFunctionDefinition(GD);
Douglas Gregor44eac332010-07-13 06:02:28 +00001220 }
Chris Lattnerb5e81562010-04-13 17:57:11 +00001221
1222 if (const VarDecl *VD = dyn_cast<VarDecl>(D))
1223 return EmitGlobalVarDefinition(VD);
Chris Lattner4357a822010-04-13 17:39:09 +00001224
David Blaikieb219cfc2011-09-23 05:06:16 +00001225 llvm_unreachable("Invalid argument to EmitGlobalDefinition()");
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001226}
1227
Chris Lattner74391b42009-03-22 21:03:39 +00001228/// GetOrCreateLLVMFunction - If the specified mangled name is not in the
1229/// module, create and return an llvm Function with the specified type. If there
1230/// is something in the module with the specified name, return it potentially
1231/// bitcasted to the right type.
1232///
1233/// If D is non-null, it specifies a decl that correspond to this. This is used
1234/// to set the attributes on the function when it is first created.
John McCallf746aa62010-03-19 23:29:14 +00001235llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001236CodeGenModule::GetOrCreateLLVMFunction(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001237 llvm::Type *Ty,
John McCallf85e1932011-06-15 23:02:42 +00001238 GlobalDecl D, bool ForVTable,
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001239 llvm::AttributeSet ExtraAttrs) {
Chris Lattner0558e792009-03-21 09:25:43 +00001240 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +00001241 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner0558e792009-03-21 09:25:43 +00001242 if (Entry) {
Benjamin Kramerd48bcb22012-08-22 15:37:55 +00001243 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola6a836702010-03-04 18:17:24 +00001244 const FunctionDecl *FD = cast_or_null<FunctionDecl>(D.getDecl());
1245 if (FD && !FD->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +00001246 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +00001247 }
1248
Chris Lattner0558e792009-03-21 09:25:43 +00001249 if (Entry->getType()->getElementType() == Ty)
1250 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +00001251
Chris Lattner0558e792009-03-21 09:25:43 +00001252 // Make sure the result is of the correct type.
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001253 return llvm::ConstantExpr::getBitCast(Entry, Ty->getPointerTo());
Chris Lattner0558e792009-03-21 09:25:43 +00001254 }
Mike Stump1eb44332009-09-09 15:08:12 +00001255
Eli Friedman654ad402009-11-09 05:07:37 +00001256 // This function doesn't have a complete type (for example, the return
1257 // type is an incomplete struct). Use a fake type instead, and make
1258 // sure not to try to set attributes.
1259 bool IsIncompleteFunction = false;
John McCall784f2112010-04-28 00:00:30 +00001260
Chris Lattner2acc6e32011-07-18 04:24:23 +00001261 llvm::FunctionType *FTy;
John McCall784f2112010-04-28 00:00:30 +00001262 if (isa<llvm::FunctionType>(Ty)) {
1263 FTy = cast<llvm::FunctionType>(Ty);
1264 } else {
John McCall0774cb82011-05-15 01:53:33 +00001265 FTy = llvm::FunctionType::get(VoidTy, false);
Eli Friedman654ad402009-11-09 05:07:37 +00001266 IsIncompleteFunction = true;
1267 }
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001268
John McCall784f2112010-04-28 00:00:30 +00001269 llvm::Function *F = llvm::Function::Create(FTy,
Eli Friedman654ad402009-11-09 05:07:37 +00001270 llvm::Function::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +00001271 MangledName, &getModule());
1272 assert(F->getName() == MangledName && "name was uniqued!");
Eli Friedman654ad402009-11-09 05:07:37 +00001273 if (D.getDecl())
Anders Carlssonb2bcf1c2010-02-06 02:44:09 +00001274 SetFunctionAttributes(D, F, IsIncompleteFunction);
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001275 if (ExtraAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex)) {
1276 llvm::AttrBuilder B(ExtraAttrs, llvm::AttributeSet::FunctionIndex);
Bill Wendling909b6de2013-01-23 00:21:06 +00001277 F->addAttributes(llvm::AttributeSet::FunctionIndex,
1278 llvm::AttributeSet::get(VMContext,
1279 llvm::AttributeSet::FunctionIndex,
1280 B));
1281 }
Eli Friedman654ad402009-11-09 05:07:37 +00001282
Chris Lattner67b00522009-03-21 09:44:56 +00001283 // This is the first use or definition of a mangled name. If there is a
1284 // deferred decl with this name, remember that we need to emit it at the end
1285 // of the file.
John McCallf746aa62010-03-19 23:29:14 +00001286 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +00001287 if (DDI != DeferredDecls.end()) {
1288 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1289 // list, and remove it from DeferredDecls (since we don't need it anymore).
1290 DeferredDeclsToEmit.push_back(DDI->second);
1291 DeferredDecls.erase(DDI);
John McCallbfdcdc82010-12-15 04:00:32 +00001292
1293 // Otherwise, there are cases we have to worry about where we're
1294 // using a declaration for which we must emit a definition but where
1295 // we might not find a top-level definition:
1296 // - member functions defined inline in their classes
1297 // - friend functions defined inline in some class
1298 // - special member functions with implicit definitions
1299 // If we ever change our AST traversal to walk into class methods,
1300 // this will be unnecessary.
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001301 //
1302 // We also don't emit a definition for a function if it's going to be an entry
1303 // in a vtable, unless it's already marked as used.
David Blaikie4e4d0842012-03-11 07:00:24 +00001304 } else if (getLangOpts().CPlusPlus && D.getDecl()) {
John McCallbfdcdc82010-12-15 04:00:32 +00001305 // Look for a declaration that's lexically in a record.
1306 const FunctionDecl *FD = cast<FunctionDecl>(D.getDecl());
Eli Friedmanb135f0f2012-07-02 21:05:30 +00001307 FD = FD->getMostRecentDecl();
John McCallbfdcdc82010-12-15 04:00:32 +00001308 do {
1309 if (isa<CXXRecordDecl>(FD->getLexicalDeclContext())) {
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001310 if (FD->isImplicit() && !ForVTable) {
John McCallbfdcdc82010-12-15 04:00:32 +00001311 assert(FD->isUsed() && "Sema didn't mark implicit function as used!");
Douglas Gregora29bf412011-02-09 02:03:05 +00001312 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +00001313 break;
Sean Hunt10620eb2011-05-06 20:44:56 +00001314 } else if (FD->doesThisDeclarationHaveABody()) {
Douglas Gregora29bf412011-02-09 02:03:05 +00001315 DeferredDeclsToEmit.push_back(D.getWithDecl(FD));
John McCallbfdcdc82010-12-15 04:00:32 +00001316 break;
1317 }
Rafael Espindola7b9a5aa2010-03-02 21:28:26 +00001318 }
Douglas Gregoref96ee02012-01-14 16:38:05 +00001319 FD = FD->getPreviousDecl();
John McCallbfdcdc82010-12-15 04:00:32 +00001320 } while (FD);
Chris Lattner67b00522009-03-21 09:44:56 +00001321 }
Mike Stump1eb44332009-09-09 15:08:12 +00001322
John McCall784f2112010-04-28 00:00:30 +00001323 // Make sure the result is of the requested type.
1324 if (!IsIncompleteFunction) {
1325 assert(F->getType()->getElementType() == Ty);
1326 return F;
1327 }
1328
Chris Lattner9cbe4f02011-07-09 17:41:47 +00001329 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
John McCall784f2112010-04-28 00:00:30 +00001330 return llvm::ConstantExpr::getBitCast(F, PTy);
Chris Lattner0558e792009-03-21 09:25:43 +00001331}
1332
Chris Lattner74391b42009-03-22 21:03:39 +00001333/// GetAddrOfFunction - Return the address of the given function. If Ty is
1334/// non-null, then this function will use the specified type if it has to
1335/// create it (this occurs when we see a definition of the function).
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001336llvm::Constant *CodeGenModule::GetAddrOfFunction(GlobalDecl GD,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001337 llvm::Type *Ty,
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001338 bool ForVTable) {
Chris Lattner74391b42009-03-22 21:03:39 +00001339 // If there was no specific requested type, just convert it now.
1340 if (!Ty)
Anders Carlsson4a6835e2009-09-10 23:38:47 +00001341 Ty = getTypes().ConvertType(cast<ValueDecl>(GD.getDecl())->getType());
Chris Lattnerbcaedae2010-06-30 19:14:05 +00001342
Chris Lattner5f9e2722011-07-23 10:55:15 +00001343 StringRef MangledName = getMangledName(GD);
Anders Carlsson1faa89f2011-02-05 04:35:53 +00001344 return GetOrCreateLLVMFunction(MangledName, Ty, GD, ForVTable);
Chris Lattner74391b42009-03-22 21:03:39 +00001345}
Eli Friedman77ba7082008-05-30 19:50:47 +00001346
Chris Lattner74391b42009-03-22 21:03:39 +00001347/// CreateRuntimeFunction - Create a new runtime function with the specified
1348/// type and name.
1349llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001350CodeGenModule::CreateRuntimeFunction(llvm::FunctionType *FTy,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001351 StringRef Name,
Bill Wendlingc4c62fd2013-01-31 00:30:05 +00001352 llvm::AttributeSet ExtraAttrs) {
John McCallf85e1932011-06-15 23:02:42 +00001353 return GetOrCreateLLVMFunction(Name, FTy, GlobalDecl(), /*ForVTable=*/false,
1354 ExtraAttrs);
Chris Lattner74391b42009-03-22 21:03:39 +00001355}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001356
Richard Smitha9b21d22012-02-17 06:48:11 +00001357/// isTypeConstant - Determine whether an object of this type can be emitted
1358/// as a constant.
1359///
1360/// If ExcludeCtor is true, the duration when the object's constructor runs
1361/// will not be considered. The caller will need to verify that the object is
1362/// not written to during its construction.
1363bool CodeGenModule::isTypeConstant(QualType Ty, bool ExcludeCtor) {
1364 if (!Ty.isConstant(Context) && !Ty->isReferenceType())
Eli Friedman20e098b2009-12-11 21:23:03 +00001365 return false;
Richard Smitha9b21d22012-02-17 06:48:11 +00001366
David Blaikie4e4d0842012-03-11 07:00:24 +00001367 if (Context.getLangOpts().CPlusPlus) {
Richard Smitha9b21d22012-02-17 06:48:11 +00001368 if (const CXXRecordDecl *Record
1369 = Context.getBaseElementType(Ty)->getAsCXXRecordDecl())
1370 return ExcludeCtor && !Record->hasMutableFields() &&
1371 Record->hasTrivialDestructor();
Eli Friedman20e098b2009-12-11 21:23:03 +00001372 }
Richard Smitha9b21d22012-02-17 06:48:11 +00001373
Eli Friedman20e098b2009-12-11 21:23:03 +00001374 return true;
1375}
1376
Chris Lattner74391b42009-03-22 21:03:39 +00001377/// GetOrCreateLLVMGlobal - If the specified mangled name is not in the module,
1378/// create and return an llvm GlobalVariable with the specified type. If there
1379/// is something in the module with the specified name, return it potentially
1380/// bitcasted to the right type.
1381///
1382/// If D is non-null, it specifies a decl that correspond to this. This is used
1383/// to set the attributes on the global when it is first created.
John McCallf746aa62010-03-19 23:29:14 +00001384llvm::Constant *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001385CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001386 llvm::PointerType *Ty,
Rafael Espindolac532b502011-01-18 21:07:57 +00001387 const VarDecl *D,
1388 bool UnnamedAddr) {
Daniel Dunbar3c827a72008-08-05 23:31:02 +00001389 // Lookup the entry, lazily creating it if necessary.
John McCallf746aa62010-03-19 23:29:14 +00001390 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
Chris Lattner99b53612009-03-21 08:03:33 +00001391 if (Entry) {
Benjamin Kramerd48bcb22012-08-22 15:37:55 +00001392 if (WeakRefReferences.erase(Entry)) {
Rafael Espindola6a836702010-03-04 18:17:24 +00001393 if (D && !D->hasAttr<WeakAttr>())
Anders Carlsson7270ee42010-03-23 04:31:31 +00001394 Entry->setLinkage(llvm::Function::ExternalLinkage);
Rafael Espindola6a836702010-03-04 18:17:24 +00001395 }
1396
Rafael Espindolac532b502011-01-18 21:07:57 +00001397 if (UnnamedAddr)
1398 Entry->setUnnamedAddr(true);
1399
Chris Lattner74391b42009-03-22 21:03:39 +00001400 if (Entry->getType() == Ty)
Chris Lattner570585c2009-03-21 09:16:30 +00001401 return Entry;
Mike Stump1eb44332009-09-09 15:08:12 +00001402
Chris Lattner99b53612009-03-21 08:03:33 +00001403 // Make sure the result is of the correct type.
Owen Anderson3c4972d2009-07-29 18:54:39 +00001404 return llvm::ConstantExpr::getBitCast(Entry, Ty);
Daniel Dunbar49988882009-01-13 02:25:00 +00001405 }
Mike Stump1eb44332009-09-09 15:08:12 +00001406
Chris Lattner67b00522009-03-21 09:44:56 +00001407 // This is the first use or definition of a mangled name. If there is a
1408 // deferred decl with this name, remember that we need to emit it at the end
1409 // of the file.
John McCallf746aa62010-03-19 23:29:14 +00001410 llvm::StringMap<GlobalDecl>::iterator DDI = DeferredDecls.find(MangledName);
Chris Lattner67b00522009-03-21 09:44:56 +00001411 if (DDI != DeferredDecls.end()) {
1412 // Move the potentially referenced deferred decl to the DeferredDeclsToEmit
1413 // list, and remove it from DeferredDecls (since we don't need it anymore).
1414 DeferredDeclsToEmit.push_back(DDI->second);
1415 DeferredDecls.erase(DDI);
1416 }
Mike Stump1eb44332009-09-09 15:08:12 +00001417
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001418 unsigned AddrSpace = GetGlobalVarAddressSpace(D, Ty->getAddressSpace());
Mike Stump1eb44332009-09-09 15:08:12 +00001419 llvm::GlobalVariable *GV =
1420 new llvm::GlobalVariable(getModule(), Ty->getElementType(), false,
Chris Lattner99b53612009-03-21 08:03:33 +00001421 llvm::GlobalValue::ExternalLinkage,
John McCallf746aa62010-03-19 23:29:14 +00001422 0, MangledName, 0,
Hans Wennborg5e2d5de2012-06-23 11:51:46 +00001423 llvm::GlobalVariable::NotThreadLocal, AddrSpace);
Chris Lattner99b53612009-03-21 08:03:33 +00001424
1425 // Handle things which are present even on external declarations.
Chris Lattner74391b42009-03-22 21:03:39 +00001426 if (D) {
Mike Stumpf5408fe2009-05-16 07:57:57 +00001427 // FIXME: This code is overly simple and should be merged with other global
1428 // handling.
Richard Smitha9b21d22012-02-17 06:48:11 +00001429 GV->setConstant(isTypeConstant(D->getType(), false));
Chris Lattner99b53612009-03-21 08:03:33 +00001430
John McCall110e8e52010-10-29 22:22:43 +00001431 // Set linkage and visibility in case we never see a definition.
John McCallaf146032010-10-30 11:50:40 +00001432 NamedDecl::LinkageInfo LV = D->getLinkageAndVisibility();
1433 if (LV.linkage() != ExternalLinkage) {
John McCall15e310a2011-02-19 02:53:41 +00001434 // Don't set internal linkage on declarations.
John McCall110e8e52010-10-29 22:22:43 +00001435 } else {
1436 if (D->hasAttr<DLLImportAttr>())
1437 GV->setLinkage(llvm::GlobalValue::DLLImportLinkage);
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00001438 else if (D->hasAttr<WeakAttr>() || D->isWeakImported())
John McCall110e8e52010-10-29 22:22:43 +00001439 GV->setLinkage(llvm::GlobalValue::ExternalWeakLinkage);
Chris Lattner99b53612009-03-21 08:03:33 +00001440
John McCallaf146032010-10-30 11:50:40 +00001441 // Set visibility on a declaration only if it's explicit.
1442 if (LV.visibilityExplicit())
1443 GV->setVisibility(GetLLVMVisibility(LV.visibility()));
John McCall110e8e52010-10-29 22:22:43 +00001444 }
Eli Friedman56ebe502009-04-19 21:05:03 +00001445
Hans Wennborgde981f32012-06-28 08:01:44 +00001446 if (D->isThreadSpecified())
1447 setTLSMode(GV, *D);
Chris Lattner74391b42009-03-22 21:03:39 +00001448 }
Mike Stump1eb44332009-09-09 15:08:12 +00001449
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001450 if (AddrSpace != Ty->getAddressSpace())
1451 return llvm::ConstantExpr::getBitCast(GV, Ty);
1452 else
1453 return GV;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001454}
1455
Chris Lattner74391b42009-03-22 21:03:39 +00001456
Anders Carlsson3bd62022011-01-29 18:20:20 +00001457llvm::GlobalVariable *
Chris Lattner5f9e2722011-07-23 10:55:15 +00001458CodeGenModule::CreateOrReplaceCXXRuntimeVariable(StringRef Name,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001459 llvm::Type *Ty,
Anders Carlsson3bd62022011-01-29 18:20:20 +00001460 llvm::GlobalValue::LinkageTypes Linkage) {
1461 llvm::GlobalVariable *GV = getModule().getNamedGlobal(Name);
1462 llvm::GlobalVariable *OldGV = 0;
1463
1464
1465 if (GV) {
1466 // Check if the variable has the right type.
1467 if (GV->getType()->getElementType() == Ty)
1468 return GV;
1469
1470 // Because C++ name mangling, the only way we can end up with an already
1471 // existing global with the same name is if it has been declared extern "C".
Nico Weberc5f80462012-10-11 10:13:44 +00001472 assert(GV->isDeclaration() && "Declaration has wrong type!");
Anders Carlsson3bd62022011-01-29 18:20:20 +00001473 OldGV = GV;
1474 }
1475
1476 // Create a new variable.
1477 GV = new llvm::GlobalVariable(getModule(), Ty, /*isConstant=*/true,
1478 Linkage, 0, Name);
1479
1480 if (OldGV) {
1481 // Replace occurrences of the old variable if needed.
1482 GV->takeName(OldGV);
1483
1484 if (!OldGV->use_empty()) {
1485 llvm::Constant *NewPtrForOldDecl =
1486 llvm::ConstantExpr::getBitCast(GV, OldGV->getType());
1487 OldGV->replaceAllUsesWith(NewPtrForOldDecl);
1488 }
1489
1490 OldGV->eraseFromParent();
1491 }
1492
1493 return GV;
1494}
1495
Chris Lattner74391b42009-03-22 21:03:39 +00001496/// GetAddrOfGlobalVar - Return the llvm::Constant for the address of the
1497/// given global variable. If Ty is non-null and if the global doesn't exist,
Eric Christopher0ff258b2012-04-16 23:55:04 +00001498/// then it will be created with the specified type instead of whatever the
Chris Lattner74391b42009-03-22 21:03:39 +00001499/// normal requested type would be.
1500llvm::Constant *CodeGenModule::GetAddrOfGlobalVar(const VarDecl *D,
Chris Lattner2acc6e32011-07-18 04:24:23 +00001501 llvm::Type *Ty) {
Chris Lattner74391b42009-03-22 21:03:39 +00001502 assert(D->hasGlobalStorage() && "Not a global variable");
1503 QualType ASTTy = D->getType();
1504 if (Ty == 0)
1505 Ty = getTypes().ConvertTypeForMem(ASTTy);
Mike Stump1eb44332009-09-09 15:08:12 +00001506
Chris Lattner2acc6e32011-07-18 04:24:23 +00001507 llvm::PointerType *PTy =
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001508 llvm::PointerType::get(Ty, getContext().getTargetAddressSpace(ASTTy));
John McCallf746aa62010-03-19 23:29:14 +00001509
Chris Lattner5f9e2722011-07-23 10:55:15 +00001510 StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001511 return GetOrCreateLLVMGlobal(MangledName, PTy, D);
Chris Lattner74391b42009-03-22 21:03:39 +00001512}
1513
1514/// CreateRuntimeVariable - Create a new runtime global variable with the
1515/// specified type and name.
1516llvm::Constant *
Chris Lattner2acc6e32011-07-18 04:24:23 +00001517CodeGenModule::CreateRuntimeVariable(llvm::Type *Ty,
Chris Lattner5f9e2722011-07-23 10:55:15 +00001518 StringRef Name) {
John McCall1de4d4e2011-04-07 08:22:57 +00001519 return GetOrCreateLLVMGlobal(Name, llvm::PointerType::getUnqual(Ty), 0,
Rafael Espindolac532b502011-01-18 21:07:57 +00001520 true);
Chris Lattner74391b42009-03-22 21:03:39 +00001521}
1522
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001523void CodeGenModule::EmitTentativeDefinition(const VarDecl *D) {
1524 assert(!D->getInit() && "Cannot emit definite definitions here!");
1525
Douglas Gregor7520bd12009-04-21 19:28:58 +00001526 if (MayDeferGeneration(D)) {
1527 // If we have not seen a reference to this variable yet, place it
1528 // into the deferred declarations table to be emitted if needed
1529 // later.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001530 StringRef MangledName = getMangledName(D);
John McCallf746aa62010-03-19 23:29:14 +00001531 if (!GetGlobalValue(MangledName)) {
Anders Carlsson555b4bb2009-09-10 23:43:36 +00001532 DeferredDecls[MangledName] = D;
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001533 return;
Douglas Gregor7520bd12009-04-21 19:28:58 +00001534 }
1535 }
1536
1537 // The tentative definition is the only definition.
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001538 EmitGlobalVarDefinition(D);
1539}
1540
Chris Lattner2acc6e32011-07-18 04:24:23 +00001541CharUnits CodeGenModule::GetTargetTypeStoreSize(llvm::Type *Ty) const {
Ken Dyck06f486e2011-01-18 02:01:14 +00001542 return Context.toCharUnitsFromBits(
Micah Villmow25a6a842012-10-08 16:25:52 +00001543 TheDataLayout.getTypeStoreSizeInBits(Ty));
Ken Dyck687cc4a2010-01-26 13:48:07 +00001544}
1545
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001546llvm::Constant *
1547CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
1548 const Expr *rawInit) {
1549 ArrayRef<ExprWithCleanups::CleanupObject> cleanups;
1550 if (const ExprWithCleanups *withCleanups =
1551 dyn_cast<ExprWithCleanups>(rawInit)) {
1552 cleanups = withCleanups->getObjects();
1553 rawInit = withCleanups->getSubExpr();
1554 }
1555
1556 const InitListExpr *init = dyn_cast<InitListExpr>(rawInit);
1557 if (!init || !init->initializesStdInitializerList() ||
1558 init->getNumInits() == 0)
1559 return 0;
1560
1561 ASTContext &ctx = getContext();
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001562 unsigned numInits = init->getNumInits();
Sebastian Redl062a82c2012-02-27 23:20:01 +00001563 // FIXME: This check is here because we would otherwise silently miscompile
1564 // nested global std::initializer_lists. Better would be to have a real
1565 // implementation.
1566 for (unsigned i = 0; i < numInits; ++i) {
1567 const InitListExpr *inner = dyn_cast<InitListExpr>(init->getInit(i));
1568 if (inner && inner->initializesStdInitializerList()) {
1569 ErrorUnsupported(inner, "nested global std::initializer_list");
1570 return 0;
1571 }
1572 }
1573
1574 // Synthesize a fake VarDecl for the array and initialize that.
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001575 QualType elementType = init->getInit(0)->getType();
1576 llvm::APInt numElements(ctx.getTypeSize(ctx.getSizeType()), numInits);
1577 QualType arrayType = ctx.getConstantArrayType(elementType, numElements,
1578 ArrayType::Normal, 0);
1579
1580 IdentifierInfo *name = &ctx.Idents.get(D->getNameAsString() + "__initlist");
1581 TypeSourceInfo *sourceInfo = ctx.getTrivialTypeSourceInfo(
1582 arrayType, D->getLocation());
1583 VarDecl *backingArray = VarDecl::Create(ctx, const_cast<DeclContext*>(
1584 D->getDeclContext()),
1585 D->getLocStart(), D->getLocation(),
1586 name, arrayType, sourceInfo,
1587 SC_Static, SC_Static);
1588
1589 // Now clone the InitListExpr to initialize the array instead.
1590 // Incredible hack: we want to use the existing InitListExpr here, so we need
1591 // to tell it that it no longer initializes a std::initializer_list.
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00001592 ArrayRef<Expr*> Inits(const_cast<InitListExpr*>(init)->getInits(),
1593 init->getNumInits());
1594 Expr *arrayInit = new (ctx) InitListExpr(ctx, init->getLBraceLoc(), Inits,
1595 init->getRBraceLoc());
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001596 arrayInit->setType(arrayType);
1597
1598 if (!cleanups.empty())
1599 arrayInit = ExprWithCleanups::Create(ctx, arrayInit, cleanups);
1600
1601 backingArray->setInit(arrayInit);
1602
1603 // Emit the definition of the array.
1604 EmitGlobalVarDefinition(backingArray);
1605
1606 // Inspect the initializer list to validate it and determine its type.
1607 // FIXME: doing this every time is probably inefficient; caching would be nice
1608 RecordDecl *record = init->getType()->castAs<RecordType>()->getDecl();
1609 RecordDecl::field_iterator field = record->field_begin();
1610 if (field == record->field_end()) {
1611 ErrorUnsupported(D, "weird std::initializer_list");
1612 return 0;
1613 }
1614 QualType elementPtr = ctx.getPointerType(elementType.withConst());
1615 // Start pointer.
1616 if (!ctx.hasSameType(field->getType(), elementPtr)) {
1617 ErrorUnsupported(D, "weird std::initializer_list");
1618 return 0;
1619 }
1620 ++field;
1621 if (field == record->field_end()) {
1622 ErrorUnsupported(D, "weird std::initializer_list");
1623 return 0;
1624 }
1625 bool isStartEnd = false;
1626 if (ctx.hasSameType(field->getType(), elementPtr)) {
1627 // End pointer.
1628 isStartEnd = true;
1629 } else if(!ctx.hasSameType(field->getType(), ctx.getSizeType())) {
1630 ErrorUnsupported(D, "weird std::initializer_list");
1631 return 0;
1632 }
1633
1634 // Now build an APValue representing the std::initializer_list.
1635 APValue initListValue(APValue::UninitStruct(), 0, 2);
1636 APValue &startField = initListValue.getStructField(0);
1637 APValue::LValuePathEntry startOffsetPathEntry;
1638 startOffsetPathEntry.ArrayIndex = 0;
1639 startField = APValue(APValue::LValueBase(backingArray),
1640 CharUnits::fromQuantity(0),
1641 llvm::makeArrayRef(startOffsetPathEntry),
1642 /*IsOnePastTheEnd=*/false, 0);
1643
1644 if (isStartEnd) {
1645 APValue &endField = initListValue.getStructField(1);
1646 APValue::LValuePathEntry endOffsetPathEntry;
1647 endOffsetPathEntry.ArrayIndex = numInits;
1648 endField = APValue(APValue::LValueBase(backingArray),
1649 ctx.getTypeSizeInChars(elementType) * numInits,
1650 llvm::makeArrayRef(endOffsetPathEntry),
1651 /*IsOnePastTheEnd=*/true, 0);
1652 } else {
1653 APValue &sizeField = initListValue.getStructField(1);
1654 sizeField = APValue(llvm::APSInt(numElements));
1655 }
1656
1657 // Emit the constant for the initializer_list.
Richard Smitha3ca41f2012-03-02 23:27:11 +00001658 llvm::Constant *llvmInit =
1659 EmitConstantValueForMemory(initListValue, D->getType());
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001660 assert(llvmInit && "failed to initialize as constant");
1661 return llvmInit;
1662}
1663
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001664unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
1665 unsigned AddrSpace) {
1666 if (LangOpts.CUDA && CodeGenOpts.CUDAIsDevice) {
1667 if (D->hasAttr<CUDAConstantAttr>())
1668 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_constant);
1669 else if (D->hasAttr<CUDASharedAttr>())
1670 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_shared);
1671 else
1672 AddrSpace = getContext().getTargetAddressSpace(LangAS::cuda_device);
1673 }
1674
1675 return AddrSpace;
1676}
1677
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001678void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
Chris Lattner8f32f712007-07-14 00:23:28 +00001679 llvm::Constant *Init = 0;
Eli Friedman77ba7082008-05-30 19:50:47 +00001680 QualType ASTTy = D->getType();
Richard Smith7ca48502012-02-13 22:16:19 +00001681 CXXRecordDecl *RD = ASTTy->getBaseElementTypeUnsafe()->getAsCXXRecordDecl();
1682 bool NeedsGlobalCtor = false;
1683 bool NeedsGlobalDtor = RD && !RD->hasTrivialDestructor();
Mike Stump1eb44332009-09-09 15:08:12 +00001684
Richard Smith2d6a5672012-01-14 04:30:29 +00001685 const VarDecl *InitDecl;
1686 const Expr *InitExpr = D->getAnyInitializer(InitDecl);
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001687
Anders Carlsson3bb92692010-01-26 17:43:42 +00001688 if (!InitExpr) {
Eli Friedmancd5f4aa2008-05-30 20:39:54 +00001689 // This is a tentative definition; tentative definitions are
Daniel Dunbar03f5ad92009-04-15 22:08:45 +00001690 // implicitly initialized with { 0 }.
1691 //
1692 // Note that tentative definitions are only emitted at the end of
1693 // a translation unit, so they should never have incomplete
1694 // type. In addition, EmitTentativeDefinition makes sure that we
1695 // never attempt to emit a tentative definition if a real one
1696 // exists. A use may still exists, however, so we still may need
1697 // to do a RAUW.
1698 assert(!ASTTy->isIncompleteType() && "Unexpected incomplete type");
Anders Carlssonb0d0ea02009-08-02 21:18:22 +00001699 Init = EmitNullConstant(D->getType());
Eli Friedman77ba7082008-05-30 19:50:47 +00001700 } else {
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001701 // If this is a std::initializer_list, emit the special initializer.
1702 Init = MaybeEmitGlobalStdInitializerListInitializer(D, InitExpr);
1703 // An empty init list will perform zero-initialization, which happens
1704 // to be exactly what we want.
1705 // FIXME: It does so in a global constructor, which is *not* what we
1706 // want.
1707
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001708 if (!Init) {
1709 initializedGlobalDecl = GlobalDecl(D);
Sebastian Redl19b1a6e2012-02-25 20:51:20 +00001710 Init = EmitConstantInit(*InitDecl);
Fariborz Jahanian4904bf42012-06-26 16:06:38 +00001711 }
Eli Friedman6e656f42009-02-20 01:18:21 +00001712 if (!Init) {
Anders Carlsson3bb92692010-01-26 17:43:42 +00001713 QualType T = InitExpr->getType();
Douglas Gregorc446d182010-05-05 20:15:55 +00001714 if (D->getType()->isReferenceType())
1715 T = D->getType();
Richard Smith2d6a5672012-01-14 04:30:29 +00001716
David Blaikie4e4d0842012-03-11 07:00:24 +00001717 if (getLangOpts().CPlusPlus) {
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001718 Init = EmitNullConstant(T);
Richard Smith7ca48502012-02-13 22:16:19 +00001719 NeedsGlobalCtor = true;
Anders Carlsson89ed31d2009-08-08 23:24:23 +00001720 } else {
1721 ErrorUnsupported(D, "static initializer");
1722 Init = llvm::UndefValue::get(getTypes().ConvertType(T));
1723 }
John McCallbf40cb52010-07-15 23:40:35 +00001724 } else {
1725 // We don't need an initializer, so remove the entry for the delayed
Richard Smith7ca48502012-02-13 22:16:19 +00001726 // initializer position (just in case this entry was delayed) if we
1727 // also don't need to register a destructor.
David Blaikie4e4d0842012-03-11 07:00:24 +00001728 if (getLangOpts().CPlusPlus && !NeedsGlobalDtor)
John McCallbf40cb52010-07-15 23:40:35 +00001729 DelayedCXXInitPosition.erase(D);
Eli Friedman6e656f42009-02-20 01:18:21 +00001730 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001731 }
Eli Friedman77ba7082008-05-30 19:50:47 +00001732
Chris Lattner2acc6e32011-07-18 04:24:23 +00001733 llvm::Type* InitType = Init->getType();
Chris Lattner570585c2009-03-21 09:16:30 +00001734 llvm::Constant *Entry = GetAddrOfGlobalVar(D, InitType);
Mike Stump1eb44332009-09-09 15:08:12 +00001735
Chris Lattner570585c2009-03-21 09:16:30 +00001736 // Strip off a bitcast if we got one back.
1737 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
Chris Lattner9d4a15f2009-07-16 16:48:25 +00001738 assert(CE->getOpcode() == llvm::Instruction::BitCast ||
1739 // all zero index gep.
1740 CE->getOpcode() == llvm::Instruction::GetElementPtr);
Chris Lattner570585c2009-03-21 09:16:30 +00001741 Entry = CE->getOperand(0);
1742 }
Mike Stump1eb44332009-09-09 15:08:12 +00001743
Chris Lattner570585c2009-03-21 09:16:30 +00001744 // Entry is now either a Function or GlobalVariable.
1745 llvm::GlobalVariable *GV = dyn_cast<llvm::GlobalVariable>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00001746
Chris Lattner570585c2009-03-21 09:16:30 +00001747 // We have a definition after a declaration with the wrong type.
1748 // We must make a new GlobalVariable* and update everything that used OldGV
1749 // (a declaration or tentative definition) with the new GlobalVariable*
1750 // (which will be a definition).
1751 //
1752 // This happens if there is a prototype for a global (e.g.
1753 // "extern int x[];") and then a definition of a different type (e.g.
1754 // "int x[10];"). This also happens when an initializer has a different type
1755 // from the type of the global (this happens with unions).
Chris Lattner570585c2009-03-21 09:16:30 +00001756 if (GV == 0 ||
1757 GV->getType()->getElementType() != InitType ||
Peter Collingbourne207f4d82011-03-18 22:38:29 +00001758 GV->getType()->getAddressSpace() !=
Peter Collingbourne4dc34eb2012-05-20 21:08:35 +00001759 GetGlobalVarAddressSpace(D, getContext().getTargetAddressSpace(ASTTy))) {
Mike Stump1eb44332009-09-09 15:08:12 +00001760
John McCallf746aa62010-03-19 23:29:14 +00001761 // Move the old entry aside so that we'll create a new one.
Chris Lattner5f9e2722011-07-23 10:55:15 +00001762 Entry->setName(StringRef());
Daniel Dunbar232350d2009-02-19 05:36:41 +00001763
Chris Lattner570585c2009-03-21 09:16:30 +00001764 // Make a new global with the correct type, this is now guaranteed to work.
1765 GV = cast<llvm::GlobalVariable>(GetAddrOfGlobalVar(D, InitType));
Chris Lattner0558e792009-03-21 09:25:43 +00001766
Eli Friedman77ba7082008-05-30 19:50:47 +00001767 // Replace all uses of the old global with the new global
Mike Stump1eb44332009-09-09 15:08:12 +00001768 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00001769 llvm::ConstantExpr::getBitCast(GV, Entry->getType());
Chris Lattner570585c2009-03-21 09:16:30 +00001770 Entry->replaceAllUsesWith(NewPtrForOldDecl);
Eli Friedman77ba7082008-05-30 19:50:47 +00001771
1772 // Erase the old global, since it is no longer used.
Chris Lattner570585c2009-03-21 09:16:30 +00001773 cast<llvm::GlobalValue>(Entry)->eraseFromParent();
Chris Lattner8f32f712007-07-14 00:23:28 +00001774 }
Devang Patel8e53e722007-10-26 16:31:40 +00001775
Julien Lerouge77f68bb2011-09-09 22:41:49 +00001776 if (D->hasAttr<AnnotateAttr>())
1777 AddGlobalAnnotations(D, GV);
Nate Begeman8bd4afe2008-04-19 04:17:09 +00001778
Chris Lattner88a69ad2007-07-13 05:13:43 +00001779 GV->setInitializer(Init);
Chris Lattnere78b86f2009-08-05 05:20:29 +00001780
1781 // If it is safe to mark the global 'constant', do so now.
Richard Smitha9b21d22012-02-17 06:48:11 +00001782 GV->setConstant(!NeedsGlobalCtor && !NeedsGlobalDtor &&
1783 isTypeConstant(D->getType(), true));
Mike Stump1eb44332009-09-09 15:08:12 +00001784
Ken Dyck8b752f12010-01-27 17:10:57 +00001785 GV->setAlignment(getContext().getDeclAlign(D).getQuantity());
Richard Smitha9b21d22012-02-17 06:48:11 +00001786
Chris Lattner88a69ad2007-07-13 05:13:43 +00001787 // Set the llvm linkage type as appropriate.
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001788 llvm::GlobalValue::LinkageTypes Linkage =
1789 GetLLVMLinkageVarDefinition(D, GV);
1790 GV->setLinkage(Linkage);
1791 if (Linkage == llvm::GlobalVariable::CommonLinkage)
Chris Lattnere78b86f2009-08-05 05:20:29 +00001792 // common vars aren't constant even if declared const.
1793 GV->setConstant(false);
Daniel Dunbar7e714cd2009-04-10 20:26:50 +00001794
Daniel Dunbar7c65e992009-04-14 08:05:55 +00001795 SetCommonAttributes(D, GV);
Daniel Dunbar04d40782009-04-14 06:00:08 +00001796
John McCall3030eb82010-11-06 09:44:32 +00001797 // Emit the initializer function if necessary.
Richard Smith7ca48502012-02-13 22:16:19 +00001798 if (NeedsGlobalCtor || NeedsGlobalDtor)
1799 EmitCXXGlobalVarDeclInitFunc(D, GV, NeedsGlobalCtor);
John McCall3030eb82010-11-06 09:44:32 +00001800
Kostya Serebryany05c5ebc2012-08-21 06:53:28 +00001801 // If we are compiling with ASan, add metadata indicating dynamically
1802 // initialized globals.
Will Dietz4f45bc02013-01-18 11:30:38 +00001803 if (SanOpts.Address && NeedsGlobalCtor) {
Kostya Serebryany05c5ebc2012-08-21 06:53:28 +00001804 llvm::Module &M = getModule();
1805
1806 llvm::NamedMDNode *DynamicInitializers =
1807 M.getOrInsertNamedMetadata("llvm.asan.dynamically_initialized_globals");
1808 llvm::Value *GlobalToAdd[] = { GV };
1809 llvm::MDNode *ThisGlobal = llvm::MDNode::get(VMContext, GlobalToAdd);
1810 DynamicInitializers->addOperand(ThisGlobal);
1811 }
1812
Sanjiv Gupta686226b2008-06-05 08:59:10 +00001813 // Emit global variable debug information.
Eric Christopher73fb3502011-10-13 21:45:18 +00001814 if (CGDebugInfo *DI = getModuleDebugInfo())
Douglas Gregor4cdad312012-10-23 20:05:01 +00001815 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
Alexey Samsonovfd00eec2012-05-04 07:39:27 +00001816 DI->EmitGlobalVariable(GV, D);
Chris Lattner88a69ad2007-07-13 05:13:43 +00001817}
Reid Spencer5f016e22007-07-11 17:01:13 +00001818
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001819llvm::GlobalValue::LinkageTypes
1820CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
1821 llvm::GlobalVariable *GV) {
1822 GVALinkage Linkage = getContext().GetGVALinkageForVariable(D);
1823 if (Linkage == GVA_Internal)
1824 return llvm::Function::InternalLinkage;
1825 else if (D->hasAttr<DLLImportAttr>())
1826 return llvm::Function::DLLImportLinkage;
1827 else if (D->hasAttr<DLLExportAttr>())
1828 return llvm::Function::DLLExportLinkage;
1829 else if (D->hasAttr<WeakAttr>()) {
1830 if (GV->isConstant())
1831 return llvm::GlobalVariable::WeakODRLinkage;
1832 else
1833 return llvm::GlobalVariable::WeakAnyLinkage;
1834 } else if (Linkage == GVA_TemplateInstantiation ||
1835 Linkage == GVA_ExplicitTemplateInstantiation)
John McCall99ace162011-04-12 01:46:54 +00001836 return llvm::GlobalVariable::WeakODRLinkage;
David Blaikie4e4d0842012-03-11 07:00:24 +00001837 else if (!getLangOpts().CPlusPlus &&
Eric Christophera6cf1e72010-12-02 02:45:55 +00001838 ((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
1839 D->getAttr<CommonAttr>()) &&
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001840 !D->hasExternalStorage() && !D->getInit() &&
Fariborz Jahanianab27d6e2011-06-20 17:50:03 +00001841 !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
1842 !D->getAttr<WeakImportAttr>()) {
Fariborz Jahanian354e7122010-10-27 16:21:54 +00001843 // Thread local vars aren't considered common linkage.
1844 return llvm::GlobalVariable::CommonLinkage;
1845 }
1846 return llvm::GlobalVariable::ExternalLinkage;
1847}
1848
John McCalla923c972012-12-12 22:21:47 +00001849/// Replace the uses of a function that was declared with a non-proto type.
1850/// We want to silently drop extra arguments from call sites
1851static void replaceUsesOfNonProtoConstant(llvm::Constant *old,
1852 llvm::Function *newFn) {
1853 // Fast path.
1854 if (old->use_empty()) return;
1855
1856 llvm::Type *newRetTy = newFn->getReturnType();
1857 SmallVector<llvm::Value*, 4> newArgs;
1858
1859 for (llvm::Value::use_iterator ui = old->use_begin(), ue = old->use_end();
1860 ui != ue; ) {
1861 llvm::Value::use_iterator use = ui++; // Increment before the use is erased.
1862 llvm::User *user = *use;
1863
1864 // Recognize and replace uses of bitcasts. Most calls to
1865 // unprototyped functions will use bitcasts.
1866 if (llvm::ConstantExpr *bitcast = dyn_cast<llvm::ConstantExpr>(user)) {
1867 if (bitcast->getOpcode() == llvm::Instruction::BitCast)
1868 replaceUsesOfNonProtoConstant(bitcast, newFn);
1869 continue;
1870 }
1871
1872 // Recognize calls to the function.
1873 llvm::CallSite callSite(user);
1874 if (!callSite) continue;
1875 if (!callSite.isCallee(use)) continue;
1876
1877 // If the return types don't match exactly, then we can't
1878 // transform this call unless it's dead.
1879 if (callSite->getType() != newRetTy && !callSite->use_empty())
1880 continue;
1881
1882 // Get the call site's attribute list.
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001883 SmallVector<llvm::AttributeSet, 8> newAttrs;
John McCalla923c972012-12-12 22:21:47 +00001884 llvm::AttributeSet oldAttrs = callSite.getAttributes();
1885
1886 // Collect any return attributes from the call.
Bill Wendlinga37ce612013-01-21 21:57:40 +00001887 if (oldAttrs.hasAttributes(llvm::AttributeSet::ReturnIndex))
Bill Wendlinged01f842013-01-21 22:45:00 +00001888 newAttrs.push_back(
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001889 llvm::AttributeSet::get(newFn->getContext(),
1890 oldAttrs.getRetAttributes()));
John McCalla923c972012-12-12 22:21:47 +00001891
1892 // If the function was passed too few arguments, don't transform.
1893 unsigned newNumArgs = newFn->arg_size();
1894 if (callSite.arg_size() < newNumArgs) continue;
1895
1896 // If extra arguments were passed, we silently drop them.
1897 // If any of the types mismatch, we don't transform.
1898 unsigned argNo = 0;
1899 bool dontTransform = false;
1900 for (llvm::Function::arg_iterator ai = newFn->arg_begin(),
1901 ae = newFn->arg_end(); ai != ae; ++ai, ++argNo) {
1902 if (callSite.getArgument(argNo)->getType() != ai->getType()) {
1903 dontTransform = true;
1904 break;
1905 }
1906
1907 // Add any parameter attributes.
Bill Wendling89530e42013-01-23 06:15:10 +00001908 if (oldAttrs.hasAttributes(argNo + 1))
1909 newAttrs.
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001910 push_back(llvm::
1911 AttributeSet::get(newFn->getContext(),
1912 oldAttrs.getParamAttributes(argNo + 1)));
John McCalla923c972012-12-12 22:21:47 +00001913 }
1914 if (dontTransform)
1915 continue;
1916
Bill Wendlinge67e4c92013-01-18 21:26:07 +00001917 if (oldAttrs.hasAttributes(llvm::AttributeSet::FunctionIndex))
Bill Wendlingb263bdf2013-01-27 02:46:53 +00001918 newAttrs.push_back(llvm::AttributeSet::get(newFn->getContext(),
1919 oldAttrs.getFnAttributes()));
John McCalla923c972012-12-12 22:21:47 +00001920
1921 // Okay, we can transform this. Create the new call instruction and copy
1922 // over the required information.
1923 newArgs.append(callSite.arg_begin(), callSite.arg_begin() + argNo);
1924
1925 llvm::CallSite newCall;
1926 if (callSite.isCall()) {
1927 newCall = llvm::CallInst::Create(newFn, newArgs, "",
1928 callSite.getInstruction());
1929 } else {
1930 llvm::InvokeInst *oldInvoke =
1931 cast<llvm::InvokeInst>(callSite.getInstruction());
1932 newCall = llvm::InvokeInst::Create(newFn,
1933 oldInvoke->getNormalDest(),
1934 oldInvoke->getUnwindDest(),
1935 newArgs, "",
1936 callSite.getInstruction());
1937 }
1938 newArgs.clear(); // for the next iteration
1939
1940 if (!newCall->getType()->isVoidTy())
1941 newCall->takeName(callSite.getInstruction());
1942 newCall.setAttributes(
1943 llvm::AttributeSet::get(newFn->getContext(), newAttrs));
1944 newCall.setCallingConv(callSite.getCallingConv());
1945
1946 // Finally, remove the old call, replacing any uses with the new one.
1947 if (!callSite->use_empty())
1948 callSite->replaceAllUsesWith(newCall.getInstruction());
1949
1950 // Copy debug location attached to CI.
1951 if (!callSite->getDebugLoc().isUnknown())
1952 newCall->setDebugLoc(callSite->getDebugLoc());
1953 callSite->eraseFromParent();
1954 }
1955}
1956
Chris Lattnerbdb01322009-05-05 06:16:31 +00001957/// ReplaceUsesOfNonProtoTypeWithRealFunction - This function is called when we
1958/// implement a function with no prototype, e.g. "int foo() {}". If there are
1959/// existing call uses of the old function in the module, this adjusts them to
1960/// call the new function directly.
1961///
1962/// This is not just a cleanup: the always_inline pass requires direct calls to
1963/// functions to be able to inline them. If there is a bitcast in the way, it
1964/// won't inline them. Instcombine normally deletes these calls, but it isn't
1965/// run at -O0.
1966static void ReplaceUsesOfNonProtoTypeWithRealFunction(llvm::GlobalValue *Old,
1967 llvm::Function *NewFn) {
1968 // If we're redefining a global as a function, don't transform it.
John McCalla923c972012-12-12 22:21:47 +00001969 if (!isa<llvm::Function>(Old)) return;
Mike Stump1eb44332009-09-09 15:08:12 +00001970
John McCalla923c972012-12-12 22:21:47 +00001971 replaceUsesOfNonProtoConstant(Old, NewFn);
Chris Lattnerbdb01322009-05-05 06:16:31 +00001972}
1973
Rafael Espindola02503932012-03-08 15:51:03 +00001974void CodeGenModule::HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
1975 TemplateSpecializationKind TSK = VD->getTemplateSpecializationKind();
1976 // If we have a definition, this might be a deferred decl. If the
1977 // instantiation is explicit, make sure we emit it at the end.
1978 if (VD->getDefinition() && TSK == TSK_ExplicitInstantiationDefinition)
1979 GetAddrOfGlobalVar(VD);
Rafael Espindola234fe652012-03-05 10:54:55 +00001980}
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00001981
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001982void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001983 const FunctionDecl *D = cast<FunctionDecl>(GD.getDecl());
John McCalld26bc762011-03-09 04:27:21 +00001984
John McCall1f6f9612011-03-09 08:12:35 +00001985 // Compute the function info and LLVM type.
John McCallde5d3c72012-02-17 03:33:10 +00001986 const CGFunctionInfo &FI = getTypes().arrangeGlobalDeclaration(GD);
1987 llvm::FunctionType *Ty = getTypes().GetFunctionType(FI);
John McCalld26bc762011-03-09 04:27:21 +00001988
Chris Lattner9fa959d2009-05-12 20:58:15 +00001989 // Get or create the prototype for the function.
Chris Lattnerb4880ba2009-05-12 21:21:08 +00001990 llvm::Constant *Entry = GetAddrOfFunction(GD, Ty);
Mike Stump1eb44332009-09-09 15:08:12 +00001991
Chris Lattner0558e792009-03-21 09:25:43 +00001992 // Strip off a bitcast if we got one back.
1993 if (llvm::ConstantExpr *CE = dyn_cast<llvm::ConstantExpr>(Entry)) {
1994 assert(CE->getOpcode() == llvm::Instruction::BitCast);
1995 Entry = CE->getOperand(0);
1996 }
Mike Stump1eb44332009-09-09 15:08:12 +00001997
1998
Chris Lattner0558e792009-03-21 09:25:43 +00001999 if (cast<llvm::GlobalValue>(Entry)->getType()->getElementType() != Ty) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00002000 llvm::GlobalValue *OldFn = cast<llvm::GlobalValue>(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00002001
Daniel Dunbar42745812009-03-09 23:53:08 +00002002 // If the types mismatch then we have to rewrite the definition.
Chris Lattnerbdb01322009-05-05 06:16:31 +00002003 assert(OldFn->isDeclaration() &&
Chris Lattner0558e792009-03-21 09:25:43 +00002004 "Shouldn't replace non-declaration");
Chris Lattner34809502009-03-21 08:53:37 +00002005
Chris Lattner62b33ea2009-03-21 08:38:50 +00002006 // F is the Function* for the one with the wrong type, we must make a new
2007 // Function* and update everything that used F (a declaration) with the new
2008 // Function* (which will be a definition).
2009 //
2010 // This happens if there is a prototype for a function
2011 // (e.g. "int f()") and then a definition of a different type
John McCallf746aa62010-03-19 23:29:14 +00002012 // (e.g. "int f(int x)"). Move the old function aside so that it
2013 // doesn't interfere with GetAddrOfFunction.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002014 OldFn->setName(StringRef());
Chris Lattnerb4880ba2009-05-12 21:21:08 +00002015 llvm::Function *NewFn = cast<llvm::Function>(GetAddrOfFunction(GD, Ty));
Mike Stump1eb44332009-09-09 15:08:12 +00002016
John McCalla923c972012-12-12 22:21:47 +00002017 // This might be an implementation of a function without a
2018 // prototype, in which case, try to do special replacement of
2019 // calls which match the new prototype. The really key thing here
2020 // is that we also potentially drop arguments from the call site
2021 // so as to make a direct call, which makes the inliner happier
2022 // and suppresses a number of optimizer warnings (!) about
2023 // dropping arguments.
2024 if (!OldFn->use_empty()) {
Chris Lattnerbdb01322009-05-05 06:16:31 +00002025 ReplaceUsesOfNonProtoTypeWithRealFunction(OldFn, NewFn);
Chris Lattner9fa959d2009-05-12 20:58:15 +00002026 OldFn->removeDeadConstantUsers();
2027 }
Mike Stump1eb44332009-09-09 15:08:12 +00002028
Chris Lattner62b33ea2009-03-21 08:38:50 +00002029 // Replace uses of F with the Function we will endow with a body.
Chris Lattnerbdb01322009-05-05 06:16:31 +00002030 if (!Entry->use_empty()) {
Mike Stump1eb44332009-09-09 15:08:12 +00002031 llvm::Constant *NewPtrForOldDecl =
Owen Anderson3c4972d2009-07-29 18:54:39 +00002032 llvm::ConstantExpr::getBitCast(NewFn, Entry->getType());
Chris Lattnerbdb01322009-05-05 06:16:31 +00002033 Entry->replaceAllUsesWith(NewPtrForOldDecl);
2034 }
Mike Stump1eb44332009-09-09 15:08:12 +00002035
Chris Lattner62b33ea2009-03-21 08:38:50 +00002036 // Ok, delete the old function now, which is dead.
Chris Lattnerbdb01322009-05-05 06:16:31 +00002037 OldFn->eraseFromParent();
Mike Stump1eb44332009-09-09 15:08:12 +00002038
Chris Lattner0558e792009-03-21 09:25:43 +00002039 Entry = NewFn;
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002040 }
Mike Stump1eb44332009-09-09 15:08:12 +00002041
John McCall112c9672010-11-02 21:04:24 +00002042 // We need to set linkage and visibility on the function before
2043 // generating code for it because various parts of IR generation
2044 // want to propagate this information down (e.g. to local static
2045 // declarations).
Chris Lattner0558e792009-03-21 09:25:43 +00002046 llvm::Function *Fn = cast<llvm::Function>(Entry);
John McCall8b242332010-05-25 04:30:21 +00002047 setFunctionLinkage(D, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002048
John McCall112c9672010-11-02 21:04:24 +00002049 // FIXME: this is redundant with part of SetFunctionDefinitionAttributes
Anders Carlsson0ffeaad2011-01-29 19:39:23 +00002050 setGlobalVisibility(Fn, D);
John McCall112c9672010-11-02 21:04:24 +00002051
John McCalld26bc762011-03-09 04:27:21 +00002052 CodeGenFunction(*this).GenerateCode(D, Fn, FI);
Daniel Dunbar6bfed7e2008-08-01 00:01:51 +00002053
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002054 SetFunctionDefinitionAttributes(D, Fn);
2055 SetLLVMFunctionAttributesForDefinition(D, Fn);
Mike Stump1eb44332009-09-09 15:08:12 +00002056
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002057 if (const ConstructorAttr *CA = D->getAttr<ConstructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00002058 AddGlobalCtor(Fn, CA->getPriority());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002059 if (const DestructorAttr *DA = D->getAttr<DestructorAttr>())
Daniel Dunbar219df662008-09-08 23:44:31 +00002060 AddGlobalDtor(Fn, DA->getPriority());
Julien Lerouge77f68bb2011-09-09 22:41:49 +00002061 if (D->hasAttr<AnnotateAttr>())
2062 AddGlobalAnnotations(D, Fn);
Daniel Dunbarbd012ff2008-07-29 23:18:29 +00002063}
2064
John McCallf746aa62010-03-19 23:29:14 +00002065void CodeGenModule::EmitAliasDefinition(GlobalDecl GD) {
2066 const ValueDecl *D = cast<ValueDecl>(GD.getDecl());
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002067 const AliasAttr *AA = D->getAttr<AliasAttr>();
Chris Lattnerbd532712009-03-22 21:47:11 +00002068 assert(AA && "Not an alias?");
2069
Chris Lattner5f9e2722011-07-23 10:55:15 +00002070 StringRef MangledName = getMangledName(GD);
Mike Stump1eb44332009-09-09 15:08:12 +00002071
John McCallf746aa62010-03-19 23:29:14 +00002072 // If there is a definition in the module, then it wins over the alias.
2073 // This is dubious, but allow it to be safe. Just ignore the alias.
2074 llvm::GlobalValue *Entry = GetGlobalValue(MangledName);
2075 if (Entry && !Entry->isDeclaration())
2076 return;
2077
Chris Lattner2acc6e32011-07-18 04:24:23 +00002078 llvm::Type *DeclTy = getTypes().ConvertTypeForMem(D->getType());
Chris Lattnerbd532712009-03-22 21:47:11 +00002079
2080 // Create a reference to the named value. This ensures that it is emitted
2081 // if a deferred decl.
2082 llvm::Constant *Aliasee;
2083 if (isa<llvm::FunctionType>(DeclTy))
Alex Rosenbergc857ce82012-10-05 23:12:53 +00002084 Aliasee = GetOrCreateLLVMFunction(AA->getAliasee(), DeclTy, GD,
Anders Carlsson1faa89f2011-02-05 04:35:53 +00002085 /*ForVTable=*/false);
Chris Lattnerbd532712009-03-22 21:47:11 +00002086 else
John McCallf746aa62010-03-19 23:29:14 +00002087 Aliasee = GetOrCreateLLVMGlobal(AA->getAliasee(),
Owen Anderson96e0fc72009-07-29 22:16:19 +00002088 llvm::PointerType::getUnqual(DeclTy), 0);
Chris Lattnerbd532712009-03-22 21:47:11 +00002089
2090 // Create the new alias itself, but don't set a name yet.
Mike Stump1eb44332009-09-09 15:08:12 +00002091 llvm::GlobalValue *GA =
Chris Lattnerbd532712009-03-22 21:47:11 +00002092 new llvm::GlobalAlias(Aliasee->getType(),
2093 llvm::Function::ExternalLinkage,
2094 "", Aliasee, &getModule());
Mike Stump1eb44332009-09-09 15:08:12 +00002095
Chris Lattnerbd532712009-03-22 21:47:11 +00002096 if (Entry) {
John McCallf746aa62010-03-19 23:29:14 +00002097 assert(Entry->isDeclaration());
2098
Chris Lattnerbd532712009-03-22 21:47:11 +00002099 // If there is a declaration in the module, then we had an extern followed
2100 // by the alias, as in:
2101 // extern int test6();
2102 // ...
2103 // int test6() __attribute__((alias("test7")));
2104 //
2105 // Remove it and replace uses of it with the alias.
John McCallf746aa62010-03-19 23:29:14 +00002106 GA->takeName(Entry);
Mike Stump1eb44332009-09-09 15:08:12 +00002107
Owen Anderson3c4972d2009-07-29 18:54:39 +00002108 Entry->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GA,
Chris Lattnerbd532712009-03-22 21:47:11 +00002109 Entry->getType()));
Chris Lattnerbd532712009-03-22 21:47:11 +00002110 Entry->eraseFromParent();
John McCallf746aa62010-03-19 23:29:14 +00002111 } else {
Anders Carlsson9a20d552010-06-22 16:16:50 +00002112 GA->setName(MangledName);
Chris Lattnerbd532712009-03-22 21:47:11 +00002113 }
Mike Stump1eb44332009-09-09 15:08:12 +00002114
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002115 // Set attributes which are particular to an alias; this is a
2116 // specialization of the attributes which may be set on a global
2117 // variable/function.
Argyrios Kyrtzidis40b598e2009-06-30 02:34:44 +00002118 if (D->hasAttr<DLLExportAttr>()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002119 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
2120 // The dllexport attribute is ignored for undefined symbols.
Argyrios Kyrtzidis06a54a32010-07-07 11:31:19 +00002121 if (FD->hasBody())
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002122 GA->setLinkage(llvm::Function::DLLExportLinkage);
2123 } else {
2124 GA->setLinkage(llvm::Function::DLLExportLinkage);
2125 }
Mike Stump1eb44332009-09-09 15:08:12 +00002126 } else if (D->hasAttr<WeakAttr>() ||
Rafael Espindola11e8ce72010-02-23 22:00:30 +00002127 D->hasAttr<WeakRefAttr>() ||
Douglas Gregor0a0d2b12011-03-23 00:50:03 +00002128 D->isWeakImported()) {
Daniel Dunbar7c65e992009-04-14 08:05:55 +00002129 GA->setLinkage(llvm::Function::WeakAnyLinkage);
2130 }
2131
2132 SetCommonAttributes(D, GA);
Chris Lattnerbd532712009-03-22 21:47:11 +00002133}
2134
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00002135llvm::Function *CodeGenModule::getIntrinsic(unsigned IID,
Chris Lattner2d3ba4f2011-07-23 17:14:25 +00002136 ArrayRef<llvm::Type*> Tys) {
Jay Foaddf983a82011-07-12 14:06:48 +00002137 return llvm::Intrinsic::getDeclaration(&getModule(), (llvm::Intrinsic::ID)IID,
Benjamin Kramer8dd55a32011-07-14 17:45:50 +00002138 Tys);
Chris Lattner7acda7c2007-12-18 00:25:38 +00002139}
Chris Lattnerbef20ac2007-08-31 04:31:45 +00002140
Daniel Dunbar1d552912009-07-23 22:52:48 +00002141static llvm::StringMapEntry<llvm::Constant*> &
2142GetConstantCFStringEntry(llvm::StringMap<llvm::Constant*> &Map,
2143 const StringLiteral *Literal,
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002144 bool TargetIsLSB,
Daniel Dunbar1d552912009-07-23 22:52:48 +00002145 bool &IsUTF16,
2146 unsigned &StringLength) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002147 StringRef String = Literal->getString();
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002148 unsigned NumBytes = String.size();
Daniel Dunbar1d552912009-07-23 22:52:48 +00002149
Daniel Dunbarf015b032009-09-22 10:03:52 +00002150 // Check for simple case.
2151 if (!Literal->containsNonAsciiOrNull()) {
2152 StringLength = NumBytes;
Benjamin Kramer2f4eaef2010-08-17 12:54:38 +00002153 return Map.GetOrCreateValue(String);
Daniel Dunbarf015b032009-09-22 10:03:52 +00002154 }
2155
Bill Wendling84392d02012-03-30 00:26:17 +00002156 // Otherwise, convert the UTF8 literals into a string of shorts.
2157 IsUTF16 = true;
2158
2159 SmallVector<UTF16, 128> ToBuf(NumBytes + 1); // +1 for ending nulls.
Roman Divacky31ba6132012-09-06 15:59:27 +00002160 const UTF8 *FromPtr = (const UTF8 *)String.data();
Daniel Dunbar1d552912009-07-23 22:52:48 +00002161 UTF16 *ToPtr = &ToBuf[0];
Mike Stump1eb44332009-09-09 15:08:12 +00002162
Fariborz Jahaniane7ddfb92010-09-07 19:57:04 +00002163 (void)ConvertUTF8toUTF16(&FromPtr, FromPtr + NumBytes,
2164 &ToPtr, ToPtr + NumBytes,
2165 strictConversion);
Mike Stump1eb44332009-09-09 15:08:12 +00002166
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002167 // ConvertUTF8toUTF16 returns the length in ToPtr.
Daniel Dunbar1d552912009-07-23 22:52:48 +00002168 StringLength = ToPtr - &ToBuf[0];
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002169
Bill Wendling84392d02012-03-30 00:26:17 +00002170 // Add an explicit null.
2171 *ToPtr = 0;
2172 return Map.
2173 GetOrCreateValue(StringRef(reinterpret_cast<const char *>(ToBuf.data()),
2174 (StringLength + 1) * 2));
Daniel Dunbar1d552912009-07-23 22:52:48 +00002175}
2176
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002177static llvm::StringMapEntry<llvm::Constant*> &
2178GetConstantStringEntry(llvm::StringMap<llvm::Constant*> &Map,
Bill Wendling8322c232012-03-29 22:12:09 +00002179 const StringLiteral *Literal,
2180 unsigned &StringLength) {
2181 StringRef String = Literal->getString();
2182 StringLength = String.size();
2183 return Map.GetOrCreateValue(String);
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002184}
2185
Daniel Dunbar1d552912009-07-23 22:52:48 +00002186llvm::Constant *
2187CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
2188 unsigned StringLength = 0;
2189 bool isUTF16 = false;
2190 llvm::StringMapEntry<llvm::Constant*> &Entry =
Mike Stump1eb44332009-09-09 15:08:12 +00002191 GetConstantCFStringEntry(CFConstantStringMap, Literal,
Micah Villmow25a6a842012-10-08 16:25:52 +00002192 getDataLayout().isLittleEndian(),
Daniel Dunbar70ee9752009-07-23 23:41:22 +00002193 isUTF16, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00002194
Daniel Dunbar1d552912009-07-23 22:52:48 +00002195 if (llvm::Constant *C = Entry.getValue())
2196 return C;
Mike Stump1eb44332009-09-09 15:08:12 +00002197
Chris Lattner8b418682012-02-07 00:39:47 +00002198 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002199 llvm::Constant *Zeros[] = { Zero, Zero };
Mike Stump1eb44332009-09-09 15:08:12 +00002200
Chris Lattner9d4a15f2009-07-16 16:48:25 +00002201 // If we don't already have it, get __CFConstantStringClassReference.
Anders Carlssonc9e20912007-08-21 00:21:21 +00002202 if (!CFConstantStringClassRef) {
Chris Lattner2acc6e32011-07-18 04:24:23 +00002203 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Owen Anderson96e0fc72009-07-29 22:16:19 +00002204 Ty = llvm::ArrayType::get(Ty, 0);
Mike Stump1eb44332009-09-09 15:08:12 +00002205 llvm::Constant *GV = CreateRuntimeVariable(Ty,
Chris Lattner9d4a15f2009-07-16 16:48:25 +00002206 "__CFConstantStringClassReference");
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002207 // Decay array -> ptr
2208 CFConstantStringClassRef =
Jay Foada5c04342011-07-21 14:31:17 +00002209 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlssonc9e20912007-08-21 00:21:21 +00002210 }
Mike Stump1eb44332009-09-09 15:08:12 +00002211
Anders Carlssone3daa762008-11-15 18:54:24 +00002212 QualType CFTy = getContext().getCFConstantStringType();
Daniel Dunbar3e9df992008-08-23 18:37:06 +00002213
Chris Lattner2acc6e32011-07-18 04:24:23 +00002214 llvm::StructType *STy =
Anders Carlssone3daa762008-11-15 18:54:24 +00002215 cast<llvm::StructType>(getTypes().ConvertType(CFTy));
2216
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00002217 llvm::Constant *Fields[4];
Douglas Gregor44b43212008-12-11 16:49:14 +00002218
Anders Carlssonc9e20912007-08-21 00:21:21 +00002219 // Class pointer.
Anders Carlsson5add6832009-08-16 05:55:31 +00002220 Fields[0] = CFConstantStringClassRef;
Mike Stump1eb44332009-09-09 15:08:12 +00002221
Anders Carlssonc9e20912007-08-21 00:21:21 +00002222 // Flags.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002223 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Mike Stump1eb44332009-09-09 15:08:12 +00002224 Fields[1] = isUTF16 ? llvm::ConstantInt::get(Ty, 0x07d0) :
Anders Carlsson5add6832009-08-16 05:55:31 +00002225 llvm::ConstantInt::get(Ty, 0x07C8);
2226
Anders Carlssonc9e20912007-08-21 00:21:21 +00002227 // String pointer.
Bill Wendling84392d02012-03-30 00:26:17 +00002228 llvm::Constant *C = 0;
2229 if (isUTF16) {
2230 ArrayRef<uint16_t> Arr =
David Greene5ba58a12013-01-15 22:09:41 +00002231 llvm::makeArrayRef<uint16_t>(reinterpret_cast<uint16_t*>(
2232 const_cast<char *>(Entry.getKey().data())),
Bill Wendling84392d02012-03-30 00:26:17 +00002233 Entry.getKey().size() / 2);
2234 C = llvm::ConstantDataArray::get(VMContext, Arr);
2235 } else {
2236 C = llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
2237 }
Daniel Dunbara9668e02009-04-03 00:57:44 +00002238
Chris Lattner95b851e2009-07-16 05:03:48 +00002239 llvm::GlobalValue::LinkageTypes Linkage;
Bill Wendling1bf7a3f2012-01-10 08:46:39 +00002240 if (isUTF16)
Chris Lattner278b9f02009-10-14 05:55:45 +00002241 // FIXME: why do utf strings get "_" labels instead of "L" labels?
Chris Lattner95b851e2009-07-16 05:03:48 +00002242 Linkage = llvm::GlobalValue::InternalLinkage;
Bill Wendling1bf7a3f2012-01-10 08:46:39 +00002243 else
Rafael Espindola584acf22011-03-14 17:55:00 +00002244 // FIXME: With OS X ld 123.2 (xcode 4) and LTO we would get a linker error
2245 // when using private linkage. It is not clear if this is a bug in ld
2246 // or a reasonable new restriction.
Rafael Espindoladc0f1372011-03-14 21:08:19 +00002247 Linkage = llvm::GlobalValue::LinkerPrivateLinkage;
Chris Lattner278b9f02009-10-14 05:55:45 +00002248
Bill Wendling1bf7a3f2012-01-10 08:46:39 +00002249 // Note: -fwritable-strings doesn't make the backing store strings of
2250 // CFStrings writable. (See <rdar://problem/10657500>)
Mike Stump1eb44332009-09-09 15:08:12 +00002251 llvm::GlobalVariable *GV =
Bill Wendling1bf7a3f2012-01-10 08:46:39 +00002252 new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
2253 Linkage, C, ".str");
Rafael Espindolab266a1f2011-01-17 16:31:00 +00002254 GV->setUnnamedAddr(true);
Daniel Dunbara9668e02009-04-03 00:57:44 +00002255 if (isUTF16) {
Ken Dyck4da244c2010-01-26 18:46:23 +00002256 CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
2257 GV->setAlignment(Align.getQuantity());
Daniel Dunbarf7e903d2011-04-12 23:30:52 +00002258 } else {
2259 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2260 GV->setAlignment(Align.getQuantity());
Daniel Dunbara9668e02009-04-03 00:57:44 +00002261 }
Bill Wendling84392d02012-03-30 00:26:17 +00002262
2263 // String.
Jay Foada5c04342011-07-21 14:31:17 +00002264 Fields[2] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Anders Carlsson5add6832009-08-16 05:55:31 +00002265
Bill Wendling84392d02012-03-30 00:26:17 +00002266 if (isUTF16)
2267 // Cast the UTF16 string to the correct type.
2268 Fields[2] = llvm::ConstantExpr::getBitCast(Fields[2], Int8PtrTy);
2269
Anders Carlssonc9e20912007-08-21 00:21:21 +00002270 // String length.
2271 Ty = getTypes().ConvertType(getContext().LongTy);
Anders Carlsson5add6832009-08-16 05:55:31 +00002272 Fields[3] = llvm::ConstantInt::get(Ty, StringLength);
Mike Stump1eb44332009-09-09 15:08:12 +00002273
Anders Carlssonc9e20912007-08-21 00:21:21 +00002274 // The struct.
Owen Anderson08e25242009-07-27 22:29:56 +00002275 C = llvm::ConstantStruct::get(STy, Fields);
Mike Stump1eb44332009-09-09 15:08:12 +00002276 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2277 llvm::GlobalVariable::PrivateLinkage, C,
Chris Lattner95b851e2009-07-16 05:03:48 +00002278 "_unnamed_cfstring_");
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002279 if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00002280 GV->setSection(Sect);
Daniel Dunbar1d552912009-07-23 22:52:48 +00002281 Entry.setValue(GV);
Mike Stump1eb44332009-09-09 15:08:12 +00002282
Anders Carlsson0c678292007-11-01 00:41:52 +00002283 return GV;
Anders Carlssonc9e20912007-08-21 00:21:21 +00002284}
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002285
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002286static RecordDecl *
2287CreateRecordDecl(const ASTContext &Ctx, RecordDecl::TagKind TK,
2288 DeclContext *DC, IdentifierInfo *Id) {
2289 SourceLocation Loc;
David Blaikie4e4d0842012-03-11 07:00:24 +00002290 if (Ctx.getLangOpts().CPlusPlus)
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002291 return CXXRecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2292 else
2293 return RecordDecl::Create(Ctx, TK, DC, Loc, Loc, Id);
2294}
2295
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00002296llvm::Constant *
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002297CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002298 unsigned StringLength = 0;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002299 llvm::StringMapEntry<llvm::Constant*> &Entry =
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002300 GetConstantStringEntry(CFConstantStringMap, Literal, StringLength);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002301
2302 if (llvm::Constant *C = Entry.getValue())
2303 return C;
2304
Chris Lattner812234b2012-02-06 22:47:00 +00002305 llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002306 llvm::Constant *Zeros[] = { Zero, Zero };
2307
Fariborz Jahanianec951e02010-04-23 22:33:39 +00002308 // If we don't already have it, get _NSConstantStringClassReference.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002309 if (!ConstantStringClassRef) {
David Blaikie4e4d0842012-03-11 07:00:24 +00002310 std::string StringClass(getLangOpts().ObjCConstantStringClass);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002311 llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002312 llvm::Constant *GV;
John McCall260611a2012-06-20 06:18:46 +00002313 if (LangOpts.ObjCRuntime.isNonFragile()) {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00002314 std::string str =
2315 StringClass.empty() ? "OBJC_CLASS_$_NSConstantString"
2316 : "OBJC_CLASS_$_" + StringClass;
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00002317 GV = getObjCRuntime().GetClassGlobal(str);
2318 // Make sure the result is of the correct type.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002319 llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00002320 ConstantStringClassRef =
2321 llvm::ConstantExpr::getBitCast(GV, PTy);
2322 } else {
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00002323 std::string str =
2324 StringClass.empty() ? "_NSConstantStringClassReference"
2325 : "_" + StringClass + "ClassReference";
Chris Lattner2acc6e32011-07-18 04:24:23 +00002326 llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
Fariborz Jahanian25dba5d2011-05-17 22:46:11 +00002327 GV = CreateRuntimeVariable(PTy, str);
Fariborz Jahanian6f40e222011-05-17 22:21:16 +00002328 // Decay array -> ptr
2329 ConstantStringClassRef =
Jay Foada5c04342011-07-21 14:31:17 +00002330 llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002331 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002332 }
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002333
2334 if (!NSConstantStringType) {
2335 // Construct the type for a constant NSString.
2336 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2337 Context.getTranslationUnitDecl(),
2338 &Context.Idents.get("__builtin_NSString"));
2339 D->startDefinition();
2340
2341 QualType FieldTypes[3];
2342
2343 // const int *isa;
2344 FieldTypes[0] = Context.getPointerType(Context.IntTy.withConst());
2345 // const char *str;
2346 FieldTypes[1] = Context.getPointerType(Context.CharTy.withConst());
2347 // unsigned int length;
2348 FieldTypes[2] = Context.UnsignedIntTy;
2349
2350 // Create fields
2351 for (unsigned i = 0; i < 3; ++i) {
2352 FieldDecl *Field = FieldDecl::Create(Context, D,
2353 SourceLocation(),
2354 SourceLocation(), 0,
2355 FieldTypes[i], /*TInfo=*/0,
2356 /*BitWidth=*/0,
2357 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002358 ICIS_NoInit);
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002359 Field->setAccess(AS_public);
2360 D->addDecl(Field);
2361 }
2362
2363 D->completeDefinition();
2364 QualType NSTy = Context.getTagDeclType(D);
2365 NSConstantStringType = cast<llvm::StructType>(getTypes().ConvertType(NSTy));
2366 }
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002367
Benjamin Kramer1d236ab2011-10-15 12:20:02 +00002368 llvm::Constant *Fields[3];
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002369
2370 // Class pointer.
Fariborz Jahanian4c733072010-10-19 17:19:29 +00002371 Fields[0] = ConstantStringClassRef;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002372
2373 // String pointer.
Chris Lattner94010692012-02-05 02:30:40 +00002374 llvm::Constant *C =
2375 llvm::ConstantDataArray::getString(VMContext, Entry.getKey());
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002376
2377 llvm::GlobalValue::LinkageTypes Linkage;
2378 bool isConstant;
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002379 Linkage = llvm::GlobalValue::PrivateLinkage;
David Blaikie4e4d0842012-03-11 07:00:24 +00002380 isConstant = !LangOpts.WritableStrings;
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002381
2382 llvm::GlobalVariable *GV =
2383 new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
2384 ".str");
Rafael Espindola803d3072011-01-17 22:11:21 +00002385 GV->setUnnamedAddr(true);
Fariborz Jahaniancf8e1682011-05-13 18:13:10 +00002386 CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
2387 GV->setAlignment(Align.getQuantity());
Jay Foada5c04342011-07-21 14:31:17 +00002388 Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002389
2390 // String length.
Chris Lattner2acc6e32011-07-18 04:24:23 +00002391 llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002392 Fields[2] = llvm::ConstantInt::get(Ty, StringLength);
2393
2394 // The struct.
Douglas Gregor45c4ea72011-08-09 15:54:21 +00002395 C = llvm::ConstantStruct::get(NSConstantStringType, Fields);
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002396 GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
2397 llvm::GlobalVariable::PrivateLinkage, C,
2398 "_unnamed_nsstring_");
2399 // FIXME. Fix section.
Fariborz Jahanianec951e02010-04-23 22:33:39 +00002400 if (const char *Sect =
John McCall260611a2012-06-20 06:18:46 +00002401 LangOpts.ObjCRuntime.isNonFragile()
Douglas Gregorbcfd1f52011-09-02 00:18:52 +00002402 ? getContext().getTargetInfo().getNSStringNonFragileABISection()
2403 : getContext().getTargetInfo().getNSStringSection())
Fariborz Jahanian2bb5dda2010-04-23 17:41:07 +00002404 GV->setSection(Sect);
2405 Entry.setValue(GV);
2406
2407 return GV;
Fariborz Jahanian33e982b2010-04-22 20:26:39 +00002408}
2409
Douglas Gregor0815b572011-08-09 17:23:49 +00002410QualType CodeGenModule::getObjCFastEnumerationStateType() {
2411 if (ObjCFastEnumerationStateType.isNull()) {
2412 RecordDecl *D = CreateRecordDecl(Context, TTK_Struct,
2413 Context.getTranslationUnitDecl(),
2414 &Context.Idents.get("__objcFastEnumerationState"));
2415 D->startDefinition();
2416
2417 QualType FieldTypes[] = {
2418 Context.UnsignedLongTy,
2419 Context.getPointerType(Context.getObjCIdType()),
2420 Context.getPointerType(Context.UnsignedLongTy),
2421 Context.getConstantArrayType(Context.UnsignedLongTy,
2422 llvm::APInt(32, 5), ArrayType::Normal, 0)
2423 };
2424
2425 for (size_t i = 0; i < 4; ++i) {
2426 FieldDecl *Field = FieldDecl::Create(Context,
2427 D,
2428 SourceLocation(),
2429 SourceLocation(), 0,
2430 FieldTypes[i], /*TInfo=*/0,
2431 /*BitWidth=*/0,
2432 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00002433 ICIS_NoInit);
Douglas Gregor0815b572011-08-09 17:23:49 +00002434 Field->setAccess(AS_public);
2435 D->addDecl(Field);
2436 }
2437
2438 D->completeDefinition();
2439 ObjCFastEnumerationStateType = Context.getTagDeclType(D);
2440 }
2441
2442 return ObjCFastEnumerationStateType;
2443}
2444
Eli Friedman64f45a22011-11-01 02:23:42 +00002445llvm::Constant *
2446CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
2447 assert(!E->getType()->isPointerType() && "Strings are always arrays");
2448
2449 // Don't emit it as the address of the string, emit the string data itself
2450 // as an inline array.
Chris Lattner812234b2012-02-06 22:47:00 +00002451 if (E->getCharByteWidth() == 1) {
2452 SmallString<64> Str(E->getString());
2453
2454 // Resize the string to the right size, which is indicated by its type.
2455 const ConstantArrayType *CAT = Context.getAsConstantArrayType(E->getType());
2456 Str.resize(CAT->getSize().getZExtValue());
2457 return llvm::ConstantDataArray::getString(VMContext, Str, false);
2458 }
Chris Lattner94010692012-02-05 02:30:40 +00002459
2460 llvm::ArrayType *AType =
2461 cast<llvm::ArrayType>(getTypes().ConvertType(E->getType()));
2462 llvm::Type *ElemTy = AType->getElementType();
2463 unsigned NumElements = AType->getNumElements();
Chris Lattnerd79ed432012-02-06 22:52:04 +00002464
2465 // Wide strings have either 2-byte or 4-byte elements.
2466 if (ElemTy->getPrimitiveSizeInBits() == 16) {
2467 SmallVector<uint16_t, 32> Elements;
2468 Elements.reserve(NumElements);
2469
2470 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2471 Elements.push_back(E->getCodeUnit(i));
2472 Elements.resize(NumElements);
2473 return llvm::ConstantDataArray::get(VMContext, Elements);
Chris Lattner94010692012-02-05 02:30:40 +00002474 }
2475
Chris Lattnerd79ed432012-02-06 22:52:04 +00002476 assert(ElemTy->getPrimitiveSizeInBits() == 32);
2477 SmallVector<uint32_t, 32> Elements;
2478 Elements.reserve(NumElements);
2479
2480 for(unsigned i = 0, e = E->getLength(); i != e; ++i)
2481 Elements.push_back(E->getCodeUnit(i));
2482 Elements.resize(NumElements);
2483 return llvm::ConstantDataArray::get(VMContext, Elements);
Eli Friedman64f45a22011-11-01 02:23:42 +00002484}
2485
Daniel Dunbar61432932008-08-13 23:20:05 +00002486/// GetAddrOfConstantStringFromLiteral - Return a pointer to a
2487/// constant array for the given string literal.
2488llvm::Constant *
2489CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
John McCalla5e19c62011-08-04 01:03:22 +00002490 CharUnits Align = getContext().getTypeAlignInChars(S->getType());
Eli Friedman64f45a22011-11-01 02:23:42 +00002491 if (S->isAscii() || S->isUTF8()) {
Chris Lattner812234b2012-02-06 22:47:00 +00002492 SmallString<64> Str(S->getString());
2493
2494 // Resize the string to the right size, which is indicated by its type.
2495 const ConstantArrayType *CAT = Context.getAsConstantArrayType(S->getType());
2496 Str.resize(CAT->getSize().getZExtValue());
2497 return GetAddrOfConstantString(Str, /*GlobalName*/ 0, Align.getQuantity());
Eli Friedman7eb79c12009-11-16 05:55:46 +00002498 }
Eli Friedman64f45a22011-11-01 02:23:42 +00002499
Chris Lattner812234b2012-02-06 22:47:00 +00002500 // FIXME: the following does not memoize wide strings.
Eli Friedman64f45a22011-11-01 02:23:42 +00002501 llvm::Constant *C = GetConstantArrayFromStringLiteral(S);
2502 llvm::GlobalVariable *GV =
2503 new llvm::GlobalVariable(getModule(),C->getType(),
David Blaikie4e4d0842012-03-11 07:00:24 +00002504 !LangOpts.WritableStrings,
Eli Friedman64f45a22011-11-01 02:23:42 +00002505 llvm::GlobalValue::PrivateLinkage,
2506 C,".str");
Seth Cantrell7d6a7c02012-01-18 12:11:32 +00002507
Eli Friedman64f45a22011-11-01 02:23:42 +00002508 GV->setAlignment(Align.getQuantity());
2509 GV->setUnnamedAddr(true);
Eli Friedman64f45a22011-11-01 02:23:42 +00002510 return GV;
Daniel Dunbar61432932008-08-13 23:20:05 +00002511}
2512
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002513/// GetAddrOfConstantStringFromObjCEncode - Return a pointer to a constant
2514/// array for the given ObjCEncodeExpr node.
2515llvm::Constant *
2516CodeGenModule::GetAddrOfConstantStringFromObjCEncode(const ObjCEncodeExpr *E) {
2517 std::string Str;
2518 getContext().getObjCEncodingForType(E->getEncodedType(), Str);
Eli Friedmana210f352009-03-07 20:17:55 +00002519
2520 return GetAddrOfConstantCString(Str);
Chris Lattnereaf2bb82009-02-24 22:18:39 +00002521}
2522
2523
Chris Lattnera7ad98f2008-02-11 00:02:17 +00002524/// GenerateWritableString -- Creates storage for a string literal.
John McCalla5e19c62011-08-04 01:03:22 +00002525static llvm::GlobalVariable *GenerateStringLiteral(StringRef str,
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002526 bool constant,
Daniel Dunbar5fabf9d2008-10-17 21:56:50 +00002527 CodeGenModule &CGM,
John McCalla5e19c62011-08-04 01:03:22 +00002528 const char *GlobalName,
2529 unsigned Alignment) {
Daniel Dunbar61432932008-08-13 23:20:05 +00002530 // Create Constant for this string literal. Don't add a '\0'.
Owen Anderson0032b272009-08-13 21:57:51 +00002531 llvm::Constant *C =
Chris Lattner94010692012-02-05 02:30:40 +00002532 llvm::ConstantDataArray::getString(CGM.getLLVMContext(), str, false);
Mike Stump1eb44332009-09-09 15:08:12 +00002533
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002534 // Create a global variable for this string
Rafael Espindola1257bc62011-01-10 22:34:03 +00002535 llvm::GlobalVariable *GV =
2536 new llvm::GlobalVariable(CGM.getModule(), C->getType(), constant,
2537 llvm::GlobalValue::PrivateLinkage,
2538 C, GlobalName);
John McCalla5e19c62011-08-04 01:03:22 +00002539 GV->setAlignment(Alignment);
Rafael Espindola1257bc62011-01-10 22:34:03 +00002540 GV->setUnnamedAddr(true);
2541 return GV;
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002542}
2543
Daniel Dunbar61432932008-08-13 23:20:05 +00002544/// GetAddrOfConstantString - Returns a pointer to a character array
2545/// containing the literal. This contents are exactly that of the
2546/// given string, i.e. it will not be null terminated automatically;
2547/// see GetAddrOfConstantCString. Note that whether the result is
2548/// actually a pointer to an LLVM constant depends on
2549/// Feature.WriteableStrings.
2550///
2551/// The result has pointer to array type.
Chris Lattner5f9e2722011-07-23 10:55:15 +00002552llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
John McCalla5e19c62011-08-04 01:03:22 +00002553 const char *GlobalName,
2554 unsigned Alignment) {
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00002555 // Get the default prefix if a name wasn't specified.
2556 if (!GlobalName)
Chris Lattner95b851e2009-07-16 05:03:48 +00002557 GlobalName = ".str";
Daniel Dunbar8e5c2b82009-03-31 23:42:16 +00002558
2559 // Don't share any string literals if strings aren't constant.
David Blaikie4e4d0842012-03-11 07:00:24 +00002560 if (LangOpts.WritableStrings)
John McCalla5e19c62011-08-04 01:03:22 +00002561 return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
Mike Stump1eb44332009-09-09 15:08:12 +00002562
John McCalla5e19c62011-08-04 01:03:22 +00002563 llvm::StringMapEntry<llvm::GlobalVariable *> &Entry =
Benjamin Kramer9de43422011-03-05 13:45:23 +00002564 ConstantStringMap.GetOrCreateValue(Str);
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002565
John McCalla5e19c62011-08-04 01:03:22 +00002566 if (llvm::GlobalVariable *GV = Entry.getValue()) {
2567 if (Alignment > GV->getAlignment()) {
2568 GV->setAlignment(Alignment);
2569 }
2570 return GV;
2571 }
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002572
2573 // Create a global variable for this.
Chris Lattner812234b2012-02-06 22:47:00 +00002574 llvm::GlobalVariable *GV = GenerateStringLiteral(Str, true, *this, GlobalName,
2575 Alignment);
John McCalla5e19c62011-08-04 01:03:22 +00002576 Entry.setValue(GV);
2577 return GV;
Chris Lattner45e8cbd2007-11-28 05:34:05 +00002578}
Daniel Dunbar61432932008-08-13 23:20:05 +00002579
2580/// GetAddrOfConstantCString - Returns a pointer to a character
Benjamin Kramer9de43422011-03-05 13:45:23 +00002581/// array containing the literal and a terminating '\0'
Daniel Dunbar61432932008-08-13 23:20:05 +00002582/// character. The result has pointer to array type.
Benjamin Kramer9de43422011-03-05 13:45:23 +00002583llvm::Constant *CodeGenModule::GetAddrOfConstantCString(const std::string &Str,
John McCalla5e19c62011-08-04 01:03:22 +00002584 const char *GlobalName,
2585 unsigned Alignment) {
Chris Lattner5f9e2722011-07-23 10:55:15 +00002586 StringRef StrWithNull(Str.c_str(), Str.size() + 1);
John McCalla5e19c62011-08-04 01:03:22 +00002587 return GetAddrOfConstantString(StrWithNull, GlobalName, Alignment);
Daniel Dunbar61432932008-08-13 23:20:05 +00002588}
Daniel Dunbar41071de2008-08-15 23:26:23 +00002589
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002590/// EmitObjCPropertyImplementations - Emit information for synthesized
2591/// properties for an implementation.
Mike Stump1eb44332009-09-09 15:08:12 +00002592void CodeGenModule::EmitObjCPropertyImplementations(const
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002593 ObjCImplementationDecl *D) {
Mike Stump1eb44332009-09-09 15:08:12 +00002594 for (ObjCImplementationDecl::propimpl_iterator
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002595 i = D->propimpl_begin(), e = D->propimpl_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00002596 ObjCPropertyImplDecl *PID = *i;
Mike Stump1eb44332009-09-09 15:08:12 +00002597
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002598 // Dynamic is just for type-checking.
2599 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize) {
2600 ObjCPropertyDecl *PD = PID->getPropertyDecl();
2601
2602 // Determine which methods need to be implemented, some may have
Jordan Rose1e4691b2012-10-10 16:42:25 +00002603 // been overridden. Note that ::isPropertyAccessor is not the method
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002604 // we want, that just indicates if the decl came from a
2605 // property. What we want to know is if the method is defined in
2606 // this implementation.
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002607 if (!D->getInstanceMethod(PD->getGetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00002608 CodeGenFunction(*this).GenerateObjCGetter(
2609 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002610 if (!PD->isReadOnly() &&
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002611 !D->getInstanceMethod(PD->getSetterName()))
Fariborz Jahanianfef30b52008-12-09 20:23:04 +00002612 CodeGenFunction(*this).GenerateObjCSetter(
2613 const_cast<ObjCImplementationDecl *>(D), PID);
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002614 }
2615 }
2616}
2617
John McCalle81ac692011-03-22 07:05:39 +00002618static bool needsDestructMethod(ObjCImplementationDecl *impl) {
Jordy Rosedb8264e2011-07-22 02:08:32 +00002619 const ObjCInterfaceDecl *iface = impl->getClassInterface();
2620 for (const ObjCIvarDecl *ivar = iface->all_declared_ivar_begin();
John McCalle81ac692011-03-22 07:05:39 +00002621 ivar; ivar = ivar->getNextIvar())
2622 if (ivar->getType().isDestructedType())
2623 return true;
2624
2625 return false;
2626}
2627
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002628/// EmitObjCIvarInitializations - Emit information for ivar initialization
2629/// for an implementation.
2630void CodeGenModule::EmitObjCIvarInitializations(ObjCImplementationDecl *D) {
John McCalle81ac692011-03-22 07:05:39 +00002631 // We might need a .cxx_destruct even if we don't have any ivar initializers.
2632 if (needsDestructMethod(D)) {
2633 IdentifierInfo *II = &getContext().Idents.get(".cxx_destruct");
2634 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
2635 ObjCMethodDecl *DTORMethod =
2636 ObjCMethodDecl::Create(getContext(), D->getLocation(), D->getLocation(),
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002637 cxxSelector, getContext().VoidTy, 0, D,
2638 /*isInstance=*/true, /*isVariadic=*/false,
Jordan Rose1e4691b2012-10-10 16:42:25 +00002639 /*isPropertyAccessor=*/true, /*isImplicitlyDeclared=*/true,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002640 /*isDefined=*/false, ObjCMethodDecl::Required);
John McCalle81ac692011-03-22 07:05:39 +00002641 D->addInstanceMethod(DTORMethod);
2642 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, DTORMethod, false);
John McCallb03527a2012-10-17 04:53:31 +00002643 D->setHasDestructors(true);
John McCalle81ac692011-03-22 07:05:39 +00002644 }
2645
2646 // If the implementation doesn't have any ivar initializers, we don't need
2647 // a .cxx_construct.
David Chisnall827bbcc2011-03-17 14:19:08 +00002648 if (D->getNumIvarInitializers() == 0)
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002649 return;
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002650
John McCalle81ac692011-03-22 07:05:39 +00002651 IdentifierInfo *II = &getContext().Idents.get(".cxx_construct");
2652 Selector cxxSelector = getContext().Selectors.getSelector(0, &II);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002653 // The constructor returns 'self'.
2654 ObjCMethodDecl *CTORMethod = ObjCMethodDecl::Create(getContext(),
2655 D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00002656 D->getLocation(),
Argyrios Kyrtzidis11d77162011-10-03 06:36:36 +00002657 cxxSelector,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002658 getContext().getObjCIdType(), 0,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002659 D, /*isInstance=*/true,
2660 /*isVariadic=*/false,
Jordan Rose1e4691b2012-10-10 16:42:25 +00002661 /*isPropertyAccessor=*/true,
Argyrios Kyrtzidis75cf3e82011-08-17 19:25:08 +00002662 /*isImplicitlyDeclared=*/true,
2663 /*isDefined=*/false,
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002664 ObjCMethodDecl::Required);
2665 D->addInstanceMethod(CTORMethod);
2666 CodeGenFunction(*this).GenerateObjCCtorDtorMethod(D, CTORMethod, true);
John McCallb03527a2012-10-17 04:53:31 +00002667 D->setHasNonZeroConstructors(true);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002668}
2669
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002670/// EmitNamespace - Emit all declarations in a namespace.
Anders Carlsson984e0682009-04-01 00:58:25 +00002671void CodeGenModule::EmitNamespace(const NamespaceDecl *ND) {
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002672 for (RecordDecl::decl_iterator I = ND->decls_begin(), E = ND->decls_end();
Anders Carlsson984e0682009-04-01 00:58:25 +00002673 I != E; ++I)
2674 EmitTopLevelDecl(*I);
2675}
2676
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002677// EmitLinkageSpec - Emit all declarations in a linkage spec.
2678void CodeGenModule::EmitLinkageSpec(const LinkageSpecDecl *LSD) {
Eli Friedmanf976be82009-08-01 20:48:04 +00002679 if (LSD->getLanguage() != LinkageSpecDecl::lang_c &&
2680 LSD->getLanguage() != LinkageSpecDecl::lang_cxx) {
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002681 ErrorUnsupported(LSD, "linkage spec");
2682 return;
2683 }
2684
Argyrios Kyrtzidis17945a02009-06-30 02:36:12 +00002685 for (RecordDecl::decl_iterator I = LSD->decls_begin(), E = LSD->decls_end();
Fariborz Jahanianc1868e52012-10-26 20:22:11 +00002686 I != E; ++I) {
Fariborz Jahanian107dae42012-10-26 22:20:25 +00002687 // Meta-data for ObjC class includes references to implemented methods.
2688 // Generate class's method definitions first.
Fariborz Jahanianc1868e52012-10-26 20:22:11 +00002689 if (ObjCImplDecl *OID = dyn_cast<ObjCImplDecl>(*I)) {
2690 for (ObjCContainerDecl::method_iterator M = OID->meth_begin(),
2691 MEnd = OID->meth_end();
2692 M != MEnd; ++M)
2693 EmitTopLevelDecl(*M);
2694 }
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002695 EmitTopLevelDecl(*I);
Fariborz Jahanianc1868e52012-10-26 20:22:11 +00002696 }
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002697}
2698
Daniel Dunbar41071de2008-08-15 23:26:23 +00002699/// EmitTopLevelDecl - Emit code for a single top level declaration.
2700void CodeGenModule::EmitTopLevelDecl(Decl *D) {
2701 // If an error has occurred, stop code generation, but continue
2702 // parsing and semantic analysis (to ensure all warnings and errors
2703 // are emitted).
2704 if (Diags.hasErrorOccurred())
2705 return;
2706
Douglas Gregor16e8be22009-06-29 17:30:29 +00002707 // Ignore dependent declarations.
2708 if (D->getDeclContext() && D->getDeclContext()->isDependentContext())
2709 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002710
Daniel Dunbar41071de2008-08-15 23:26:23 +00002711 switch (D->getKind()) {
Anders Carlsson293361a2009-08-25 13:14:46 +00002712 case Decl::CXXConversion:
Anders Carlsson2b77ba82009-04-04 20:47:02 +00002713 case Decl::CXXMethod:
Daniel Dunbar41071de2008-08-15 23:26:23 +00002714 case Decl::Function:
Douglas Gregor16e8be22009-06-29 17:30:29 +00002715 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00002716 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2717 cast<FunctionDecl>(D)->isLateTemplateParsed())
Douglas Gregor16e8be22009-06-29 17:30:29 +00002718 return;
Mike Stump1eb44332009-09-09 15:08:12 +00002719
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002720 EmitGlobal(cast<FunctionDecl>(D));
2721 break;
2722
Daniel Dunbar41071de2008-08-15 23:26:23 +00002723 case Decl::Var:
Anders Carlsson555b4bb2009-09-10 23:43:36 +00002724 EmitGlobal(cast<VarDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002725 break;
2726
John McCall26fbc722011-04-12 01:01:22 +00002727 // Indirect fields from global anonymous structs and unions can be
2728 // ignored; only the actual variable requires IR gen support.
2729 case Decl::IndirectField:
2730 break;
2731
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002732 // C++ Decls
Daniel Dunbar41071de2008-08-15 23:26:23 +00002733 case Decl::Namespace:
Anders Carlsson984e0682009-04-01 00:58:25 +00002734 EmitNamespace(cast<NamespaceDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002735 break;
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002736 // No code generation needed.
John McCall9d0c6612009-11-17 09:33:40 +00002737 case Decl::UsingShadow:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002738 case Decl::Using:
Douglas Gregordd9967a2009-09-02 23:49:23 +00002739 case Decl::UsingDirective:
Douglas Gregor127102b2009-06-29 20:59:39 +00002740 case Decl::ClassTemplate:
2741 case Decl::FunctionTemplate:
Richard Smith3e4c6c42011-05-05 21:57:07 +00002742 case Decl::TypeAliasTemplate:
Anders Carlsson018837b2009-09-23 19:19:16 +00002743 case Decl::NamespaceAlias:
Douglas Gregor6a576ab2011-06-05 05:04:23 +00002744 case Decl::Block:
Michael Han684aa732013-02-22 17:15:32 +00002745 case Decl::Empty:
Douglas Gregor9cfbe482009-06-20 00:51:54 +00002746 break;
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002747 case Decl::CXXConstructor:
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002748 // Skip function templates
Francois Pichet8387e2a2011-04-22 22:18:13 +00002749 if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
2750 cast<FunctionDecl>(D)->isLateTemplateParsed())
Anders Carlsson1fe598c2009-11-24 05:16:24 +00002751 return;
2752
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002753 EmitCXXConstructors(cast<CXXConstructorDecl>(D));
2754 break;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002755 case Decl::CXXDestructor:
Francois Pichet8387e2a2011-04-22 22:18:13 +00002756 if (cast<FunctionDecl>(D)->isLateTemplateParsed())
2757 return;
Anders Carlsson27ae5362009-04-17 01:58:57 +00002758 EmitCXXDestructors(cast<CXXDestructorDecl>(D));
2759 break;
Anders Carlsson36674d22009-06-11 21:22:55 +00002760
2761 case Decl::StaticAssert:
2762 // Nothing to do.
2763 break;
2764
Anders Carlsson95d4e5d2009-04-15 15:55:24 +00002765 // Objective-C Decls
Mike Stump1eb44332009-09-09 15:08:12 +00002766
Fariborz Jahanian38e24c72009-03-18 22:33:24 +00002767 // Forward declarations, no (immediate) code generation.
Chris Lattner285d0db2009-04-01 02:36:43 +00002768 case Decl::ObjCInterface:
Eric Christopherffb0c3a2012-07-19 22:22:55 +00002769 case Decl::ObjCCategory:
Chris Lattner285d0db2009-04-01 02:36:43 +00002770 break;
2771
Douglas Gregorbd9482d2012-01-01 21:23:57 +00002772 case Decl::ObjCProtocol: {
2773 ObjCProtocolDecl *Proto = cast<ObjCProtocolDecl>(D);
2774 if (Proto->isThisDeclarationADefinition())
2775 ObjCRuntime->GenerateProtocol(Proto);
Daniel Dunbar41071de2008-08-15 23:26:23 +00002776 break;
Douglas Gregorbd9482d2012-01-01 21:23:57 +00002777 }
2778
Daniel Dunbar41071de2008-08-15 23:26:23 +00002779 case Decl::ObjCCategoryImpl:
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002780 // Categories have properties but don't support synthesize so we
2781 // can ignore them here.
Peter Collingbournee9265232011-07-27 20:29:46 +00002782 ObjCRuntime->GenerateCategory(cast<ObjCCategoryImplDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002783 break;
2784
Daniel Dunbaraf05bb92008-08-26 08:29:31 +00002785 case Decl::ObjCImplementation: {
2786 ObjCImplementationDecl *OMD = cast<ObjCImplementationDecl>(D);
2787 EmitObjCPropertyImplementations(OMD);
Fariborz Jahanian109dfc62010-04-28 21:28:56 +00002788 EmitObjCIvarInitializations(OMD);
Peter Collingbournee9265232011-07-27 20:29:46 +00002789 ObjCRuntime->GenerateClass(OMD);
Eric Christopherbe6c6862012-04-11 05:56:05 +00002790 // Emit global variable debug information.
2791 if (CGDebugInfo *DI = getModuleDebugInfo())
Alexey Samsonov96a66392012-12-03 18:28:12 +00002792 if (getCodeGenOpts().getDebugInfo() >= CodeGenOptions::LimitedDebugInfo)
2793 DI->getOrCreateInterfaceType(getContext().getObjCInterfaceType(
2794 OMD->getClassInterface()), OMD->getLocation());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002795 break;
Mike Stump1eb44332009-09-09 15:08:12 +00002796 }
Daniel Dunbar41071de2008-08-15 23:26:23 +00002797 case Decl::ObjCMethod: {
2798 ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(D);
2799 // If this is not a prototype, emit the body.
Argyrios Kyrtzidis6fb0aee2009-06-30 02:35:26 +00002800 if (OMD->getBody())
Daniel Dunbar41071de2008-08-15 23:26:23 +00002801 CodeGenFunction(*this).GenerateObjCMethod(OMD);
2802 break;
2803 }
Mike Stump1eb44332009-09-09 15:08:12 +00002804 case Decl::ObjCCompatibleAlias:
David Chisnall29254f42012-01-31 18:59:20 +00002805 ObjCRuntime->RegisterAlias(cast<ObjCCompatibleAliasDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002806 break;
2807
Anders Carlsson91e20dd2009-04-02 05:55:18 +00002808 case Decl::LinkageSpec:
2809 EmitLinkageSpec(cast<LinkageSpecDecl>(D));
Daniel Dunbar41071de2008-08-15 23:26:23 +00002810 break;
Daniel Dunbar41071de2008-08-15 23:26:23 +00002811
2812 case Decl::FileScopeAsm: {
2813 FileScopeAsmDecl *AD = cast<FileScopeAsmDecl>(D);
Chris Lattner5f9e2722011-07-23 10:55:15 +00002814 StringRef AsmString = AD->getAsmString()->getString();
Mike Stump1eb44332009-09-09 15:08:12 +00002815
Daniel Dunbar41071de2008-08-15 23:26:23 +00002816 const std::string &S = getModule().getModuleInlineAsm();
2817 if (S.empty())
2818 getModule().setModuleInlineAsm(AsmString);
Joerg Sonnenberger8ce9cca2012-08-10 10:57:52 +00002819 else if (S.end()[-1] == '\n')
Chris Lattner9f5bff02011-07-23 20:04:25 +00002820 getModule().setModuleInlineAsm(S + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002821 else
Benjamin Kramer8d042582009-12-11 13:33:18 +00002822 getModule().setModuleInlineAsm(S + '\n' + AsmString.str());
Daniel Dunbar41071de2008-08-15 23:26:23 +00002823 break;
2824 }
Mike Stump1eb44332009-09-09 15:08:12 +00002825
Douglas Gregorb6cbe512013-01-14 17:21:00 +00002826 case Decl::Import: {
2827 ImportDecl *Import = cast<ImportDecl>(D);
2828
2829 // Ignore import declarations that come from imported modules.
2830 if (clang::Module *Owner = Import->getOwningModule()) {
2831 if (getLangOpts().CurrentModule.empty() ||
2832 Owner->getTopLevelModule()->Name == getLangOpts().CurrentModule)
2833 break;
2834 }
2835
Douglas Gregor858afb32013-01-14 20:53:57 +00002836 ImportedModules.insert(Import->getImportedModule());
Douglas Gregorb6cbe512013-01-14 17:21:00 +00002837 break;
2838 }
2839
Mike Stump1eb44332009-09-09 15:08:12 +00002840 default:
Mike Stumpf5408fe2009-05-16 07:57:57 +00002841 // Make sure we handled everything we should, every other kind is a
2842 // non-top-level decl. FIXME: Would be nice to have an isTopLevelDeclKind
2843 // function. Need to recode Decl::Kind to do that easily.
Daniel Dunbar41071de2008-08-15 23:26:23 +00002844 assert(isa<TypeDecl>(D) && "Unsupported decl kind");
2845 }
2846}
John McCall744016d2010-07-06 23:57:41 +00002847
2848/// Turns the given pointer into a constant.
2849static llvm::Constant *GetPointerConstant(llvm::LLVMContext &Context,
2850 const void *Ptr) {
2851 uintptr_t PtrInt = reinterpret_cast<uintptr_t>(Ptr);
Chris Lattner2acc6e32011-07-18 04:24:23 +00002852 llvm::Type *i64 = llvm::Type::getInt64Ty(Context);
John McCall744016d2010-07-06 23:57:41 +00002853 return llvm::ConstantInt::get(i64, PtrInt);
2854}
2855
2856static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
2857 llvm::NamedMDNode *&GlobalMetadata,
2858 GlobalDecl D,
2859 llvm::GlobalValue *Addr) {
2860 if (!GlobalMetadata)
2861 GlobalMetadata =
2862 CGM.getModule().getOrInsertNamedMetadata("clang.global.decl.ptrs");
2863
2864 // TODO: should we report variant information for ctors/dtors?
2865 llvm::Value *Ops[] = {
2866 Addr,
2867 GetPointerConstant(CGM.getLLVMContext(), D.getDecl())
2868 };
Jay Foad6f141652011-04-21 19:59:12 +00002869 GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
John McCall744016d2010-07-06 23:57:41 +00002870}
2871
2872/// Emits metadata nodes associating all the global values in the
2873/// current module with the Decls they came from. This is useful for
2874/// projects using IR gen as a subroutine.
2875///
2876/// Since there's currently no way to associate an MDNode directly
2877/// with an llvm::GlobalValue, we create a global named metadata
2878/// with the name 'clang.global.decl.ptrs'.
2879void CodeGenModule::EmitDeclMetadata() {
2880 llvm::NamedMDNode *GlobalMetadata = 0;
2881
2882 // StaticLocalDeclMap
Chris Lattner5f9e2722011-07-23 10:55:15 +00002883 for (llvm::DenseMap<GlobalDecl,StringRef>::iterator
John McCall744016d2010-07-06 23:57:41 +00002884 I = MangledDeclNames.begin(), E = MangledDeclNames.end();
2885 I != E; ++I) {
2886 llvm::GlobalValue *Addr = getModule().getNamedValue(I->second);
2887 EmitGlobalDeclMetadata(*this, GlobalMetadata, I->first, Addr);
2888 }
2889}
2890
2891/// Emits metadata nodes for all the local variables in the current
2892/// function.
2893void CodeGenFunction::EmitDeclMetadata() {
2894 if (LocalDeclMap.empty()) return;
2895
2896 llvm::LLVMContext &Context = getLLVMContext();
2897
2898 // Find the unique metadata ID for this name.
2899 unsigned DeclPtrKind = Context.getMDKindID("clang.decl.ptr");
2900
2901 llvm::NamedMDNode *GlobalMetadata = 0;
2902
2903 for (llvm::DenseMap<const Decl*, llvm::Value*>::iterator
2904 I = LocalDeclMap.begin(), E = LocalDeclMap.end(); I != E; ++I) {
2905 const Decl *D = I->first;
2906 llvm::Value *Addr = I->second;
2907
2908 if (llvm::AllocaInst *Alloca = dyn_cast<llvm::AllocaInst>(Addr)) {
2909 llvm::Value *DAddr = GetPointerConstant(getLLVMContext(), D);
Jay Foad6f141652011-04-21 19:59:12 +00002910 Alloca->setMetadata(DeclPtrKind, llvm::MDNode::get(Context, DAddr));
John McCall744016d2010-07-06 23:57:41 +00002911 } else if (llvm::GlobalValue *GV = dyn_cast<llvm::GlobalValue>(Addr)) {
2912 GlobalDecl GD = GlobalDecl(cast<VarDecl>(D));
2913 EmitGlobalDeclMetadata(CGM, GlobalMetadata, GD, GV);
2914 }
2915 }
2916}
Daniel Dunbar673431a2010-07-16 00:00:15 +00002917
Nick Lewycky3dc05412011-05-05 00:08:20 +00002918void CodeGenModule::EmitCoverageFile() {
2919 if (!getCodeGenOpts().CoverageFile.empty()) {
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002920 if (llvm::NamedMDNode *CUNode = TheModule.getNamedMetadata("llvm.dbg.cu")) {
2921 llvm::NamedMDNode *GCov = TheModule.getOrInsertNamedMetadata("llvm.gcov");
2922 llvm::LLVMContext &Ctx = TheModule.getContext();
Nick Lewycky3dc05412011-05-05 00:08:20 +00002923 llvm::MDString *CoverageFile =
2924 llvm::MDString::get(Ctx, getCodeGenOpts().CoverageFile);
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002925 for (int i = 0, e = CUNode->getNumOperands(); i != e; ++i) {
2926 llvm::MDNode *CU = CUNode->getOperand(i);
Nick Lewycky3dc05412011-05-05 00:08:20 +00002927 llvm::Value *node[] = { CoverageFile, CU };
Nick Lewycky5ea4f442011-05-04 20:46:58 +00002928 llvm::MDNode *N = llvm::MDNode::get(Ctx, node);
2929 GCov->addOperand(N);
2930 }
2931 }
2932 }
2933}
Nico Weberc5f80462012-10-11 10:13:44 +00002934
2935llvm::Constant *CodeGenModule::EmitUuidofInitializer(StringRef Uuid,
2936 QualType GuidType) {
2937 // Sema has checked that all uuid strings are of the form
2938 // "12345678-1234-1234-1234-1234567890ab".
2939 assert(Uuid.size() == 36);
2940 const char *Uuidstr = Uuid.data();
2941 for (int i = 0; i < 36; ++i) {
2942 if (i == 8 || i == 13 || i == 18 || i == 23) assert(Uuidstr[i] == '-');
Jordan Rose3f6f51e2013-02-08 22:30:41 +00002943 else assert(isHexDigit(Uuidstr[i]));
Nico Weberc5f80462012-10-11 10:13:44 +00002944 }
2945
2946 llvm::APInt Field0(32, StringRef(Uuidstr , 8), 16);
2947 llvm::APInt Field1(16, StringRef(Uuidstr + 9, 4), 16);
2948 llvm::APInt Field2(16, StringRef(Uuidstr + 14, 4), 16);
Nico Weber193646f2012-10-17 00:34:34 +00002949 static const int Field3ValueOffsets[] = { 19, 21, 24, 26, 28, 30, 32, 34 };
Nico Weberc5f80462012-10-11 10:13:44 +00002950
2951 APValue InitStruct(APValue::UninitStruct(), /*NumBases=*/0, /*NumFields=*/4);
2952 InitStruct.getStructField(0) = APValue(llvm::APSInt(Field0));
2953 InitStruct.getStructField(1) = APValue(llvm::APSInt(Field1));
2954 InitStruct.getStructField(2) = APValue(llvm::APSInt(Field2));
2955 APValue& Arr = InitStruct.getStructField(3);
2956 Arr = APValue(APValue::UninitArray(), 8, 8);
2957 for (int t = 0; t < 8; ++t)
Nico Weber43085812012-10-13 21:56:05 +00002958 Arr.getArrayInitializedElt(t) = APValue(llvm::APSInt(
2959 llvm::APInt(8, StringRef(Uuidstr + Field3ValueOffsets[t], 2), 16)));
Nico Weberc5f80462012-10-11 10:13:44 +00002960
2961 return EmitConstantValue(InitStruct, GuidType);
2962}